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 "wsutil/tempfile.h"
87 #include "wsutil/file_util.h"
88 #include "wsutil/cpu_info.h"
89 #include "wsutil/os_version_info.h"
90 #include "wsutil/str_util.h"
91 #include "wsutil/inet_addr.h"
92 #include "wsutil/time_util.h"
94 #include "caputils/ws80211_utils.h"
99 * Get information about libpcap format from "wiretap/libpcap.h".
100 * Get information about pcapng format from "wiretap/pcapng_module.h".
101 * XXX - can we just use pcap_open_offline() to read the pipe?
103 #include "wiretap/libpcap.h"
104 #include "wiretap/pcapng_module.h"
105 #include "wiretap/pcapng.h"
107 /**#define DEBUG_DUMPCAP**/
108 /**#define DEBUG_CHILD_DUMPCAP**/
112 #include <conio.h> /* _getch() */
116 #ifdef DEBUG_CHILD_DUMPCAP
117 FILE *debug_log; /* for logging debug messages to */
118 /* a file if DEBUG_CHILD_DUMPCAP */
122 static GAsyncQueue *pcap_queue;
123 static gint64 pcap_queue_bytes;
124 static gint64 pcap_queue_packets;
125 static gint64 pcap_queue_byte_limit = 0;
126 static gint64 pcap_queue_packet_limit = 0;
128 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
130 static gchar *sig_pipe_name = NULL;
131 static HANDLE sig_pipe_handle = NULL;
132 static gboolean signal_pipe_check_running(void);
136 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
137 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
140 /** Stop a low-level capture (stops the capture child). */
141 static void capture_loop_stop(void);
142 /** Close a pipe, or socket if \a from_socket is TRUE */
143 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
145 #if !defined (__linux__)
146 #ifndef HAVE_PCAP_BREAKLOOP
148 * We don't have pcap_breakloop(), which is the only way to ensure that
149 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
150 * won't, if the call to read the next packet or batch of packets is
151 * is interrupted by a signal on UN*X, just go back and try again to
154 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
155 * the signal handler, set a flag to stop capturing; however, without
156 * a guarantee of that sort, we can't guarantee that we'll stop capturing
157 * if the read will be retried and won't time out if no packets arrive.
159 * Therefore, on at least some platforms, we work around the lack of
160 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
161 * to wait for packets to arrive, so that we're probably going to be
162 * blocked in the select() when the signal arrives, and can just bail
163 * out of the loop at that point.
165 * However, we don't want to do that on BSD (because "select()" doesn't work
166 * correctly on BPF devices on at least some releases of some flavors of
167 * BSD), and we don't want to do it on Windows (because "select()" is
168 * something for sockets, not for arbitrary handles). (Note that "Windows"
169 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
170 * using WinPcap, not a UNIX libpcap.)
172 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
173 * on BSD times out even if no packets have arrived, so we'll eventually
174 * exit pcap_dispatch() with an indication that no packets have arrived,
175 * and will break out of the capture loop at that point.
177 * On Windows, we can't send a SIGINT to stop capturing, so none of this
178 * applies in any case.
180 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
181 * want to include it if it's not present on this platform, however.
183 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
184 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
186 # define MUST_DO_SELECT
187 # endif /* avoid select */
188 #endif /* HAVE_PCAP_BREAKLOOP */
190 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
191 * in pcap_dispatch(); on the other hand, select() works just fine there.
192 * Hence we use a select for that come what may.
194 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
195 * internally, and, with TPACKET_V3, once that's supported, it'll
196 * support timeouts, at least as I understand the way the code works.
198 #define MUST_DO_SELECT
201 /** init the capture filter */
204 INITFILTER_BAD_FILTER,
205 INITFILTER_OTHER_ERROR
206 } initfilter_status_t;
209 STATE_EXPECT_REC_HDR,
222 typedef struct _pcap_pipe_info {
223 gboolean byte_swapped; /**< TRUE if data in the pipe is byte swapped. */
224 struct pcap_hdr hdr; /**< Pcap header when capturing from a pipe */
225 struct pcaprec_modified_hdr rechdr; /**< Pcap record header when capturing from a pipe */
228 typedef struct _pcapng_pipe_info {
229 struct pcapng_block_header_s bh; /**< Pcapng general block header when capturing from a pipe */
230 struct pcapng_section_header_block_s shb; /**< Pcapng section header when capturing from a pipe */
231 GList *saved_blocks; /**< Pcapng block list of SHB and IDBs for multi_file_on */
232 } pcapng_pipe_info_t;
234 struct _loop_data; /* forward declaration so we can use it in the cap_pipe_dispatch function pointer */
237 * A source of packets from which we're capturing.
239 typedef struct _capture_src {
244 #ifdef MUST_DO_SELECT
245 int pcap_fd; /**< pcap file descriptor */
252 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
253 /**< capture pipe (unix only "input file") */
254 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
255 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
256 gboolean from_pcapng; /**< TRUE if we're capturing from pcapng format */
258 pcap_pipe_info_t pcap; /**< Pcap info when capturing from a pipe */
259 pcapng_pipe_info_t pcapng; /**< Pcapng info when capturing from a pipe */
262 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
264 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
265 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
266 char * cap_pipe_databuf; /**< Pointer to the data buffer we've allocated */
267 size_t cap_pipe_databuf_size; /**< Current size of the data buffer */
268 guint cap_pipe_max_pkt_size; /**< Maximum packet size allowed */
270 char * cap_pipe_buf; /**< Pointer to the buffer we read into */
271 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
272 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
274 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
275 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
277 int (*cap_pipe_dispatch)(struct _loop_data *, struct _capture_src *, char *, int);
278 cap_pipe_state_t cap_pipe_state;
279 cap_pipe_err_t cap_pipe_err;
282 GMutex *cap_pipe_read_mtx;
283 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
288 * Global capture loop state.
290 typedef struct _loop_data {
292 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
293 int err; /**< if non-zero, error seen while capturing */
294 gint packets_captured; /**< Number of packets we have already captured */
295 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
297 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
299 GArray *pcaps; /**< Array of capture_src's on which we're capturing */
303 guint64 bytes_written; /**< Bytes written for the current file. */
304 /* autostop conditions */
305 int packets_written; /**< Packets written for the current file. */
307 /* ring buffer conditions */
308 GTimer *file_duration_timer;
309 time_t next_interval_time;
313 typedef struct _pcap_queue_element {
314 capture_src *pcap_src;
316 struct pcap_pkthdr phdr;
317 struct pcapng_block_header_s bh;
320 } pcap_queue_element;
323 * Standard secondary message for unexpected errors.
325 static const char please_report[] =
326 "Please report this to the Wireshark developers.\n"
327 "https://bugs.wireshark.org/\n"
328 "(This is not a crash; please do not report it as such.)";
331 * This needs to be static, so that the SIGINT handler can clear the "go"
334 static loop_data global_ld;
337 * Timeout, in milliseconds, for reads from the stream of captured packets
338 * from a capture device.
340 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
341 * 64-bit applications, with sub-second timeouts not to work. The bug is
342 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
344 #if defined(__APPLE__) && defined(__LP64__)
345 static gboolean need_timeout_workaround;
347 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
349 #define CAP_READ_TIMEOUT 250
353 * Timeout, in microseconds, for reads from the stream of captured packets
354 * from a pipe. Pipes don't have the same problem that BPF devices do
355 * in Mac OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
356 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
357 * of the offending versions of Snow Leopard.
359 * On Windows this value is converted to milliseconds and passed to
360 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
361 * will return immediately.
364 #define PIPE_READ_TIMEOUT 100000
366 #define PIPE_READ_TIMEOUT 250000
369 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
372 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
373 const char *message, gpointer user_data _U_);
375 /* capture related options */
376 static capture_options global_capture_opts;
377 static gboolean quiet = FALSE;
378 static gboolean use_threads = FALSE;
379 static guint64 start_time;
381 static void capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
383 static void capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
385 static void capture_loop_write_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, const u_char *pd);
386 static void capture_loop_queue_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, const u_char *pd);
387 static void capture_loop_get_errmsg(char *errmsg, size_t errmsglen,
388 char *secondary_errmsg,
389 size_t secondary_errmsglen,
390 const char *fname, int err,
393 static void WS_NORETURN exit_main(int err);
395 static void report_new_capture_file(const char *filename);
396 static void report_packet_count(unsigned int packet_count);
397 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
398 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
399 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
401 #define MSG_MAX_LENGTH 4096
404 print_usage(FILE *output)
406 fprintf(output, "\nUsage: dumpcap [options] ...\n");
407 fprintf(output, "\n");
408 fprintf(output, "Capture interface:\n");
409 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
410 " or for remote capturing, use one of these formats:\n"
411 " rpcap://<host>/<interface>\n"
412 " TCP@<host>:<port>\n");
413 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
414 #ifdef HAVE_PCAP_CREATE
415 fprintf(output, " -s <snaplen> packet snapshot length (def: appropriate maximum)\n");
417 fprintf(output, " -s <snaplen> packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
419 fprintf(output, " -p don't capture in promiscuous mode\n");
420 #ifdef HAVE_PCAP_CREATE
421 fprintf(output, " -I capture in monitor mode, if available\n");
423 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
424 fprintf(output, " -B <buffer size> size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
426 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
427 fprintf(output, " --time-stamp-type <type> timestamp method for interface\n");
428 fprintf(output, " -D print list of interfaces and exit\n");
429 fprintf(output, " -L print list of link-layer types of iface and exit\n");
430 fprintf(output, " --list-time-stamp-types print list of timestamp types for iface and exit\n");
431 #ifdef HAVE_BPF_IMAGE
432 fprintf(output, " -d print generated BPF code for capture filter\n");
434 fprintf(output, " -k set channel on wifi interface:\n"
435 " <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
436 fprintf(output, " -S print statistics for each interface once per second\n");
437 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
438 fprintf(output, "\n");
439 #ifdef HAVE_PCAP_REMOTE
440 fprintf(output, "RPCAP options:\n");
441 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
442 fprintf(output, " -u use UDP for RPCAP data transfer\n");
443 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
444 #ifdef HAVE_PCAP_SETSAMPLING
445 fprintf(output, " -m <sampling type> use packet sampling\n");
446 fprintf(output, " count:NUM - capture one packet of every NUM\n");
447 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
450 fprintf(output, "Stop conditions:\n");
451 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
452 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
453 fprintf(output, " filesize:NUM - stop this file after NUM kB\n");
454 fprintf(output, " files:NUM - stop after NUM files\n");
455 fprintf(output, " packets:NUM - stop after NUM packets\n");
456 /*fprintf(output, "\n");*/
457 fprintf(output, "Output (files):\n");
458 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
459 fprintf(output, " -g enable group read access on the output file(s)\n");
460 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
461 fprintf(output, " interval:NUM - create time intervals of NUM secs\n");
462 fprintf(output, " filesize:NUM - switch to next file after NUM kB\n");
463 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
464 fprintf(output, " packets:NUM - ringbuffer: replace after NUM packets\n");
465 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
466 fprintf(output, " -P use libpcap format instead of pcapng\n");
467 fprintf(output, " --capture-comment <comment>\n");
468 fprintf(output, " add a capture comment to the output file\n");
469 fprintf(output, " (only for pcapng)\n");
470 fprintf(output, "\n");
471 fprintf(output, "Miscellaneous:\n");
472 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
473 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
474 fprintf(output, " within dumpcap\n");
475 fprintf(output, " -t use a separate thread per interface\n");
476 fprintf(output, " -q don't report packet capture counts\n");
477 fprintf(output, " -v print version information and exit\n");
478 fprintf(output, " -h display this help and exit\n");
479 fprintf(output, "\n");
481 fprintf(output, "Dumpcap can benefit from an enabled BPF JIT compiler if available.\n");
482 fprintf(output, "You might want to enable it by executing:\n");
483 fprintf(output, " \"echo 1 > /proc/sys/net/core/bpf_jit_enable\"\n");
484 fprintf(output, "Note that this can make your system less secure!\n");
485 fprintf(output, "\n");
487 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
488 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
489 fprintf(output, "\n");
490 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
494 * Report an error in command-line arguments.
495 * If we're a capture child, send a message back to the parent, otherwise
499 dumpcap_cmdarg_err(const char *fmt, va_list ap)
503 /* Generate a 'special format' message back to parent */
504 msg = g_strdup_vprintf(fmt, ap);
505 sync_pipe_errmsg_to_parent(2, msg, "");
508 fprintf(stderr, "dumpcap: ");
509 vfprintf(stderr, fmt, ap);
510 fprintf(stderr, "\n");
515 * Report additional information for an error in command-line arguments.
516 * If we're a capture child, send a message back to the parent, otherwise
520 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
524 msg = g_strdup_vprintf(fmt, ap);
525 sync_pipe_errmsg_to_parent(2, msg, "");
528 vfprintf(stderr, fmt, ap);
529 fprintf(stderr, "\n");
535 #if 0 /* Set to enable capability debugging */
536 /* see 'man cap_to_text()' for explanation of output */
537 /* '=' means 'all= ' ie: no capabilities */
538 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
540 print_caps(const char *pfx) {
541 cap_t caps = cap_get_proc();
542 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
543 "%s: EUID: %d Capabilities: %s", pfx,
544 geteuid(), cap_to_text(caps, NULL));
548 print_caps(const char *pfx _U_) {
553 relinquish_all_capabilities(void)
555 /* Drop any and all capabilities this process may have. */
556 /* Allowed whether or not process has any privileges. */
557 cap_t caps = cap_init(); /* all capabilities initialized to off */
558 print_caps("Pre-clear");
559 if (cap_set_proc(caps)) {
560 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
562 print_caps("Post-clear");
568 * Platform-dependent suggestions for fixing permissions.
570 #if defined(__linux__)
571 #define PLATFORM_PERMISSIONS_SUGGESTION \
573 "On Debian and Debian derivatives such as Ubuntu, if you have " \
574 "installed Wireshark from a package, try running" \
576 " sudo dpkg-reconfigure wireshark-common" \
578 "selecting \"<Yes>\" in response to the question" \
580 " Should non-superusers be able to capture packets?" \
582 "adding yourself to the \"wireshark\" group by running" \
584 " sudo usermod -a -G wireshark {your username}" \
586 "and then logging out and logging back in again."
587 #elif defined(__APPLE__)
588 #define PLATFORM_PERMISSIONS_SUGGESTION \
590 "If you installed Wireshark using the package from wireshark.org, "\
591 "Try re-installing it and checking the box for the \"Set capture " \
592 "permissions on startup\" item."
594 #define PLATFORM_PERMISSIONS_SUGGESTION
598 get_pcap_failure_secondary_error_message(cap_device_open_err open_err,
599 const char *open_err_str
607 * On Windows, first make sure they *have* WinPcap installed.
611 "In order to capture packets, WinPcap must be installed; see\n"
613 " https://www.winpcap.org/\n"
615 "for a downloadable version of WinPcap and for instructions on how to install\n"
621 * Now deal with ancient versions of libpcap that, on HP-UX, don't
622 * correctly figure out how to open a device given the device name.
625 /* HP-UX-specific suggestion. */
626 static const char ppamsg[] = "can't find PPA for ";
628 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0) {
630 "You are running (T)Wireshark with a version of the libpcap library\n"
631 "that doesn't handle HP-UX network devices well; this means that\n"
632 "(T)Wireshark may not be able to capture packets.\n"
634 "To fix this, you should install libpcap 0.6.2, or a later version\n"
635 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
636 "packaged binary form from the Software Porting And Archive Centre\n"
637 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
638 "at the URL lists a number of mirror sites.";
643 * OK, now just return a largely platform-independent error that might
644 * have platform-specific suggestions at the end (for example, suggestions
645 * for how to get permission to capture).
647 if (open_err == CAP_DEVICE_OPEN_ERR_GENERIC) {
649 * We don't know what kind of error it is, so throw all the
650 * suggestions at the user.
653 "Please check to make sure you have sufficient permissions, and that you have "
654 "the proper interface or pipe specified."
655 PLATFORM_PERMISSIONS_SUGGESTION;
656 } else if (open_err == CAP_DEVICE_OPEN_ERR_PERMISSIONS) {
658 * This is a permissions error, so no need to specify any other
662 "Please check to make sure you have sufficient permissions."
663 PLATFORM_PERMISSIONS_SUGGESTION;
666 * This is not a permissons error, so no need to suggest
667 * checking permissions.
670 "Please check that you have the proper interface or pipe specified.";
675 get_capture_device_open_failure_messages(cap_device_open_err open_err,
676 const char *open_err_str,
678 char *errmsg, size_t errmsg_len,
679 char *secondary_errmsg,
680 size_t secondary_errmsg_len)
682 g_snprintf(errmsg, (gulong) errmsg_len,
683 "The capture session could not be initiated on interface '%s' (%s).",
684 iface, open_err_str);
685 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, "%s",
686 get_pcap_failure_secondary_error_message(open_err, open_err_str));
690 compile_capture_filter(const char *iface, pcap_t *pcap_h,
691 struct bpf_program *fcode, const char *cfilter)
693 bpf_u_int32 netnum, netmask;
694 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
696 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
698 * Well, we can't get the netmask for this interface; it's used
699 * only for filters that check for broadcast IP addresses, so
700 * we just punt and use 0. It might be nice to warn the user,
701 * but that's a pain in a GUI application, as it'd involve popping
702 * up a message box, and it's not clear how often this would make
703 * a difference (only filters that check for IP broadcast addresses
707 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
712 * Sigh. Older versions of libpcap don't properly declare the
713 * third argument to pcap_compile() as a const pointer. Cast
717 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
723 #ifdef HAVE_BPF_IMAGE
725 show_filter_code(capture_options *capture_opts)
727 interface_options *interface_opts;
729 cap_device_open_err open_err;
730 gchar open_err_str[PCAP_ERRBUF_SIZE];
731 char errmsg[MSG_MAX_LENGTH+1];
732 char secondary_errmsg[MSG_MAX_LENGTH+1];
733 struct bpf_program fcode;
734 struct bpf_insn *insn;
738 for (j = 0; j < capture_opts->ifaces->len; j++) {
739 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, j);
740 pcap_h = open_capture_device(capture_opts, interface_opts,
741 CAP_READ_TIMEOUT, &open_err, &open_err_str);
742 if (pcap_h == NULL) {
743 /* Open failed; get messages */
744 get_capture_device_open_failure_messages(open_err, open_err_str,
745 interface_opts->name,
746 errmsg, sizeof errmsg,
748 sizeof secondary_errmsg);
749 /* And report them */
750 report_capture_error(errmsg, secondary_errmsg);
754 /* Set the link-layer type. */
755 if (!set_pcap_datalink(pcap_h, interface_opts->linktype, interface_opts->name,
756 errmsg, sizeof errmsg,
757 secondary_errmsg, sizeof secondary_errmsg)) {
759 report_capture_error(errmsg, secondary_errmsg);
763 /* OK, try to compile the capture filter. */
764 if (!compile_capture_filter(interface_opts->name, pcap_h, &fcode,
765 interface_opts->cfilter)) {
767 report_cfilter_error(capture_opts, j, errmsg);
772 /* Now print the filter code. */
773 insn = fcode.bf_insns;
775 for (i = 0; i < fcode.bf_len; insn++, i++)
776 printf("%s\n", bpf_image(insn, i));
778 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
779 /* to remove any suid privileges. */
780 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
781 /* (euid/egid have already previously been set to ruid/rgid. */
782 /* (See comment in main() for details) */
784 relinquish_special_privs_perm();
786 relinquish_all_capabilities();
789 /* Let our parent know we succeeded. */
790 pipe_write_block(2, SP_SUCCESS, NULL);
797 * capture_interface_list() is expected to do the right thing to get
798 * a list of interfaces.
800 * In most of the programs in the Wireshark suite, "the right thing"
801 * is to run dumpcap and ask it for the list, because dumpcap may
802 * be the only program in the suite with enough privileges to get
805 * In dumpcap itself, however, we obviously can't run dumpcap to
806 * ask for the list. Therefore, our capture_interface_list() should
807 * just call get_interface_list().
810 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
812 return get_interface_list(err, err_str);
816 * Output a machine readable list of the interfaces
817 * This list is retrieved by the sync_interface_list_open() function
818 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
821 print_machine_readable_interfaces(GList *if_list)
828 char addr_str[WS_INET6_ADDRSTRLEN];
831 /* Let our parent know we succeeded. */
832 pipe_write_block(2, SP_SUCCESS, NULL);
835 i = 1; /* Interface id number */
836 for (if_entry = g_list_first(if_list); if_entry != NULL;
837 if_entry = g_list_next(if_entry)) {
838 if_info = (if_info_t *)if_entry->data;
839 printf("%d. %s\t", i++, if_info->name);
842 * Print the contents of the if_entry struct in a parseable format.
843 * Each if_entry element is tab-separated. Addresses are comma-
846 /* XXX - Make sure our description doesn't contain a tab */
847 if (if_info->vendor_description != NULL)
848 printf("%s\t", if_info->vendor_description);
852 /* XXX - Make sure our friendly name doesn't contain a tab */
853 if (if_info->friendly_name != NULL)
854 printf("%s\t", if_info->friendly_name);
858 printf("%i\t", if_info->type);
860 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
861 addr = g_slist_next(addr)) {
862 if (addr != g_slist_nth(if_info->addrs, 0))
865 if_addr = (if_addr_t *)addr->data;
866 switch(if_addr->ifat_type) {
868 printf("%s", ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str, sizeof(addr_str)));
871 printf("%s", ws_inet_ntop6(&if_addr->addr.ip6_addr, addr_str, sizeof(addr_str)));
874 printf("<type unknown %i>", if_addr->ifat_type);
878 if (if_info->loopback)
879 printf("\tloopback");
882 printf("\t%s", if_info->extcap);
888 * If you change the machine-readable output format of this function,
889 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
892 print_machine_readable_if_capabilities(if_capabilities_t *caps, int queries)
894 GList *lt_entry, *ts_entry;
895 const gchar *desc_str;
898 /* Let our parent know we succeeded. */
899 pipe_write_block(2, SP_SUCCESS, NULL);
902 if (queries & CAPS_QUERY_LINK_TYPES) {
903 if (caps->can_set_rfmon)
907 for (lt_entry = caps->data_link_types; lt_entry != NULL;
908 lt_entry = g_list_next(lt_entry)) {
909 data_link_info_t *data_link_info = (data_link_info_t *)lt_entry->data;
910 if (data_link_info->description != NULL)
911 desc_str = data_link_info->description;
913 desc_str = "(not supported)";
914 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
919 if (queries & CAPS_QUERY_TIMESTAMP_TYPES) {
920 for (ts_entry = caps->timestamp_types; ts_entry != NULL;
921 ts_entry = g_list_next(ts_entry)) {
922 timestamp_info_t *timestamp = (timestamp_info_t *)ts_entry->data;
923 if (timestamp->description != NULL)
924 desc_str = timestamp->description;
927 printf("%s\t%s\n", timestamp->name, desc_str);
937 /* Print the number of packets captured for each interface until we're killed. */
939 print_statistics_loop(gboolean machine_readable)
941 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
947 char errbuf[PCAP_ERRBUF_SIZE];
950 if_list = get_interface_list(&err, &err_str);
951 if (if_list == NULL) {
953 cmdarg_err("There are no interfaces on which a capture can be done");
955 cmdarg_err("%s", err_str);
961 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
962 if_info = (if_info_t *)if_entry->data;
965 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
966 * connections. We avoid collecting stats on them.
968 if (!strncmp(if_info->name, "nf", 2)) {
969 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
975 #ifdef HAVE_PCAP_OPEN
976 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
978 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
982 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
983 if_stat->name = g_strdup(if_info->name);
985 stat_list = g_list_append(stat_list, if_stat);
990 cmdarg_err("There are no interfaces on which a capture can be done");
995 /* Let our parent know we succeeded. */
996 pipe_write_block(2, SP_SUCCESS, NULL);
999 if (!machine_readable) {
1000 printf("%-15s %10s %10s\n", "Interface", "Received",
1004 global_ld.go = TRUE;
1005 while (global_ld.go) {
1006 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1007 if_stat = (if_stat_t *)stat_entry->data;
1008 pcap_stats(if_stat->pch, &ps);
1010 if (!machine_readable) {
1011 printf("%-15s %10u %10u\n", if_stat->name,
1012 ps.ps_recv, ps.ps_drop);
1014 printf("%s\t%u\t%u\n", if_stat->name,
1015 ps.ps_recv, ps.ps_drop);
1020 /* If we have a dummy signal pipe check it */
1021 if (!signal_pipe_check_running()) {
1022 global_ld.go = FALSE;
1030 /* XXX - Not reached. Should we look for 'q' in stdin? */
1031 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1032 if_stat = (if_stat_t *)stat_entry->data;
1033 pcap_close(if_stat->pch);
1034 g_free(if_stat->name);
1037 g_list_free(stat_list);
1038 free_interface_list(if_list);
1046 capture_cleanup_handler(DWORD dwCtrlType)
1048 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1049 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1050 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1051 like SIGTERM at least when the machine's shutting down.
1053 For now, if we're running as a command rather than a capture child,
1054 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1055 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1056 in that way on UN*X.
1058 If we're not running as a capture child, we might be running as
1059 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1060 user logs out. (XXX - can we explicitly check whether we're
1061 running as a service?) */
1063 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1064 "Console: Control signal");
1065 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1066 "Console: Control signal, CtrlType: %lu", dwCtrlType);
1068 /* Keep capture running if we're a service and a user logs off */
1069 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1070 capture_loop_stop();
1078 capture_cleanup_handler(int signum _U_)
1080 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1081 SIGTERM. We assume that if the user wanted it to keep running
1082 after they logged out, they'd have nohupped it. */
1084 /* Note: don't call g_log() in the signal handler: if we happened to be in
1085 * g_log() in process context when the signal came in, g_log will detect
1086 * the "recursion" and abort.
1089 capture_loop_stop();
1095 report_capture_count(gboolean reportit)
1097 /* Don't print this if we're a capture child. */
1098 if (!capture_child && reportit) {
1099 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packets_captured);
1100 /* stderr could be line buffered */
1108 report_counts_for_siginfo(void)
1110 report_capture_count(quiet);
1111 infoprint = FALSE; /* we just reported it */
1115 report_counts_siginfo(int signum _U_)
1117 int sav_errno = errno;
1119 /* If we've been told to delay printing, just set a flag asking
1120 that we print counts (if we're supposed to), otherwise print
1121 the count of packets captured (if we're supposed to). */
1125 report_counts_for_siginfo();
1128 #endif /* SIGINFO */
1131 exit_main(int status)
1134 /* Shutdown windows sockets */
1137 /* can be helpful for debugging */
1138 #ifdef DEBUG_DUMPCAP
1139 printf("Press any key\n");
1145 capture_opts_cleanup(&global_capture_opts);
1151 * If we were linked with libcap (not related to libpcap), make sure we have
1152 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1153 * (See comment in main() for details)
1156 relinquish_privs_except_capture(void)
1158 /* If 'started_with_special_privs' (ie: suid) then enable for
1159 * ourself the NET_ADMIN and NET_RAW capabilities and then
1160 * drop our suid privileges.
1162 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1163 * stuff we don't need (and shouldn't have).
1164 * CAP_NET_RAW: Packet capture (raw sockets).
1167 if (started_with_special_privs()) {
1168 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1169 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1171 cap_t caps = cap_init(); /* all capabilities initialized to off */
1173 print_caps("Pre drop, pre set");
1175 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1176 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1179 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1180 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1182 if (cap_set_proc(caps)) {
1183 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1185 print_caps("Pre drop, post set");
1187 relinquish_special_privs_perm();
1189 print_caps("Post drop, pre set");
1190 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1191 if (cap_set_proc(caps)) {
1192 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1194 print_caps("Post drop, post set");
1200 #endif /* HAVE_LIBCAP */
1202 /* Take care of byte order in the libpcap headers read from pipes.
1203 * (function taken from wiretap/libpcap.c) */
1205 cap_pipe_adjust_pcap_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1208 /* Byte-swap the record header fields. */
1209 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1210 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1211 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1212 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1215 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1216 swapped, in order to match the BPF header layout.
1218 Unfortunately, some files were, according to a comment in the "libpcap"
1219 source, written with version 2.3 in their headers but without the
1220 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1221 would make no sense - we assume that we need to swap them. */
1222 if (hdr->version_major == 2 &&
1223 (hdr->version_minor < 3 ||
1224 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1227 temp = rechdr->orig_len;
1228 rechdr->orig_len = rechdr->incl_len;
1229 rechdr->incl_len = temp;
1233 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1237 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1241 return recv(pipe_fd, buf, (int)sz, 0);
1246 return ws_read(pipe_fd, buf, sz);
1252 * Thread function that reads from a pipe and pushes the data
1253 * to the main application thread.
1256 * XXX Right now we use async queues for basic signaling. The main thread
1257 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1258 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1259 * Iff the read is successful cap_pipe_read pushes an item onto
1260 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1261 * the queues themselves (yet).
1263 * We might want to move some of the cap_pipe_dispatch logic here so that
1264 * we can let cap_thread_read run independently, queuing up multiple reads
1265 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1267 static void *cap_thread_read(void *arg)
1269 capture_src *pcap_src;
1272 DWORD last_err, bytes_read;
1277 pcap_src = (capture_src *)arg;
1278 while (pcap_src->cap_pipe_err == PIPOK) {
1279 g_async_queue_pop(pcap_src->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1280 g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1282 while (bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1283 if ((pcap_src->from_cap_socket)
1290 b = cap_pipe_read(pcap_src->cap_pipe_fd, pcap_src->cap_pipe_buf+bytes_read,
1291 pcap_src->cap_pipe_bytes_to_read - bytes_read, pcap_src->from_cap_socket);
1294 pcap_src->cap_pipe_err = PIPEOF;
1298 pcap_src->cap_pipe_err = PIPERR;
1309 /* If we try to use read() on a named pipe on Windows with partial
1310 * data it appears to return EOF.
1313 res = ReadFile(pcap_src->cap_pipe_h, pcap_src->cap_pipe_buf+bytes_read,
1314 pcap_src->cap_pipe_bytes_to_read - bytes_read,
1319 last_err = GetLastError();
1320 if (last_err == ERROR_MORE_DATA) {
1322 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1323 pcap_src->cap_pipe_err = PIPEOF;
1327 pcap_src->cap_pipe_err = PIPERR;
1330 } else if (b == 0 && pcap_src->cap_pipe_bytes_to_read > 0) {
1331 pcap_src->cap_pipe_err = PIPEOF;
1338 pcap_src->cap_pipe_bytes_read = bytes_read;
1339 if (pcap_src->cap_pipe_bytes_read >= pcap_src->cap_pipe_bytes_to_read) {
1340 g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1342 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1348 /* Provide select() functionality for a single file descriptor
1349 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1351 * Returns the same values as select.
1354 cap_pipe_select(int pipe_fd)
1357 struct timeval timeout;
1360 FD_SET(pipe_fd, &rfds);
1362 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1363 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1365 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1368 #define DEF_TCP_PORT 19000
1371 cap_open_socket(char *pipename, capture_src *pcap_src, char *errmsg, int errmsgl)
1373 char *sockname = pipename + 4;
1374 struct sockaddr_in sa;
1381 memset(&sa, 0, sizeof(sa));
1383 p = strchr(sockname, ':');
1385 len = strlen(sockname);
1386 port = DEF_TCP_PORT;
1390 port = strtoul(p + 1, &p, 10);
1391 if (*p || port > 65535) {
1400 g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
1402 if (!ws_inet_pton4(buf, (guint32 *)&sa.sin_addr)) {
1406 sa.sin_family = AF_INET;
1407 sa.sin_port = g_htons((u_short)port);
1409 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1410 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1412 LPTSTR errorText = NULL;
1415 lastError = WSAGetLastError();
1416 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1417 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1418 FORMAT_MESSAGE_IGNORE_INSERTS,
1419 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1420 (LPTSTR)&errorText, 0, NULL);
1422 g_snprintf(errmsg, errmsgl,
1423 "The capture session could not be initiated due to the socket error: \n"
1425 " %d: %s", lastError, errorText ? (char *)errorText : "Unknown");
1427 LocalFree(errorText);
1429 " %d: %s", errno, g_strerror(errno));
1431 pcap_src->cap_pipe_err = PIPERR;
1434 cap_pipe_close(fd, TRUE);
1438 pcap_src->from_cap_socket = TRUE;
1442 g_snprintf(errmsg, errmsgl,
1443 "The capture session could not be initiated because\n"
1444 "\"%s\" is not a valid socket specification", pipename);
1445 pcap_src->cap_pipe_err = PIPERR;
1449 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1453 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1457 closesocket(pipe_fd);
1465 cap_pipe_read_data_bytes(capture_src *pcap_src, char *errmsg, int errmsgl)
1468 int fd = pcap_src->cap_pipe_fd;
1470 DWORD sz, bytes_read = 0;
1472 size_t sz, bytes_read = 0;
1476 #ifdef LOG_CAPTURE_VERBOSE
1477 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_read_data_bytes read %lu of %lu",
1478 pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1480 sz = pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read;
1481 while (bytes_read < sz) {
1483 g_snprintf(errmsg, errmsgl, "Invalid file descriptor.");
1487 sel_ret = cap_pipe_select(fd);
1489 g_snprintf(errmsg, errmsgl,
1490 "Unexpected error from select: %s.", g_strerror(errno));
1492 } else if (sel_ret > 0) {
1493 b = cap_pipe_read(fd, pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read+bytes_read,
1494 sz-bytes_read, pcap_src->from_cap_socket);
1497 g_snprintf(errmsg, errmsgl, "End of file on pipe during cap_pipe_read.");
1500 LPTSTR errorText = NULL;
1501 int lastError = WSAGetLastError();
1503 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1504 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1505 FORMAT_MESSAGE_IGNORE_INSERTS,
1506 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1507 (LPTSTR)&errorText, 0, NULL);
1508 g_snprintf(errmsg, errmsgl, "Error on pipe data during cap_pipe_read: "
1509 " %d: %s", lastError, errorText ? (char *)errorText : "Unknown");
1511 LocalFree(errorText);
1513 g_snprintf(errmsg, errmsgl, "Error on pipe data during cap_pipe_read: %s.",
1522 pcap_src->cap_pipe_bytes_read += bytes_read;
1523 #ifdef LOG_CAPTURE_VERBOSE
1524 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_read_data_bytes read %lu of %lu",
1525 pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1530 /* Some forward declarations for breaking up cap_pipe_open_live for pcap and pcapng formats */
1531 static void pcap_pipe_open_live(int fd, capture_src *pcap_src, struct pcap_hdr *hdr, char *errmsg, int errmsgl);
1532 static void pcapng_pipe_open_live(int fd, capture_src *pcap_src, char *errmsg, int errmsgl);
1533 static int pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, int errmsgl);
1535 /* Mimic pcap_open_live() for pipe captures
1537 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1538 * open it, and read the header.
1540 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1541 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1543 cap_pipe_open_live(char *pipename,
1544 capture_src *pcap_src,
1546 char *errmsg, int errmsgl)
1549 ws_statb64 pipe_stat;
1550 struct sockaddr_un sa;
1554 char* extcap_pipe_name;
1556 gboolean extcap_pipe = FALSE;
1558 int fd = -1, sel_ret;
1561 pcap_src->cap_pipe_fd = -1;
1563 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1566 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1569 * XXX - this blocks until a pcap per-file header has been written to
1570 * the pipe, so it could block indefinitely.
1572 if (strcmp(pipename, "-") == 0) {
1574 fd = 0; /* read from stdin */
1576 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1578 } else if (!strncmp(pipename, "TCP@", 4)) {
1579 if ((fd = cap_open_socket(pipename, pcap_src, errmsg, errmsgl)) < 0) {
1584 if ( g_strrstr(pipename, EXTCAP_PIPE_PREFIX) != NULL )
1587 if (ws_stat64(pipename, &pipe_stat) < 0) {
1588 if (errno == ENOENT || errno == ENOTDIR)
1589 pcap_src->cap_pipe_err = PIPNEXIST;
1591 g_snprintf(errmsg, errmsgl,
1592 "The capture session could not be initiated "
1593 "due to error getting information on pipe/socket: %s.", g_strerror(errno));
1594 pcap_src->cap_pipe_err = PIPERR;
1598 if (S_ISFIFO(pipe_stat.st_mode)) {
1599 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1601 g_snprintf(errmsg, errmsgl,
1602 "The capture session could not be initiated "
1603 "due to error on pipe open: %s.", g_strerror(errno));
1604 pcap_src->cap_pipe_err = PIPERR;
1607 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1608 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1610 g_snprintf(errmsg, errmsgl,
1611 "The capture session could not be initiated "
1612 "due to error on socket create: %s.", g_strerror(errno));
1613 pcap_src->cap_pipe_err = PIPERR;
1616 sa.sun_family = AF_UNIX;
1618 * The Single UNIX Specification says:
1620 * The size of sun_path has intentionally been left undefined.
1621 * This is because different implementations use different sizes.
1622 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1623 * of 104. Since most implementations originate from BSD versions,
1624 * the size is typically in the range 92 to 108.
1626 * Applications should not assume a particular length for sun_path
1627 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1631 * The <sys/un.h> header shall define the sockaddr_un structure,
1632 * which shall include at least the following members:
1634 * sa_family_t sun_family Address family.
1635 * char sun_path[] Socket pathname.
1637 * so we assume that it's an array, with a specified size,
1638 * and that the size reflects the maximum path length.
1640 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1641 /* Path name too long */
1642 g_snprintf(errmsg, errmsgl,
1643 "The capture session coud not be initiated "
1644 "due to error on socket connect: Path name too long.");
1645 pcap_src->cap_pipe_err = PIPERR;
1649 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1651 g_snprintf(errmsg, errmsgl,
1652 "The capture session coud not be initiated "
1653 "due to error on socket connect: %s.", g_strerror(errno));
1654 pcap_src->cap_pipe_err = PIPERR;
1659 if (S_ISCHR(pipe_stat.st_mode)) {
1661 * Assume the user specified an interface on a system where
1662 * interfaces are in /dev. Pretend we haven't seen it.
1664 pcap_src->cap_pipe_err = PIPNEXIST;
1666 g_snprintf(errmsg, errmsgl,
1667 "The capture session could not be initiated because\n"
1668 "\"%s\" is neither an interface nor a socket nor a pipe.", pipename);
1669 pcap_src->cap_pipe_err = PIPERR;
1675 #define PIPE_STR "\\pipe\\"
1676 /* Under Windows, named pipes _must_ have the form
1677 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1679 pncopy = g_strdup(pipename);
1680 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1681 pos = strchr(pncopy + 3, '\\');
1682 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1689 g_snprintf(errmsg, errmsgl,
1690 "The capture session could not be initiated because\n"
1691 "\"%s\" is neither an interface nor a pipe.", pipename);
1692 pcap_src->cap_pipe_err = PIPNEXIST;
1695 extcap_pipe_name = g_strconcat("\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, NULL);
1696 extcap_pipe = strstr(pipename, extcap_pipe_name) ? TRUE : FALSE;
1697 g_free(extcap_pipe_name);
1699 /* Wait for the pipe to appear */
1702 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1704 pcap_src->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1705 OPEN_EXISTING, 0, NULL);
1707 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE)
1710 if (GetLastError() != ERROR_PIPE_BUSY) {
1711 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1712 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1713 g_snprintf(errmsg, errmsgl,
1714 "The capture session on \"%s\" could not be started "
1715 "due to error on pipe open: %s (error %lu).",
1716 pipename, utf_16to8(err_str), GetLastError());
1718 pcap_src->cap_pipe_err = PIPERR;
1722 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1723 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1724 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1725 g_snprintf(errmsg, errmsgl,
1726 "The capture session on \"%s\" timed out during "
1727 "pipe open: %s (error %lu).",
1728 pipename, utf_16to8(err_str), GetLastError());
1730 pcap_src->cap_pipe_err = PIPERR;
1737 pcap_src->from_cap_pipe = TRUE;
1740 * We start with a 2KB buffer for packet data, which should be
1741 * large enough for most regular network packets. We increase it,
1742 * up to the maximum size we allow, as necessary.
1744 pcap_src->cap_pipe_databuf = (char*)g_malloc(2048);
1745 pcap_src->cap_pipe_databuf_size = 2048;
1748 if (pcap_src->from_cap_socket)
1751 /* read the pcap header */
1753 while (bytes_read < sizeof magic) {
1754 sel_ret = cap_pipe_select(fd);
1756 g_snprintf(errmsg, errmsgl,
1757 "Unexpected error from select: %s.", g_strerror(errno));
1759 } else if (sel_ret > 0) {
1760 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
1761 sizeof magic-bytes_read,
1762 pcap_src->from_cap_socket);
1763 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1764 if (extcap_pipe && b <= 0)
1769 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1771 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1781 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
1783 pcap_src->cap_pipe_buf = (char *) &magic;
1784 pcap_src->cap_pipe_bytes_read = 0;
1785 pcap_src->cap_pipe_bytes_to_read = sizeof(magic);
1786 /* We don't have to worry about cap_pipe_read_mtx here */
1787 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1788 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1789 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1790 if (pcap_src->cap_pipe_bytes_read <= 0 && extcap_pipe)
1793 if (pcap_src->cap_pipe_bytes_read <= 0) {
1794 if (pcap_src->cap_pipe_bytes_read == 0)
1795 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1797 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1806 case PCAP_NSEC_MAGIC:
1807 /* Host that wrote it has our byte order, and was running
1808 a program using either standard or ss990417 libpcap. */
1809 pcap_src->cap_pipe_info.pcap.byte_swapped = FALSE;
1810 pcap_src->cap_pipe_modified = FALSE;
1811 pcap_src->ts_nsec = magic == PCAP_NSEC_MAGIC;
1813 case PCAP_MODIFIED_MAGIC:
1814 /* Host that wrote it has our byte order, but was running
1815 a program using either ss990915 or ss991029 libpcap. */
1816 pcap_src->cap_pipe_info.pcap.byte_swapped = FALSE;
1817 pcap_src->cap_pipe_modified = TRUE;
1819 case PCAP_SWAPPED_MAGIC:
1820 case PCAP_SWAPPED_NSEC_MAGIC:
1821 /* Host that wrote it has a byte order opposite to ours,
1822 and was running a program using either standard or
1823 ss990417 libpcap. */
1824 pcap_src->cap_pipe_info.pcap.byte_swapped = TRUE;
1825 pcap_src->cap_pipe_modified = FALSE;
1826 pcap_src->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
1828 case PCAP_SWAPPED_MODIFIED_MAGIC:
1829 /* Host that wrote it out has a byte order opposite to
1830 ours, and was running a program using either ss990915
1831 or ss991029 libpcap. */
1832 pcap_src->cap_pipe_info.pcap.byte_swapped = TRUE;
1833 pcap_src->cap_pipe_modified = TRUE;
1835 case BLOCK_TYPE_SHB:
1836 /* This isn't pcap, it's pcapng. */
1837 pcap_src->from_pcapng = TRUE;
1838 pcap_src->cap_pipe_dispatch = pcapng_pipe_dispatch;
1839 global_capture_opts.use_pcapng = TRUE; /* we can only output in pcapng format */
1840 pcapng_pipe_open_live(fd, pcap_src, errmsg, errmsgl);
1843 /* Not a pcap type we know about, or not pcap at all. */
1844 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format or not libpcap data.");
1848 pcap_pipe_open_live(fd, pcap_src, (struct pcap_hdr *) hdr, errmsg, errmsgl);
1852 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1853 pcap_src->cap_pipe_err = PIPERR;
1854 cap_pipe_close(fd, pcap_src->from_cap_socket);
1855 pcap_src->cap_pipe_fd = -1;
1857 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1862 pcap_pipe_open_live(int fd,
1863 capture_src *pcap_src,
1864 struct pcap_hdr *hdr,
1865 char *errmsg, int errmsgl)
1871 if (pcap_src->from_cap_socket)
1874 /* Read the rest of the header */
1876 while (bytes_read < sizeof(struct pcap_hdr)) {
1877 sel_ret = cap_pipe_select(fd);
1879 g_snprintf(errmsg, errmsgl,
1880 "Unexpected error from select: %s.", g_strerror(errno));
1882 } else if (sel_ret > 0) {
1883 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
1884 sizeof(struct pcap_hdr) - bytes_read,
1885 pcap_src->from_cap_socket);
1888 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open.");
1890 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s.",
1900 pcap_src->cap_pipe_buf = (char *) hdr;
1901 pcap_src->cap_pipe_bytes_read = 0;
1902 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1903 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1904 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1905 if (pcap_src->cap_pipe_bytes_read <= 0) {
1906 if (pcap_src->cap_pipe_bytes_read == 0)
1907 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open.");
1909 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s.",
1916 if (pcap_src->cap_pipe_info.pcap.byte_swapped) {
1917 /* Byte-swap the header fields about which we care. */
1918 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
1919 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
1920 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
1921 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
1923 pcap_src->linktype = hdr->network;
1925 if (pcap_src->linktype == DLT_DBUS) {
1927 * The maximum D-Bus message size is 128MB, so allow packets up
1930 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_DBUS;
1933 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
1935 if (hdr->version_major < 2) {
1936 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format version %d.%d",
1937 hdr->version_major, hdr->version_minor);
1941 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
1942 pcap_src->cap_pipe_err = PIPOK;
1943 pcap_src->cap_pipe_fd = fd;
1947 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcap_pipe_open_live: error %s", errmsg);
1948 pcap_src->cap_pipe_err = PIPERR;
1949 cap_pipe_close(fd, pcap_src->from_cap_socket);
1950 pcap_src->cap_pipe_fd = -1;
1952 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1956 /* Read the pcapng section header block */
1958 pcapng_read_shb(capture_src *pcap_src,
1962 struct pcapng_section_header_block_s *shb = &pcap_src->cap_pipe_info.pcapng.shb;
1965 if (pcap_src->from_cap_socket)
1968 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_block_header_s) + sizeof(struct pcapng_section_header_block_s);
1969 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl)) {
1975 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf + sizeof(struct pcapng_block_header_s);
1976 pcap_src->cap_pipe_bytes_read = 0;
1977 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_section_header_block_s);
1978 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1979 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1980 if (pcap_src->cap_pipe_bytes_read <= 0) {
1981 if (pcap_src->cap_pipe_bytes_read == 0)
1982 g_snprintf(errmsg, errmsgl, "End of file on pipe section header during open.");
1984 g_snprintf(errmsg, errmsgl, "Error on pipe section header during open: %s.",
1988 /* Continuing with STATE_EXPECT_DATA requires reading into cap_pipe_databuf at offset cap_pipe_bytes_read */
1989 pcap_src->cap_pipe_bytes_read = sizeof(struct pcapng_block_header_s) + sizeof(struct pcapng_section_header_block_s);
1992 memcpy(shb, pcap_src->cap_pipe_databuf + sizeof(struct pcapng_block_header_s), sizeof(struct pcapng_section_header_block_s));
1996 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng SHB MAGIC");
1998 case PCAPNG_SWAPPED_MAGIC:
1999 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng SHB SWAPPED MAGIC");
2001 * pcapng sources can contain all sorts of block types. Rather than add a bunch of
2002 * complexity to this code (which is often privileged), punt and tell the user to
2003 * swap bytes elsewhere.
2005 #if G_BYTE_ORDER == G_BIG_ENDIAN
2006 #define OUR_ENDIAN "big"
2007 #define IFACE_ENDIAN "little"
2009 #define OUR_ENDIAN "little"
2010 #define IFACE_ENDIAN "big"
2012 g_snprintf(errmsg, errmsgl, "Interface %u is " IFACE_ENDIAN " endian but we're " OUR_ENDIAN " endian.",
2013 pcap_src->interface_id);
2016 /* Not a pcapng type we know about, or not pcapng at all. */
2017 g_snprintf(errmsg, errmsgl, "Unrecognized pcapng format or not pcapng data.");
2021 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
2023 /* Setup state to capture any options following the section header block */
2024 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2029 /* Save SHB and IDB blocks to playback whenever we change output files. */
2030 /* The list is saved in reverse order of blocks added */
2032 pcapng_block_save(capture_src *pcap_src)
2034 pcapng_pipe_info_t *pcapng = &pcap_src->cap_pipe_info.pcapng;
2035 struct pcapng_block_header_s *bh = &pcapng->bh;
2037 /* Delete all the old blocks first whenever we get a SHB */
2038 if (bh->block_type == BLOCK_TYPE_SHB) {
2039 g_list_free_full(pcapng->saved_blocks, g_free);
2040 pcapng->saved_blocks = NULL;
2041 } else if (bh->block_type != BLOCK_TYPE_IDB) {
2045 gpointer data = g_malloc(bh->block_total_length);
2049 memcpy(data, pcap_src->cap_pipe_databuf, bh->block_total_length);
2051 pcapng->saved_blocks = g_list_prepend(pcapng->saved_blocks, data);
2057 pcapng_pipe_open_live(int fd,
2058 capture_src *pcap_src,
2062 guint32 type = BLOCK_TYPE_SHB;
2063 struct pcapng_block_header_s *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2065 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_open_live: fd %d", fd);
2067 if (pcap_src->from_cap_socket)
2070 memcpy(pcap_src->cap_pipe_databuf, &type, sizeof(guint32));
2071 /* read the rest of the pcapng general block header */
2072 pcap_src->cap_pipe_bytes_read = sizeof(guint32);
2073 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_block_header_s);
2074 pcap_src->cap_pipe_err = PIPOK;
2075 pcap_src->cap_pipe_fd = fd;
2076 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl)) {
2079 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(struct pcapng_block_header_s));
2083 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
2085 bh->block_type = type;
2086 pcap_src->cap_pipe_buf = (char *) &bh->block_total_length;
2087 pcap_src->cap_pipe_bytes_read = 0;
2088 pcap_src->cap_pipe_bytes_to_read = sizeof(bh->block_total_length);
2089 /* We don't have to worry about cap_pipe_read_mtx here */
2090 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2091 g_async_queue_pop(pcap_src->cap_pipe_done_q);
2092 if (pcap_src->cap_pipe_bytes_read <= 0) {
2093 if (pcap_src->cap_pipe_bytes_read == 0)
2094 g_snprintf(errmsg, errmsgl, "End of file on pipe block_total_length during open.");
2096 g_snprintf(errmsg, errmsgl, "Error on pipe block_total_length during open: %s.",
2100 pcap_src->cap_pipe_bytes_read = sizeof(struct pcapng_block_header_s);
2101 memcpy(pcap_src->cap_pipe_databuf, bh, sizeof(struct pcapng_block_header_s));
2102 pcap_src->cap_pipe_err = PIPOK;
2103 pcap_src->cap_pipe_fd = fd;
2106 if (pcapng_read_shb(pcap_src, errmsg, errmsgl)) {
2113 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_open_live: error %s", errmsg);
2114 pcap_src->cap_pipe_err = PIPERR;
2115 cap_pipe_close(fd, pcap_src->from_cap_socket);
2116 pcap_src->cap_pipe_fd = -1;
2118 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2122 /* We read one record from the pipe, take care of byte order in the record
2123 * header, write the record to the capture file, and update capture statistics. */
2125 pcap_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, int errmsgl)
2127 struct pcap_pkthdr phdr;
2128 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2136 pcap_pipe_info_t *pcap_info = &pcap_src->cap_pipe_info.pcap;
2138 #ifdef LOG_CAPTURE_VERBOSE
2139 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcap_pipe_dispatch");
2142 switch (pcap_src->cap_pipe_state) {
2144 case STATE_EXPECT_REC_HDR:
2146 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2149 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2150 pcap_src->cap_pipe_bytes_to_read = pcap_src->cap_pipe_modified ?
2151 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2152 pcap_src->cap_pipe_bytes_read = 0;
2155 pcap_src->cap_pipe_buf = (char *) &pcap_info->rechdr;
2156 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2157 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2162 case STATE_READ_REC_HDR:
2164 if (pcap_src->from_cap_socket)
2167 b = cap_pipe_read(pcap_src->cap_pipe_fd, ((char *)&pcap_info->rechdr)+pcap_src->cap_pipe_bytes_read,
2168 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read, pcap_src->from_cap_socket);
2171 result = PD_PIPE_EOF;
2173 result = PD_PIPE_ERR;
2176 pcap_src->cap_pipe_bytes_read += b;
2180 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2181 if (pcap_src->cap_pipe_err == PIPEOF) {
2182 result = PD_PIPE_EOF;
2184 } else if (pcap_src->cap_pipe_err == PIPERR) {
2185 result = PD_PIPE_ERR;
2193 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2195 result = PD_REC_HDR_READ;
2198 case STATE_EXPECT_DATA:
2200 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2203 pcap_src->cap_pipe_state = STATE_READ_DATA;
2204 pcap_src->cap_pipe_bytes_to_read = pcap_info->rechdr.hdr.incl_len;
2205 pcap_src->cap_pipe_bytes_read = 0;
2208 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2209 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2210 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2215 case STATE_READ_DATA:
2217 if (pcap_src->from_cap_socket)
2220 b = cap_pipe_read(pcap_src->cap_pipe_fd,
2221 pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read,
2222 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read,
2223 pcap_src->from_cap_socket);
2226 result = PD_PIPE_EOF;
2228 result = PD_PIPE_ERR;
2231 pcap_src->cap_pipe_bytes_read += b;
2236 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2237 if (pcap_src->cap_pipe_err == PIPEOF) {
2238 result = PD_PIPE_EOF;
2240 } else if (pcap_src->cap_pipe_err == PIPERR) {
2241 result = PD_PIPE_ERR;
2249 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2251 result = PD_DATA_READ;
2255 g_snprintf(errmsg, errmsgl, "pcap_pipe_dispatch: invalid state");
2258 } /* switch (pcap_src->cap_pipe_state) */
2261 * We've now read as much data as we were expecting, so process it.
2265 case PD_REC_HDR_READ:
2266 /* We've read the header. Take care of byte order. */
2267 cap_pipe_adjust_pcap_header(pcap_src->cap_pipe_info.pcap.byte_swapped, &pcap_info->hdr,
2268 &pcap_info->rechdr.hdr);
2269 if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_max_pkt_size) {
2271 * The record contains more data than the advertised/allowed in the
2272 * pcap header, do not try to read more data (do not change to
2273 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2274 * instead stop with an error.
2276 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2277 ld->packets_captured+1, pcap_info->rechdr.hdr.incl_len);
2281 if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_databuf_size) {
2283 * Grow the buffer to the packet size, rounded up to a power of
2286 new_bufsize = pcap_info->rechdr.hdr.incl_len;
2288 * http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2291 new_bufsize |= new_bufsize >> 1;
2292 new_bufsize |= new_bufsize >> 2;
2293 new_bufsize |= new_bufsize >> 4;
2294 new_bufsize |= new_bufsize >> 8;
2295 new_bufsize |= new_bufsize >> 16;
2297 pcap_src->cap_pipe_databuf = (char*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2298 pcap_src->cap_pipe_databuf_size = new_bufsize;
2302 * The record has some data following the header, try to read it next
2305 if (pcap_info->rechdr.hdr.incl_len) {
2306 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2311 * No data following the record header? Then no more data needs to be
2312 * read and we will fallthrough and emit an empty packet.
2316 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2317 phdr.ts.tv_sec = pcap_info->rechdr.hdr.ts_sec;
2318 phdr.ts.tv_usec = pcap_info->rechdr.hdr.ts_usec;
2319 phdr.caplen = pcap_info->rechdr.hdr.incl_len;
2320 phdr.len = pcap_info->rechdr.hdr.orig_len;
2323 capture_loop_queue_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2325 capture_loop_write_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2327 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2331 pcap_src->cap_pipe_err = PIPEOF;
2336 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2337 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2338 g_snprintf(errmsg, errmsgl,
2339 "Error reading from pipe: %s (error %lu)",
2340 utf_16to8(err_str), GetLastError());
2343 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2351 pcap_src->cap_pipe_err = PIPERR;
2352 /* Return here rather than inside the switch to prevent GCC warning */
2357 pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, int errmsgl)
2359 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2366 struct pcapng_block_header_s *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2368 #ifdef LOG_CAPTURE_VERBOSE
2369 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch");
2372 switch (pcap_src->cap_pipe_state) {
2374 case STATE_EXPECT_REC_HDR:
2375 #ifdef LOG_CAPTURE_VERBOSE
2376 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_EXPECT_REC_HDR");
2379 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2382 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2383 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_block_header_s);
2384 pcap_src->cap_pipe_bytes_read = 0;
2387 if (!pcap_src->from_cap_socket) {
2388 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2389 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2391 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2396 case STATE_READ_REC_HDR:
2397 #ifdef LOG_CAPTURE_VERBOSE
2398 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_READ_REC_HDR");
2401 if (pcap_src->from_cap_socket) {
2403 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl)) {
2408 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2409 if (pcap_src->cap_pipe_err == PIPEOF) {
2410 result = PD_PIPE_EOF;
2412 } else if (pcap_src->cap_pipe_err == PIPERR) {
2413 result = PD_PIPE_ERR;
2421 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2423 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(struct pcapng_block_header_s));
2424 result = PD_REC_HDR_READ;
2427 case STATE_EXPECT_DATA:
2428 #ifdef LOG_CAPTURE_VERBOSE
2429 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_EXPECT_DATA");
2432 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2434 pcap_src->cap_pipe_state = STATE_READ_DATA;
2435 pcap_src->cap_pipe_bytes_to_read = bh->block_total_length;
2438 if (!pcap_src->from_cap_socket) {
2439 pcap_src->cap_pipe_bytes_to_read -= pcap_src->cap_pipe_bytes_read;
2440 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf + pcap_src->cap_pipe_bytes_read;
2441 pcap_src->cap_pipe_bytes_read = 0;
2442 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2444 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2449 case STATE_READ_DATA:
2450 #ifdef LOG_CAPTURE_VERBOSE
2451 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_READ_DATA");
2454 if (pcap_src->from_cap_socket) {
2456 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl)) {
2462 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2463 if (pcap_src->cap_pipe_err == PIPEOF) {
2464 result = PD_PIPE_EOF;
2466 } else if (pcap_src->cap_pipe_err == PIPERR) {
2467 result = PD_PIPE_ERR;
2475 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2478 result = PD_DATA_READ;
2482 g_snprintf(errmsg, errmsgl, "pcapng_pipe_dispatch: invalid state");
2485 } /* switch (pcap_src->cap_pipe_state) */
2488 * We've now read as much data as we were expecting, so process it.
2492 case PD_REC_HDR_READ:
2493 if (bh->block_type == BLOCK_TYPE_SHB) {
2494 /* we need to read ahead to get the endianess before getting the block type and length */
2495 pcapng_read_shb(pcap_src, errmsg, errmsgl);
2499 if (bh->block_total_length > pcap_src->cap_pipe_max_pkt_size) {
2501 * The record contains more data than the advertised/allowed in the
2502 * pcapng header, do not try to read more data (do not change to
2503 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2504 * instead stop with an error.
2506 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2507 ld->packets_captured+1, bh->block_total_length);
2511 if (bh->block_total_length > pcap_src->cap_pipe_databuf_size) {
2513 * Grow the buffer to the packet size, rounded up to a power of
2516 new_bufsize = bh->block_total_length;
2518 * http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2521 new_bufsize |= new_bufsize >> 1;
2522 new_bufsize |= new_bufsize >> 2;
2523 new_bufsize |= new_bufsize >> 4;
2524 new_bufsize |= new_bufsize >> 8;
2525 new_bufsize |= new_bufsize >> 16;
2527 pcap_src->cap_pipe_databuf = (guchar*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2528 pcap_src->cap_pipe_databuf_size = new_bufsize;
2531 /* The record always has at least the block total length following the header */
2532 if (bh->block_total_length < sizeof(struct pcapng_block_header_s)+sizeof(guint32)) {
2533 g_snprintf(errmsg, errmsgl, "malformed pcapng block_total_length < minimum");
2534 pcap_src->cap_pipe_err = PIPEOF;
2537 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2541 if (!pcapng_block_save(pcap_src)) {
2542 g_snprintf(errmsg, errmsgl, "pcapng_pipe_dispatch block save failed");
2546 capture_loop_queue_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
2548 capture_loop_write_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
2550 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2554 pcap_src->cap_pipe_err = PIPEOF;
2559 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2560 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2561 g_snprintf(errmsg, errmsgl,
2562 "Error reading from pipe: %s (error %lu)",
2563 utf_16to8(err_str), GetLastError());
2566 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2574 pcap_src->cap_pipe_err = PIPERR;
2575 /* Return here rather than inside the switch to prevent GCC warning */
2579 /** Open the capture input file (pcap or capture pipe).
2580 * Returns TRUE if it succeeds, FALSE otherwise. */
2582 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2583 char *errmsg, size_t errmsg_len,
2584 char *secondary_errmsg, size_t secondary_errmsg_len)
2586 cap_device_open_err open_err;
2587 gchar open_err_str[PCAP_ERRBUF_SIZE];
2588 gchar *sync_msg_str;
2589 interface_options *interface_opts;
2590 capture_src *pcap_src;
2594 WORD wVersionRequested;
2598 /* XXX - opening Winsock on tshark? */
2600 /* Initialize Windows Socket if we are in a Win32 OS
2601 This needs to be done before querying the interface for network/netmask */
2603 /* XXX - do we really require 1.1 or earlier?
2604 Are there any versions that support only 2.0 or higher? */
2605 wVersionRequested = MAKEWORD(1, 1);
2606 err = WSAStartup(wVersionRequested, &wsaData);
2610 case WSASYSNOTREADY:
2611 g_snprintf(errmsg, (gulong) errmsg_len,
2612 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2615 case WSAVERNOTSUPPORTED:
2616 g_snprintf(errmsg, (gulong) errmsg_len,
2617 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2618 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2621 case WSAEINPROGRESS:
2622 g_snprintf(errmsg, (gulong) errmsg_len,
2623 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2627 g_snprintf(errmsg, (gulong) errmsg_len,
2628 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2632 g_snprintf(errmsg, (gulong) errmsg_len,
2633 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2637 g_snprintf(errmsg, (gulong) errmsg_len,
2638 "Couldn't initialize Windows Sockets: error %d", err);
2641 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2645 if ((use_threads == FALSE) &&
2646 (capture_opts->ifaces->len > 1)) {
2647 g_snprintf(errmsg, (gulong) errmsg_len,
2648 "Using threads is required for capturing on multiple interfaces.");
2652 for (i = 0; i < capture_opts->ifaces->len; i++) {
2653 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
2654 pcap_src = (capture_src *)g_malloc(sizeof (capture_src));
2655 if (pcap_src == NULL) {
2656 g_snprintf(errmsg, (gulong) errmsg_len,
2657 "Could not allocate memory.");
2660 memset(pcap_src, 0, sizeof(capture_src));
2661 #ifdef MUST_DO_SELECT
2662 pcap_src->pcap_fd = -1;
2664 pcap_src->interface_id = i;
2665 pcap_src->linktype = -1;
2667 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2669 pcap_src->cap_pipe_fd = -1;
2670 pcap_src->cap_pipe_dispatch = pcap_pipe_dispatch;
2671 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2672 pcap_src->cap_pipe_err = PIPOK;
2674 pcap_src->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2675 g_mutex_init(pcap_src->cap_pipe_read_mtx);
2676 pcap_src->cap_pipe_pending_q = g_async_queue_new();
2677 pcap_src->cap_pipe_done_q = g_async_queue_new();
2679 g_array_append_val(ld->pcaps, pcap_src);
2681 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts->name);
2682 pcap_src->pcap_h = open_capture_device(capture_opts, interface_opts,
2683 CAP_READ_TIMEOUT, &open_err, &open_err_str);
2685 if (pcap_src->pcap_h != NULL) {
2686 /* we've opened "iface" as a network device */
2688 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2689 /* Find out if we're getting nanosecond-precision time stamps */
2690 pcap_src->ts_nsec = have_high_resolution_timestamp(pcap_src->pcap_h);
2693 #if defined(HAVE_PCAP_SETSAMPLING)
2694 if (interface_opts->sampling_method != CAPTURE_SAMP_NONE) {
2695 struct pcap_samp *samp;
2697 if ((samp = pcap_setsampling(pcap_src->pcap_h)) != NULL) {
2698 switch (interface_opts->sampling_method) {
2699 case CAPTURE_SAMP_BY_COUNT:
2700 samp->method = PCAP_SAMP_1_EVERY_N;
2703 case CAPTURE_SAMP_BY_TIMER:
2704 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2708 sync_msg_str = g_strdup_printf(
2709 "Unknown sampling method %d specified,\n"
2710 "continue without packet sampling",
2711 interface_opts->sampling_method);
2712 report_capture_error("Couldn't set the capture "
2713 "sampling", sync_msg_str);
2714 g_free(sync_msg_str);
2716 samp->value = interface_opts->sampling_param;
2718 report_capture_error("Couldn't set the capture sampling",
2719 "Cannot get packet sampling data structure");
2724 /* setting the data link type only works on real interfaces */
2725 if (!set_pcap_datalink(pcap_src->pcap_h, interface_opts->linktype,
2726 interface_opts->name,
2728 secondary_errmsg, secondary_errmsg_len)) {
2731 pcap_src->linktype = get_pcap_datalink(pcap_src->pcap_h, interface_opts->name);
2733 /* We couldn't open "iface" as a network device. */
2734 /* Try to open it as a pipe */
2735 gboolean pipe_err = FALSE;
2736 cap_pipe_open_live(interface_opts->name, pcap_src, &pcap_src->cap_pipe_info.pcap.hdr, errmsg, (int) errmsg_len);
2739 if (pcap_src->from_cap_socket) {
2741 if (pcap_src->cap_pipe_fd == -1) {
2746 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;
3088 packet_count_before = ld->packets_captured;
3089 if (pcap_src->from_cap_pipe) {
3090 /* dispatch from capture pipe */
3091 #ifdef LOG_CAPTURE_VERBOSE
3092 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
3095 if (pcap_src->from_cap_socket) {
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);
3108 /* Windows does not have select() for pipes. */
3109 /* Proceed with _dispatch() which waits for cap_pipe_done_q
3110 * notification from cap_thread_read() when ReadFile() on
3111 * the pipe has read enough bytes. */
3117 * "select()" says we can read from the pipe without blocking
3119 inpkts = pcap_src->cap_pipe_dispatch(ld, pcap_src, errmsg, errmsg_len);
3127 /* dispatch from pcap */
3128 #ifdef MUST_DO_SELECT
3130 * If we have "pcap_get_selectable_fd()", we use it to get the
3131 * descriptor on which to select; if that's -1, it means there
3132 * is no descriptor on which you can do a "select()" (perhaps
3133 * because you're capturing on a special device, and that device's
3134 * driver unfortunately doesn't support "select()", in which case
3135 * we don't do the select - which means it might not be possible
3136 * to stop a capture until a packet arrives. If that's unacceptable,
3137 * plead with whoever supplies the software for that device to add
3138 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3139 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3140 * later, so it can use pcap_breakloop().
3142 #ifdef LOG_CAPTURE_VERBOSE
3143 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3145 if (pcap_src->pcap_fd != -1) {
3146 sel_ret = cap_pipe_select(pcap_src->pcap_fd);
3149 * "select()" says we can read from it without blocking; go for
3152 * We don't have pcap_breakloop(), so we only process one packet
3153 * per pcap_dispatch() call, to allow a signal to stop the
3154 * processing immediately, rather than processing all packets
3155 * in a batch before quitting.
3158 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3160 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3164 /* Error, rather than pcap_breakloop(). */
3165 pcap_src->pcap_err = TRUE;
3167 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3170 if (sel_ret < 0 && errno != EINTR) {
3171 g_snprintf(errmsg, errmsg_len,
3172 "Unexpected error from select: %s", g_strerror(errno));
3173 report_capture_error(errmsg, please_report);
3179 #endif /* MUST_DO_SELECT */
3181 /* dispatch from pcap without select */
3183 #ifdef LOG_CAPTURE_VERBOSE
3184 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3188 * On Windows, we don't support asynchronously telling a process to
3189 * stop capturing; instead, we check for an indication on a pipe
3190 * after processing packets. We therefore process only one packet
3191 * at a time, so that we can check the pipe after every packet.
3194 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3196 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3200 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3202 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3207 /* Error, rather than pcap_breakloop(). */
3208 pcap_src->pcap_err = TRUE;
3210 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3212 #else /* pcap_next_ex */
3213 #ifdef LOG_CAPTURE_VERBOSE
3214 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3216 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3219 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3220 * see https://wiki.wireshark.org/CaptureSetup/WinPcapRemote
3221 * This should be fixed in the WinPcap 4.0 alpha release.
3223 * For reference, an example remote interface:
3224 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3227 /* emulate dispatch from pcap */
3230 struct pcap_pkthdr *pkt_header;
3235 (in = pcap_next_ex(pcap_src->pcap_h, &pkt_header, &pkt_data)) == 1) {
3237 capture_loop_queue_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
3239 capture_loop_write_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
3244 pcap_src->pcap_err = TRUE;
3248 #endif /* pcap_next_ex */
3252 #ifdef LOG_CAPTURE_VERBOSE
3253 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3256 return ld->packets_captured - packet_count_before;
3260 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3261 * want to grab only the characters between the '{' and '}' delimiters.
3263 * Returns a GString that must be freed with g_string_free(). */
3265 isolate_uuid(const char *iface)
3270 ptr = strchr(iface, '{');
3272 return g_string_new(iface);
3273 gstr = g_string_new(ptr + 1);
3275 ptr = strchr(gstr->str, '}');
3279 gstr = g_string_truncate(gstr, ptr - gstr->str);
3284 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3285 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3287 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3288 char *errmsg, int errmsg_len)
3291 gchar *capfile_name;
3292 gchar *prefix, *suffix;
3293 gboolean is_tempfile;
3295 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3296 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3298 if (capture_opts->save_file != NULL) {
3299 /* We return to the caller while the capture is in progress.
3300 * Therefore we need to take a copy of save_file in
3301 * case the caller destroys it after we return.
3303 capfile_name = g_strdup(capture_opts->save_file);
3305 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3306 if (capture_opts->multi_files_on) {
3307 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3308 g_snprintf(errmsg, errmsg_len,
3309 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3310 g_free(capfile_name);
3313 if (strcmp(capfile_name, "-") == 0) {
3314 /* write to stdout */
3317 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3318 _setmode(1, O_BINARY);
3321 /* Try to open the specified FIFO for use as a capture buffer.
3322 Do *not* create it if it doesn't exist. There's nothing
3323 to truncate. If we need to read it, We Have A Problem. */
3324 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY, 0);
3326 } /* if (...output_to_pipe ... */
3329 if (capture_opts->multi_files_on) {
3330 /* ringbuffer is enabled */
3331 *save_file_fd = ringbuf_init(capfile_name,
3332 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3333 capture_opts->group_read_access);
3335 /* we need the ringbuf name */
3336 if (*save_file_fd != -1) {
3337 g_free(capfile_name);
3338 capfile_name = g_strdup(ringbuf_current_filename());
3341 /* Try to open/create the specified file for use as a capture buffer. */
3342 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY|O_TRUNC|O_CREAT,
3343 (capture_opts->group_read_access) ? 0640 : 0600);
3346 is_tempfile = FALSE;
3348 /* Choose a random name for the temporary capture buffer */
3349 if (global_capture_opts.ifaces->len > 1) {
3351 * More than one interface; just use the number of interfaces
3352 * to generate the temporary file name prefix.
3354 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3357 * One interface; use its description, if it has one, to generate
3358 * the temporary file name, otherwise use its name.
3361 const interface_options *interface_opts;
3363 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
3366 * Do we have a description?
3368 if (interface_opts->descr) {
3372 * Strip off any stuff we shouldn't use in the file name,
3373 * by getting the last component of what would be a file
3376 basename = g_path_get_basename(interface_opts->descr);
3379 * No - use the name.
3381 * Strip off any stuff we shouldn't use in the file name,
3382 * by getting the last component of what would be a file
3385 basename = g_path_get_basename(interface_opts->name);
3388 * This is Windows, where we might have an ugly GUID-based
3391 * If it's an ugly GUID-based name, use the generic portion
3392 * of the interface GUID to form the basis of the filename.
3394 if (strncmp("NPF_{", basename, 5) == 0) {
3396 * We have a GUID-based name; extract the GUID digits
3397 * as the basis of the filename.
3400 iface = isolate_uuid(basename);
3402 basename = g_strdup(iface->str);
3403 g_string_free(iface, TRUE);
3407 /* generate the temp file name prefix */
3408 prefix = g_strconcat("wireshark_", basename, NULL);
3412 /* Generate the appropriate suffix. */
3413 if (capture_opts->use_pcapng) {
3418 *save_file_fd = create_tempfile(&tmpname, prefix, suffix);
3420 capfile_name = g_strdup(tmpname);
3424 /* did we fail to open the output file? */
3425 if (*save_file_fd == -1) {
3427 g_snprintf(errmsg, errmsg_len,
3428 "The temporary file to which the capture would be saved (\"%s\") "
3429 "could not be opened: %s.", capfile_name, g_strerror(errno));
3431 if (capture_opts->multi_files_on) {
3432 ringbuf_error_cleanup();
3435 g_snprintf(errmsg, errmsg_len,
3436 "The file to which the capture would be saved (\"%s\") "
3437 "could not be opened: %s.", capfile_name,
3440 g_free(capfile_name);
3444 if (capture_opts->save_file != NULL) {
3445 g_free(capture_opts->save_file);
3447 capture_opts->save_file = capfile_name;
3448 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3449 "g_free(capfile_name)". */
3454 static time_t get_next_time_interval(int interval_s) {
3455 time_t next_time = time(NULL);
3456 next_time -= next_time % interval_s;
3457 next_time += interval_s;
3461 /* Do the work of handling either the file size or file duration capture
3462 conditions being reached, and switching files or stopping. */
3464 do_file_switch_or_stop(capture_options *capture_opts)
3467 capture_src *pcap_src;
3468 interface_options *interface_opts;
3469 gboolean successful;
3471 if (capture_opts->multi_files_on) {
3472 if (capture_opts->has_autostop_files &&
3473 ++global_ld.file_count >= capture_opts->autostop_files) {
3474 /* no files left: stop here */
3475 global_ld.go = FALSE;
3479 /* Switch to the next ringbuffer file */
3480 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3481 &global_ld.save_file_fd, &global_ld.err)) {
3483 /* File switch succeeded: reset the conditions */
3484 global_ld.bytes_written = 0;
3485 global_ld.packets_written = 0;
3486 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3487 if (pcap_src->from_pcapng) {
3488 /* Write the saved SHB and all IDBs to start of next file */
3489 /* The blocks were saved in reverse so reverse it before iterating */
3490 GList *rlist = g_list_reverse(pcap_src->cap_pipe_info.pcapng.saved_blocks);
3491 GList *list = rlist;
3493 while (list && successful) {
3494 struct pcapng_block_header_s *bh = (struct pcapng_block_header_s *) list->data;
3495 successful = pcapng_write_block(global_ld.pdh,
3496 (const guint8 *) bh,
3497 bh->block_total_length,
3498 &global_ld.bytes_written, &global_ld.err);
3499 list = g_list_next(list);
3501 pcap_src->cap_pipe_info.pcapng.saved_blocks = g_list_reverse(rlist);
3503 if (capture_opts->use_pcapng) {
3505 GString *cpu_info_str;
3506 GString *os_info_str;
3508 cpu_info_str = g_string_new("");
3509 os_info_str = g_string_new("");
3510 get_cpu_info(cpu_info_str);
3511 get_os_version_info(os_info_str);
3513 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
3514 successful = pcapng_write_session_header_block(global_ld.pdh,
3515 (const char *)capture_opts->capture_comment, /* Comment */
3516 cpu_info_str->str, /* HW */
3517 os_info_str->str, /* OS */
3519 -1, /* section_length */
3520 &(global_ld.bytes_written),
3522 g_string_free(cpu_info_str, TRUE);
3525 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3526 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
3527 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3528 successful = pcapng_write_interface_description_block(global_ld.pdh,
3529 NULL, /* OPT_COMMENT 1 */
3530 interface_opts->name, /* IDB_NAME 2 */
3531 interface_opts->descr, /* IDB_DESCRIPTION 3 */
3532 interface_opts->cfilter, /* IDB_FILTER 11 */
3533 os_info_str->str, /* IDB_OS 12 */
3536 &(global_ld.bytes_written),
3537 0, /* IDB_IF_SPEED 8 */
3538 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3542 g_string_free(os_info_str, TRUE);
3545 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3546 successful = libpcap_write_file_header(global_ld.pdh, pcap_src->linktype, pcap_src->snaplen,
3547 pcap_src->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3551 fclose(global_ld.pdh);
3552 global_ld.pdh = NULL;
3553 global_ld.go = FALSE;
3556 if (global_ld.file_duration_timer) {
3557 g_timer_reset(global_ld.file_duration_timer);
3559 if (global_ld.next_interval_time) {
3560 global_ld.next_interval_time = get_next_time_interval(global_ld.interval_s);
3562 fflush(global_ld.pdh);
3564 report_packet_count(global_ld.inpkts_to_sync_pipe);
3565 global_ld.inpkts_to_sync_pipe = 0;
3566 report_new_capture_file(capture_opts->save_file);
3568 /* File switch failed: stop here */
3569 global_ld.go = FALSE;
3573 /* single file, stop now */
3574 global_ld.go = FALSE;
3581 pcap_read_handler(void* arg)
3583 capture_src *pcap_src;
3584 char errmsg[MSG_MAX_LENGTH+1];
3586 pcap_src = (capture_src *)arg;
3588 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3589 pcap_src->interface_id);
3591 while (global_ld.go) {
3592 /* dispatch incoming packets */
3593 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_src);
3595 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3596 pcap_src->interface_id);
3597 g_thread_exit(NULL);
3601 /* Do the low-level work of a capture.
3602 Returns TRUE if it succeeds, FALSE otherwise. */
3604 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3607 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3609 struct timeval upd_time, cur_time;
3613 GTimer *autostop_duration_timer = NULL;
3616 gboolean cfilter_error = FALSE;
3617 char errmsg[MSG_MAX_LENGTH+1];
3618 char secondary_errmsg[MSG_MAX_LENGTH+1];
3619 capture_src *pcap_src;
3620 interface_options *interface_opts;
3621 guint i, error_index = 0;
3624 *secondary_errmsg = '\0';
3626 /* init the loop data */
3627 global_ld.go = TRUE;
3628 global_ld.packets_captured = 0;
3630 global_ld.report_packet_count = FALSE;
3632 global_ld.inpkts_to_sync_pipe = 0;
3633 global_ld.err = 0; /* no error seen yet */
3634 global_ld.pdh = NULL;
3635 global_ld.save_file_fd = -1;
3636 global_ld.file_count = 0;
3637 global_ld.file_duration_timer = NULL;
3638 global_ld.next_interval_time = 0;
3639 global_ld.interval_s = 0;
3641 /* We haven't yet gotten the capture statistics. */
3642 *stats_known = FALSE;
3644 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3645 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3647 /* open the "input file" from network interface or capture pipe */
3648 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3649 secondary_errmsg, sizeof(secondary_errmsg))) {
3652 for (i = 0; i < capture_opts->ifaces->len; i++) {
3653 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3654 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
3655 /* init the input filter from the network interface (capture pipe will do nothing) */
3657 * When remote capturing WinPCap crashes when the capture filter
3658 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3661 switch (capture_loop_init_filter(pcap_src->pcap_h, pcap_src->from_cap_pipe,
3662 interface_opts->name,
3663 interface_opts->cfilter?interface_opts->cfilter:"")) {
3665 case INITFILTER_NO_ERROR:
3668 case INITFILTER_BAD_FILTER:
3669 cfilter_error = TRUE;
3671 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_src->pcap_h));
3674 case INITFILTER_OTHER_ERROR:
3675 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3676 pcap_geterr(pcap_src->pcap_h));
3677 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3682 /* If we're supposed to write to a capture file, open it for output
3683 (temporary/specified name/ringbuffer) */
3684 if (capture_opts->saving_to_file) {
3685 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3686 errmsg, sizeof(errmsg))) {
3690 /* set up to write to the already-opened capture output file/files */
3691 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3696 /* XXX - capture SIGTERM and close the capture, in case we're on a
3697 Linux 2.0[.x] system and you have to explicitly close the capture
3698 stream in order to turn promiscuous mode off? We need to do that
3699 in other places as well - and I don't think that works all the
3700 time in any case, due to libpcap bugs. */
3702 /* Well, we should be able to start capturing.
3704 Sync out the capture file, so the header makes it to the file system,
3705 and send a "capture started successfully and capture file created"
3706 message to our parent so that they'll open the capture file and
3707 update its windows to indicate that we have a live capture in
3709 fflush(global_ld.pdh);
3710 report_new_capture_file(capture_opts->save_file);
3713 if (capture_opts->has_file_interval) {
3714 global_ld.interval_s = capture_opts->file_interval;
3715 global_ld.next_interval_time = get_next_time_interval(global_ld.interval_s);
3717 /* create stop conditions */
3718 if (capture_opts->has_autostop_filesize) {
3719 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3720 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3723 if (capture_opts->has_autostop_duration) {
3724 autostop_duration_timer = g_timer_new();
3727 if (capture_opts->multi_files_on) {
3728 if (capture_opts->has_file_duration) {
3729 global_ld.file_duration_timer = g_timer_new();
3733 /* init the time values */
3735 upd_time = GetTickCount();
3737 gettimeofday(&upd_time, NULL);
3739 start_time = create_timestamp();
3740 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3741 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3743 /* WOW, everything is prepared! */
3744 /* please fasten your seat belts, we will enter now the actual capture loop */
3746 pcap_queue = g_async_queue_new();
3747 pcap_queue_bytes = 0;
3748 pcap_queue_packets = 0;
3749 for (i = 0; i < global_ld.pcaps->len; i++) {
3750 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3751 /* XXX - Add an interface name here? */
3752 pcap_src->tid = g_thread_new("Capture read", pcap_read_handler, pcap_src);
3755 while (global_ld.go) {
3756 /* dispatch incoming packets */
3758 pcap_queue_element *queue_element;
3760 g_async_queue_lock(pcap_queue);
3761 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3762 if (queue_element) {
3763 if (queue_element->pcap_src->from_pcapng) {
3764 pcap_queue_bytes -= queue_element->u.bh.block_total_length;
3765 pcap_queue_packets -= 1;
3767 pcap_queue_bytes -= queue_element->u.phdr.caplen;
3768 pcap_queue_packets -= 1;
3771 g_async_queue_unlock(pcap_queue);
3772 if (queue_element) {
3773 if (queue_element->pcap_src->from_pcapng) {
3774 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3775 "Dequeued a block of length %d captured on interface %d.",
3776 queue_element->u.bh.block_total_length, queue_element->pcap_src->interface_id);
3778 capture_loop_write_pcapng_cb(queue_element->pcap_src,
3779 &queue_element->u.bh,
3782 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3783 "Dequeued a packet of length %d captured on interface %d.",
3784 queue_element->u.phdr.caplen, queue_element->pcap_src->interface_id);
3786 capture_loop_write_packet_cb((u_char *) queue_element->pcap_src,
3787 &queue_element->u.phdr,
3790 g_free(queue_element->pd);
3791 g_free(queue_element);
3797 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3798 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3799 sizeof(errmsg), pcap_src);
3802 /* Were we asked to print packet counts by the SIGINFO handler? */
3803 if (global_ld.report_packet_count) {
3804 fprintf(stderr, "%u packet%s captured\n", global_ld.packets_captured,
3805 plurality(global_ld.packets_captured, "", "s"));
3806 global_ld.report_packet_count = FALSE;
3811 /* any news from our parent (signal pipe)? -> just stop the capture */
3812 if (!signal_pipe_check_running()) {
3813 global_ld.go = FALSE;
3818 global_ld.inpkts_to_sync_pipe += inpkts;
3820 if (capture_opts->output_to_pipe) {
3821 fflush(global_ld.pdh);
3825 /* Only update once every 500ms so as not to overload slow displays.
3826 * This also prevents too much context-switching between the dumpcap
3827 * and wireshark processes.
3829 #define DUMPCAP_UPD_TIME 500
3832 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3833 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) /* wrap just causes an extra update */
3835 gettimeofday(&cur_time, NULL);
3836 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3837 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000))
3841 upd_time = cur_time;
3844 if (pcap_stats(pch, stats) >= 0) {
3845 *stats_known = TRUE;
3848 /* Let the parent process know. */
3849 if (global_ld.inpkts_to_sync_pipe) {
3851 fflush(global_ld.pdh);
3853 /* Send our parent a message saying we've written out
3854 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3856 report_packet_count(global_ld.inpkts_to_sync_pipe);
3858 global_ld.inpkts_to_sync_pipe = 0;
3861 /* check capture duration condition */
3862 if (autostop_duration_timer != NULL && g_timer_elapsed(autostop_duration_timer, NULL) >= capture_opts->autostop_duration) {
3863 /* The maximum capture time has elapsed; stop the capture. */
3864 global_ld.go = FALSE;
3868 /* check capture file duration condition */
3869 if (global_ld.file_duration_timer != NULL && g_timer_elapsed(global_ld.file_duration_timer, NULL) >= capture_opts->file_duration) {
3870 /* duration limit reached, do we have another file? */
3871 if (!do_file_switch_or_stop(capture_opts))
3873 } /* cnd_file_duration */
3875 /* check capture file interval condition */
3876 if (global_ld.interval_s && time(NULL) >= global_ld.next_interval_time) {
3877 /* end of interval reached, do we have another file? */
3878 if (!do_file_switch_or_stop(capture_opts))
3880 } /* cnd_file_interval */
3884 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3886 pcap_queue_element *queue_element;
3888 for (i = 0; i < global_ld.pcaps->len; i++) {
3889 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3890 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3891 pcap_src->interface_id);
3892 g_thread_join(pcap_src->tid);
3893 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3894 pcap_src->interface_id);
3897 g_async_queue_lock(pcap_queue);
3898 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3899 if (queue_element) {
3900 pcap_queue_bytes -= queue_element->u.phdr.caplen;
3901 pcap_queue_packets -= 1;
3903 g_async_queue_unlock(pcap_queue);
3904 if (queue_element == NULL) {
3907 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3908 "Dequeued a packet of length %d captured on interface %d.",
3909 queue_element->u.phdr.caplen, queue_element->pcap_src->interface_id);
3910 capture_loop_write_packet_cb((u_char *)queue_element->pcap_src,
3911 &queue_element->u.phdr,
3913 g_free(queue_element->pd);
3914 g_free(queue_element);
3915 global_ld.inpkts_to_sync_pipe += 1;
3916 if (capture_opts->output_to_pipe) {
3917 fflush(global_ld.pdh);
3923 /* delete stop conditions */
3924 if (global_ld.file_duration_timer != NULL)
3925 g_timer_destroy(global_ld.file_duration_timer);
3926 if (autostop_duration_timer != NULL)
3927 g_timer_destroy(autostop_duration_timer);
3929 /* did we have a pcap (input) error? */
3930 for (i = 0; i < capture_opts->ifaces->len; i++) {
3931 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3932 if (pcap_src->pcap_err) {
3933 /* On Linux, if an interface goes down while you're capturing on it,
3934 you'll get a "recvfrom: Network is down" or
3935 "The interface went down" error (ENETDOWN).
3936 (At least you will if g_strerror() doesn't show a local translation
3939 On FreeBSD, DragonFly BSD, and macOS, if a network adapter
3940 disappears while you're capturing on it, you'll get a
3941 "read: Device not configured" error (ENXIO). (See previous
3942 parenthetical note.)
3944 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3946 These should *not* be reported to the Wireshark developers. */
3949 cap_err_str = pcap_geterr(pcap_src->pcap_h);
3950 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3951 strcmp(cap_err_str, "The interface went down") == 0 ||
3952 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3953 strcmp(cap_err_str, "read: I/O error") == 0 ||
3954 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3955 report_capture_error("The network adapter on which the capture was being done "
3956 "is no longer running; the capture has stopped.",
3959 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3961 report_capture_error(errmsg, please_report);
3964 } else if (pcap_src->from_cap_pipe && pcap_src->cap_pipe_err == PIPERR) {
3965 report_capture_error(errmsg, "");
3969 /* did we have an output error while capturing? */
3970 if (global_ld.err == 0) {
3973 capture_loop_get_errmsg(errmsg, sizeof(errmsg), secondary_errmsg,
3974 sizeof(secondary_errmsg),
3975 capture_opts->save_file, global_ld.err, FALSE);
3976 report_capture_error(errmsg, secondary_errmsg);
3980 if (capture_opts->saving_to_file) {
3981 /* close the output file */
3982 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3986 /* there might be packets not yet notified to the parent */
3987 /* (do this after closing the file, so all packets are already flushed) */
3988 if (global_ld.inpkts_to_sync_pipe) {
3990 report_packet_count(global_ld.inpkts_to_sync_pipe);
3991 global_ld.inpkts_to_sync_pipe = 0;
3994 /* If we've displayed a message about a write error, there's no point
3995 in displaying another message about an error on close. */
3996 if (!close_ok && write_ok) {
3997 capture_loop_get_errmsg(errmsg, sizeof(errmsg), secondary_errmsg,
3998 sizeof(secondary_errmsg),
3999 capture_opts->save_file, err_close, TRUE);
4000 report_capture_error(errmsg, secondary_errmsg);
4004 * XXX We exhibit different behaviour between normal mode and sync mode
4005 * when the pipe is stdin and not already at EOF. If we're a child, the
4006 * parent's stdin isn't closed, so if the user starts another capture,
4007 * cap_pipe_open_live() will very likely not see the expected magic bytes and
4008 * will say "Unrecognized libpcap format". On the other hand, in normal
4009 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
4012 report_capture_count(TRUE);
4014 /* get packet drop statistics from pcap */
4015 for (i = 0; i < capture_opts->ifaces->len; i++) {
4017 guint32 pcap_dropped = 0;
4019 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4020 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
4021 received = pcap_src->received;
4022 if (pcap_src->pcap_h != NULL) {
4023 g_assert(!pcap_src->from_cap_pipe);
4024 /* Get the capture statistics, so we know how many packets were dropped. */
4026 * Older versions of libpcap didn't set ps_ifdrop on some
4027 * platforms; initialize it to 0 to handle that.
4029 stats->ps_ifdrop = 0;
4030 if (pcap_stats(pcap_src->pcap_h, stats) >= 0) {
4031 *stats_known = TRUE;
4032 /* Let the parent process know. */
4033 pcap_dropped += stats->ps_drop;
4035 g_snprintf(errmsg, sizeof(errmsg),
4036 "Can't get packet-drop statistics: %s",
4037 pcap_geterr(pcap_src->pcap_h));
4038 report_capture_error(errmsg, please_report);
4041 report_packet_drops(received, pcap_dropped, pcap_src->dropped, pcap_src->flushed, stats->ps_ifdrop, interface_opts->display_name);
4044 /* close the input file (pcap or capture pipe) */
4045 capture_loop_close_input(&global_ld);
4047 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
4049 /* ok, if the write and the close were successful. */
4050 return write_ok && close_ok;
4053 if (capture_opts->multi_files_on) {
4054 /* cleanup ringbuffer */
4055 ringbuf_error_cleanup();
4057 /* We can't use the save file, and we have no FILE * for the stream
4058 to close in order to close it, so close the FD directly. */
4059 if (global_ld.save_file_fd != -1) {
4060 ws_close(global_ld.save_file_fd);
4063 /* We couldn't even start the capture, so get rid of the capture
4065 if (capture_opts->save_file != NULL) {
4066 ws_unlink(capture_opts->save_file);
4067 g_free(capture_opts->save_file);
4070 capture_opts->save_file = NULL;
4072 report_cfilter_error(capture_opts, error_index, errmsg);
4074 report_capture_error(errmsg, secondary_errmsg);
4076 /* close the input file (pcap or cap_pipe) */
4077 capture_loop_close_input(&global_ld);
4079 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
4086 capture_loop_stop(void)
4088 #ifdef HAVE_PCAP_BREAKLOOP
4090 capture_src *pcap_src;
4092 for (i = 0; i < global_ld.pcaps->len; i++) {
4093 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4094 if (pcap_src->pcap_h != NULL)
4095 pcap_breakloop(pcap_src->pcap_h);
4098 global_ld.go = FALSE;
4103 capture_loop_get_errmsg(char *errmsg, size_t errmsglen, char *secondary_errmsg,
4104 size_t secondary_errmsglen, const char *fname,
4105 int err, gboolean is_close)
4107 static const char find_space[] =
4108 "You will need to free up space on that file system"
4109 " or put the capture file on a different file system.";
4114 g_snprintf(errmsg, (gulong)errmsglen,
4115 "Not all the packets could be written to the file"
4116 " to which the capture was being saved\n"
4117 "(\"%s\") because there is no space left on the file system\n"
4118 "on which that file resides.",
4120 g_snprintf(secondary_errmsg, (gulong)secondary_errmsglen, "%s",
4126 g_snprintf(errmsg, (gulong)errmsglen,
4127 "Not all the packets could be written to the file"
4128 " to which the capture was being saved\n"
4129 "(\"%s\") because you are too close to, or over,"
4130 " your disk quota\n"
4131 "on the file system on which that file resides.",
4133 g_snprintf(secondary_errmsg, (gulong)secondary_errmsglen, "%s",
4140 g_snprintf(errmsg, (gulong)errmsglen,
4141 "The file to which the capture was being saved\n"
4142 "(\"%s\") could not be closed: %s.",
4143 fname, g_strerror(err));
4145 g_snprintf(errmsg, (gulong)errmsglen,
4146 "An error occurred while writing to the file"
4147 " to which the capture was being saved\n"
4149 fname, g_strerror(err));
4151 g_snprintf(secondary_errmsg, (gulong)secondary_errmsglen,
4152 "%s", please_report);
4158 * We wrote one packet. Update some statistics and check if we've met any
4159 * autostop or ring buffer conditions.
4162 capture_loop_wrote_one_packet(capture_src *pcap_src) {
4163 global_ld.packets_captured++;
4164 global_ld.packets_written++;
4165 pcap_src->received++;
4167 /* check -c NUM / -a packets:NUM */
4168 if (global_capture_opts.has_autostop_packets && global_ld.packets_captured >= global_capture_opts.autostop_packets) {
4169 fflush(global_ld.pdh);
4170 global_ld.go = FALSE;
4173 /* check -b packets:NUM */
4174 if (global_capture_opts.has_file_packets && global_ld.packets_written >= global_capture_opts.file_packets) {
4175 do_file_switch_or_stop(&global_capture_opts);
4178 /* check -a filesize:NUM */
4179 if (global_capture_opts.has_autostop_filesize &&
4180 global_capture_opts.autostop_filesize > 0 &&
4181 global_ld.bytes_written / 1000 >= global_capture_opts.autostop_filesize) {
4182 /* Capture size limit reached, do we have another file? */
4183 do_file_switch_or_stop(&global_capture_opts);
4188 /* one pcapng block was captured, process it */
4190 capture_loop_write_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, const u_char *pd)
4195 * This should never be called if we're not writing pcapng.
4197 g_assert(global_capture_opts.use_pcapng);
4199 /* We may be called multiple times from pcap_dispatch(); if we've set
4200 the "stop capturing" flag, ignore this packet, as we're not
4201 supposed to be saving any more packets. */
4202 if (!global_ld.go) {
4203 pcap_src->flushed++;
4207 if (global_ld.pdh) {
4208 gboolean successful;
4210 /* We're supposed to write the packet to a file; do so.
4211 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4212 "ld->err" to the error. */
4213 successful = pcapng_write_block(global_ld.pdh,
4215 bh->block_total_length,
4216 &global_ld.bytes_written, &err);
4218 fflush(global_ld.pdh);
4220 global_ld.go = FALSE;
4221 global_ld.err = err;
4222 pcap_src->dropped++;
4223 } else if (bh->block_type == BLOCK_TYPE_EPB || bh->block_type == BLOCK_TYPE_SPB || bh->block_type == BLOCK_TYPE_SYSTEMD_JOURNAL) {
4224 /* count packet only if we actually have an EPB or SPB */
4225 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4226 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4227 "Wrote a packet of length %d captured on interface %u.",
4228 bh->block_total_length, pcap_src->interface_id);
4230 capture_loop_wrote_one_packet(pcap_src);
4235 /* one packet was captured, process it */
4237 capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
4240 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4242 guint ts_mul = pcap_src->ts_nsec ? 1000000000 : 1000000;
4244 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_write_packet_cb");
4246 /* We may be called multiple times from pcap_dispatch(); if we've set
4247 the "stop capturing" flag, ignore this packet, as we're not
4248 supposed to be saving any more packets. */
4249 if (!global_ld.go) {
4250 pcap_src->flushed++;
4254 if (global_ld.pdh) {
4255 gboolean successful;
4257 /* We're supposed to write the packet to a file; do so.
4258 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4259 "ld->err" to the error. */
4260 if (global_capture_opts.use_pcapng) {
4261 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
4263 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4264 phdr->caplen, phdr->len,
4265 pcap_src->interface_id,
4268 &global_ld.bytes_written, &err);
4270 successful = libpcap_write_packet(global_ld.pdh,
4271 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4272 phdr->caplen, phdr->len,
4274 &global_ld.bytes_written, &err);
4277 global_ld.go = FALSE;
4278 global_ld.err = err;
4279 pcap_src->dropped++;
4281 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4282 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4283 "Wrote a packet of length %d captured on interface %u.",
4284 phdr->caplen, pcap_src->interface_id);
4286 capture_loop_wrote_one_packet(pcap_src);
4291 /* one packet was captured, queue it */
4293 capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
4296 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4297 pcap_queue_element *queue_element;
4298 gboolean limit_reached;
4300 /* We may be called multiple times from pcap_dispatch(); if we've set
4301 the "stop capturing" flag, ignore this packet, as we're not
4302 supposed to be saving any more packets. */
4303 if (!global_ld.go) {
4304 pcap_src->flushed++;
4308 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4309 if (queue_element == NULL) {
4310 pcap_src->dropped++;
4313 queue_element->pcap_src = pcap_src;
4314 queue_element->u.phdr = *phdr;
4315 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4316 if (queue_element->pd == NULL) {
4317 pcap_src->dropped++;
4318 g_free(queue_element);
4321 memcpy(queue_element->pd, pd, phdr->caplen);
4322 g_async_queue_lock(pcap_queue);
4323 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4324 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4325 limit_reached = FALSE;
4326 g_async_queue_push_unlocked(pcap_queue, queue_element);
4327 pcap_queue_bytes += phdr->caplen;
4328 pcap_queue_packets += 1;
4330 limit_reached = TRUE;
4332 g_async_queue_unlock(pcap_queue);
4333 if (limit_reached) {
4334 pcap_src->dropped++;
4335 g_free(queue_element->pd);
4336 g_free(queue_element);
4337 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4338 "Dropped a packet of length %d captured on interface %u.",
4339 phdr->caplen, pcap_src->interface_id);
4341 pcap_src->received++;
4342 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4343 "Queued a packet of length %d captured on interface %u.",
4344 phdr->caplen, pcap_src->interface_id);
4346 /* I don't want to hold the mutex over the debug output. So the
4347 output may be wrong */
4348 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4349 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4350 pcap_queue_bytes, pcap_queue_packets);
4353 /* one pcapng block was captured, queue it */
4355 capture_loop_queue_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, const u_char *pd)
4357 pcap_queue_element *queue_element;
4358 gboolean limit_reached;
4360 /* We may be called multiple times from pcap_dispatch(); if we've set
4361 the "stop capturing" flag, ignore this packet, as we're not
4362 supposed to be saving any more packets. */
4363 if (!global_ld.go) {
4364 pcap_src->flushed++;
4368 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4369 if (queue_element == NULL) {
4370 pcap_src->dropped++;
4373 queue_element->pcap_src = pcap_src;
4374 queue_element->u.bh = *bh;
4375 queue_element->pd = (u_char *)g_malloc(bh->block_total_length);
4376 if (queue_element->pd == NULL) {
4377 pcap_src->dropped++;
4378 g_free(queue_element);
4381 memcpy(queue_element->pd, pd, bh->block_total_length);
4382 g_async_queue_lock(pcap_queue);
4383 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4384 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4385 limit_reached = FALSE;
4386 g_async_queue_push_unlocked(pcap_queue, queue_element);
4387 pcap_queue_bytes += bh->block_total_length;
4388 pcap_queue_packets += 1;
4390 limit_reached = TRUE;
4392 g_async_queue_unlock(pcap_queue);
4393 if (limit_reached) {
4394 pcap_src->dropped++;
4395 g_free(queue_element->pd);
4396 g_free(queue_element);
4397 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4398 "Dropped a packet of length %d captured on interface %u.",
4399 bh->block_total_length, pcap_src->interface_id);
4401 pcap_src->received++;
4402 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4403 "Queued a packet of length %d captured on interface %u.",
4404 bh->block_total_length, pcap_src->interface_id);
4406 /* I don't want to hold the mutex over the debug output. So the
4407 output may be wrong */
4408 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4409 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4410 pcap_queue_bytes, pcap_queue_packets);
4414 set_80211_channel(const char *iface, const char *opt)
4418 guint32 center_freq1 = 0;
4419 guint32 center_freq2 = 0;
4422 gchar **options = NULL;
4424 options = g_strsplit_set(opt, ",", 4);
4425 for (args = 0; options[args]; args++);
4428 freq = get_nonzero_guint32(options[0], "802.11 channel frequency");
4430 if (args >= 1 && options[1]) {
4431 type = ws80211_str_to_chan_type(options[1]);
4433 cmdarg_err("\"%s\" is not a valid 802.11 channel type", options[1]);
4439 if (args >= 2 && options[2])
4440 center_freq1 = get_nonzero_guint32(options[2], "VHT center frequency");
4442 if (args >= 3 && options[3])
4443 center_freq2 = get_nonzero_guint32(options[3], "VHT center frequency 2");
4445 ret = ws80211_init();
4447 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4451 ret = ws80211_set_freq(iface, freq, type, center_freq1, center_freq2);
4454 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4460 pipe_write_block(2, SP_SUCCESS, NULL);
4463 g_strfreev(options);
4468 get_dumpcap_compiled_info(GString *str)
4470 /* Capture libraries */
4471 g_string_append(str, ", ");
4472 get_compiled_caplibs_version(str);
4476 get_dumpcap_runtime_info(GString *str)
4478 /* Capture libraries */
4479 g_string_append(str, ", ");
4480 get_runtime_caplibs_version(str);
4483 /* And now our feature presentation... [ fade to music ] */
4485 real_main(int argc, char *argv[])
4487 GString *comp_info_str;
4488 GString *runtime_info_str;
4490 static const struct option long_options[] = {
4491 {"help", no_argument, NULL, 'h'},
4492 {"version", no_argument, NULL, 'v'},
4493 LONGOPT_CAPTURE_COMMON
4497 gboolean arg_error = FALSE;
4503 struct sigaction action, oldaction;
4506 gboolean start_capture = TRUE;
4507 gboolean stats_known;
4508 struct pcap_stat stats;
4509 GLogLevelFlags log_flags;
4510 gboolean list_interfaces = FALSE;
4511 int caps_queries = 0;
4512 #ifdef HAVE_BPF_IMAGE
4513 gboolean print_bpf_code = FALSE;
4515 gboolean set_chan = FALSE;
4516 gchar *set_chan_arg = NULL;
4517 gboolean machine_readable = FALSE;
4518 gboolean print_statistics = FALSE;
4519 int status, run_once_args = 0;
4522 #if defined(__APPLE__) && defined(__LP64__)
4523 struct utsname osinfo;
4527 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
4529 /* Get the compile-time version information string */
4530 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
4532 /* Get the run-time version information string */
4533 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
4535 /* Add it to the information to be reported on a crash. */
4536 ws_add_crash_info("Dumpcap (Wireshark) %s\n"
4541 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
4542 g_string_free(comp_info_str, TRUE);
4543 g_string_free(runtime_info_str, TRUE);
4546 create_app_running_mutex();
4549 * Initialize our DLL search path. MUST be called before LoadLibrary
4552 ws_init_dll_search_path();
4555 #ifdef HAVE_BPF_IMAGE
4556 #define OPTSTRING_d "d"
4558 #define OPTSTRING_d ""
4561 #ifdef HAVE_PCAP_REMOTE
4562 #define OPTSTRING_r "r"
4563 #define OPTSTRING_u "u"
4565 #define OPTSTRING_r ""
4566 #define OPTSTRING_u ""
4569 #ifdef HAVE_PCAP_SETSAMPLING
4570 #define OPTSTRING_m "m:"
4572 #define OPTSTRING_m ""
4575 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
4577 #ifdef DEBUG_CHILD_DUMPCAP
4578 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4579 fprintf (stderr, "Unable to open debug log file .\n");
4584 #if defined(__APPLE__) && defined(__LP64__)
4586 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
4587 * a bug workaround - timeouts less than 1 second don't work with libpcap
4588 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
4589 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4590 * The problem is extremely unlikely to be reintroduced in a future
4593 if (uname(&osinfo) == 0) {
4595 * {Mac} OS X/macOS 10.x uses Darwin {x+4}.0.0; 10.x.y uses Darwin
4596 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4597 * number of 10.0.0, not 10.1.0 - go figure).
4599 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
4600 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
4601 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
4602 need_timeout_workaround = TRUE;
4607 * Determine if dumpcap is being requested to run in a special
4608 * capture_child mode by going thru the command line args to see if
4609 * a -Z is present. (-Z is a hidden option).
4611 * The primary result of running in capture_child mode is that
4612 * all messages sent out on stderr are in a special type/len/string
4613 * format to allow message processing by type. These messages include
4614 * error messages if dumpcap fails to start the operation it was
4615 * requested to do, as well as various "status" messages which are sent
4616 * when an actual capture is in progress, and a "success" message sent
4617 * if dumpcap was requested to perform an operation other than a
4620 * Capture_child mode would normally be requested by a parent process
4621 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4622 * to which dumpcap stderr has been redirected. It might also have
4623 * another pipe to obtain dumpcap stdout output; for operations other
4624 * than a capture, that information is formatted specially for easier
4625 * parsing by the parent process.
4627 * Capture_child mode needs to be determined immediately upon
4628 * startup so that any messages generated by dumpcap in this mode
4629 * (eg: during initialization) will be formatted properly.
4632 for (i=1; i<argc; i++) {
4633 if (strcmp("-Z", argv[i]) == 0) {
4634 capture_child = TRUE;
4635 machine_readable = TRUE; /* request machine-readable output */
4637 /* set output pipe to binary mode, to avoid ugly text conversions */
4638 _setmode(2, O_BINARY);
4643 /* The default_log_handler will use stdout, which makes trouble in */
4644 /* capture child mode, as it uses stdout for its sync_pipe. */
4645 /* So: the filtering is done in the console_log_handler and not here.*/
4646 /* We set the log handlers right up front to make sure that any log */
4647 /* messages when running as child will be sent back to the parent */
4648 /* with the correct format. */
4653 G_LOG_LEVEL_CRITICAL|
4654 G_LOG_LEVEL_WARNING|
4655 G_LOG_LEVEL_MESSAGE|
4659 G_LOG_FLAG_RECURSION);
4661 g_log_set_handler(NULL,
4663 console_log_handler, NULL /* user_data */);
4664 g_log_set_handler(LOG_DOMAIN_MAIN,
4666 console_log_handler, NULL /* user_data */);
4667 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4669 console_log_handler, NULL /* user_data */);
4670 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4672 console_log_handler, NULL /* user_data */);
4674 /* Initialize the pcaps list */
4675 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(capture_src *));
4678 /* Load wpcap if possible. Do this before collecting the run-time version information */
4681 /* ... and also load the packet.dll from wpcap */
4682 /* XXX - currently not required, may change later. */
4683 /*wpcap_packet_load();*/
4685 /* Start windows sockets */
4686 result = WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4689 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_ERROR,
4690 "ERROR: WSAStartup failed with error: %d", result);
4694 /* Set handler for Ctrl+C key */
4695 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4697 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4698 and exit. Do the same with SIGPIPE, in case, for example,
4699 we're writing to our standard output and it's a pipe.
4700 Do the same with SIGHUP if it's not being ignored (if we're
4701 being run under nohup, it might be ignored, in which case we
4702 should leave it ignored).
4704 XXX - apparently, Coverity complained that part of action
4705 wasn't initialized. Perhaps it's running on Linux, where
4706 struct sigaction has an ignored "sa_restorer" element and
4707 where "sa_handler" and "sa_sigaction" might not be two
4708 members of a union. */
4709 memset(&action, 0, sizeof(action));
4710 action.sa_handler = capture_cleanup_handler;
4712 * Arrange that system calls not get restarted, because when
4713 * our signal handler returns we don't want to restart
4714 * a call that was waiting for packets to arrive.
4716 action.sa_flags = 0;
4717 sigemptyset(&action.sa_mask);
4718 sigaction(SIGTERM, &action, NULL);
4719 sigaction(SIGINT, &action, NULL);
4720 sigaction(SIGPIPE, &action, NULL);
4721 sigaction(SIGHUP, NULL, &oldaction);
4722 if (oldaction.sa_handler == SIG_DFL)
4723 sigaction(SIGHUP, &action, NULL);
4726 /* Catch SIGINFO and, if we get it and we're capturing in
4727 quiet mode, report the number of packets we've captured. */
4728 action.sa_handler = report_counts_siginfo;
4729 action.sa_flags = SA_RESTART;
4730 sigemptyset(&action.sa_mask);
4731 sigaction(SIGINFO, &action, NULL);
4732 #endif /* SIGINFO */
4735 /* ----------------------------------------------------------------- */
4736 /* Privilege and capability handling */
4738 /* 1. Running not as root or suid root; no special capabilities. */
4741 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4744 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4746 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4747 /* capabilities; Drop all other capabilities; */
4748 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4749 /* else: after pcap_open_live() in capture_loop_open_input() */
4750 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4751 /* (Note: this means that the process, although logged in */
4752 /* as root, does not have various permissions such as the */
4753 /* ability to bypass file access permissions). */
4754 /* XXX: Should we just leave capabilities alone in this case */
4755 /* so that user gets expected effect that root can do */
4758 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4760 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4761 /* else: after pcap_open_live() in capture_loop_open_input() */
4762 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4763 /* pcap_open_live). */
4765 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4767 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4768 /* capabilities; Drop all other capabilities; */
4769 /* Drop suid privileges (euid=ruid); */
4770 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4771 /* else: after pcap_open_live() in capture_loop_open_input() */
4772 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4774 /* XXX: For some Linux versions/distros with capabilities */
4775 /* a 'normal' process with any capabilities cannot be */
4776 /* 'killed' (signaled) from another (same uid) non-privileged */
4778 /* For example: If (non-suid) Wireshark forks a */
4779 /* child suid dumpcap which acts as described here (case 5), */
4780 /* Wireshark will be unable to kill (signal) the child */
4781 /* dumpcap process until the capabilities have been dropped */
4782 /* (after pcap_open_live()). */
4783 /* This behaviour will apparently be changed in the kernel */
4784 /* to allow the kill (signal) in this case. */
4785 /* See the following for details: */
4786 /* https://www.mail-archive.com/ [wrapped] */
4787 /* linux-security-module@vger.kernel.org/msg02913.html */
4789 /* It is therefore conceivable that if dumpcap somehow hangs */
4790 /* in pcap_open_live or before that wireshark will not */
4791 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4792 /* In this case, exiting wireshark will kill the child */
4793 /* dumpcap process. */
4795 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4796 /* capabilities; Using libcap. Note: capset cmd (which see) */
4797 /* used to assign capabilities to file. */
4799 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4800 /* else: after pcap_open_live() in capture_loop_open_input() */
4801 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4803 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4804 /* longer required (similar to capture). */
4806 /* ----------------------------------------------------------------- */
4808 init_process_policies();
4811 /* If 'started with special privileges' (and using libcap) */
4812 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4813 /* Set euid/egid = ruid/rgid to remove suid privileges */
4814 relinquish_privs_except_capture();
4817 /* Set the initial values in the capture options. This might be overwritten
4818 by the command line parameters. */
4819 capture_opts_init(&global_capture_opts);
4820 /* We always save to a file - if no file was specified, we save to a
4822 global_capture_opts.saving_to_file = TRUE;
4823 global_capture_opts.has_ring_num_files = TRUE;
4825 /* Pass on capture_child mode for capture_opts */
4826 global_capture_opts.capture_child = capture_child;
4828 /* Now get our args */
4829 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4831 case 'h': /* Print help and exit */
4832 printf("Dumpcap (Wireshark) %s\n"
4833 "Capture network packets and dump them into a pcapng or pcap file.\n"
4834 "See https://www.wireshark.org for more information.\n",
4835 get_ws_vcs_version_info());
4836 print_usage(stdout);
4839 case 'v': /* Show version and exit */
4840 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
4841 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
4842 show_version("Dumpcap (Wireshark)", comp_info_str, runtime_info_str);
4843 g_string_free(comp_info_str, TRUE);
4844 g_string_free(runtime_info_str, TRUE);
4847 /*** capture option specific ***/
4848 case 'a': /* autostop criteria */
4849 case 'b': /* Ringbuffer option */
4850 case 'c': /* Capture x packets */
4851 case 'f': /* capture filter */
4852 case 'g': /* enable group read access on file(s) */
4853 case 'i': /* Use interface x */
4854 case LONGOPT_SET_TSTAMP_TYPE: /* Set capture timestamp type */
4855 case 'n': /* Use pcapng format */
4856 case 'p': /* Don't capture in promiscuous mode */
4857 case 'P': /* Use pcap format */
4858 case 's': /* Set the snapshot (capture) length */
4859 case 'w': /* Write to capture file x */
4860 case 'y': /* Set the pcap data link type */
4861 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4862 #ifdef HAVE_PCAP_REMOTE
4863 case 'u': /* Use UDP for data transfer */
4864 case 'r': /* Capture own RPCAP traffic too */
4865 case 'A': /* Authentication */
4867 #ifdef HAVE_PCAP_SETSAMPLING
4868 case 'm': /* Sampling */
4870 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
4871 case 'B': /* Buffer size */
4873 #ifdef HAVE_PCAP_CREATE
4874 case 'I': /* Monitor mode */
4876 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4881 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4883 capture_child = TRUE;
4885 /* set output pipe to binary mode, to avoid ugly text conversions */
4886 _setmode(2, O_BINARY);
4888 * optarg = the control ID, aka the PPID, currently used for the
4891 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4892 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4893 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4894 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4896 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4897 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4898 "Signal pipe: Unable to open %s. Dead parent?",
4906 case 'q': /* Quiet */
4912 /*** all non capture option specific ***/
4913 case 'D': /* Print a list of capture devices and exit */
4914 if (!list_interfaces) {
4915 list_interfaces = TRUE;
4919 case 'L': /* Print list of link-layer types and exit */
4920 if (!(caps_queries & CAPS_QUERY_LINK_TYPES)) {
4921 caps_queries |= CAPS_QUERY_LINK_TYPES;
4925 case LONGOPT_LIST_TSTAMP_TYPES:
4926 caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
4928 #ifdef HAVE_BPF_IMAGE
4929 case 'd': /* Print BPF code for capture filter and exit */
4930 if (!print_bpf_code) {
4931 print_bpf_code = TRUE;
4936 case 'S': /* Print interface statistics once a second */
4937 if (!print_statistics) {
4938 print_statistics = TRUE;
4942 case 'k': /* Set wireless channel */
4945 set_chan_arg = optarg;
4948 cmdarg_err("Only one -k flag may be specified");
4952 case 'M': /* For -D, -L, and -S, print machine-readable output */
4953 machine_readable = TRUE;
4956 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4959 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4962 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4964 case '?': /* Bad flag - print usage message */
4973 /* user specified file name as regular command-line argument */
4974 /* XXX - use it as the capture file name (or something else)? */
4980 * Extra command line arguments were specified; complain.
4981 * XXX - interpret as capture filter, as tcpdump and tshark do?
4983 cmdarg_err("Invalid argument: %s", argv[0]);
4988 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4991 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4992 /* Use some default if the user hasn't specified some */
4993 /* XXX: Are these defaults good enough? */
4994 pcap_queue_byte_limit = 1000 * 1000;
4995 pcap_queue_packet_limit = 1000;
4998 print_usage(stderr);
5002 if (run_once_args > 1) {
5003 #ifdef HAVE_BPF_IMAGE
5004 cmdarg_err("Only one of -D, -L, -d, -k or -S may be supplied.");
5006 cmdarg_err("Only one of -D, -L, -k or -S may be supplied.");
5009 } else if (run_once_args == 1) {
5010 /* We're supposed to print some information, rather than
5011 to capture traffic; did they specify a ring buffer option? */
5012 if (global_capture_opts.multi_files_on) {
5013 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
5017 /* We're supposed to capture traffic; */
5019 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
5020 if (global_capture_opts.ifaces->len > 1) {
5022 global_capture_opts.use_pcapng = TRUE;
5025 if (global_capture_opts.capture_comment &&
5026 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
5027 /* XXX - for ringbuffer, should we apply the comment to each file? */
5028 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
5032 /* Was the ring buffer option specified and, if so, does it make sense? */
5033 if (global_capture_opts.multi_files_on) {
5034 /* Ring buffer works only under certain conditions:
5035 a) ring buffer does not work with temporary files;
5036 b) it makes no sense to enable the ring buffer if the maximum
5037 file size is set to "infinite". */
5038 if (global_capture_opts.save_file == NULL) {
5039 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
5040 global_capture_opts.multi_files_on = FALSE;
5042 if (!global_capture_opts.has_autostop_filesize &&
5043 !global_capture_opts.has_file_duration &&
5044 !global_capture_opts.has_file_interval &&
5045 !global_capture_opts.has_file_packets) {
5046 cmdarg_err("Ring buffer requested, but no maximum capture file size, duration "
5047 "interval, or packets were specified.");
5049 /* XXX - this must be redesigned as the conditions changed */
5050 global_capture_opts.multi_files_on = FALSE;
5053 if (global_capture_opts.has_file_duration && global_capture_opts.has_file_interval) {
5054 cmdarg_err("Ring buffer file duration and interval can't be used at the same time.");
5061 * "-D" requires no interface to be selected; it's supposed to list
5064 if (list_interfaces) {
5065 /* Get the list of interfaces */
5070 if_list = capture_interface_list(&err, &err_str, NULL);
5071 if (if_list == NULL) {
5074 * If we're being run by another program, just give them
5075 * an empty list of interfaces, don't report this as
5076 * an error; that lets them decide whether to report
5077 * this as an error or not.
5079 if (!machine_readable) {
5080 cmdarg_err("There are no interfaces on which a capture can be done");
5084 cmdarg_err("%s", err_str);
5090 if (machine_readable) /* tab-separated values to stdout */
5091 print_machine_readable_interfaces(if_list);
5093 capture_opts_print_interfaces(if_list);
5094 free_interface_list(if_list);
5099 * "-S" requires no interface to be selected; it gives statistics
5100 * for all interfaces.
5102 if (print_statistics) {
5103 status = print_statistics_loop(machine_readable);
5108 interface_options *interface_opts;
5110 if (global_capture_opts.ifaces->len != 1) {
5111 cmdarg_err("Need one interface");
5115 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
5116 status = set_80211_channel(interface_opts->name, set_chan_arg);
5121 * "-L", "-d", and capturing act on a particular interface, so we have to
5122 * have an interface; if none was specified, pick a default.
5124 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
5126 /* cmdarg_err() already called .... */
5131 /* Get the list of link-layer and/or timestamp types for the capture device. */
5132 if_capabilities_t *caps;
5133 cap_device_open_err err;
5137 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
5138 int if_caps_queries = caps_queries;
5139 interface_options *interface_opts;
5141 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, ii);
5143 caps = get_if_capabilities(interface_opts, &err, &err_str);
5145 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
5146 "%s", interface_opts->name, err_str,
5147 get_pcap_failure_secondary_error_message(err, err_str));
5151 if ((if_caps_queries & CAPS_QUERY_LINK_TYPES) && caps->data_link_types == NULL) {
5152 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts->name);
5154 } /* No timestamp types is no big deal. So we will just ignore it */
5156 if (interface_opts->monitor_mode)
5157 if_caps_queries |= CAPS_MONITOR_MODE;
5159 if (machine_readable) /* tab-separated values to stdout */
5160 /* XXX: We need to change the format and adapt consumers */
5161 print_machine_readable_if_capabilities(caps, if_caps_queries);
5163 /* XXX: We might want to print also the interface name */
5164 capture_opts_print_if_capabilities(caps, interface_opts->name, if_caps_queries);
5165 free_if_capabilities(caps);
5170 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
5171 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5172 interface_options *interface_opts;
5174 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5175 if (interface_opts->timestamp_type) {
5176 interface_opts->timestamp_type_id = pcap_tstamp_type_name_to_val(interface_opts->timestamp_type);
5177 if (interface_opts->timestamp_type_id < 0) {
5178 cmdarg_err("Invalid argument to option: --time-stamp-type=%s", interface_opts->timestamp_type);
5185 /* We're supposed to do a capture, or print the BPF code for a filter. */
5187 /* Let the user know what interfaces were chosen. */
5188 if (capture_child) {
5189 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5190 interface_options *interface_opts;
5192 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5193 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
5194 interface_opts->name);
5197 str = g_string_new("");
5199 if (global_capture_opts.ifaces->len < 2)
5201 if (global_capture_opts.ifaces->len < 4)
5204 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5205 interface_options *interface_opts;
5207 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5209 if (global_capture_opts.ifaces->len > 2) {
5210 g_string_append_printf(str, ",");
5212 g_string_append_printf(str, " ");
5213 if (j == global_capture_opts.ifaces->len - 1) {
5214 g_string_append_printf(str, "and ");
5217 g_string_append_printf(str, "'%s'", interface_opts->display_name);
5220 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
5222 fprintf(stderr, "Capturing on %s\n", str->str);
5223 g_string_free(str, TRUE);
5226 /* Process the snapshot length, as that affects the generated BPF code. */
5227 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
5229 #ifdef HAVE_BPF_IMAGE
5230 if (print_bpf_code) {
5231 show_filter_code(&global_capture_opts);
5236 /* We're supposed to do a capture. Process the ring buffer arguments. */
5237 capture_opts_trim_ring_num_files(&global_capture_opts);
5239 /* flush stderr prior to starting the main capture loop */
5242 /* Now start the capture. */
5243 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
5247 /* capture failed */
5250 return 0; /* never here, make compiler happy */
5255 wmain(int argc, wchar_t *wc_argv[])
5259 argv = arg_list_utf_16to8(argc, wc_argv);
5260 return real_main(argc, argv);
5264 main(int argc, char *argv[])
5266 return real_main(argc, argv);
5271 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
5272 const char *message, gpointer user_data _U_)
5279 /* ignore log message, if log_level isn't interesting */
5280 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5281 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
5286 switch(log_level & G_LOG_LEVEL_MASK) {
5287 case G_LOG_LEVEL_ERROR:
5290 case G_LOG_LEVEL_CRITICAL:
5293 case G_LOG_LEVEL_WARNING:
5296 case G_LOG_LEVEL_MESSAGE:
5299 case G_LOG_LEVEL_INFO:
5302 case G_LOG_LEVEL_DEBUG:
5306 fprintf(stderr, "unknown log_level %d\n", log_level);
5308 g_assert_not_reached();
5311 /* Generate the output message */
5312 if (log_level & G_LOG_LEVEL_MESSAGE) {
5313 /* normal user messages without additional infos */
5314 msg = g_strdup_printf("%s\n", message);
5316 /* create a "timestamp" */
5318 today = localtime(&curr);
5320 /* info/debug messages with additional infos */
5322 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
5323 today->tm_hour, today->tm_min, today->tm_sec,
5324 log_domain != NULL ? log_domain : "",
5327 msg = g_strdup_printf("Time not representable %8s %s %s\n",
5328 log_domain != NULL ? log_domain : "",
5332 /* DEBUG & INFO msgs (if we're debugging today) */
5333 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
5334 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5335 #ifdef DEBUG_DUMPCAP
5336 fprintf(stderr, "%s", msg);
5339 #ifdef DEBUG_CHILD_DUMPCAP
5340 fprintf(debug_log, "%s", msg);
5348 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
5349 /* to parent especially formatted if dumpcap running as child. */
5350 if (capture_child) {
5351 sync_pipe_errmsg_to_parent(2, msg, "");
5353 fprintf(stderr, "%s", msg);
5360 /****************************************************************************************************************/
5361 /* indication report routines */
5365 report_packet_count(unsigned int packet_count)
5367 char tmp[SP_DECISIZE+1+1];
5368 static unsigned int count = 0;
5370 if (capture_child) {
5371 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
5372 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
5373 pipe_write_block(2, SP_PACKET_COUNT, tmp);
5375 count += packet_count;
5376 fprintf(stderr, "\rPackets: %u ", count);
5377 /* stderr could be line buffered */
5383 report_new_capture_file(const char *filename)
5385 if (capture_child) {
5386 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
5387 pipe_write_block(2, SP_FILE, filename);
5391 * Prevent a SIGINFO handler from writing to the standard error
5392 * while we're doing so; instead, have it just set a flag telling
5393 * us to print that information when we're done.
5396 #endif /* SIGINFO */
5397 fprintf(stderr, "File: %s\n", filename);
5398 /* stderr could be line buffered */
5403 * Allow SIGINFO handlers to write.
5408 * If a SIGINFO handler asked us to write out capture counts, do so.
5411 report_counts_for_siginfo();
5412 #endif /* SIGINFO */
5417 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
5419 interface_options *interface_opts;
5420 char tmp[MSG_MAX_LENGTH+1+6];
5422 if (i < capture_opts->ifaces->len) {
5423 if (capture_child) {
5424 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
5425 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
5426 pipe_write_block(2, SP_BAD_FILTER, tmp);
5429 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5430 * the error message below.
5432 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
5434 "Invalid capture filter \"%s\" for interface '%s'.\n"
5436 "That string isn't a valid capture filter (%s).\n"
5437 "See the User's Guide for a description of the capture filter syntax.",
5438 interface_opts->cfilter, interface_opts->name, errmsg);
5444 report_capture_error(const char *error_msg, const char *secondary_error_msg)
5446 if (capture_child) {
5447 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5448 "Primary Error: %s", error_msg);
5449 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5450 "Secondary Error: %s", secondary_error_msg);
5451 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5453 cmdarg_err("%s", error_msg);
5454 if (secondary_error_msg[0] != '\0')
5455 cmdarg_err_cont("%s", secondary_error_msg);
5460 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
5462 char tmp[SP_DECISIZE+1+1];
5463 guint32 total_drops = pcap_drops + drops + flushed;
5465 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
5467 if (capture_child) {
5468 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5469 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
5470 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
5471 /* XXX: Need to provide interface id, changes to consumers required. */
5472 pipe_write_block(2, SP_DROPS, tmp);
5475 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
5476 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
5477 received ? 100.0 * received / (received + total_drops) : 0.0);
5478 /* stderr could be line buffered */
5484 /************************************************************************************************/
5485 /* signal_pipe handling */
5490 signal_pipe_check_running(void)
5492 /* any news from our parent? -> just stop the capture */
5496 /* if we are running standalone, no check required */
5497 if (!capture_child) {
5501 if (!sig_pipe_name || !sig_pipe_handle) {
5502 /* This shouldn't happen */
5503 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5504 "Signal pipe: No name or handle");
5509 * XXX - We should have the process ID of the parent (from the "-Z" flag)
5510 * at this point. Should we check to see if the parent is still alive,
5511 * e.g. by using OpenProcess?
5514 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5516 if (!result || avail > 0) {
5517 /* peek failed or some bytes really available */
5518 /* (if not piping from stdin this would fail) */
5519 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5520 "Signal pipe: Stop capture: %s", sig_pipe_name);
5521 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5522 "Signal pipe: %s (%p) result: %u avail: %lu", sig_pipe_name,
5523 sig_pipe_handle, result, avail);
5526 /* pipe ok and no bytes available */
5533 * Editor modelines - https://www.wireshark.org/tools/modelines.html
5538 * indent-tabs-mode: nil
5541 * vi: set shiftwidth=4 tabstop=8 expandtab:
5542 * :indentSize=4:tabSize=8:noTabs=true: