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 <wsutil/cmdarg_err.h>
44 #include <wsutil/crash_info.h>
45 #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"
69 #include <wsutil/unicode-utils.h>
76 #include <wsutil/clopts_common.h>
77 #include <wsutil/privileges.h>
79 #include "sync_pipe.h"
81 #include "capture_opts.h"
82 #include <capchild/capture_session.h>
83 #include <capchild/capture_sync.h>
85 #include "conditions.h"
86 #include "capture_stop_conditions.h"
88 #include "wsutil/tempfile.h"
90 #include "wsutil/file_util.h"
91 #include "wsutil/cpu_info.h"
92 #include "wsutil/os_version_info.h"
93 #include "wsutil/str_util.h"
94 #include "wsutil/inet_addr.h"
95 #include "wsutil/time_util.h"
97 #include "caputils/ws80211_utils.h"
102 * Get information about libpcap format from "wiretap/libpcap.h".
103 * Get information about pcapng format from "wiretap/pcapng_module.h".
104 * XXX - can we just use pcap_open_offline() to read the pipe?
106 #include "wiretap/libpcap.h"
107 #include "wiretap/pcapng_module.h"
108 #include "wiretap/pcapng.h"
110 /**#define DEBUG_DUMPCAP**/
111 /**#define DEBUG_CHILD_DUMPCAP**/
115 #include <conio.h> /* _getch() */
119 #ifdef DEBUG_CHILD_DUMPCAP
120 FILE *debug_log; /* for logging debug messages to */
121 /* a file if DEBUG_CHILD_DUMPCAP */
125 static GAsyncQueue *pcap_queue;
126 static gint64 pcap_queue_bytes;
127 static gint64 pcap_queue_packets;
128 static gint64 pcap_queue_byte_limit = 0;
129 static gint64 pcap_queue_packet_limit = 0;
131 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
133 static gchar *sig_pipe_name = NULL;
134 static HANDLE sig_pipe_handle = NULL;
135 static gboolean signal_pipe_check_running(void);
139 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
140 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
143 /** Stop a low-level capture (stops the capture child). */
144 static void capture_loop_stop(void);
145 /** Close a pipe, or socket if \a from_socket is TRUE */
146 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
148 #if !defined (__linux__)
149 #ifndef HAVE_PCAP_BREAKLOOP
151 * We don't have pcap_breakloop(), which is the only way to ensure that
152 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
153 * won't, if the call to read the next packet or batch of packets is
154 * is interrupted by a signal on UN*X, just go back and try again to
157 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
158 * the signal handler, set a flag to stop capturing; however, without
159 * a guarantee of that sort, we can't guarantee that we'll stop capturing
160 * if the read will be retried and won't time out if no packets arrive.
162 * Therefore, on at least some platforms, we work around the lack of
163 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
164 * to wait for packets to arrive, so that we're probably going to be
165 * blocked in the select() when the signal arrives, and can just bail
166 * out of the loop at that point.
168 * However, we don't want to do that on BSD (because "select()" doesn't work
169 * correctly on BPF devices on at least some releases of some flavors of
170 * BSD), and we don't want to do it on Windows (because "select()" is
171 * something for sockets, not for arbitrary handles). (Note that "Windows"
172 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
173 * using WinPcap, not a UNIX libpcap.)
175 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
176 * on BSD times out even if no packets have arrived, so we'll eventually
177 * exit pcap_dispatch() with an indication that no packets have arrived,
178 * and will break out of the capture loop at that point.
180 * On Windows, we can't send a SIGINT to stop capturing, so none of this
181 * applies in any case.
183 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
184 * want to include it if it's not present on this platform, however.
186 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
187 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
189 # define MUST_DO_SELECT
190 # endif /* avoid select */
191 #endif /* HAVE_PCAP_BREAKLOOP */
193 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
194 * in pcap_dispatch(); on the other hand, select() works just fine there.
195 * Hence we use a select for that come what may.
197 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
198 * internally, and, with TPACKET_V3, once that's supported, it'll
199 * support timeouts, at least as I understand the way the code works.
201 #define MUST_DO_SELECT
204 /** init the capture filter */
207 INITFILTER_BAD_FILTER,
208 INITFILTER_OTHER_ERROR
209 } initfilter_status_t;
212 STATE_EXPECT_REC_HDR,
225 typedef struct _pcap_pipe_info {
226 struct pcap_hdr hdr; /**< Pcap header when capturing from a pipe */
227 struct pcaprec_modified_hdr rechdr; /**< Pcap record header when capturing from a pipe */
230 typedef struct _pcapng_pipe_info {
231 struct pcapng_block_header_s bh; /**< Pcapng general block header when capturing from a pipe */
232 struct pcapng_section_header_block_s shb; /**< Pcapng section header when capturing from a pipe */
233 GList *saved_blocks; /**< Pcapng block list of SHB and IDBs for multi_file_on */
234 } pcapng_pipe_info_t;
236 struct _loop_data; /* forward declaration so we can use it in the cap_pipe_dispatch function pointer */
239 * A source of packets from which we're capturing.
241 typedef struct _capture_src {
246 #ifdef MUST_DO_SELECT
247 int pcap_fd; /**< pcap file descriptor */
254 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
255 /**< capture pipe (unix only "input file") */
256 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
257 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
258 gboolean from_pcapng; /**< TRUE if we're capturing from pcapng format */
260 pcap_pipe_info_t pcap; /**< Pcap info when capturing from a pipe */
261 pcapng_pipe_info_t pcapng; /**< Pcapng info when capturing from a pipe */
264 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
266 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
267 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
268 gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
269 char * cap_pipe_databuf; /**< Pointer to the data buffer we've allocated */
270 size_t cap_pipe_databuf_size; /**< Current size of the data buffer */
271 guint cap_pipe_max_pkt_size; /**< Maximum packet size allowed */
273 char * cap_pipe_buf; /**< Pointer to the buffer we read into */
274 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
275 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
277 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
278 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
280 int (*cap_pipe_dispatch)(struct _loop_data *, struct _capture_src *, char *, int);
281 cap_pipe_state_t cap_pipe_state;
282 cap_pipe_err_t cap_pipe_err;
285 GMutex *cap_pipe_read_mtx;
286 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
291 * Global capture loop state.
293 typedef struct _loop_data {
295 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
296 int err; /**< if non-zero, error seen while capturing */
297 gint packet_count; /**< Number of packets we have already captured */
298 gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
299 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
301 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
303 GArray *pcaps; /**< Array of capture_src's on which we're capturing */
307 guint64 bytes_written;
308 guint32 autostop_files;
311 typedef struct _pcap_queue_element {
312 capture_src *pcap_src;
314 struct pcap_pkthdr phdr;
315 struct pcapng_block_header_s bh;
318 } pcap_queue_element;
321 * Standard secondary message for unexpected errors.
323 static const char please_report[] =
324 "Please report this to the Wireshark developers.\n"
325 "https://bugs.wireshark.org/\n"
326 "(This is not a crash; please do not report it as such.)";
329 * This needs to be static, so that the SIGINT handler can clear the "go"
332 static loop_data global_ld;
335 * Timeout, in milliseconds, for reads from the stream of captured packets
336 * from a capture device.
338 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
339 * 64-bit applications, with sub-second timeouts not to work. The bug is
340 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
342 #if defined(__APPLE__) && defined(__LP64__)
343 static gboolean need_timeout_workaround;
345 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
347 #define CAP_READ_TIMEOUT 250
351 * Timeout, in microseconds, for reads from the stream of captured packets
352 * from a pipe. Pipes don't have the same problem that BPF devices do
353 * in Mac OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
354 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
355 * of the offending versions of Snow Leopard.
357 * On Windows this value is converted to milliseconds and passed to
358 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
359 * will return immediately.
362 #define PIPE_READ_TIMEOUT 100000
364 #define PIPE_READ_TIMEOUT 250000
367 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
370 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
371 const char *message, gpointer user_data _U_);
373 /* capture related options */
374 static capture_options global_capture_opts;
375 static gboolean quiet = FALSE;
376 static gboolean use_threads = FALSE;
377 static guint64 start_time;
379 static void capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
381 static void capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
383 static void capture_loop_write_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, const u_char *pd);
384 static void capture_loop_queue_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, const u_char *pd);
385 static void capture_loop_get_errmsg(char *errmsg, size_t errmsglen,
386 char *secondary_errmsg,
387 size_t secondary_errmsglen,
388 const char *fname, int err,
391 static void WS_NORETURN exit_main(int err);
393 static void report_new_capture_file(const char *filename);
394 static void report_packet_count(unsigned int packet_count);
395 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
396 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
397 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
399 #define MSG_MAX_LENGTH 4096
402 print_usage(FILE *output)
404 fprintf(output, "\nUsage: dumpcap [options] ...\n");
405 fprintf(output, "\n");
406 fprintf(output, "Capture interface:\n");
407 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
408 " or for remote capturing, use one of these formats:\n"
409 " rpcap://<host>/<interface>\n"
410 " TCP@<host>:<port>\n");
411 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
412 #ifdef HAVE_PCAP_CREATE
413 fprintf(output, " -s <snaplen> packet snapshot length (def: appropriate maximum)\n");
415 fprintf(output, " -s <snaplen> packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
417 fprintf(output, " -p don't capture in promiscuous mode\n");
418 #ifdef HAVE_PCAP_CREATE
419 fprintf(output, " -I capture in monitor mode, if available\n");
421 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
422 fprintf(output, " -B <buffer size> size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
424 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
425 fprintf(output, " --time-stamp-type <type> timestamp method for interface\n");
426 fprintf(output, " -D print list of interfaces and exit\n");
427 fprintf(output, " -L print list of link-layer types of iface and exit\n");
428 fprintf(output, " --list-time-stamp-types print list of timestamp types for iface and exit\n");
429 #ifdef HAVE_BPF_IMAGE
430 fprintf(output, " -d print generated BPF code for capture filter\n");
432 fprintf(output, " -k set channel on wifi interface:\n"
433 " <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
434 fprintf(output, " -S print statistics for each interface once per second\n");
435 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
436 fprintf(output, "\n");
437 #ifdef HAVE_PCAP_REMOTE
438 fprintf(output, "RPCAP options:\n");
439 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
440 fprintf(output, " -u use UDP for RPCAP data transfer\n");
441 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
442 #ifdef HAVE_PCAP_SETSAMPLING
443 fprintf(output, " -m <sampling type> use packet sampling\n");
444 fprintf(output, " count:NUM - capture one packet of every NUM\n");
445 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
448 fprintf(output, "Stop conditions:\n");
449 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
450 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
451 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
452 fprintf(output, " files:NUM - stop after NUM files\n");
453 /*fprintf(output, "\n");*/
454 fprintf(output, "Output (files):\n");
455 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
456 fprintf(output, " -g enable group read access on the output file(s)\n");
457 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
458 fprintf(output, " interval:NUM - create time intervals of NUM secs\n");
459 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
460 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
461 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
462 fprintf(output, " -P use libpcap format instead of pcapng\n");
463 fprintf(output, " --capture-comment <comment>\n");
464 fprintf(output, " add a capture comment to the output file\n");
465 fprintf(output, " (only for pcapng)\n");
466 fprintf(output, "\n");
467 fprintf(output, "Miscellaneous:\n");
468 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
469 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
470 fprintf(output, " within dumpcap\n");
471 fprintf(output, " -t use a separate thread per interface\n");
472 fprintf(output, " -q don't report packet capture counts\n");
473 fprintf(output, " -v print version information and exit\n");
474 fprintf(output, " -h display this help and exit\n");
475 fprintf(output, "\n");
477 fprintf(output, "Dumpcap can benefit from an enabled BPF JIT compiler if available.\n");
478 fprintf(output, "You might want to enable it by executing:\n");
479 fprintf(output, " \"echo 1 > /proc/sys/net/core/bpf_jit_enable\"\n");
480 fprintf(output, "Note that this can make your system less secure!\n");
481 fprintf(output, "\n");
483 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
484 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
485 fprintf(output, "\n");
486 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
490 * Report an error in command-line arguments.
491 * If we're a capture child, send a message back to the parent, otherwise
495 dumpcap_cmdarg_err(const char *fmt, va_list ap)
499 /* Generate a 'special format' message back to parent */
500 msg = g_strdup_vprintf(fmt, ap);
501 sync_pipe_errmsg_to_parent(2, msg, "");
504 fprintf(stderr, "dumpcap: ");
505 vfprintf(stderr, fmt, ap);
506 fprintf(stderr, "\n");
511 * Report additional information for an error in command-line arguments.
512 * If we're a capture child, send a message back to the parent, otherwise
516 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
520 msg = g_strdup_vprintf(fmt, ap);
521 sync_pipe_errmsg_to_parent(2, msg, "");
524 vfprintf(stderr, fmt, ap);
525 fprintf(stderr, "\n");
531 #if 0 /* Set to enable capability debugging */
532 /* see 'man cap_to_text()' for explanation of output */
533 /* '=' means 'all= ' ie: no capabilities */
534 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
536 print_caps(const char *pfx) {
537 cap_t caps = cap_get_proc();
538 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
539 "%s: EUID: %d Capabilities: %s", pfx,
540 geteuid(), cap_to_text(caps, NULL));
544 print_caps(const char *pfx _U_) {
549 relinquish_all_capabilities(void)
551 /* Drop any and all capabilities this process may have. */
552 /* Allowed whether or not process has any privileges. */
553 cap_t caps = cap_init(); /* all capabilities initialized to off */
554 print_caps("Pre-clear");
555 if (cap_set_proc(caps)) {
556 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
558 print_caps("Post-clear");
564 * Platform-dependent suggestions for fixing permissions.
566 #if defined(__linux__)
567 #define PLATFORM_PERMISSIONS_SUGGESTION \
569 "On Debian and Debian derivatives such as Ubuntu, if you have " \
570 "installed Wireshark from a package, try running" \
572 " sudo dpkg-reconfigure wireshark-common" \
574 "selecting \"<Yes>\" in response to the question" \
576 " Should non-superusers be able to capture packets?" \
578 "adding yourself to the \"wireshark\" group by running" \
580 " sudo usermod -a -G wireshark {your username}" \
582 "and then logging out and logging back in again."
583 #elif defined(__APPLE__)
584 #define PLATFORM_PERMISSIONS_SUGGESTION \
586 "If you installed Wireshark using the package from wireshark.org, "\
587 "Try re-installing it and checking the box for the \"Set capture " \
588 "permissions on startup\" item."
590 #define PLATFORM_PERMISSIONS_SUGGESTION
594 get_pcap_failure_secondary_error_message(cap_device_open_err open_err,
595 const char *open_err_str
603 * On Windows, first make sure they *have* WinPcap installed.
607 "In order to capture packets, WinPcap must be installed; see\n"
609 " https://www.winpcap.org/\n"
611 "for a downloadable version of WinPcap and for instructions on how to install\n"
617 * Now deal with ancient versions of libpcap that, on HP-UX, don't
618 * correctly figure out how to open a device given the device name.
621 /* HP-UX-specific suggestion. */
622 static const char ppamsg[] = "can't find PPA for ";
624 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0) {
626 "You are running (T)Wireshark with a version of the libpcap library\n"
627 "that doesn't handle HP-UX network devices well; this means that\n"
628 "(T)Wireshark may not be able to capture packets.\n"
630 "To fix this, you should install libpcap 0.6.2, or a later version\n"
631 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
632 "packaged binary form from the Software Porting And Archive Centre\n"
633 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
634 "at the URL lists a number of mirror sites.";
639 * OK, now just return a largely platform-independent error that might
640 * have platform-specific suggestions at the end (for example, suggestions
641 * for how to get permission to capture).
643 if (open_err == CAP_DEVICE_OPEN_ERR_GENERIC) {
645 * We don't know what kind of error it is, so throw all the
646 * suggestions at the user.
649 "Please check to make sure you have sufficient permissions, and that you have "
650 "the proper interface or pipe specified."
651 PLATFORM_PERMISSIONS_SUGGESTION;
652 } else if (open_err == CAP_DEVICE_OPEN_ERR_PERMISSIONS) {
654 * This is a permissions error, so no need to specify any other
658 "Please check to make sure you have sufficient permissions."
659 PLATFORM_PERMISSIONS_SUGGESTION;
662 * This is not a permissons error, so no need to suggest
663 * checking permissions.
666 "Please check that you have the proper interface or pipe specified.";
671 get_capture_device_open_failure_messages(cap_device_open_err open_err,
672 const char *open_err_str,
674 char *errmsg, size_t errmsg_len,
675 char *secondary_errmsg,
676 size_t secondary_errmsg_len)
678 g_snprintf(errmsg, (gulong) errmsg_len,
679 "The capture session could not be initiated on interface '%s' (%s).",
680 iface, open_err_str);
681 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, "%s",
682 get_pcap_failure_secondary_error_message(open_err, open_err_str));
686 compile_capture_filter(const char *iface, pcap_t *pcap_h,
687 struct bpf_program *fcode, const char *cfilter)
689 bpf_u_int32 netnum, netmask;
690 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
692 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
694 * Well, we can't get the netmask for this interface; it's used
695 * only for filters that check for broadcast IP addresses, so
696 * we just punt and use 0. It might be nice to warn the user,
697 * but that's a pain in a GUI application, as it'd involve popping
698 * up a message box, and it's not clear how often this would make
699 * a difference (only filters that check for IP broadcast addresses
703 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
708 * Sigh. Older versions of libpcap don't properly declare the
709 * third argument to pcap_compile() as a const pointer. Cast
713 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
719 #ifdef HAVE_BPF_IMAGE
721 show_filter_code(capture_options *capture_opts)
723 interface_options *interface_opts;
725 cap_device_open_err open_err;
726 gchar open_err_str[PCAP_ERRBUF_SIZE];
727 char errmsg[MSG_MAX_LENGTH+1];
728 char secondary_errmsg[MSG_MAX_LENGTH+1];
729 struct bpf_program fcode;
730 struct bpf_insn *insn;
734 for (j = 0; j < capture_opts->ifaces->len; j++) {
735 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, j);
736 pcap_h = open_capture_device(capture_opts, interface_opts,
737 CAP_READ_TIMEOUT, &open_err, &open_err_str);
738 if (pcap_h == NULL) {
739 /* Open failed; get messages */
740 get_capture_device_open_failure_messages(open_err, open_err_str,
741 interface_opts->name,
742 errmsg, sizeof errmsg,
744 sizeof secondary_errmsg);
745 /* And report them */
746 report_capture_error(errmsg, secondary_errmsg);
750 /* Set the link-layer type. */
751 if (!set_pcap_datalink(pcap_h, interface_opts->linktype, interface_opts->name,
752 errmsg, sizeof errmsg,
753 secondary_errmsg, sizeof secondary_errmsg)) {
755 report_capture_error(errmsg, secondary_errmsg);
759 /* OK, try to compile the capture filter. */
760 if (!compile_capture_filter(interface_opts->name, pcap_h, &fcode,
761 interface_opts->cfilter)) {
763 report_cfilter_error(capture_opts, j, errmsg);
768 /* Now print the filter code. */
769 insn = fcode.bf_insns;
771 for (i = 0; i < fcode.bf_len; insn++, i++)
772 printf("%s\n", bpf_image(insn, i));
774 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
775 /* to remove any suid privileges. */
776 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
777 /* (euid/egid have already previously been set to ruid/rgid. */
778 /* (See comment in main() for details) */
780 relinquish_special_privs_perm();
782 relinquish_all_capabilities();
785 /* Let our parent know we succeeded. */
786 pipe_write_block(2, SP_SUCCESS, NULL);
793 * capture_interface_list() is expected to do the right thing to get
794 * a list of interfaces.
796 * In most of the programs in the Wireshark suite, "the right thing"
797 * is to run dumpcap and ask it for the list, because dumpcap may
798 * be the only program in the suite with enough privileges to get
801 * In dumpcap itself, however, we obviously can't run dumpcap to
802 * ask for the list. Therefore, our capture_interface_list() should
803 * just call get_interface_list().
806 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
808 return get_interface_list(err, err_str);
812 * Output a machine readable list of the interfaces
813 * This list is retrieved by the sync_interface_list_open() function
814 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
817 print_machine_readable_interfaces(GList *if_list)
824 char addr_str[WS_INET6_ADDRSTRLEN];
827 /* Let our parent know we succeeded. */
828 pipe_write_block(2, SP_SUCCESS, NULL);
831 i = 1; /* Interface id number */
832 for (if_entry = g_list_first(if_list); if_entry != NULL;
833 if_entry = g_list_next(if_entry)) {
834 if_info = (if_info_t *)if_entry->data;
835 printf("%d. %s\t", i++, if_info->name);
838 * Print the contents of the if_entry struct in a parseable format.
839 * Each if_entry element is tab-separated. Addresses are comma-
842 /* XXX - Make sure our description doesn't contain a tab */
843 if (if_info->vendor_description != NULL)
844 printf("%s\t", if_info->vendor_description);
848 /* XXX - Make sure our friendly name doesn't contain a tab */
849 if (if_info->friendly_name != NULL)
850 printf("%s\t", if_info->friendly_name);
854 printf("%i\t", if_info->type);
856 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
857 addr = g_slist_next(addr)) {
858 if (addr != g_slist_nth(if_info->addrs, 0))
861 if_addr = (if_addr_t *)addr->data;
862 switch(if_addr->ifat_type) {
864 printf("%s", ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str, sizeof(addr_str)));
867 printf("%s", ws_inet_ntop6(&if_addr->addr.ip6_addr, addr_str, sizeof(addr_str)));
870 printf("<type unknown %i>", if_addr->ifat_type);
874 if (if_info->loopback)
875 printf("\tloopback");
878 printf("\t%s", if_info->extcap);
884 * If you change the machine-readable output format of this function,
885 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
888 print_machine_readable_if_capabilities(if_capabilities_t *caps, int queries)
890 GList *lt_entry, *ts_entry;
891 const gchar *desc_str;
894 /* Let our parent know we succeeded. */
895 pipe_write_block(2, SP_SUCCESS, NULL);
898 if (queries & CAPS_QUERY_LINK_TYPES) {
899 if (caps->can_set_rfmon)
903 for (lt_entry = caps->data_link_types; lt_entry != NULL;
904 lt_entry = g_list_next(lt_entry)) {
905 data_link_info_t *data_link_info = (data_link_info_t *)lt_entry->data;
906 if (data_link_info->description != NULL)
907 desc_str = data_link_info->description;
909 desc_str = "(not supported)";
910 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
915 if (queries & CAPS_QUERY_TIMESTAMP_TYPES) {
916 for (ts_entry = caps->timestamp_types; ts_entry != NULL;
917 ts_entry = g_list_next(ts_entry)) {
918 timestamp_info_t *timestamp = (timestamp_info_t *)ts_entry->data;
919 if (timestamp->description != NULL)
920 desc_str = timestamp->description;
923 printf("%s\t%s\n", timestamp->name, desc_str);
933 /* Print the number of packets captured for each interface until we're killed. */
935 print_statistics_loop(gboolean machine_readable)
937 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
943 char errbuf[PCAP_ERRBUF_SIZE];
946 if_list = get_interface_list(&err, &err_str);
947 if (if_list == NULL) {
949 cmdarg_err("There are no interfaces on which a capture can be done");
951 cmdarg_err("%s", err_str);
957 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
958 if_info = (if_info_t *)if_entry->data;
961 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
962 * connections. We avoid collecting stats on them.
964 if (!strncmp(if_info->name, "nf", 2)) {
965 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
971 #ifdef HAVE_PCAP_OPEN
972 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
974 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
978 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
979 if_stat->name = g_strdup(if_info->name);
981 stat_list = g_list_append(stat_list, if_stat);
986 cmdarg_err("There are no interfaces on which a capture can be done");
991 /* Let our parent know we succeeded. */
992 pipe_write_block(2, SP_SUCCESS, NULL);
995 if (!machine_readable) {
996 printf("%-15s %10s %10s\n", "Interface", "Received",
1000 global_ld.go = TRUE;
1001 while (global_ld.go) {
1002 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1003 if_stat = (if_stat_t *)stat_entry->data;
1004 pcap_stats(if_stat->pch, &ps);
1006 if (!machine_readable) {
1007 printf("%-15s %10u %10u\n", if_stat->name,
1008 ps.ps_recv, ps.ps_drop);
1010 printf("%s\t%u\t%u\n", if_stat->name,
1011 ps.ps_recv, ps.ps_drop);
1016 /* If we have a dummy signal pipe check it */
1017 if (!signal_pipe_check_running()) {
1018 global_ld.go = FALSE;
1026 /* XXX - Not reached. Should we look for 'q' in stdin? */
1027 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1028 if_stat = (if_stat_t *)stat_entry->data;
1029 pcap_close(if_stat->pch);
1030 g_free(if_stat->name);
1033 g_list_free(stat_list);
1034 free_interface_list(if_list);
1042 capture_cleanup_handler(DWORD dwCtrlType)
1044 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1045 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1046 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1047 like SIGTERM at least when the machine's shutting down.
1049 For now, if we're running as a command rather than a capture child,
1050 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1051 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1052 in that way on UN*X.
1054 If we're not running as a capture child, we might be running as
1055 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1056 user logs out. (XXX - can we explicitly check whether we're
1057 running as a service?) */
1059 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1060 "Console: Control signal");
1061 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1062 "Console: Control signal, CtrlType: %lu", dwCtrlType);
1064 /* Keep capture running if we're a service and a user logs off */
1065 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1066 capture_loop_stop();
1074 capture_cleanup_handler(int signum _U_)
1076 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1077 SIGTERM. We assume that if the user wanted it to keep running
1078 after they logged out, they'd have nohupped it. */
1080 /* Note: don't call g_log() in the signal handler: if we happened to be in
1081 * g_log() in process context when the signal came in, g_log will detect
1082 * the "recursion" and abort.
1085 capture_loop_stop();
1091 report_capture_count(gboolean reportit)
1093 /* Don't print this if we're a capture child. */
1094 if (!capture_child && reportit) {
1095 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packet_count);
1096 /* stderr could be line buffered */
1104 report_counts_for_siginfo(void)
1106 report_capture_count(quiet);
1107 infoprint = FALSE; /* we just reported it */
1111 report_counts_siginfo(int signum _U_)
1113 int sav_errno = errno;
1115 /* If we've been told to delay printing, just set a flag asking
1116 that we print counts (if we're supposed to), otherwise print
1117 the count of packets captured (if we're supposed to). */
1121 report_counts_for_siginfo();
1124 #endif /* SIGINFO */
1127 exit_main(int status)
1130 /* Shutdown windows sockets */
1133 /* can be helpful for debugging */
1134 #ifdef DEBUG_DUMPCAP
1135 printf("Press any key\n");
1141 capture_opts_cleanup(&global_capture_opts);
1147 * If we were linked with libcap (not related to libpcap), make sure we have
1148 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1149 * (See comment in main() for details)
1152 relinquish_privs_except_capture(void)
1154 /* If 'started_with_special_privs' (ie: suid) then enable for
1155 * ourself the NET_ADMIN and NET_RAW capabilities and then
1156 * drop our suid privileges.
1158 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1159 * stuff we don't need (and shouldn't have).
1160 * CAP_NET_RAW: Packet capture (raw sockets).
1163 if (started_with_special_privs()) {
1164 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1165 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1167 cap_t caps = cap_init(); /* all capabilities initialized to off */
1169 print_caps("Pre drop, pre set");
1171 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1172 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1175 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1176 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1178 if (cap_set_proc(caps)) {
1179 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1181 print_caps("Pre drop, post set");
1183 relinquish_special_privs_perm();
1185 print_caps("Post drop, pre set");
1186 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1187 if (cap_set_proc(caps)) {
1188 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1190 print_caps("Post drop, post set");
1196 #endif /* HAVE_LIBCAP */
1198 /* Take care of byte order in the libpcap headers read from pipes.
1199 * (function taken from wiretap/libpcap.c) */
1201 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1204 /* Byte-swap the record header fields. */
1205 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1206 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1207 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1208 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1211 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1212 swapped, in order to match the BPF header layout.
1214 Unfortunately, some files were, according to a comment in the "libpcap"
1215 source, written with version 2.3 in their headers but without the
1216 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1217 would make no sense - we assume that we need to swap them. */
1218 if (hdr->version_major == 2 &&
1219 (hdr->version_minor < 3 ||
1220 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1223 temp = rechdr->orig_len;
1224 rechdr->orig_len = rechdr->incl_len;
1225 rechdr->incl_len = temp;
1229 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1233 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1237 return recv(pipe_fd, buf, (int)sz, 0);
1242 return ws_read(pipe_fd, buf, sz);
1248 * Thread function that reads from a pipe and pushes the data
1249 * to the main application thread.
1252 * XXX Right now we use async queues for basic signaling. The main thread
1253 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1254 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1255 * Iff the read is successful cap_pipe_read pushes an item onto
1256 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1257 * the queues themselves (yet).
1259 * We might want to move some of the cap_pipe_dispatch logic here so that
1260 * we can let cap_thread_read run independently, queuing up multiple reads
1261 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1263 static void *cap_thread_read(void *arg)
1265 capture_src *pcap_src;
1268 DWORD last_err, bytes_read;
1273 pcap_src = (capture_src *)arg;
1274 while (pcap_src->cap_pipe_err == PIPOK) {
1275 g_async_queue_pop(pcap_src->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1276 g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1278 while (bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1279 if ((pcap_src->from_cap_socket)
1286 b = cap_pipe_read(pcap_src->cap_pipe_fd, pcap_src->cap_pipe_buf+bytes_read,
1287 pcap_src->cap_pipe_bytes_to_read - bytes_read, pcap_src->from_cap_socket);
1290 pcap_src->cap_pipe_err = PIPEOF;
1294 pcap_src->cap_pipe_err = PIPERR;
1305 /* If we try to use read() on a named pipe on Windows with partial
1306 * data it appears to return EOF.
1309 res = ReadFile(pcap_src->cap_pipe_h, pcap_src->cap_pipe_buf+bytes_read,
1310 pcap_src->cap_pipe_bytes_to_read - bytes_read,
1315 last_err = GetLastError();
1316 if (last_err == ERROR_MORE_DATA) {
1318 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1319 pcap_src->cap_pipe_err = PIPEOF;
1323 pcap_src->cap_pipe_err = PIPERR;
1326 } else if (b == 0 && pcap_src->cap_pipe_bytes_to_read > 0) {
1327 pcap_src->cap_pipe_err = PIPEOF;
1334 pcap_src->cap_pipe_bytes_read = bytes_read;
1335 if (pcap_src->cap_pipe_bytes_read >= pcap_src->cap_pipe_bytes_to_read) {
1336 g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1338 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1344 /* Provide select() functionality for a single file descriptor
1345 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1347 * Returns the same values as select.
1350 cap_pipe_select(int pipe_fd)
1353 struct timeval timeout;
1356 FD_SET(pipe_fd, &rfds);
1358 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1359 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1361 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1364 #define DEF_TCP_PORT 19000
1367 cap_open_socket(char *pipename, capture_src *pcap_src, char *errmsg, int errmsgl)
1369 char *sockname = pipename + 4;
1370 struct sockaddr_in sa;
1377 memset(&sa, 0, sizeof(sa));
1379 p = strchr(sockname, ':');
1381 len = strlen(sockname);
1382 port = DEF_TCP_PORT;
1386 port = strtoul(p + 1, &p, 10);
1387 if (*p || port > 65535) {
1396 g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
1398 if (!ws_inet_pton4(buf, (guint32 *)&sa.sin_addr)) {
1402 sa.sin_family = AF_INET;
1403 sa.sin_port = g_htons((u_short)port);
1405 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1406 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1408 LPTSTR errorText = NULL;
1411 lastError = WSAGetLastError();
1412 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1413 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1414 FORMAT_MESSAGE_IGNORE_INSERTS,
1415 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1416 (LPTSTR)&errorText, 0, NULL);
1418 g_snprintf(errmsg, errmsgl,
1419 "The capture session could not be initiated due to the socket error: \n"
1421 " %d: %s", lastError, errorText ? (char *)errorText : "Unknown");
1423 LocalFree(errorText);
1425 " %d: %s", errno, g_strerror(errno));
1427 pcap_src->cap_pipe_err = PIPERR;
1430 cap_pipe_close(fd, TRUE);
1434 pcap_src->from_cap_socket = TRUE;
1438 g_snprintf(errmsg, errmsgl,
1439 "The capture session could not be initiated because\n"
1440 "\"%s\" is not a valid socket specification", pipename);
1441 pcap_src->cap_pipe_err = PIPERR;
1445 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1449 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1453 closesocket(pipe_fd);
1461 cap_pipe_read_data_bytes(capture_src *pcap_src, char *errmsg, int errmsgl)
1464 int fd = pcap_src->cap_pipe_fd;
1466 DWORD sz, bytes_read = 0;
1468 size_t sz, bytes_read = 0;
1472 #ifdef LOG_CAPTURE_VERBOSE
1473 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_read_data_bytes read %lu of %lu",
1474 pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1476 sz = pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read;
1477 while (bytes_read < sz) {
1479 g_snprintf(errmsg, errmsgl, "Invalid file descriptor.");
1483 sel_ret = cap_pipe_select(fd);
1485 g_snprintf(errmsg, errmsgl,
1486 "Unexpected error from select: %s.", g_strerror(errno));
1488 } else if (sel_ret > 0) {
1489 b = cap_pipe_read(fd, pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read+bytes_read,
1490 sz-bytes_read, pcap_src->from_cap_socket);
1493 g_snprintf(errmsg, errmsgl, "End of file on pipe during cap_pipe_read.");
1496 LPTSTR errorText = NULL;
1497 int lastError = WSAGetLastError();
1499 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1500 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1501 FORMAT_MESSAGE_IGNORE_INSERTS,
1502 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1503 (LPTSTR)&errorText, 0, NULL);
1504 g_snprintf(errmsg, errmsgl, "Error on pipe data during cap_pipe_read: "
1505 " %d: %s", lastError, errorText ? (char *)errorText : "Unknown");
1507 LocalFree(errorText);
1509 g_snprintf(errmsg, errmsgl, "Error on pipe data during cap_pipe_read: %s.",
1518 pcap_src->cap_pipe_bytes_read += bytes_read;
1519 #ifdef LOG_CAPTURE_VERBOSE
1520 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_read_data_bytes read %lu of %lu",
1521 pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1526 /* Some forward declarations for breaking up cap_pipe_open_live for pcap and pcapng formats */
1527 static void pcap_pipe_open_live(int fd, capture_src *pcap_src, struct pcap_hdr *hdr, char *errmsg, int errmsgl);
1528 static void pcapng_pipe_open_live(int fd, capture_src *pcap_src, char *errmsg, int errmsgl);
1529 static int pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, int errmsgl);
1531 /* Mimic pcap_open_live() for pipe captures
1533 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1534 * open it, and read the header.
1536 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1537 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1539 cap_pipe_open_live(char *pipename,
1540 capture_src *pcap_src,
1542 char *errmsg, int errmsgl)
1545 ws_statb64 pipe_stat;
1546 struct sockaddr_un sa;
1550 char* extcap_pipe_name;
1552 gboolean extcap_pipe = FALSE;
1554 int fd = -1, sel_ret;
1557 pcap_src->cap_pipe_fd = -1;
1559 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1562 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1565 * XXX - this blocks until a pcap per-file header has been written to
1566 * the pipe, so it could block indefinitely.
1568 if (strcmp(pipename, "-") == 0) {
1570 fd = 0; /* read from stdin */
1572 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1574 } else if (!strncmp(pipename, "TCP@", 4)) {
1575 if ((fd = cap_open_socket(pipename, pcap_src, errmsg, errmsgl)) < 0) {
1580 if ( g_strrstr(pipename, EXTCAP_PIPE_PREFIX) != NULL )
1583 if (ws_stat64(pipename, &pipe_stat) < 0) {
1584 if (errno == ENOENT || errno == ENOTDIR)
1585 pcap_src->cap_pipe_err = PIPNEXIST;
1587 g_snprintf(errmsg, errmsgl,
1588 "The capture session could not be initiated "
1589 "due to error getting information on pipe/socket: %s.", g_strerror(errno));
1590 pcap_src->cap_pipe_err = PIPERR;
1594 if (S_ISFIFO(pipe_stat.st_mode)) {
1595 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1597 g_snprintf(errmsg, errmsgl,
1598 "The capture session could not be initiated "
1599 "due to error on pipe open: %s.", g_strerror(errno));
1600 pcap_src->cap_pipe_err = PIPERR;
1603 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1604 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1606 g_snprintf(errmsg, errmsgl,
1607 "The capture session could not be initiated "
1608 "due to error on socket create: %s.", g_strerror(errno));
1609 pcap_src->cap_pipe_err = PIPERR;
1612 sa.sun_family = AF_UNIX;
1614 * The Single UNIX Specification says:
1616 * The size of sun_path has intentionally been left undefined.
1617 * This is because different implementations use different sizes.
1618 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1619 * of 104. Since most implementations originate from BSD versions,
1620 * the size is typically in the range 92 to 108.
1622 * Applications should not assume a particular length for sun_path
1623 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1627 * The <sys/un.h> header shall define the sockaddr_un structure,
1628 * which shall include at least the following members:
1630 * sa_family_t sun_family Address family.
1631 * char sun_path[] Socket pathname.
1633 * so we assume that it's an array, with a specified size,
1634 * and that the size reflects the maximum path length.
1636 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1637 /* Path name too long */
1638 g_snprintf(errmsg, errmsgl,
1639 "The capture session coud not be initiated "
1640 "due to error on socket connect: Path name too long.");
1641 pcap_src->cap_pipe_err = PIPERR;
1645 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1647 g_snprintf(errmsg, errmsgl,
1648 "The capture session coud not be initiated "
1649 "due to error on socket connect: %s.", g_strerror(errno));
1650 pcap_src->cap_pipe_err = PIPERR;
1655 if (S_ISCHR(pipe_stat.st_mode)) {
1657 * Assume the user specified an interface on a system where
1658 * interfaces are in /dev. Pretend we haven't seen it.
1660 pcap_src->cap_pipe_err = PIPNEXIST;
1662 g_snprintf(errmsg, errmsgl,
1663 "The capture session could not be initiated because\n"
1664 "\"%s\" is neither an interface nor a socket nor a pipe.", pipename);
1665 pcap_src->cap_pipe_err = PIPERR;
1671 #define PIPE_STR "\\pipe\\"
1672 /* Under Windows, named pipes _must_ have the form
1673 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1675 pncopy = g_strdup(pipename);
1676 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1677 pos = strchr(pncopy + 3, '\\');
1678 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1685 g_snprintf(errmsg, errmsgl,
1686 "The capture session could not be initiated because\n"
1687 "\"%s\" is neither an interface nor a pipe.", pipename);
1688 pcap_src->cap_pipe_err = PIPNEXIST;
1691 extcap_pipe_name = g_strconcat("\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, NULL);
1692 extcap_pipe = strstr(pipename, extcap_pipe_name) ? TRUE : FALSE;
1693 g_free(extcap_pipe_name);
1695 /* Wait for the pipe to appear */
1698 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1700 pcap_src->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1701 OPEN_EXISTING, 0, NULL);
1703 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE)
1706 if (GetLastError() != ERROR_PIPE_BUSY) {
1707 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1708 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1709 g_snprintf(errmsg, errmsgl,
1710 "The capture session on \"%s\" could not be started "
1711 "due to error on pipe open: %s (error %lu).",
1712 pipename, utf_16to8(err_str), GetLastError());
1714 pcap_src->cap_pipe_err = PIPERR;
1718 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1719 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1720 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1721 g_snprintf(errmsg, errmsgl,
1722 "The capture session on \"%s\" timed out during "
1723 "pipe open: %s (error %lu).",
1724 pipename, utf_16to8(err_str), GetLastError());
1726 pcap_src->cap_pipe_err = PIPERR;
1733 pcap_src->from_cap_pipe = TRUE;
1736 * We start with a 2KB buffer for packet data, which should be
1737 * large enough for most regular network packets. We increase it,
1738 * up to the maximum size we allow, as necessary.
1740 pcap_src->cap_pipe_databuf = (char*)g_malloc(2048);
1741 pcap_src->cap_pipe_databuf_size = 2048;
1744 if (pcap_src->from_cap_socket)
1747 /* read the pcap header */
1749 while (bytes_read < sizeof magic) {
1750 sel_ret = cap_pipe_select(fd);
1752 g_snprintf(errmsg, errmsgl,
1753 "Unexpected error from select: %s.", g_strerror(errno));
1755 } else if (sel_ret > 0) {
1756 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
1757 sizeof magic-bytes_read,
1758 pcap_src->from_cap_socket);
1759 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1760 if (extcap_pipe && b <= 0)
1765 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1767 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1777 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
1779 pcap_src->cap_pipe_buf = (char *) &magic;
1780 pcap_src->cap_pipe_bytes_read = 0;
1781 pcap_src->cap_pipe_bytes_to_read = sizeof(magic);
1782 /* We don't have to worry about cap_pipe_read_mtx here */
1783 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1784 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1785 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1786 if (pcap_src->cap_pipe_bytes_read <= 0 && extcap_pipe)
1789 if (pcap_src->cap_pipe_bytes_read <= 0) {
1790 if (pcap_src->cap_pipe_bytes_read == 0)
1791 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1793 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1802 case PCAP_NSEC_MAGIC:
1803 /* Host that wrote it has our byte order, and was running
1804 a program using either standard or ss990417 libpcap. */
1805 pcap_src->cap_pipe_byte_swapped = FALSE;
1806 pcap_src->cap_pipe_modified = FALSE;
1807 pcap_src->ts_nsec = magic == PCAP_NSEC_MAGIC;
1809 case PCAP_MODIFIED_MAGIC:
1810 /* Host that wrote it has our byte order, but was running
1811 a program using either ss990915 or ss991029 libpcap. */
1812 pcap_src->cap_pipe_byte_swapped = FALSE;
1813 pcap_src->cap_pipe_modified = TRUE;
1815 case PCAP_SWAPPED_MAGIC:
1816 case PCAP_SWAPPED_NSEC_MAGIC:
1817 /* Host that wrote it has a byte order opposite to ours,
1818 and was running a program using either standard or
1819 ss990417 libpcap. */
1820 pcap_src->cap_pipe_byte_swapped = TRUE;
1821 pcap_src->cap_pipe_modified = FALSE;
1822 pcap_src->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
1824 case PCAP_SWAPPED_MODIFIED_MAGIC:
1825 /* Host that wrote it out has a byte order opposite to
1826 ours, and was running a program using either ss990915
1827 or ss991029 libpcap. */
1828 pcap_src->cap_pipe_byte_swapped = TRUE;
1829 pcap_src->cap_pipe_modified = TRUE;
1831 case BLOCK_TYPE_SHB:
1832 /* This isn't pcap, it's pcapng. */
1833 pcap_src->from_pcapng = TRUE;
1834 pcap_src->cap_pipe_dispatch = pcapng_pipe_dispatch;
1835 global_capture_opts.use_pcapng = TRUE; /* we can only output in pcapng format */
1836 pcapng_pipe_open_live(fd, pcap_src, errmsg, errmsgl);
1839 /* Not a pcap type we know about, or not pcap at all. */
1840 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format or not libpcap data.");
1844 pcap_pipe_open_live(fd, pcap_src, (struct pcap_hdr *) hdr, errmsg, errmsgl);
1848 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1849 pcap_src->cap_pipe_err = PIPERR;
1850 cap_pipe_close(fd, pcap_src->from_cap_socket);
1851 pcap_src->cap_pipe_fd = -1;
1853 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1858 pcap_pipe_open_live(int fd,
1859 capture_src *pcap_src,
1860 struct pcap_hdr *hdr,
1861 char *errmsg, int errmsgl)
1867 if (pcap_src->from_cap_socket)
1870 /* Read the rest of the header */
1872 while (bytes_read < sizeof(struct pcap_hdr)) {
1873 sel_ret = cap_pipe_select(fd);
1875 g_snprintf(errmsg, errmsgl,
1876 "Unexpected error from select: %s.", g_strerror(errno));
1878 } else if (sel_ret > 0) {
1879 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
1880 sizeof(struct pcap_hdr) - bytes_read,
1881 pcap_src->from_cap_socket);
1884 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open.");
1886 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s.",
1896 pcap_src->cap_pipe_buf = (char *) hdr;
1897 pcap_src->cap_pipe_bytes_read = 0;
1898 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1899 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1900 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1901 if (pcap_src->cap_pipe_bytes_read <= 0) {
1902 if (pcap_src->cap_pipe_bytes_read == 0)
1903 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open.");
1905 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s.",
1912 if (pcap_src->cap_pipe_byte_swapped) {
1913 /* Byte-swap the header fields about which we care. */
1914 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
1915 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
1916 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
1917 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
1919 pcap_src->linktype = hdr->network;
1921 if (pcap_src->linktype == DLT_DBUS) {
1923 * The maximum D-Bus message size is 128MB, so allow packets up
1926 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_DBUS;
1929 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
1931 if (hdr->version_major < 2) {
1932 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format version %d.%d",
1933 hdr->version_major, hdr->version_minor);
1937 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
1938 pcap_src->cap_pipe_err = PIPOK;
1939 pcap_src->cap_pipe_fd = fd;
1943 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcap_pipe_open_live: error %s", errmsg);
1944 pcap_src->cap_pipe_err = PIPERR;
1945 cap_pipe_close(fd, pcap_src->from_cap_socket);
1946 pcap_src->cap_pipe_fd = -1;
1948 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1952 /* Read the pcapng section header block */
1954 pcapng_read_shb(capture_src *pcap_src,
1958 struct pcapng_block_header_s *bh = &pcap_src->cap_pipe_info.pcapng.bh;
1959 struct pcapng_section_header_block_s *shb = &pcap_src->cap_pipe_info.pcapng.shb;
1962 if (pcap_src->from_cap_socket)
1965 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_block_header_s) + sizeof(struct pcapng_section_header_block_s);
1966 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl)) {
1972 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf + sizeof(struct pcapng_block_header_s);
1973 pcap_src->cap_pipe_bytes_read = 0;
1974 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_section_header_block_s);
1975 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1976 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1977 if (pcap_src->cap_pipe_bytes_read <= 0) {
1978 if (pcap_src->cap_pipe_bytes_read == 0)
1979 g_snprintf(errmsg, errmsgl, "End of file on pipe section header during open.");
1981 g_snprintf(errmsg, errmsgl, "Error on pipe section header during open: %s.",
1985 pcap_src->cap_pipe_bytes_read = sizeof(struct pcapng_block_header_s) + sizeof(struct pcapng_section_header_block_s);
1988 memcpy(shb, pcap_src->cap_pipe_databuf + sizeof(struct pcapng_block_header_s), sizeof(struct pcapng_section_header_block_s));
1992 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng SHB MAGIC");
1993 pcap_src->cap_pipe_byte_swapped = FALSE;
1995 case PCAPNG_SWAPPED_MAGIC:
1996 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng SHB SWAPPED MAGIC");
1997 pcap_src->cap_pipe_byte_swapped = TRUE;
2000 /* Not a pcapng type we know about, or not pcapng at all. */
2001 g_snprintf(errmsg, errmsgl, "Unrecognized pcapng format or not pcapng data.");
2005 if (pcap_src->cap_pipe_byte_swapped) {
2006 /* Byte-swap the header fields about which we care. */
2007 shb->version_major = GUINT16_SWAP_LE_BE(shb->version_major);
2008 shb->version_minor = GUINT16_SWAP_LE_BE(shb->version_minor);
2009 shb->section_length = GUINT64_SWAP_LE_BE(shb->section_length);
2010 bh->block_total_length = GUINT32_SWAP_LE_BE(bh->block_total_length);
2013 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
2015 /* Setup state to capture the rest of the section header block */
2016 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2022 pcapng_write_saved_block(capture_src *pcap_src, struct pcapng_block_header_s *bh)
2024 guint32 length = bh->block_total_length;
2026 if (pcap_src->cap_pipe_byte_swapped) {
2027 length = GUINT32_SWAP_LE_BE(length);
2030 return pcapng_write_block(global_ld.pdh,
2031 (const guint8 *) bh,
2033 &global_ld.bytes_written, &global_ld.err);
2036 /* Save SHB and IDB blocks to playback whenever we change output files. */
2037 /* The list is saved in reverse order of blocks added */
2039 pcapng_block_save(capture_src *pcap_src)
2041 pcapng_pipe_info_t *pcapng = &pcap_src->cap_pipe_info.pcapng;
2042 struct pcapng_block_header_s *bh = &pcapng->bh;
2044 /* Delete all the old blocks first whenever we get a SHB */
2045 if (bh->block_type == BLOCK_TYPE_SHB) {
2046 g_list_free_full(pcapng->saved_blocks, g_free);
2047 pcapng->saved_blocks = NULL;
2048 } else if (bh->block_type != BLOCK_TYPE_IDB) {
2052 gpointer data = g_malloc(bh->block_total_length);
2056 memcpy(data, pcap_src->cap_pipe_databuf, bh->block_total_length);
2058 pcapng->saved_blocks = g_list_prepend(pcapng->saved_blocks, data);
2064 pcapng_pipe_open_live(int fd,
2065 capture_src *pcap_src,
2069 guint32 type = BLOCK_TYPE_SHB;
2070 struct pcapng_block_header_s *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2072 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_open_live: fd %d", fd);
2074 if (pcap_src->from_cap_socket)
2077 memcpy(pcap_src->cap_pipe_databuf, &type, sizeof(guint32));
2078 /* read the rest of the pcapng general block header */
2079 pcap_src->cap_pipe_bytes_read = sizeof(guint32);
2080 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_block_header_s);
2081 pcap_src->cap_pipe_err = PIPOK;
2082 pcap_src->cap_pipe_fd = fd;
2083 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl)) {
2086 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(struct pcapng_block_header_s));
2090 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
2092 bh->block_type = type;
2093 pcap_src->cap_pipe_buf = (char *) &bh->block_total_length;
2094 pcap_src->cap_pipe_bytes_read = 0;
2095 pcap_src->cap_pipe_bytes_to_read = sizeof(bh->block_total_length);
2096 /* We don't have to worry about cap_pipe_read_mtx here */
2097 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2098 g_async_queue_pop(pcap_src->cap_pipe_done_q);
2099 if (pcap_src->cap_pipe_bytes_read <= 0) {
2100 if (pcap_src->cap_pipe_bytes_read == 0)
2101 g_snprintf(errmsg, errmsgl, "End of file on pipe block_total_length during open.");
2103 g_snprintf(errmsg, errmsgl, "Error on pipe block_total_length during open: %s.",
2107 pcap_src->cap_pipe_bytes_read = sizeof(struct pcapng_block_header_s);
2108 memcpy(pcap_src->cap_pipe_databuf, bh, sizeof(struct pcapng_block_header_s));
2109 pcap_src->cap_pipe_err = PIPOK;
2110 pcap_src->cap_pipe_fd = fd;
2113 if (pcapng_read_shb(pcap_src, errmsg, errmsgl)) {
2120 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_open_live: error %s", errmsg);
2121 pcap_src->cap_pipe_err = PIPERR;
2122 cap_pipe_close(fd, pcap_src->from_cap_socket);
2123 pcap_src->cap_pipe_fd = -1;
2125 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2129 /* We read one record from the pipe, take care of byte order in the record
2130 * header, write the record to the capture file, and update capture statistics. */
2132 pcap_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, int errmsgl)
2134 struct pcap_pkthdr phdr;
2135 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2143 pcap_pipe_info_t *pcap_info = &pcap_src->cap_pipe_info.pcap;
2145 #ifdef LOG_CAPTURE_VERBOSE
2146 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcap_pipe_dispatch");
2149 switch (pcap_src->cap_pipe_state) {
2151 case STATE_EXPECT_REC_HDR:
2153 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2156 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2157 pcap_src->cap_pipe_bytes_to_read = pcap_src->cap_pipe_modified ?
2158 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2159 pcap_src->cap_pipe_bytes_read = 0;
2162 pcap_src->cap_pipe_buf = (char *) &pcap_info->rechdr;
2163 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2164 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2169 case STATE_READ_REC_HDR:
2171 if (pcap_src->from_cap_socket)
2174 b = cap_pipe_read(pcap_src->cap_pipe_fd, ((char *)&pcap_info->rechdr)+pcap_src->cap_pipe_bytes_read,
2175 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read, pcap_src->from_cap_socket);
2178 result = PD_PIPE_EOF;
2180 result = PD_PIPE_ERR;
2183 pcap_src->cap_pipe_bytes_read += b;
2187 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2188 if (pcap_src->cap_pipe_err == PIPEOF) {
2189 result = PD_PIPE_EOF;
2191 } else if (pcap_src->cap_pipe_err == PIPERR) {
2192 result = PD_PIPE_ERR;
2200 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2202 result = PD_REC_HDR_READ;
2205 case STATE_EXPECT_DATA:
2207 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2210 pcap_src->cap_pipe_state = STATE_READ_DATA;
2211 pcap_src->cap_pipe_bytes_to_read = pcap_info->rechdr.hdr.incl_len;
2212 pcap_src->cap_pipe_bytes_read = 0;
2215 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2216 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2217 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2222 case STATE_READ_DATA:
2224 if (pcap_src->from_cap_socket)
2227 b = cap_pipe_read(pcap_src->cap_pipe_fd,
2228 pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read,
2229 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read,
2230 pcap_src->from_cap_socket);
2233 result = PD_PIPE_EOF;
2235 result = PD_PIPE_ERR;
2238 pcap_src->cap_pipe_bytes_read += b;
2243 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2244 if (pcap_src->cap_pipe_err == PIPEOF) {
2245 result = PD_PIPE_EOF;
2247 } else if (pcap_src->cap_pipe_err == PIPERR) {
2248 result = PD_PIPE_ERR;
2256 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2258 result = PD_DATA_READ;
2262 g_snprintf(errmsg, errmsgl, "pcap_pipe_dispatch: invalid state");
2265 } /* switch (pcap_src->cap_pipe_state) */
2268 * We've now read as much data as we were expecting, so process it.
2272 case PD_REC_HDR_READ:
2273 /* We've read the header. Take care of byte order. */
2274 cap_pipe_adjust_header(pcap_src->cap_pipe_byte_swapped, &pcap_info->hdr,
2275 &pcap_info->rechdr.hdr);
2276 if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_max_pkt_size) {
2278 * The record contains more data than the advertised/allowed in the
2279 * pcap header, do not try to read more data (do not change to
2280 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2281 * instead stop with an error.
2283 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2284 ld->packet_count+1, pcap_info->rechdr.hdr.incl_len);
2288 if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_databuf_size) {
2290 * Grow the buffer to the packet size, rounded up to a power of
2293 new_bufsize = pcap_info->rechdr.hdr.incl_len;
2295 * http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2298 new_bufsize |= new_bufsize >> 1;
2299 new_bufsize |= new_bufsize >> 2;
2300 new_bufsize |= new_bufsize >> 4;
2301 new_bufsize |= new_bufsize >> 8;
2302 new_bufsize |= new_bufsize >> 16;
2304 pcap_src->cap_pipe_databuf = (char*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2305 pcap_src->cap_pipe_databuf_size = new_bufsize;
2309 * The record has some data following the header, try to read it next
2312 if (pcap_info->rechdr.hdr.incl_len) {
2313 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2318 * No data following the record header? Then no more data needs to be
2319 * read and we will fallthrough and emit an empty packet.
2323 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2324 phdr.ts.tv_sec = pcap_info->rechdr.hdr.ts_sec;
2325 phdr.ts.tv_usec = pcap_info->rechdr.hdr.ts_usec;
2326 phdr.caplen = pcap_info->rechdr.hdr.incl_len;
2327 phdr.len = pcap_info->rechdr.hdr.orig_len;
2330 capture_loop_queue_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2332 capture_loop_write_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2334 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2338 pcap_src->cap_pipe_err = PIPEOF;
2343 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2344 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2345 g_snprintf(errmsg, errmsgl,
2346 "Error reading from pipe: %s (error %lu)",
2347 utf_16to8(err_str), GetLastError());
2350 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2358 pcap_src->cap_pipe_err = PIPERR;
2359 /* Return here rather than inside the switch to prevent GCC warning */
2364 pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, int errmsgl)
2366 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2373 struct pcapng_block_header_s *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2375 #ifdef LOG_CAPTURE_VERBOSE
2376 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch");
2379 switch (pcap_src->cap_pipe_state) {
2381 case STATE_EXPECT_REC_HDR:
2382 #ifdef LOG_CAPTURE_VERBOSE
2383 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_EXPECT_REC_HDR");
2386 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2389 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2390 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_block_header_s);
2391 pcap_src->cap_pipe_bytes_read = 0;
2394 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2395 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2396 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2401 case STATE_READ_REC_HDR:
2402 #ifdef LOG_CAPTURE_VERBOSE
2403 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_READ_REC_HDR");
2406 if (pcap_src->from_cap_socket) {
2408 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl)) {
2413 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2414 if (pcap_src->cap_pipe_err == PIPEOF) {
2415 result = PD_PIPE_EOF;
2417 } else if (pcap_src->cap_pipe_err == PIPERR) {
2418 result = PD_PIPE_ERR;
2426 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2428 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(struct pcapng_block_header_s));
2429 result = PD_REC_HDR_READ;
2432 case STATE_EXPECT_DATA:
2433 #ifdef LOG_CAPTURE_VERBOSE
2434 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_EXPECT_DATA");
2437 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2439 pcap_src->cap_pipe_state = STATE_READ_DATA;
2440 pcap_src->cap_pipe_bytes_to_read = bh->block_total_length;
2443 pcap_src->cap_pipe_bytes_to_read -= pcap_src->cap_pipe_bytes_read;
2444 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf + pcap_src->cap_pipe_bytes_read;
2445 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2446 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2451 case STATE_READ_DATA:
2452 #ifdef LOG_CAPTURE_VERBOSE
2453 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_READ_DATA");
2456 if (pcap_src->from_cap_socket) {
2458 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl)) {
2461 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2466 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2467 if (pcap_src->cap_pipe_err == PIPEOF) {
2468 result = PD_PIPE_EOF;
2470 } else if (pcap_src->cap_pipe_err == PIPERR) {
2471 result = PD_PIPE_ERR;
2477 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2480 pcap_src->cap_pipe_bytes_read = bh->block_total_length;
2483 result = PD_DATA_READ;
2487 g_snprintf(errmsg, errmsgl, "pcapng_pipe_dispatch: invalid state");
2490 } /* switch (pcap_src->cap_pipe_state) */
2493 * We've now read as much data as we were expecting, so process it.
2497 case PD_REC_HDR_READ:
2498 if (bh->block_type == BLOCK_TYPE_SHB) {
2499 /* we need to read ahead to get the endianess before getting the block type and length */
2500 pcapng_read_shb(pcap_src, errmsg, errmsgl);
2504 /* We've read the header. Take care of byte order. */
2505 if (pcap_src->cap_pipe_byte_swapped) {
2506 /* Byte-swap the record header fields. */
2507 bh->block_type = GUINT32_SWAP_LE_BE(bh->block_type);
2508 bh->block_total_length = GUINT32_SWAP_LE_BE(bh->block_total_length);
2510 if (bh->block_total_length > pcap_src->cap_pipe_max_pkt_size) {
2512 * The record contains more data than the advertised/allowed in the
2513 * pcapng header, do not try to read more data (do not change to
2514 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2515 * instead stop with an error.
2517 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2518 ld->packet_count+1, bh->block_total_length);
2522 if (bh->block_total_length > pcap_src->cap_pipe_databuf_size) {
2524 * Grow the buffer to the packet size, rounded up to a power of
2527 new_bufsize = bh->block_total_length;
2529 * http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2532 new_bufsize |= new_bufsize >> 1;
2533 new_bufsize |= new_bufsize >> 2;
2534 new_bufsize |= new_bufsize >> 4;
2535 new_bufsize |= new_bufsize >> 8;
2536 new_bufsize |= new_bufsize >> 16;
2538 pcap_src->cap_pipe_databuf = (guchar*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2539 pcap_src->cap_pipe_databuf_size = new_bufsize;
2542 /* The record always has at least the block total length following the header */
2543 if (bh->block_total_length < sizeof(struct pcapng_block_header_s)+sizeof(guint32)) {
2544 g_snprintf(errmsg, errmsgl, "malformed pcapng block_total_length < minimum");
2545 pcap_src->cap_pipe_err = PIPEOF;
2548 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2552 if (!pcapng_block_save(pcap_src)) {
2553 g_snprintf(errmsg, errmsgl, "pcapng_pipe_dispatch block save failed");
2557 capture_loop_queue_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
2559 capture_loop_write_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
2561 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2565 pcap_src->cap_pipe_err = PIPEOF;
2570 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2571 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2572 g_snprintf(errmsg, errmsgl,
2573 "Error reading from pipe: %s (error %lu)",
2574 utf_16to8(err_str), GetLastError());
2577 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2585 pcap_src->cap_pipe_err = PIPERR;
2586 /* Return here rather than inside the switch to prevent GCC warning */
2590 /** Open the capture input file (pcap or capture pipe).
2591 * Returns TRUE if it succeeds, FALSE otherwise. */
2593 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2594 char *errmsg, size_t errmsg_len,
2595 char *secondary_errmsg, size_t secondary_errmsg_len)
2597 cap_device_open_err open_err;
2598 gchar open_err_str[PCAP_ERRBUF_SIZE];
2599 gchar *sync_msg_str;
2600 interface_options *interface_opts;
2601 capture_src *pcap_src;
2605 WORD wVersionRequested;
2609 /* XXX - opening Winsock on tshark? */
2611 /* Initialize Windows Socket if we are in a Win32 OS
2612 This needs to be done before querying the interface for network/netmask */
2614 /* XXX - do we really require 1.1 or earlier?
2615 Are there any versions that support only 2.0 or higher? */
2616 wVersionRequested = MAKEWORD(1, 1);
2617 err = WSAStartup(wVersionRequested, &wsaData);
2621 case WSASYSNOTREADY:
2622 g_snprintf(errmsg, (gulong) errmsg_len,
2623 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2626 case WSAVERNOTSUPPORTED:
2627 g_snprintf(errmsg, (gulong) errmsg_len,
2628 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2629 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2632 case WSAEINPROGRESS:
2633 g_snprintf(errmsg, (gulong) errmsg_len,
2634 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2638 g_snprintf(errmsg, (gulong) errmsg_len,
2639 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2643 g_snprintf(errmsg, (gulong) errmsg_len,
2644 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2648 g_snprintf(errmsg, (gulong) errmsg_len,
2649 "Couldn't initialize Windows Sockets: error %d", err);
2652 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2656 if ((use_threads == FALSE) &&
2657 (capture_opts->ifaces->len > 1)) {
2658 g_snprintf(errmsg, (gulong) errmsg_len,
2659 "Using threads is required for capturing on multiple interfaces.");
2663 for (i = 0; i < capture_opts->ifaces->len; i++) {
2664 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
2665 pcap_src = (capture_src *)g_malloc(sizeof (capture_src));
2666 if (pcap_src == NULL) {
2667 g_snprintf(errmsg, (gulong) errmsg_len,
2668 "Could not allocate memory.");
2671 memset(pcap_src, 0, sizeof(capture_src));
2672 #ifdef MUST_DO_SELECT
2673 pcap_src->pcap_fd = -1;
2675 pcap_src->interface_id = i;
2676 pcap_src->linktype = -1;
2678 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2680 pcap_src->cap_pipe_fd = -1;
2681 pcap_src->cap_pipe_dispatch = pcap_pipe_dispatch;
2682 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2683 pcap_src->cap_pipe_err = PIPOK;
2685 pcap_src->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2686 g_mutex_init(pcap_src->cap_pipe_read_mtx);
2687 pcap_src->cap_pipe_pending_q = g_async_queue_new();
2688 pcap_src->cap_pipe_done_q = g_async_queue_new();
2690 g_array_append_val(ld->pcaps, pcap_src);
2692 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts->name);
2693 pcap_src->pcap_h = open_capture_device(capture_opts, interface_opts,
2694 CAP_READ_TIMEOUT, &open_err, &open_err_str);
2696 if (pcap_src->pcap_h != NULL) {
2697 /* we've opened "iface" as a network device */
2699 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2700 /* Find out if we're getting nanosecond-precision time stamps */
2701 pcap_src->ts_nsec = have_high_resolution_timestamp(pcap_src->pcap_h);
2704 #if defined(HAVE_PCAP_SETSAMPLING)
2705 if (interface_opts->sampling_method != CAPTURE_SAMP_NONE) {
2706 struct pcap_samp *samp;
2708 if ((samp = pcap_setsampling(pcap_src->pcap_h)) != NULL) {
2709 switch (interface_opts->sampling_method) {
2710 case CAPTURE_SAMP_BY_COUNT:
2711 samp->method = PCAP_SAMP_1_EVERY_N;
2714 case CAPTURE_SAMP_BY_TIMER:
2715 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2719 sync_msg_str = g_strdup_printf(
2720 "Unknown sampling method %d specified,\n"
2721 "continue without packet sampling",
2722 interface_opts->sampling_method);
2723 report_capture_error("Couldn't set the capture "
2724 "sampling", sync_msg_str);
2725 g_free(sync_msg_str);
2727 samp->value = interface_opts->sampling_param;
2729 report_capture_error("Couldn't set the capture sampling",
2730 "Cannot get packet sampling data structure");
2735 /* setting the data link type only works on real interfaces */
2736 if (!set_pcap_datalink(pcap_src->pcap_h, interface_opts->linktype,
2737 interface_opts->name,
2739 secondary_errmsg, secondary_errmsg_len)) {
2742 pcap_src->linktype = get_pcap_datalink(pcap_src->pcap_h, interface_opts->name);
2744 /* We couldn't open "iface" as a network device. */
2745 /* Try to open it as a pipe */
2746 cap_pipe_open_live(interface_opts->name, pcap_src, &pcap_src->cap_pipe_info.pcap.hdr, errmsg, (int) errmsg_len);
2749 if (pcap_src->cap_pipe_fd == -1) {
2751 if (pcap_src->cap_pipe_h == INVALID_HANDLE_VALUE) {
2753 if (pcap_src->cap_pipe_err == PIPNEXIST) {
2755 * We tried opening as an interface, and that failed,
2756 * so we tried to open it as a pipe, but the pipe
2757 * doesn't exist. Report the error message for
2760 get_capture_device_open_failure_messages(open_err,
2762 interface_opts->name,
2766 secondary_errmsg_len);
2769 * Else pipe (or file) does exist and cap_pipe_open_live() has
2774 /* cap_pipe_open_live() succeeded; don't want
2775 error message from pcap_open_live() */
2776 open_err_str[0] = '\0';
2780 /* XXX - will this work for tshark? */
2781 #ifdef MUST_DO_SELECT
2782 if (!pcap_src->from_cap_pipe) {
2783 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2784 pcap_src->pcap_fd = pcap_get_selectable_fd(pcap_src->pcap_h);
2786 pcap_src->pcap_fd = pcap_fileno(pcap_src->pcap_h);
2791 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2792 returned a warning; print it, but keep capturing. */
2793 if (open_err_str[0] != '\0') {
2794 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2795 report_capture_error(sync_msg_str, "");
2796 g_free(sync_msg_str);
2800 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2801 /* to remove any suid privileges. */
2802 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2803 /* (euid/egid have already previously been set to ruid/rgid. */
2804 /* (See comment in main() for details) */
2806 relinquish_special_privs_perm();
2808 relinquish_all_capabilities();
2813 /* close the capture input file (pcap or capture pipe) */
2814 static void capture_loop_close_input(loop_data *ld)
2817 capture_src *pcap_src;
2819 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2821 for (i = 0; i < ld->pcaps->len; i++) {
2822 pcap_src = g_array_index(ld->pcaps, capture_src *, i);
2823 /* Pipe, or capture device? */
2824 if (pcap_src->from_cap_pipe) {
2825 /* Pipe. If open, close the capture pipe "input file". */
2826 if (pcap_src->cap_pipe_fd >= 0) {
2827 cap_pipe_close(pcap_src->cap_pipe_fd, pcap_src->from_cap_socket);
2828 pcap_src->cap_pipe_fd = -1;
2831 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE) {
2832 CloseHandle(pcap_src->cap_pipe_h);
2833 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2836 if (pcap_src->cap_pipe_databuf != NULL) {
2837 /* Free the buffer. */
2838 g_free(pcap_src->cap_pipe_databuf);
2839 pcap_src->cap_pipe_databuf = NULL;
2841 if (pcap_src->from_pcapng) {
2842 g_list_free_full(pcap_src->cap_pipe_info.pcapng.saved_blocks, g_free);
2843 pcap_src->cap_pipe_info.pcapng.saved_blocks = NULL;
2846 /* Capture device. If open, close the pcap_t. */
2847 if (pcap_src->pcap_h != NULL) {
2848 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_src->pcap_h);
2849 pcap_close(pcap_src->pcap_h);
2850 pcap_src->pcap_h = NULL;
2858 /* Shut down windows sockets */
2864 /* init the capture filter */
2865 static initfilter_status_t
2866 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2867 const gchar * name, const gchar * cfilter)
2869 struct bpf_program fcode;
2871 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2873 /* capture filters only work on real interfaces */
2874 if (cfilter && !from_cap_pipe) {
2875 /* A capture filter was specified; set it up. */
2876 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2877 /* Treat this specially - our caller might try to compile this
2878 as a display filter and, if that succeeds, warn the user that
2879 the display and capture filter syntaxes are different. */
2880 return INITFILTER_BAD_FILTER;
2882 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2883 #ifdef HAVE_PCAP_FREECODE
2884 pcap_freecode(&fcode);
2886 return INITFILTER_OTHER_ERROR;
2888 #ifdef HAVE_PCAP_FREECODE
2889 pcap_freecode(&fcode);
2893 return INITFILTER_NO_ERROR;
2897 /* set up to write to the already-opened capture output file/files */
2899 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2903 capture_src *pcap_src;
2904 interface_options *interface_opts;
2905 gboolean successful;
2907 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2909 if ((capture_opts->use_pcapng == FALSE) &&
2910 (capture_opts->ifaces->len > 1)) {
2911 g_snprintf(errmsg, errmsg_len,
2912 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
2916 /* Set up to write to the capture file. */
2917 if (capture_opts->multi_files_on) {
2918 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2920 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2921 if (ld->pdh == NULL) {
2926 pcap_src = g_array_index(ld->pcaps, capture_src *, 0);
2927 if (pcap_src->from_pcapng) {
2928 /* We are just going to rewrite the source SHB and IDB blocks */
2931 if (capture_opts->use_pcapng) {
2933 GString *cpu_info_str;
2934 GString *os_info_str;
2936 cpu_info_str = g_string_new("");
2937 os_info_str = g_string_new("");
2938 get_cpu_info(cpu_info_str);
2939 get_os_version_info(os_info_str);
2941 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2942 successful = pcapng_write_session_header_block(ld->pdh,
2943 (const char *)capture_opts->capture_comment, /* Comment */
2944 cpu_info_str->str, /* HW */
2945 os_info_str->str, /* OS */
2947 -1, /* section_length */
2950 g_string_free(cpu_info_str, TRUE);
2953 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2954 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
2955 pcap_src = g_array_index(ld->pcaps, capture_src *, i);
2956 if (pcap_src->from_cap_pipe) {
2957 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
2959 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
2961 successful = pcapng_write_interface_description_block(global_ld.pdh,
2962 NULL, /* OPT_COMMENT 1 */
2963 interface_opts->name, /* IDB_NAME 2 */
2964 interface_opts->descr, /* IDB_DESCRIPTION 3 */
2965 interface_opts->cfilter, /* IDB_FILTER 11 */
2966 os_info_str->str, /* IDB_OS 12 */
2969 &(global_ld.bytes_written),
2970 0, /* IDB_IF_SPEED 8 */
2971 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2975 g_string_free(os_info_str, TRUE);
2978 pcap_src = g_array_index(ld->pcaps, capture_src *, 0);
2979 if (pcap_src->from_cap_pipe) {
2980 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
2982 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
2984 successful = libpcap_write_file_header(ld->pdh, pcap_src->linktype, pcap_src->snaplen,
2985 pcap_src->ts_nsec, &ld->bytes_written, &err);
2993 if (ld->pdh == NULL) {
2994 /* We couldn't set up to write to the capture file. */
2995 /* XXX - use cf_open_error_message from tshark instead? */
3000 g_snprintf(errmsg, errmsg_len,
3001 "The file to which the capture would be"
3002 " saved (\"%s\") could not be opened: Error %d.",
3003 capture_opts->save_file, err);
3005 g_snprintf(errmsg, errmsg_len,
3006 "The file to which the capture would be"
3007 " saved (\"%s\") could not be opened: %s.",
3008 capture_opts->save_file, g_strerror(err));
3020 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
3024 capture_src *pcap_src;
3025 guint64 end_time = create_timestamp();
3027 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
3029 if (capture_opts->multi_files_on) {
3030 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
3032 if (capture_opts->use_pcapng) {
3033 for (i = 0; i < global_ld.pcaps->len; i++) {
3034 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3035 if (!pcap_src->from_cap_pipe) {
3036 guint64 isb_ifrecv, isb_ifdrop;
3037 struct pcap_stat stats;
3039 if (pcap_stats(pcap_src->pcap_h, &stats) >= 0) {
3040 isb_ifrecv = pcap_src->received;
3041 isb_ifdrop = stats.ps_drop + pcap_src->dropped + pcap_src->flushed;
3043 isb_ifrecv = G_MAXUINT64;
3044 isb_ifdrop = G_MAXUINT64;
3046 pcapng_write_interface_statistics_block(ld->pdh,
3049 "Counters provided by dumpcap",
3058 if (fclose(ld->pdh) == EOF) {
3059 if (err_close != NULL) {
3069 /* dispatch incoming packets (pcap or capture pipe)
3071 * Waits for incoming packets to be available, and calls pcap_dispatch()
3072 * to cause them to be processed.
3074 * Returns the number of packets which were processed.
3076 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3077 * packet-batching behaviour does not cause packets to get held back
3081 capture_loop_dispatch(loop_data *ld,
3082 char *errmsg, int errmsg_len, capture_src *pcap_src)
3085 gint packet_count_before;
3090 packet_count_before = ld->packet_count;
3091 if (pcap_src->from_cap_pipe) {
3092 /* dispatch from capture pipe */
3093 #ifdef LOG_CAPTURE_VERBOSE
3094 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
3097 sel_ret = cap_pipe_select(pcap_src->cap_pipe_fd);
3099 if (sel_ret < 0 && errno != EINTR) {
3100 g_snprintf(errmsg, errmsg_len,
3101 "Unexpected error from select: %s", g_strerror(errno));
3102 report_capture_error(errmsg, please_report);
3107 * "select()" says we can read from the pipe without blocking
3110 inpkts = pcap_src->cap_pipe_dispatch(ld, pcap_src, errmsg, errmsg_len);
3120 /* dispatch from pcap */
3121 #ifdef MUST_DO_SELECT
3123 * If we have "pcap_get_selectable_fd()", we use it to get the
3124 * descriptor on which to select; if that's -1, it means there
3125 * is no descriptor on which you can do a "select()" (perhaps
3126 * because you're capturing on a special device, and that device's
3127 * driver unfortunately doesn't support "select()", in which case
3128 * we don't do the select - which means it might not be possible
3129 * to stop a capture until a packet arrives. If that's unacceptable,
3130 * plead with whoever supplies the software for that device to add
3131 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3132 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3133 * later, so it can use pcap_breakloop().
3135 #ifdef LOG_CAPTURE_VERBOSE
3136 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3138 if (pcap_src->pcap_fd != -1) {
3139 sel_ret = cap_pipe_select(pcap_src->pcap_fd);
3142 * "select()" says we can read from it without blocking; go for
3145 * We don't have pcap_breakloop(), so we only process one packet
3146 * per pcap_dispatch() call, to allow a signal to stop the
3147 * processing immediately, rather than processing all packets
3148 * in a batch before quitting.
3151 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3153 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3157 /* Error, rather than pcap_breakloop(). */
3158 pcap_src->pcap_err = TRUE;
3160 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3163 if (sel_ret < 0 && errno != EINTR) {
3164 g_snprintf(errmsg, errmsg_len,
3165 "Unexpected error from select: %s", g_strerror(errno));
3166 report_capture_error(errmsg, please_report);
3172 #endif /* MUST_DO_SELECT */
3174 /* dispatch from pcap without select */
3176 #ifdef LOG_CAPTURE_VERBOSE
3177 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3181 * On Windows, we don't support asynchronously telling a process to
3182 * stop capturing; instead, we check for an indication on a pipe
3183 * after processing packets. We therefore process only one packet
3184 * at a time, so that we can check the pipe after every packet.
3187 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3189 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3193 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3195 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3200 /* Error, rather than pcap_breakloop(). */
3201 pcap_src->pcap_err = TRUE;
3203 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3205 #else /* pcap_next_ex */
3206 #ifdef LOG_CAPTURE_VERBOSE
3207 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3209 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3212 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3213 * see https://wiki.wireshark.org/CaptureSetup/WinPcapRemote
3214 * This should be fixed in the WinPcap 4.0 alpha release.
3216 * For reference, an example remote interface:
3217 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3220 /* emulate dispatch from pcap */
3223 struct pcap_pkthdr *pkt_header;
3228 (in = pcap_next_ex(pcap_src->pcap_h, &pkt_header, &pkt_data)) == 1) {
3230 capture_loop_queue_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
3232 capture_loop_write_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
3237 pcap_src->pcap_err = TRUE;
3241 #endif /* pcap_next_ex */
3245 #ifdef LOG_CAPTURE_VERBOSE
3246 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3249 return ld->packet_count - packet_count_before;
3253 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3254 * want to grab only the characters between the '{' and '}' delimiters.
3256 * Returns a GString that must be freed with g_string_free(). */
3258 isolate_uuid(const char *iface)
3263 ptr = strchr(iface, '{');
3265 return g_string_new(iface);
3266 gstr = g_string_new(ptr + 1);
3268 ptr = strchr(gstr->str, '}');
3272 gstr = g_string_truncate(gstr, ptr - gstr->str);
3277 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3278 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3280 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3281 char *errmsg, int errmsg_len)
3284 gchar *capfile_name;
3285 gchar *prefix, *suffix;
3286 gboolean is_tempfile;
3288 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3289 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3291 if (capture_opts->save_file != NULL) {
3292 /* We return to the caller while the capture is in progress.
3293 * Therefore we need to take a copy of save_file in
3294 * case the caller destroys it after we return.
3296 capfile_name = g_strdup(capture_opts->save_file);
3298 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3299 if (capture_opts->multi_files_on) {
3300 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3301 g_snprintf(errmsg, errmsg_len,
3302 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3303 g_free(capfile_name);
3306 if (strcmp(capfile_name, "-") == 0) {
3307 /* write to stdout */
3310 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3311 _setmode(1, O_BINARY);
3314 /* Try to open the specified FIFO for use as a capture buffer.
3315 Do *not* create it if it doesn't exist. There's nothing
3316 to truncate. If we need to read it, We Have A Problem. */
3317 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY, 0);
3319 } /* if (...output_to_pipe ... */
3322 if (capture_opts->multi_files_on) {
3323 /* ringbuffer is enabled */
3324 *save_file_fd = ringbuf_init(capfile_name,
3325 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3326 capture_opts->group_read_access);
3328 /* we need the ringbuf name */
3329 if (*save_file_fd != -1) {
3330 g_free(capfile_name);
3331 capfile_name = g_strdup(ringbuf_current_filename());
3334 /* Try to open/create the specified file for use as a capture buffer. */
3335 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY|O_TRUNC|O_CREAT,
3336 (capture_opts->group_read_access) ? 0640 : 0600);
3339 is_tempfile = FALSE;
3341 /* Choose a random name for the temporary capture buffer */
3342 if (global_capture_opts.ifaces->len > 1) {
3344 * More than one interface; just use the number of interfaces
3345 * to generate the temporary file name prefix.
3347 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3350 * One interface; use its description, if it has one, to generate
3351 * the temporary file name, otherwise use its name.
3354 const interface_options *interface_opts;
3356 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
3359 * Do we have a description?
3361 if (interface_opts->descr) {
3365 * Strip off any stuff we shouldn't use in the file name,
3366 * by getting the last component of what would be a file
3369 basename = g_path_get_basename(interface_opts->descr);
3372 * No - use the name.
3374 * Strip off any stuff we shouldn't use in the file name,
3375 * by getting the last component of what would be a file
3378 basename = g_path_get_basename(interface_opts->name);
3381 * This is Windows, where we might have an ugly GUID-based
3384 * If it's an ugly GUID-based name, use the generic portion
3385 * of the interface GUID to form the basis of the filename.
3387 if (strncmp("NPF_{", basename, 5) == 0) {
3389 * We have a GUID-based name; extract the GUID digits
3390 * as the basis of the filename.
3393 iface = isolate_uuid(basename);
3395 basename = g_strdup(iface->str);
3396 g_string_free(iface, TRUE);
3400 /* generate the temp file name prefix */
3401 prefix = g_strconcat("wireshark_", basename, NULL);
3405 /* Generate the appropriate suffix. */
3406 if (capture_opts->use_pcapng) {
3411 *save_file_fd = create_tempfile(&tmpname, prefix, suffix);
3413 capfile_name = g_strdup(tmpname);
3417 /* did we fail to open the output file? */
3418 if (*save_file_fd == -1) {
3420 g_snprintf(errmsg, errmsg_len,
3421 "The temporary file to which the capture would be saved (\"%s\") "
3422 "could not be opened: %s.", capfile_name, g_strerror(errno));
3424 if (capture_opts->multi_files_on) {
3425 ringbuf_error_cleanup();
3428 g_snprintf(errmsg, errmsg_len,
3429 "The file to which the capture would be saved (\"%s\") "
3430 "could not be opened: %s.", capfile_name,
3433 g_free(capfile_name);
3437 if (capture_opts->save_file != NULL) {
3438 g_free(capture_opts->save_file);
3440 capture_opts->save_file = capfile_name;
3441 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3442 "g_free(capfile_name)". */
3448 /* Do the work of handling either the file size or file duration capture
3449 conditions being reached, and switching files or stopping. */
3451 do_file_switch_or_stop(capture_options *capture_opts,
3452 condition *cnd_autostop_files,
3453 condition *cnd_autostop_size,
3454 condition *cnd_file_duration,
3455 condition *cnd_file_interval)
3458 capture_src *pcap_src;
3459 interface_options *interface_opts;
3460 gboolean successful;
3462 if (capture_opts->multi_files_on) {
3463 if (cnd_autostop_files != NULL &&
3464 cnd_eval(cnd_autostop_files, (guint64)++global_ld.autostop_files)) {
3465 /* no files left: stop here */
3466 global_ld.go = FALSE;
3470 /* Switch to the next ringbuffer file */
3471 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3472 &global_ld.save_file_fd, &global_ld.err)) {
3474 /* File switch succeeded: reset the conditions */
3475 global_ld.bytes_written = 0;
3476 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3477 if (pcap_src->from_pcapng) {
3478 /* Write the saved SHB and all IDBs to start of next file */
3479 /* The blocks were saved in reverse so reverse it before iterating */
3480 GList *rlist = g_list_reverse(pcap_src->cap_pipe_info.pcapng.saved_blocks);
3481 GList *list = rlist;
3483 while (list && successful) {
3484 successful = pcapng_write_saved_block(pcap_src, (struct pcapng_block_header_s *) list->data);
3485 list = g_list_next(list);
3487 pcap_src->cap_pipe_info.pcapng.saved_blocks = g_list_reverse(rlist);
3489 if (capture_opts->use_pcapng) {
3491 GString *cpu_info_str;
3492 GString *os_info_str;
3494 cpu_info_str = g_string_new("");
3495 os_info_str = g_string_new("");
3496 get_cpu_info(cpu_info_str);
3497 get_os_version_info(os_info_str);
3499 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
3500 successful = pcapng_write_session_header_block(global_ld.pdh,
3501 (const char *)capture_opts->capture_comment, /* Comment */
3502 cpu_info_str->str, /* HW */
3503 os_info_str->str, /* OS */
3505 -1, /* section_length */
3506 &(global_ld.bytes_written),
3508 g_string_free(cpu_info_str, TRUE);
3511 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3512 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
3513 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3514 successful = pcapng_write_interface_description_block(global_ld.pdh,
3515 NULL, /* OPT_COMMENT 1 */
3516 interface_opts->name, /* IDB_NAME 2 */
3517 interface_opts->descr, /* IDB_DESCRIPTION 3 */
3518 interface_opts->cfilter, /* IDB_FILTER 11 */
3519 os_info_str->str, /* IDB_OS 12 */
3522 &(global_ld.bytes_written),
3523 0, /* IDB_IF_SPEED 8 */
3524 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3528 g_string_free(os_info_str, TRUE);
3531 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3532 successful = libpcap_write_file_header(global_ld.pdh, pcap_src->linktype, pcap_src->snaplen,
3533 pcap_src->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3537 fclose(global_ld.pdh);
3538 global_ld.pdh = NULL;
3539 global_ld.go = FALSE;
3542 if (cnd_autostop_size)
3543 cnd_reset(cnd_autostop_size);
3544 if (cnd_file_duration)
3545 cnd_reset(cnd_file_duration);
3546 if (cnd_file_interval)
3547 cnd_reset(cnd_file_interval);
3548 fflush(global_ld.pdh);
3550 report_packet_count(global_ld.inpkts_to_sync_pipe);
3551 global_ld.inpkts_to_sync_pipe = 0;
3552 report_new_capture_file(capture_opts->save_file);
3554 /* File switch failed: stop here */
3555 global_ld.go = FALSE;
3559 /* single file, stop now */
3560 global_ld.go = FALSE;
3567 pcap_read_handler(void* arg)
3569 capture_src *pcap_src;
3570 char errmsg[MSG_MAX_LENGTH+1];
3572 pcap_src = (capture_src *)arg;
3574 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3575 pcap_src->interface_id);
3577 while (global_ld.go) {
3578 /* dispatch incoming packets */
3579 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_src);
3581 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3582 pcap_src->interface_id);
3583 g_thread_exit(NULL);
3587 /* Do the low-level work of a capture.
3588 Returns TRUE if it succeeds, FALSE otherwise. */
3590 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3593 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3595 struct timeval upd_time, cur_time;
3599 condition *cnd_file_duration = NULL;
3600 condition *cnd_file_interval = NULL;
3601 condition *cnd_autostop_files = NULL;
3602 condition *cnd_autostop_size = NULL;
3603 condition *cnd_autostop_duration = NULL;
3606 gboolean cfilter_error = FALSE;
3607 char errmsg[MSG_MAX_LENGTH+1];
3608 char secondary_errmsg[MSG_MAX_LENGTH+1];
3609 capture_src *pcap_src;
3610 interface_options *interface_opts;
3611 guint i, error_index = 0;
3614 *secondary_errmsg = '\0';
3616 /* init the loop data */
3617 global_ld.go = TRUE;
3618 global_ld.packet_count = 0;
3620 global_ld.report_packet_count = FALSE;
3622 if (capture_opts->has_autostop_packets)
3623 global_ld.packet_max = capture_opts->autostop_packets;
3625 global_ld.packet_max = 0; /* no limit */
3626 global_ld.inpkts_to_sync_pipe = 0;
3627 global_ld.err = 0; /* no error seen yet */
3628 global_ld.pdh = NULL;
3629 global_ld.autostop_files = 0;
3630 global_ld.save_file_fd = -1;
3632 /* We haven't yet gotten the capture statistics. */
3633 *stats_known = FALSE;
3635 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3636 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3638 /* open the "input file" from network interface or capture pipe */
3639 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3640 secondary_errmsg, sizeof(secondary_errmsg))) {
3643 for (i = 0; i < capture_opts->ifaces->len; i++) {
3644 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3645 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
3646 /* init the input filter from the network interface (capture pipe will do nothing) */
3648 * When remote capturing WinPCap crashes when the capture filter
3649 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3652 switch (capture_loop_init_filter(pcap_src->pcap_h, pcap_src->from_cap_pipe,
3653 interface_opts->name,
3654 interface_opts->cfilter?interface_opts->cfilter:"")) {
3656 case INITFILTER_NO_ERROR:
3659 case INITFILTER_BAD_FILTER:
3660 cfilter_error = TRUE;
3662 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_src->pcap_h));
3665 case INITFILTER_OTHER_ERROR:
3666 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3667 pcap_geterr(pcap_src->pcap_h));
3668 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3673 /* If we're supposed to write to a capture file, open it for output
3674 (temporary/specified name/ringbuffer) */
3675 if (capture_opts->saving_to_file) {
3676 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3677 errmsg, sizeof(errmsg))) {
3681 /* set up to write to the already-opened capture output file/files */
3682 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3687 /* XXX - capture SIGTERM and close the capture, in case we're on a
3688 Linux 2.0[.x] system and you have to explicitly close the capture
3689 stream in order to turn promiscuous mode off? We need to do that
3690 in other places as well - and I don't think that works all the
3691 time in any case, due to libpcap bugs. */
3693 /* Well, we should be able to start capturing.
3695 Sync out the capture file, so the header makes it to the file system,
3696 and send a "capture started successfully and capture file created"
3697 message to our parent so that they'll open the capture file and
3698 update its windows to indicate that we have a live capture in
3700 fflush(global_ld.pdh);
3701 report_new_capture_file(capture_opts->save_file);
3704 /* initialize capture stop (and alike) conditions */
3705 init_capture_stop_conditions();
3706 /* create stop conditions */
3707 if (capture_opts->has_autostop_filesize) {
3708 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3709 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3712 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1000);
3714 if (capture_opts->has_autostop_duration)
3715 cnd_autostop_duration =
3716 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3718 if (capture_opts->multi_files_on) {
3719 if (capture_opts->has_file_duration)
3721 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3723 if (capture_opts->has_autostop_files)
3724 cnd_autostop_files =
3725 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_files);
3727 if (capture_opts->has_file_interval)
3729 cnd_new(CND_CLASS_INTERVAL, capture_opts->file_interval);
3732 /* init the time values */
3734 upd_time = GetTickCount();
3736 gettimeofday(&upd_time, NULL);
3738 start_time = create_timestamp();
3739 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3740 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3742 /* WOW, everything is prepared! */
3743 /* please fasten your seat belts, we will enter now the actual capture loop */
3745 pcap_queue = g_async_queue_new();
3746 pcap_queue_bytes = 0;
3747 pcap_queue_packets = 0;
3748 for (i = 0; i < global_ld.pcaps->len; i++) {
3749 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3750 /* XXX - Add an interface name here? */
3751 pcap_src->tid = g_thread_new("Capture read", pcap_read_handler, pcap_src);
3754 while (global_ld.go) {
3755 /* dispatch incoming packets */
3757 pcap_queue_element *queue_element;
3759 g_async_queue_lock(pcap_queue);
3760 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3761 if (queue_element) {
3762 if (queue_element->pcap_src->from_pcapng) {
3763 pcap_queue_bytes -= queue_element->u.bh.block_total_length;
3764 pcap_queue_packets -= 1;
3766 pcap_queue_bytes -= queue_element->u.phdr.caplen;
3767 pcap_queue_packets -= 1;
3770 g_async_queue_unlock(pcap_queue);
3771 if (queue_element) {
3772 if (queue_element->pcap_src->from_pcapng) {
3773 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3774 "Dequeued a block of length %d captured on interface %d.",
3775 queue_element->u.bh.block_total_length, queue_element->pcap_src->interface_id);
3777 capture_loop_write_pcapng_cb(queue_element->pcap_src,
3778 &queue_element->u.bh,
3781 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3782 "Dequeued a packet of length %d captured on interface %d.",
3783 queue_element->u.phdr.caplen, queue_element->pcap_src->interface_id);
3785 capture_loop_write_packet_cb((u_char *) queue_element->pcap_src,
3786 &queue_element->u.phdr,
3789 g_free(queue_element->pd);
3790 g_free(queue_element);
3796 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3797 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3798 sizeof(errmsg), pcap_src);
3801 /* Were we asked to print packet counts by the SIGINFO handler? */
3802 if (global_ld.report_packet_count) {
3803 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3804 plurality(global_ld.packet_count, "", "s"));
3805 global_ld.report_packet_count = FALSE;
3810 /* any news from our parent (signal pipe)? -> just stop the capture */
3811 if (!signal_pipe_check_running()) {
3812 global_ld.go = FALSE;
3817 global_ld.inpkts_to_sync_pipe += inpkts;
3819 /* check capture size condition */
3820 if (cnd_autostop_size != NULL &&
3821 cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
3822 /* Capture size limit reached, do we have another file? */
3823 if (!do_file_switch_or_stop(capture_opts,
3829 } /* cnd_autostop_size */
3830 if (capture_opts->output_to_pipe) {
3831 fflush(global_ld.pdh);
3835 /* Only update once every 500ms so as not to overload slow displays.
3836 * This also prevents too much context-switching between the dumpcap
3837 * and wireshark processes.
3839 #define DUMPCAP_UPD_TIME 500
3842 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3843 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) /* wrap just causes an extra update */
3845 gettimeofday(&cur_time, NULL);
3846 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3847 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000))
3851 upd_time = cur_time;
3854 if (pcap_stats(pch, stats) >= 0) {
3855 *stats_known = TRUE;
3858 /* Let the parent process know. */
3859 if (global_ld.inpkts_to_sync_pipe) {
3861 fflush(global_ld.pdh);
3863 /* Send our parent a message saying we've written out
3864 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3866 report_packet_count(global_ld.inpkts_to_sync_pipe);
3868 global_ld.inpkts_to_sync_pipe = 0;
3871 /* check capture duration condition */
3872 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3873 /* The maximum capture time has elapsed; stop the capture. */
3874 global_ld.go = FALSE;
3878 /* check capture file duration condition */
3879 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3880 /* duration limit reached, do we have another file? */
3881 if (!do_file_switch_or_stop(capture_opts,
3887 } /* cnd_file_duration */
3889 /* check capture file interval condition */
3890 if (cnd_file_interval != NULL && cnd_eval(cnd_file_interval)) {
3891 /* end of interval reached, do we have another file? */
3892 if (!do_file_switch_or_stop(capture_opts,
3898 } /* cnd_file_interval */
3902 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3904 pcap_queue_element *queue_element;
3906 for (i = 0; i < global_ld.pcaps->len; i++) {
3907 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3908 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3909 pcap_src->interface_id);
3910 g_thread_join(pcap_src->tid);
3911 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3912 pcap_src->interface_id);
3915 g_async_queue_lock(pcap_queue);
3916 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3917 if (queue_element) {
3918 pcap_queue_bytes -= queue_element->u.phdr.caplen;
3919 pcap_queue_packets -= 1;
3921 g_async_queue_unlock(pcap_queue);
3922 if (queue_element == NULL) {
3925 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3926 "Dequeued a packet of length %d captured on interface %d.",
3927 queue_element->u.phdr.caplen, queue_element->pcap_src->interface_id);
3928 capture_loop_write_packet_cb((u_char *)queue_element->pcap_src,
3929 &queue_element->u.phdr,
3931 g_free(queue_element->pd);
3932 g_free(queue_element);
3933 global_ld.inpkts_to_sync_pipe += 1;
3934 if (capture_opts->output_to_pipe) {
3935 fflush(global_ld.pdh);
3941 /* delete stop conditions */
3942 if (cnd_file_duration != NULL)
3943 cnd_delete(cnd_file_duration);
3944 if (cnd_file_interval != NULL)
3945 cnd_delete(cnd_file_interval);
3946 if (cnd_autostop_files != NULL)
3947 cnd_delete(cnd_autostop_files);
3948 if (cnd_autostop_size != NULL)
3949 cnd_delete(cnd_autostop_size);
3950 if (cnd_autostop_duration != NULL)
3951 cnd_delete(cnd_autostop_duration);
3953 /* did we have a pcap (input) error? */
3954 for (i = 0; i < capture_opts->ifaces->len; i++) {
3955 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3956 if (pcap_src->pcap_err) {
3957 /* On Linux, if an interface goes down while you're capturing on it,
3958 you'll get a "recvfrom: Network is down" or
3959 "The interface went down" error (ENETDOWN).
3960 (At least you will if g_strerror() doesn't show a local translation
3963 On FreeBSD, DragonFly BSD, and macOS, if a network adapter
3964 disappears while you're capturing on it, you'll get a
3965 "read: Device not configured" error (ENXIO). (See previous
3966 parenthetical note.)
3968 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3970 These should *not* be reported to the Wireshark developers. */
3973 cap_err_str = pcap_geterr(pcap_src->pcap_h);
3974 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3975 strcmp(cap_err_str, "The interface went down") == 0 ||
3976 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3977 strcmp(cap_err_str, "read: I/O error") == 0 ||
3978 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3979 report_capture_error("The network adapter on which the capture was being done "
3980 "is no longer running; the capture has stopped.",
3983 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3985 report_capture_error(errmsg, please_report);
3988 } else if (pcap_src->from_cap_pipe && pcap_src->cap_pipe_err == PIPERR) {
3989 report_capture_error(errmsg, "");
3993 /* did we have an output error while capturing? */
3994 if (global_ld.err == 0) {
3997 capture_loop_get_errmsg(errmsg, sizeof(errmsg), secondary_errmsg,
3998 sizeof(secondary_errmsg),
3999 capture_opts->save_file, global_ld.err, FALSE);
4000 report_capture_error(errmsg, secondary_errmsg);
4004 if (capture_opts->saving_to_file) {
4005 /* close the output file */
4006 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
4010 /* there might be packets not yet notified to the parent */
4011 /* (do this after closing the file, so all packets are already flushed) */
4012 if (global_ld.inpkts_to_sync_pipe) {
4014 report_packet_count(global_ld.inpkts_to_sync_pipe);
4015 global_ld.inpkts_to_sync_pipe = 0;
4018 /* If we've displayed a message about a write error, there's no point
4019 in displaying another message about an error on close. */
4020 if (!close_ok && write_ok) {
4021 capture_loop_get_errmsg(errmsg, sizeof(errmsg), secondary_errmsg,
4022 sizeof(secondary_errmsg),
4023 capture_opts->save_file, err_close, TRUE);
4024 report_capture_error(errmsg, secondary_errmsg);
4028 * XXX We exhibit different behaviour between normal mode and sync mode
4029 * when the pipe is stdin and not already at EOF. If we're a child, the
4030 * parent's stdin isn't closed, so if the user starts another capture,
4031 * cap_pipe_open_live() will very likely not see the expected magic bytes and
4032 * will say "Unrecognized libpcap format". On the other hand, in normal
4033 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
4036 report_capture_count(TRUE);
4038 /* get packet drop statistics from pcap */
4039 for (i = 0; i < capture_opts->ifaces->len; i++) {
4041 guint32 pcap_dropped = 0;
4043 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4044 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
4045 received = pcap_src->received;
4046 if (pcap_src->pcap_h != NULL) {
4047 g_assert(!pcap_src->from_cap_pipe);
4048 /* Get the capture statistics, so we know how many packets were dropped. */
4050 * Older versions of libpcap didn't set ps_ifdrop on some
4051 * platforms; initialize it to 0 to handle that.
4053 stats->ps_ifdrop = 0;
4054 if (pcap_stats(pcap_src->pcap_h, stats) >= 0) {
4055 *stats_known = TRUE;
4056 /* Let the parent process know. */
4057 pcap_dropped += stats->ps_drop;
4059 g_snprintf(errmsg, sizeof(errmsg),
4060 "Can't get packet-drop statistics: %s",
4061 pcap_geterr(pcap_src->pcap_h));
4062 report_capture_error(errmsg, please_report);
4065 report_packet_drops(received, pcap_dropped, pcap_src->dropped, pcap_src->flushed, stats->ps_ifdrop, interface_opts->display_name);
4068 /* close the input file (pcap or capture pipe) */
4069 capture_loop_close_input(&global_ld);
4071 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
4073 /* ok, if the write and the close were successful. */
4074 return write_ok && close_ok;
4077 if (capture_opts->multi_files_on) {
4078 /* cleanup ringbuffer */
4079 ringbuf_error_cleanup();
4081 /* We can't use the save file, and we have no FILE * for the stream
4082 to close in order to close it, so close the FD directly. */
4083 if (global_ld.save_file_fd != -1) {
4084 ws_close(global_ld.save_file_fd);
4087 /* We couldn't even start the capture, so get rid of the capture
4089 if (capture_opts->save_file != NULL) {
4090 ws_unlink(capture_opts->save_file);
4091 g_free(capture_opts->save_file);
4094 capture_opts->save_file = NULL;
4096 report_cfilter_error(capture_opts, error_index, errmsg);
4098 report_capture_error(errmsg, secondary_errmsg);
4100 /* close the input file (pcap or cap_pipe) */
4101 capture_loop_close_input(&global_ld);
4103 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
4110 capture_loop_stop(void)
4112 #ifdef HAVE_PCAP_BREAKLOOP
4114 capture_src *pcap_src;
4116 for (i = 0; i < global_ld.pcaps->len; i++) {
4117 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4118 if (pcap_src->pcap_h != NULL)
4119 pcap_breakloop(pcap_src->pcap_h);
4122 global_ld.go = FALSE;
4127 capture_loop_get_errmsg(char *errmsg, size_t errmsglen, char *secondary_errmsg,
4128 size_t secondary_errmsglen, const char *fname,
4129 int err, gboolean is_close)
4131 static const char find_space[] =
4132 "You will need to free up space on that file system"
4133 " or put the capture file on a different file system.";
4138 g_snprintf(errmsg, (gulong)errmsglen,
4139 "Not all the packets could be written to the file"
4140 " to which the capture was being saved\n"
4141 "(\"%s\") because there is no space left on the file system\n"
4142 "on which that file resides.",
4144 g_snprintf(secondary_errmsg, (gulong)secondary_errmsglen, "%s",
4150 g_snprintf(errmsg, (gulong)errmsglen,
4151 "Not all the packets could be written to the file"
4152 " to which the capture was being saved\n"
4153 "(\"%s\") because you are too close to, or over,"
4154 " your disk quota\n"
4155 "on the file system on which that file resides.",
4157 g_snprintf(secondary_errmsg, (gulong)secondary_errmsglen, "%s",
4164 g_snprintf(errmsg, (gulong)errmsglen,
4165 "The file to which the capture was being saved\n"
4166 "(\"%s\") could not be closed: %s.",
4167 fname, g_strerror(err));
4169 g_snprintf(errmsg, (gulong)errmsglen,
4170 "An error occurred while writing to the file"
4171 " to which the capture was being saved\n"
4173 fname, g_strerror(err));
4175 g_snprintf(secondary_errmsg, (gulong)secondary_errmsglen,
4176 "%s", please_report);
4181 /* one pcapng block was captured, process it */
4183 capture_loop_write_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, const u_char *pd)
4187 if (!global_capture_opts.use_pcapng) {
4190 /* We may be called multiple times from pcap_dispatch(); if we've set
4191 the "stop capturing" flag, ignore this packet, as we're not
4192 supposed to be saving any more packets. */
4193 if (!global_ld.go) {
4194 pcap_src->flushed++;
4198 if (global_ld.pdh) {
4199 gboolean successful;
4201 /* We're supposed to write the packet to a file; do so.
4202 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4203 "ld->err" to the error. */
4204 successful = pcapng_write_block(global_ld.pdh,
4206 bh->block_total_length,
4207 &global_ld.bytes_written, &err);
4209 fflush(global_ld.pdh);
4211 global_ld.go = FALSE;
4212 global_ld.err = err;
4213 pcap_src->dropped++;
4214 } else if (bh->block_type == BLOCK_TYPE_EPB || bh->block_type == BLOCK_TYPE_SPB || bh->block_type == BLOCK_TYPE_SYSTEMD_JOURNAL) {
4215 /* count packet only if we actually have an EPB or SPB */
4216 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4217 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4218 "Wrote a packet of length %d captured on interface %u.",
4219 bh->block_total_length, pcap_src->interface_id);
4221 global_ld.packet_count++;
4222 pcap_src->received++;
4223 /* if the user told us to stop after x packets, do we already have enough? */
4224 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
4225 global_ld.go = FALSE;
4231 /* one packet was captured, process it */
4233 capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
4236 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4238 guint ts_mul = pcap_src->ts_nsec ? 1000000000 : 1000000;
4240 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_write_packet_cb");
4242 /* We may be called multiple times from pcap_dispatch(); if we've set
4243 the "stop capturing" flag, ignore this packet, as we're not
4244 supposed to be saving any more packets. */
4245 if (!global_ld.go) {
4246 pcap_src->flushed++;
4250 if (global_ld.pdh) {
4251 gboolean successful;
4253 /* We're supposed to write the packet to a file; do so.
4254 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4255 "ld->err" to the error. */
4256 if (global_capture_opts.use_pcapng) {
4257 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
4259 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4260 phdr->caplen, phdr->len,
4261 pcap_src->interface_id,
4264 &global_ld.bytes_written, &err);
4266 successful = libpcap_write_packet(global_ld.pdh,
4267 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4268 phdr->caplen, phdr->len,
4270 &global_ld.bytes_written, &err);
4273 global_ld.go = FALSE;
4274 global_ld.err = err;
4275 pcap_src->dropped++;
4277 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4278 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4279 "Wrote a packet of length %d captured on interface %u.",
4280 phdr->caplen, pcap_src->interface_id);
4282 global_ld.packet_count++;
4283 pcap_src->received++;
4284 /* if the user told us to stop after x packets, do we already have enough? */
4285 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
4286 global_ld.go = FALSE;
4292 /* one packet was captured, queue it */
4294 capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
4297 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4298 pcap_queue_element *queue_element;
4299 gboolean limit_reached;
4301 /* We may be called multiple times from pcap_dispatch(); if we've set
4302 the "stop capturing" flag, ignore this packet, as we're not
4303 supposed to be saving any more packets. */
4304 if (!global_ld.go) {
4305 pcap_src->flushed++;
4309 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4310 if (queue_element == NULL) {
4311 pcap_src->dropped++;
4314 queue_element->pcap_src = pcap_src;
4315 queue_element->u.phdr = *phdr;
4316 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4317 if (queue_element->pd == NULL) {
4318 pcap_src->dropped++;
4319 g_free(queue_element);
4322 memcpy(queue_element->pd, pd, phdr->caplen);
4323 g_async_queue_lock(pcap_queue);
4324 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4325 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4326 limit_reached = FALSE;
4327 g_async_queue_push_unlocked(pcap_queue, queue_element);
4328 pcap_queue_bytes += phdr->caplen;
4329 pcap_queue_packets += 1;
4331 limit_reached = TRUE;
4333 g_async_queue_unlock(pcap_queue);
4334 if (limit_reached) {
4335 pcap_src->dropped++;
4336 g_free(queue_element->pd);
4337 g_free(queue_element);
4338 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4339 "Dropped a packet of length %d captured on interface %u.",
4340 phdr->caplen, pcap_src->interface_id);
4342 pcap_src->received++;
4343 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4344 "Queued a packet of length %d captured on interface %u.",
4345 phdr->caplen, pcap_src->interface_id);
4347 /* I don't want to hold the mutex over the debug output. So the
4348 output may be wrong */
4349 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4350 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4351 pcap_queue_bytes, pcap_queue_packets);
4354 /* one pcapng block was captured, queue it */
4356 capture_loop_queue_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, const u_char *pd)
4358 pcap_queue_element *queue_element;
4359 gboolean limit_reached;
4361 /* We may be called multiple times from pcap_dispatch(); if we've set
4362 the "stop capturing" flag, ignore this packet, as we're not
4363 supposed to be saving any more packets. */
4364 if (!global_ld.go) {
4365 pcap_src->flushed++;
4369 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4370 if (queue_element == NULL) {
4371 pcap_src->dropped++;
4374 queue_element->pcap_src = pcap_src;
4375 queue_element->u.bh = *bh;
4376 queue_element->pd = (u_char *)g_malloc(bh->block_total_length);
4377 if (queue_element->pd == NULL) {
4378 pcap_src->dropped++;
4379 g_free(queue_element);
4382 memcpy(queue_element->pd, pd, bh->block_total_length);
4383 g_async_queue_lock(pcap_queue);
4384 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4385 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4386 limit_reached = FALSE;
4387 g_async_queue_push_unlocked(pcap_queue, queue_element);
4388 pcap_queue_bytes += bh->block_total_length;
4389 pcap_queue_packets += 1;
4391 limit_reached = TRUE;
4393 g_async_queue_unlock(pcap_queue);
4394 if (limit_reached) {
4395 pcap_src->dropped++;
4396 g_free(queue_element->pd);
4397 g_free(queue_element);
4398 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4399 "Dropped a packet of length %d captured on interface %u.",
4400 bh->block_total_length, pcap_src->interface_id);
4402 pcap_src->received++;
4403 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4404 "Queued a packet of length %d captured on interface %u.",
4405 bh->block_total_length, pcap_src->interface_id);
4407 /* I don't want to hold the mutex over the debug output. So the
4408 output may be wrong */
4409 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4410 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4411 pcap_queue_bytes, pcap_queue_packets);
4415 set_80211_channel(const char *iface, const char *opt)
4419 guint32 center_freq1 = 0;
4420 guint32 center_freq2 = 0;
4423 gchar **options = NULL;
4425 options = g_strsplit_set(opt, ",", 4);
4426 for (args = 0; options[args]; args++);
4429 freq = get_nonzero_guint32(options[0], "802.11 channel frequency");
4431 if (args >= 1 && options[1]) {
4432 type = ws80211_str_to_chan_type(options[1]);
4434 cmdarg_err("\"%s\" is not a valid 802.11 channel type", options[1]);
4440 if (args >= 2 && options[2])
4441 center_freq1 = get_nonzero_guint32(options[2], "VHT center frequency");
4443 if (args >= 3 && options[3])
4444 center_freq2 = get_nonzero_guint32(options[3], "VHT center frequency 2");
4446 ret = ws80211_init();
4448 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4452 ret = ws80211_set_freq(iface, freq, type, center_freq1, center_freq2);
4455 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4461 pipe_write_block(2, SP_SUCCESS, NULL);
4464 g_strfreev(options);
4469 get_dumpcap_compiled_info(GString *str)
4471 /* Capture libraries */
4472 g_string_append(str, ", ");
4473 get_compiled_caplibs_version(str);
4477 get_dumpcap_runtime_info(GString *str)
4479 /* Capture libraries */
4480 g_string_append(str, ", ");
4481 get_runtime_caplibs_version(str);
4484 /* And now our feature presentation... [ fade to music ] */
4486 main(int argc, char *argv[])
4488 GString *comp_info_str;
4489 GString *runtime_info_str;
4491 static const struct option long_options[] = {
4492 {"help", no_argument, NULL, 'h'},
4493 {"version", no_argument, NULL, 'v'},
4494 LONGOPT_CAPTURE_COMMON
4498 gboolean arg_error = FALSE;
4504 struct sigaction action, oldaction;
4507 gboolean start_capture = TRUE;
4508 gboolean stats_known;
4509 struct pcap_stat stats;
4510 GLogLevelFlags log_flags;
4511 gboolean list_interfaces = FALSE;
4512 int caps_queries = 0;
4513 #ifdef HAVE_BPF_IMAGE
4514 gboolean print_bpf_code = FALSE;
4516 gboolean set_chan = FALSE;
4517 gchar *set_chan_arg = NULL;
4518 gboolean machine_readable = FALSE;
4519 gboolean print_statistics = FALSE;
4520 int status, run_once_args = 0;
4523 #if defined(__APPLE__) && defined(__LP64__)
4524 struct utsname osinfo;
4528 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
4530 /* Get the compile-time version information string */
4531 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
4533 /* Get the run-time version information string */
4534 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
4536 /* Add it to the information to be reported on a crash. */
4537 ws_add_crash_info("Dumpcap (Wireshark) %s\n"
4542 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
4543 g_string_free(comp_info_str, TRUE);
4544 g_string_free(runtime_info_str, TRUE);
4547 arg_list_utf_16to8(argc, argv);
4548 create_app_running_mutex();
4551 * Initialize our DLL search path. MUST be called before LoadLibrary
4554 ws_init_dll_search_path();
4557 #ifdef HAVE_BPF_IMAGE
4558 #define OPTSTRING_d "d"
4560 #define OPTSTRING_d ""
4563 #ifdef HAVE_PCAP_REMOTE
4564 #define OPTSTRING_r "r"
4565 #define OPTSTRING_u "u"
4567 #define OPTSTRING_r ""
4568 #define OPTSTRING_u ""
4571 #ifdef HAVE_PCAP_SETSAMPLING
4572 #define OPTSTRING_m "m:"
4574 #define OPTSTRING_m ""
4577 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
4579 #ifdef DEBUG_CHILD_DUMPCAP
4580 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4581 fprintf (stderr, "Unable to open debug log file .\n");
4586 #if defined(__APPLE__) && defined(__LP64__)
4588 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
4589 * a bug workaround - timeouts less than 1 second don't work with libpcap
4590 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
4591 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4592 * The problem is extremely unlikely to be reintroduced in a future
4595 if (uname(&osinfo) == 0) {
4597 * {Mac} OS X/macOS 10.x uses Darwin {x+4}.0.0; 10.x.y uses Darwin
4598 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4599 * number of 10.0.0, not 10.1.0 - go figure).
4601 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
4602 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
4603 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
4604 need_timeout_workaround = TRUE;
4609 * Determine if dumpcap is being requested to run in a special
4610 * capture_child mode by going thru the command line args to see if
4611 * a -Z is present. (-Z is a hidden option).
4613 * The primary result of running in capture_child mode is that
4614 * all messages sent out on stderr are in a special type/len/string
4615 * format to allow message processing by type. These messages include
4616 * error messages if dumpcap fails to start the operation it was
4617 * requested to do, as well as various "status" messages which are sent
4618 * when an actual capture is in progress, and a "success" message sent
4619 * if dumpcap was requested to perform an operation other than a
4622 * Capture_child mode would normally be requested by a parent process
4623 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4624 * to which dumpcap stderr has been redirected. It might also have
4625 * another pipe to obtain dumpcap stdout output; for operations other
4626 * than a capture, that information is formatted specially for easier
4627 * parsing by the parent process.
4629 * Capture_child mode needs to be determined immediately upon
4630 * startup so that any messages generated by dumpcap in this mode
4631 * (eg: during initialization) will be formatted properly.
4634 for (i=1; i<argc; i++) {
4635 if (strcmp("-Z", argv[i]) == 0) {
4636 capture_child = TRUE;
4637 machine_readable = TRUE; /* request machine-readable output */
4639 /* set output pipe to binary mode, to avoid ugly text conversions */
4640 _setmode(2, O_BINARY);
4645 /* The default_log_handler will use stdout, which makes trouble in */
4646 /* capture child mode, as it uses stdout for its sync_pipe. */
4647 /* So: the filtering is done in the console_log_handler and not here.*/
4648 /* We set the log handlers right up front to make sure that any log */
4649 /* messages when running as child will be sent back to the parent */
4650 /* with the correct format. */
4655 G_LOG_LEVEL_CRITICAL|
4656 G_LOG_LEVEL_WARNING|
4657 G_LOG_LEVEL_MESSAGE|
4661 G_LOG_FLAG_RECURSION);
4663 g_log_set_handler(NULL,
4665 console_log_handler, NULL /* user_data */);
4666 g_log_set_handler(LOG_DOMAIN_MAIN,
4668 console_log_handler, NULL /* user_data */);
4669 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4671 console_log_handler, NULL /* user_data */);
4672 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4674 console_log_handler, NULL /* user_data */);
4676 /* Initialize the pcaps list */
4677 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(capture_src *));
4680 /* Load wpcap if possible. Do this before collecting the run-time version information */
4683 /* ... and also load the packet.dll from wpcap */
4684 /* XXX - currently not required, may change later. */
4685 /*wpcap_packet_load();*/
4687 /* Start windows sockets */
4688 result = WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4691 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_ERROR,
4692 "ERROR: WSAStartup failed with error: %d", result);
4696 /* Set handler for Ctrl+C key */
4697 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4699 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4700 and exit. Do the same with SIGPIPE, in case, for example,
4701 we're writing to our standard output and it's a pipe.
4702 Do the same with SIGHUP if it's not being ignored (if we're
4703 being run under nohup, it might be ignored, in which case we
4704 should leave it ignored).
4706 XXX - apparently, Coverity complained that part of action
4707 wasn't initialized. Perhaps it's running on Linux, where
4708 struct sigaction has an ignored "sa_restorer" element and
4709 where "sa_handler" and "sa_sigaction" might not be two
4710 members of a union. */
4711 memset(&action, 0, sizeof(action));
4712 action.sa_handler = capture_cleanup_handler;
4714 * Arrange that system calls not get restarted, because when
4715 * our signal handler returns we don't want to restart
4716 * a call that was waiting for packets to arrive.
4718 action.sa_flags = 0;
4719 sigemptyset(&action.sa_mask);
4720 sigaction(SIGTERM, &action, NULL);
4721 sigaction(SIGINT, &action, NULL);
4722 sigaction(SIGPIPE, &action, NULL);
4723 sigaction(SIGHUP, NULL, &oldaction);
4724 if (oldaction.sa_handler == SIG_DFL)
4725 sigaction(SIGHUP, &action, NULL);
4728 /* Catch SIGINFO and, if we get it and we're capturing in
4729 quiet mode, report the number of packets we've captured. */
4730 action.sa_handler = report_counts_siginfo;
4731 action.sa_flags = SA_RESTART;
4732 sigemptyset(&action.sa_mask);
4733 sigaction(SIGINFO, &action, NULL);
4734 #endif /* SIGINFO */
4737 /* ----------------------------------------------------------------- */
4738 /* Privilege and capability handling */
4740 /* 1. Running not as root or suid root; no special capabilities. */
4743 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4746 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4748 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4749 /* capabilities; Drop all other capabilities; */
4750 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4751 /* else: after pcap_open_live() in capture_loop_open_input() */
4752 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4753 /* (Note: this means that the process, although logged in */
4754 /* as root, does not have various permissions such as the */
4755 /* ability to bypass file access permissions). */
4756 /* XXX: Should we just leave capabilities alone in this case */
4757 /* so that user gets expected effect that root can do */
4760 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4762 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4763 /* else: after pcap_open_live() in capture_loop_open_input() */
4764 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4765 /* pcap_open_live). */
4767 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4769 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4770 /* capabilities; Drop all other capabilities; */
4771 /* Drop suid privileges (euid=ruid); */
4772 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4773 /* else: after pcap_open_live() in capture_loop_open_input() */
4774 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4776 /* XXX: For some Linux versions/distros with capabilities */
4777 /* a 'normal' process with any capabilities cannot be */
4778 /* 'killed' (signaled) from another (same uid) non-privileged */
4780 /* For example: If (non-suid) Wireshark forks a */
4781 /* child suid dumpcap which acts as described here (case 5), */
4782 /* Wireshark will be unable to kill (signal) the child */
4783 /* dumpcap process until the capabilities have been dropped */
4784 /* (after pcap_open_live()). */
4785 /* This behaviour will apparently be changed in the kernel */
4786 /* to allow the kill (signal) in this case. */
4787 /* See the following for details: */
4788 /* https://www.mail-archive.com/ [wrapped] */
4789 /* linux-security-module@vger.kernel.org/msg02913.html */
4791 /* It is therefore conceivable that if dumpcap somehow hangs */
4792 /* in pcap_open_live or before that wireshark will not */
4793 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4794 /* In this case, exiting wireshark will kill the child */
4795 /* dumpcap process. */
4797 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4798 /* capabilities; Using libcap. Note: capset cmd (which see) */
4799 /* used to assign capabilities to file. */
4801 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4802 /* else: after pcap_open_live() in capture_loop_open_input() */
4803 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4805 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4806 /* longer required (similar to capture). */
4808 /* ----------------------------------------------------------------- */
4810 init_process_policies();
4813 /* If 'started with special privileges' (and using libcap) */
4814 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4815 /* Set euid/egid = ruid/rgid to remove suid privileges */
4816 relinquish_privs_except_capture();
4819 /* Set the initial values in the capture options. This might be overwritten
4820 by the command line parameters. */
4821 capture_opts_init(&global_capture_opts);
4822 /* We always save to a file - if no file was specified, we save to a
4824 global_capture_opts.saving_to_file = TRUE;
4825 global_capture_opts.has_ring_num_files = TRUE;
4827 /* Pass on capture_child mode for capture_opts */
4828 global_capture_opts.capture_child = capture_child;
4830 /* Now get our args */
4831 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4833 case 'h': /* Print help and exit */
4834 printf("Dumpcap (Wireshark) %s\n"
4835 "Capture network packets and dump them into a pcapng or pcap file.\n"
4836 "See https://www.wireshark.org for more information.\n",
4837 get_ws_vcs_version_info());
4838 print_usage(stdout);
4841 case 'v': /* Show version and exit */
4842 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
4843 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
4844 show_version("Dumpcap (Wireshark)", comp_info_str, runtime_info_str);
4845 g_string_free(comp_info_str, TRUE);
4846 g_string_free(runtime_info_str, TRUE);
4849 /*** capture option specific ***/
4850 case 'a': /* autostop criteria */
4851 case 'b': /* Ringbuffer option */
4852 case 'c': /* Capture x packets */
4853 case 'f': /* capture filter */
4854 case 'g': /* enable group read access on file(s) */
4855 case 'i': /* Use interface x */
4856 case LONGOPT_SET_TSTAMP_TYPE: /* Set capture timestamp type */
4857 case 'n': /* Use pcapng format */
4858 case 'p': /* Don't capture in promiscuous mode */
4859 case 'P': /* Use pcap format */
4860 case 's': /* Set the snapshot (capture) length */
4861 case 'w': /* Write to capture file x */
4862 case 'y': /* Set the pcap data link type */
4863 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4864 #ifdef HAVE_PCAP_REMOTE
4865 case 'u': /* Use UDP for data transfer */
4866 case 'r': /* Capture own RPCAP traffic too */
4867 case 'A': /* Authentication */
4869 #ifdef HAVE_PCAP_SETSAMPLING
4870 case 'm': /* Sampling */
4872 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
4873 case 'B': /* Buffer size */
4875 #ifdef HAVE_PCAP_CREATE
4876 case 'I': /* Monitor mode */
4878 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4883 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4885 capture_child = TRUE;
4887 /* set output pipe to binary mode, to avoid ugly text conversions */
4888 _setmode(2, O_BINARY);
4890 * optarg = the control ID, aka the PPID, currently used for the
4893 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4894 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4895 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4896 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4898 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4899 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4900 "Signal pipe: Unable to open %s. Dead parent?",
4908 case 'q': /* Quiet */
4914 /*** all non capture option specific ***/
4915 case 'D': /* Print a list of capture devices and exit */
4916 if (!list_interfaces) {
4917 list_interfaces = TRUE;
4921 case 'L': /* Print list of link-layer types and exit */
4922 if (!(caps_queries & CAPS_QUERY_LINK_TYPES)) {
4923 caps_queries |= CAPS_QUERY_LINK_TYPES;
4927 case LONGOPT_LIST_TSTAMP_TYPES:
4928 caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
4930 #ifdef HAVE_BPF_IMAGE
4931 case 'd': /* Print BPF code for capture filter and exit */
4932 if (!print_bpf_code) {
4933 print_bpf_code = TRUE;
4938 case 'S': /* Print interface statistics once a second */
4939 if (!print_statistics) {
4940 print_statistics = TRUE;
4944 case 'k': /* Set wireless channel */
4947 set_chan_arg = optarg;
4950 cmdarg_err("Only one -k flag may be specified");
4954 case 'M': /* For -D, -L, and -S, print machine-readable output */
4955 machine_readable = TRUE;
4958 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4961 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4964 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4966 case '?': /* Bad flag - print usage message */
4975 /* user specified file name as regular command-line argument */
4976 /* XXX - use it as the capture file name (or something else)? */
4982 * Extra command line arguments were specified; complain.
4983 * XXX - interpret as capture filter, as tcpdump and tshark do?
4985 cmdarg_err("Invalid argument: %s", argv[0]);
4990 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4993 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4994 /* Use some default if the user hasn't specified some */
4995 /* XXX: Are these defaults good enough? */
4996 pcap_queue_byte_limit = 1000 * 1000;
4997 pcap_queue_packet_limit = 1000;
5000 print_usage(stderr);
5004 if (run_once_args > 1) {
5005 #ifdef HAVE_BPF_IMAGE
5006 cmdarg_err("Only one of -D, -L, -d, -k or -S may be supplied.");
5008 cmdarg_err("Only one of -D, -L, -k or -S may be supplied.");
5011 } else if (run_once_args == 1) {
5012 /* We're supposed to print some information, rather than
5013 to capture traffic; did they specify a ring buffer option? */
5014 if (global_capture_opts.multi_files_on) {
5015 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
5019 /* We're supposed to capture traffic; */
5021 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
5022 if (global_capture_opts.ifaces->len > 1) {
5024 global_capture_opts.use_pcapng = TRUE;
5027 if (global_capture_opts.capture_comment &&
5028 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
5029 /* XXX - for ringbuffer, should we apply the comment to each file? */
5030 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
5034 /* Was the ring buffer option specified and, if so, does it make sense? */
5035 if (global_capture_opts.multi_files_on) {
5036 /* Ring buffer works only under certain conditions:
5037 a) ring buffer does not work with temporary files;
5038 b) it makes no sense to enable the ring buffer if the maximum
5039 file size is set to "infinite". */
5040 if (global_capture_opts.save_file == NULL) {
5041 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
5042 global_capture_opts.multi_files_on = FALSE;
5044 if (!global_capture_opts.has_autostop_filesize &&
5045 !global_capture_opts.has_file_duration &&
5046 !global_capture_opts.has_file_interval) {
5047 cmdarg_err("Ring buffer requested, but no maximum capture file size, duration"
5048 "or interval were specified.");
5050 /* XXX - this must be redesigned as the conditions changed */
5051 global_capture_opts.multi_files_on = FALSE;
5054 if (global_capture_opts.has_file_duration && global_capture_opts.has_file_interval) {
5055 cmdarg_err("Ring buffer file duration and interval can't be used at the same time.");
5062 * "-D" requires no interface to be selected; it's supposed to list
5065 if (list_interfaces) {
5066 /* Get the list of interfaces */
5071 if_list = capture_interface_list(&err, &err_str, NULL);
5072 if (if_list == NULL) {
5075 * If we're being run by another program, just give them
5076 * an empty list of interfaces, don't report this as
5077 * an error; that lets them decide whether to report
5078 * this as an error or not.
5080 if (!machine_readable) {
5081 cmdarg_err("There are no interfaces on which a capture can be done");
5085 cmdarg_err("%s", err_str);
5091 if (machine_readable) /* tab-separated values to stdout */
5092 print_machine_readable_interfaces(if_list);
5094 capture_opts_print_interfaces(if_list);
5095 free_interface_list(if_list);
5100 * "-S" requires no interface to be selected; it gives statistics
5101 * for all interfaces.
5103 if (print_statistics) {
5104 status = print_statistics_loop(machine_readable);
5109 interface_options *interface_opts;
5111 if (global_capture_opts.ifaces->len != 1) {
5112 cmdarg_err("Need one interface");
5116 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
5117 status = set_80211_channel(interface_opts->name, set_chan_arg);
5122 * "-L", "-d", and capturing act on a particular interface, so we have to
5123 * have an interface; if none was specified, pick a default.
5125 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
5127 /* cmdarg_err() already called .... */
5132 /* Get the list of link-layer and/or timestamp types for the capture device. */
5133 if_capabilities_t *caps;
5134 cap_device_open_err err;
5138 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
5139 int if_caps_queries = caps_queries;
5140 interface_options *interface_opts;
5142 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, ii);
5144 caps = get_if_capabilities(interface_opts, &err, &err_str);
5146 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
5147 "%s", interface_opts->name, err_str,
5148 get_pcap_failure_secondary_error_message(err, err_str));
5152 if ((if_caps_queries & CAPS_QUERY_LINK_TYPES) && caps->data_link_types == NULL) {
5153 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts->name);
5155 } /* No timestamp types is no big deal. So we will just ignore it */
5157 if (interface_opts->monitor_mode)
5158 if_caps_queries |= CAPS_MONITOR_MODE;
5160 if (machine_readable) /* tab-separated values to stdout */
5161 /* XXX: We need to change the format and adapt consumers */
5162 print_machine_readable_if_capabilities(caps, if_caps_queries);
5164 /* XXX: We might want to print also the interface name */
5165 capture_opts_print_if_capabilities(caps, interface_opts->name, if_caps_queries);
5166 free_if_capabilities(caps);
5171 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
5172 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5173 interface_options *interface_opts;
5175 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5176 if (interface_opts->timestamp_type) {
5177 interface_opts->timestamp_type_id = pcap_tstamp_type_name_to_val(interface_opts->timestamp_type);
5178 if (interface_opts->timestamp_type_id < 0) {
5179 cmdarg_err("Invalid argument to option: --time-stamp-type=%s", interface_opts->timestamp_type);
5186 /* We're supposed to do a capture, or print the BPF code for a filter. */
5188 /* Let the user know what interfaces were chosen. */
5189 if (capture_child) {
5190 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5191 interface_options *interface_opts;
5193 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5194 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
5195 interface_opts->name);
5198 str = g_string_new("");
5200 if (global_capture_opts.ifaces->len < 2)
5202 if (global_capture_opts.ifaces->len < 4)
5205 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5206 interface_options *interface_opts;
5208 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5210 if (global_capture_opts.ifaces->len > 2) {
5211 g_string_append_printf(str, ",");
5213 g_string_append_printf(str, " ");
5214 if (j == global_capture_opts.ifaces->len - 1) {
5215 g_string_append_printf(str, "and ");
5218 g_string_append_printf(str, "'%s'", interface_opts->display_name);
5221 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
5223 fprintf(stderr, "Capturing on %s\n", str->str);
5224 g_string_free(str, TRUE);
5227 /* Process the snapshot length, as that affects the generated BPF code. */
5228 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
5230 #ifdef HAVE_BPF_IMAGE
5231 if (print_bpf_code) {
5232 show_filter_code(&global_capture_opts);
5237 /* We're supposed to do a capture. Process the ring buffer arguments. */
5238 capture_opts_trim_ring_num_files(&global_capture_opts);
5240 /* flush stderr prior to starting the main capture loop */
5243 /* Now start the capture. */
5244 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
5248 /* capture failed */
5251 return 0; /* never here, make compiler happy */
5256 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
5257 const char *message, gpointer user_data _U_)
5264 /* ignore log message, if log_level isn't interesting */
5265 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5266 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
5271 switch(log_level & G_LOG_LEVEL_MASK) {
5272 case G_LOG_LEVEL_ERROR:
5275 case G_LOG_LEVEL_CRITICAL:
5278 case G_LOG_LEVEL_WARNING:
5281 case G_LOG_LEVEL_MESSAGE:
5284 case G_LOG_LEVEL_INFO:
5287 case G_LOG_LEVEL_DEBUG:
5291 fprintf(stderr, "unknown log_level %d\n", log_level);
5293 g_assert_not_reached();
5296 /* Generate the output message */
5297 if (log_level & G_LOG_LEVEL_MESSAGE) {
5298 /* normal user messages without additional infos */
5299 msg = g_strdup_printf("%s\n", message);
5301 /* create a "timestamp" */
5303 today = localtime(&curr);
5305 /* info/debug messages with additional infos */
5307 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
5308 today->tm_hour, today->tm_min, today->tm_sec,
5309 log_domain != NULL ? log_domain : "",
5312 msg = g_strdup_printf("Time not representable %8s %s %s\n",
5313 log_domain != NULL ? log_domain : "",
5317 /* DEBUG & INFO msgs (if we're debugging today) */
5318 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
5319 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5320 #ifdef DEBUG_DUMPCAP
5321 fprintf(stderr, "%s", msg);
5324 #ifdef DEBUG_CHILD_DUMPCAP
5325 fprintf(debug_log, "%s", msg);
5333 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
5334 /* to parent especially formatted if dumpcap running as child. */
5335 if (capture_child) {
5336 sync_pipe_errmsg_to_parent(2, msg, "");
5338 fprintf(stderr, "%s", msg);
5345 /****************************************************************************************************************/
5346 /* indication report routines */
5350 report_packet_count(unsigned int packet_count)
5352 char tmp[SP_DECISIZE+1+1];
5353 static unsigned int count = 0;
5355 if (capture_child) {
5356 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
5357 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
5358 pipe_write_block(2, SP_PACKET_COUNT, tmp);
5360 count += packet_count;
5361 fprintf(stderr, "\rPackets: %u ", count);
5362 /* stderr could be line buffered */
5368 report_new_capture_file(const char *filename)
5370 if (capture_child) {
5371 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
5372 pipe_write_block(2, SP_FILE, filename);
5376 * Prevent a SIGINFO handler from writing to the standard error
5377 * while we're doing so; instead, have it just set a flag telling
5378 * us to print that information when we're done.
5381 #endif /* SIGINFO */
5382 fprintf(stderr, "File: %s\n", filename);
5383 /* stderr could be line buffered */
5388 * Allow SIGINFO handlers to write.
5393 * If a SIGINFO handler asked us to write out capture counts, do so.
5396 report_counts_for_siginfo();
5397 #endif /* SIGINFO */
5402 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
5404 interface_options *interface_opts;
5405 char tmp[MSG_MAX_LENGTH+1+6];
5407 if (i < capture_opts->ifaces->len) {
5408 if (capture_child) {
5409 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
5410 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
5411 pipe_write_block(2, SP_BAD_FILTER, tmp);
5414 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5415 * the error message below.
5417 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
5419 "Invalid capture filter \"%s\" for interface '%s'.\n"
5421 "That string isn't a valid capture filter (%s).\n"
5422 "See the User's Guide for a description of the capture filter syntax.",
5423 interface_opts->cfilter, interface_opts->name, errmsg);
5429 report_capture_error(const char *error_msg, const char *secondary_error_msg)
5431 if (capture_child) {
5432 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5433 "Primary Error: %s", error_msg);
5434 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5435 "Secondary Error: %s", secondary_error_msg);
5436 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5438 cmdarg_err("%s", error_msg);
5439 if (secondary_error_msg[0] != '\0')
5440 cmdarg_err_cont("%s", secondary_error_msg);
5445 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
5447 char tmp[SP_DECISIZE+1+1];
5448 guint32 total_drops = pcap_drops + drops + flushed;
5450 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
5452 if (capture_child) {
5453 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5454 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
5455 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
5456 /* XXX: Need to provide interface id, changes to consumers required. */
5457 pipe_write_block(2, SP_DROPS, tmp);
5460 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
5461 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
5462 received ? 100.0 * received / (received + total_drops) : 0.0);
5463 /* stderr could be line buffered */
5469 /************************************************************************************************/
5470 /* signal_pipe handling */
5475 signal_pipe_check_running(void)
5477 /* any news from our parent? -> just stop the capture */
5481 /* if we are running standalone, no check required */
5482 if (!capture_child) {
5486 if (!sig_pipe_name || !sig_pipe_handle) {
5487 /* This shouldn't happen */
5488 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5489 "Signal pipe: No name or handle");
5494 * XXX - We should have the process ID of the parent (from the "-Z" flag)
5495 * at this point. Should we check to see if the parent is still alive,
5496 * e.g. by using OpenProcess?
5499 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5501 if (!result || avail > 0) {
5502 /* peek failed or some bytes really available */
5503 /* (if not piping from stdin this would fail) */
5504 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5505 "Signal pipe: Stop capture: %s", sig_pipe_name);
5506 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5507 "Signal pipe: %s (%p) result: %u avail: %lu", sig_pipe_name,
5508 sig_pipe_handle, result, avail);
5511 /* pipe ok and no bytes available */
5518 * Editor modelines - https://www.wireshark.org/tools/modelines.html
5523 * indent-tabs-mode: nil
5526 * vi: set shiftwidth=4 tabstop=8 expandtab:
5527 * :indentSize=4:tabSize=8:noTabs=true: