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 #ifdef HAVE_SYS_TYPES_H
19 # include <sys/types.h>
22 #ifdef HAVE_SYS_SOCKET_H
23 #include <sys/socket.h>
26 #ifdef HAVE_NETINET_IN_H
27 #include <netinet/in.h>
34 #ifdef HAVE_ARPA_INET_H
35 #include <arpa/inet.h>
38 #if defined(__APPLE__) && defined(__LP64__)
39 #include <sys/utsname.h>
45 #include <wsutil/cmdarg_err.h>
46 #include <wsutil/crash_info.h>
47 #include <wsutil/strtoi.h>
48 #include <version_info.h>
50 #ifndef HAVE_GETOPT_LONG
51 #include "wsutil/wsgetopt.h"
55 # include <sys/prctl.h>
56 # include <sys/capability.h>
59 #include "ringbuffer.h"
61 #include "caputils/capture_ifinfo.h"
62 #include "caputils/capture-pcap-util.h"
63 #include "caputils/capture-pcap-util-int.h"
65 #include "caputils/capture-wpcap.h"
68 #include "writecap/pcapio.h"
71 #include <wsutil/unicode-utils.h>
78 #include <wsutil/clopts_common.h>
79 #include <wsutil/privileges.h>
81 #include "sync_pipe.h"
83 #include "capture_opts.h"
84 #include <capchild/capture_session.h>
85 #include <capchild/capture_sync.h>
87 #include "conditions.h"
88 #include "capture_stop_conditions.h"
90 #include "wsutil/tempfile.h"
92 #include "wsutil/file_util.h"
93 #include "wsutil/cpu_info.h"
94 #include "wsutil/os_version_info.h"
95 #include "wsutil/str_util.h"
96 #include "wsutil/inet_addr.h"
97 #include "wsutil/time_util.h"
99 #include "caputils/ws80211_utils.h"
104 * Get information about libpcap format from "wiretap/libpcap.h".
105 * Get information about pcapng format from "wiretap/pcapng_module.h".
106 * XXX - can we just use pcap_open_offline() to read the pipe?
108 #include "wiretap/libpcap.h"
109 #include "wiretap/pcapng_module.h"
110 #include "wiretap/pcapng.h"
112 /**#define DEBUG_DUMPCAP**/
113 /**#define DEBUG_CHILD_DUMPCAP**/
117 #include <conio.h> /* _getch() */
121 /* for g_thread_new */
122 #include "wsutil/glib-compat.h"
124 #ifdef DEBUG_CHILD_DUMPCAP
125 FILE *debug_log; /* for logging debug messages to */
126 /* a file if DEBUG_CHILD_DUMPCAP */
130 static GAsyncQueue *pcap_queue;
131 static gint64 pcap_queue_bytes;
132 static gint64 pcap_queue_packets;
133 static gint64 pcap_queue_byte_limit = 0;
134 static gint64 pcap_queue_packet_limit = 0;
136 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
138 static gchar *sig_pipe_name = NULL;
139 static HANDLE sig_pipe_handle = NULL;
140 static gboolean signal_pipe_check_running(void);
144 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
145 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
148 /** Stop a low-level capture (stops the capture child). */
149 static void capture_loop_stop(void);
150 /** Close a pipe, or socket if \a from_socket is TRUE */
151 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
153 #if !defined (__linux__)
154 #ifndef HAVE_PCAP_BREAKLOOP
156 * We don't have pcap_breakloop(), which is the only way to ensure that
157 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
158 * won't, if the call to read the next packet or batch of packets is
159 * is interrupted by a signal on UN*X, just go back and try again to
162 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
163 * the signal handler, set a flag to stop capturing; however, without
164 * a guarantee of that sort, we can't guarantee that we'll stop capturing
165 * if the read will be retried and won't time out if no packets arrive.
167 * Therefore, on at least some platforms, we work around the lack of
168 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
169 * to wait for packets to arrive, so that we're probably going to be
170 * blocked in the select() when the signal arrives, and can just bail
171 * out of the loop at that point.
173 * However, we don't want to do that on BSD (because "select()" doesn't work
174 * correctly on BPF devices on at least some releases of some flavors of
175 * BSD), and we don't want to do it on Windows (because "select()" is
176 * something for sockets, not for arbitrary handles). (Note that "Windows"
177 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
178 * using WinPcap, not a UNIX libpcap.)
180 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
181 * on BSD times out even if no packets have arrived, so we'll eventually
182 * exit pcap_dispatch() with an indication that no packets have arrived,
183 * and will break out of the capture loop at that point.
185 * On Windows, we can't send a SIGINT to stop capturing, so none of this
186 * applies in any case.
188 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
189 * want to include it if it's not present on this platform, however.
191 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
192 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
194 # define MUST_DO_SELECT
195 # endif /* avoid select */
196 #endif /* HAVE_PCAP_BREAKLOOP */
198 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
199 * in pcap_dispatch(); on the other hand, select() works just fine there.
200 * Hence we use a select for that come what may.
202 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
203 * internally, and, with TPACKET_V3, once that's supported, it'll
204 * support timeouts, at least as I understand the way the code works.
206 #define MUST_DO_SELECT
209 /** init the capture filter */
212 INITFILTER_BAD_FILTER,
213 INITFILTER_OTHER_ERROR
214 } initfilter_status_t;
217 STATE_EXPECT_REC_HDR,
230 typedef struct _pcap_pipe_info {
231 struct pcap_hdr hdr; /**< Pcap header when capturing from a pipe */
232 struct pcaprec_modified_hdr rechdr; /**< Pcap record header when capturing from a pipe */
235 typedef struct _pcapng_pipe_info {
236 struct pcapng_block_header_s bh; /**< Pcapng general block header when capturing from a pipe */
237 struct pcapng_section_header_block_s shb; /**< Pcapng section header when capturing from a pipe */
238 GList *saved_blocks; /**< Pcapng block list of SHB and IDBs for multi_file_on */
239 } pcapng_pipe_info_t;
241 struct _loop_data; /* forward declaration so we can use it in the cap_pipe_dispatch function pointer */
244 * A source of packets from which we're capturing.
246 typedef struct _capture_src {
251 #ifdef MUST_DO_SELECT
252 int pcap_fd; /**< pcap file descriptor */
259 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
260 /**< capture pipe (unix only "input file") */
261 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
262 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
263 gboolean from_pcapng; /**< TRUE if we're capturing from pcapng format */
265 pcap_pipe_info_t pcap; /**< Pcap info when capturing from a pipe */
266 pcapng_pipe_info_t pcapng; /**< Pcapng info when capturing from a pipe */
269 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
271 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
272 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
273 gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
274 char * cap_pipe_databuf; /**< Pointer to the data buffer we've allocated */
275 size_t cap_pipe_databuf_size; /**< Current size of the data buffer */
276 guint cap_pipe_max_pkt_size; /**< Maximum packet size allowed */
278 char * cap_pipe_buf; /**< Pointer to the buffer we read into */
279 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
280 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
282 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
283 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
285 int (*cap_pipe_dispatch)(struct _loop_data *, struct _capture_src *, char *, int);
286 cap_pipe_state_t cap_pipe_state;
287 cap_pipe_err_t cap_pipe_err;
290 GMutex *cap_pipe_read_mtx;
291 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
296 * Global capture loop state.
298 typedef struct _loop_data {
300 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
301 int err; /**< if non-zero, error seen while capturing */
302 gint packet_count; /**< Number of packets we have already captured */
303 gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
304 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
306 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
308 GArray *pcaps; /**< Array of capture_src's on which we're capturing */
312 guint64 bytes_written;
313 guint32 autostop_files;
316 typedef struct _pcap_queue_element {
317 capture_src *pcap_src;
319 struct pcap_pkthdr phdr;
320 struct pcapng_block_header_s bh;
323 } pcap_queue_element;
326 * Standard secondary message for unexpected errors.
328 static const char please_report[] =
329 "Please report this to the Wireshark developers.\n"
330 "https://bugs.wireshark.org/\n"
331 "(This is not a crash; please do not report it as such.)";
334 * This needs to be static, so that the SIGINT handler can clear the "go"
337 static loop_data global_ld;
340 * Timeout, in milliseconds, for reads from the stream of captured packets
341 * from a capture device.
343 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
344 * 64-bit applications, with sub-second timeouts not to work. The bug is
345 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
347 #if defined(__APPLE__) && defined(__LP64__)
348 static gboolean need_timeout_workaround;
350 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
352 #define CAP_READ_TIMEOUT 250
356 * Timeout, in microseconds, for reads from the stream of captured packets
357 * from a pipe. Pipes don't have the same problem that BPF devices do
358 * in Mac OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
359 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
360 * of the offending versions of Snow Leopard.
362 * On Windows this value is converted to milliseconds and passed to
363 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
364 * will return immediately.
367 #define PIPE_READ_TIMEOUT 100000
369 #define PIPE_READ_TIMEOUT 250000
372 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
375 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
376 const char *message, gpointer user_data _U_);
378 /* capture related options */
379 static capture_options global_capture_opts;
380 static gboolean quiet = FALSE;
381 static gboolean use_threads = FALSE;
382 static guint64 start_time;
384 static void capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
386 static void capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
388 static void capture_loop_write_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, const u_char *pd);
389 static void capture_loop_queue_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, const u_char *pd);
390 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
391 int err, gboolean is_close);
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, "\n");*/
456 fprintf(output, "Output (files):\n");
457 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
458 fprintf(output, " -g enable group read access on the output file(s)\n");
459 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
460 fprintf(output, " interval:NUM - create time intervals of NUM secs\n");
461 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
462 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
463 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
464 fprintf(output, " -P use libpcap format instead of pcapng\n");
465 fprintf(output, " --capture-comment <comment>\n");
466 fprintf(output, " add a capture comment to the output file\n");
467 fprintf(output, " (only for pcapng)\n");
468 fprintf(output, "\n");
469 fprintf(output, "Miscellaneous:\n");
470 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
471 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
472 fprintf(output, " within dumpcap\n");
473 fprintf(output, " -t use a separate thread per interface\n");
474 fprintf(output, " -q don't report packet capture counts\n");
475 fprintf(output, " -v print version information and exit\n");
476 fprintf(output, " -h display this help and exit\n");
477 fprintf(output, "\n");
479 fprintf(output, "Dumpcap can benefit from an enabled BPF JIT compiler if available.\n");
480 fprintf(output, "You might want to enable it by executing:\n");
481 fprintf(output, " \"echo 1 > /proc/sys/net/core/bpf_jit_enable\"\n");
482 fprintf(output, "Note that this can make your system less secure!\n");
483 fprintf(output, "\n");
485 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
486 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
487 fprintf(output, "\n");
488 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
492 * Report an error in command-line arguments.
493 * If we're a capture child, send a message back to the parent, otherwise
497 dumpcap_cmdarg_err(const char *fmt, va_list ap)
501 /* Generate a 'special format' message back to parent */
502 msg = g_strdup_vprintf(fmt, ap);
503 sync_pipe_errmsg_to_parent(2, msg, "");
506 fprintf(stderr, "dumpcap: ");
507 vfprintf(stderr, fmt, ap);
508 fprintf(stderr, "\n");
513 * Report additional information for an error in command-line arguments.
514 * If we're a capture child, send a message back to the parent, otherwise
518 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
522 msg = g_strdup_vprintf(fmt, ap);
523 sync_pipe_errmsg_to_parent(2, msg, "");
526 vfprintf(stderr, fmt, ap);
527 fprintf(stderr, "\n");
533 #if 0 /* Set to enable capability debugging */
534 /* see 'man cap_to_text()' for explanation of output */
535 /* '=' means 'all= ' ie: no capabilities */
536 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
538 print_caps(const char *pfx) {
539 cap_t caps = cap_get_proc();
540 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
541 "%s: EUID: %d Capabilities: %s", pfx,
542 geteuid(), cap_to_text(caps, NULL));
545 print_caps(const char *pfx _U_) {
550 relinquish_all_capabilities(void)
552 /* Drop any and all capabilities this process may have. */
553 /* Allowed whether or not process has any privileges. */
554 cap_t caps = cap_init(); /* all capabilities initialized to off */
555 print_caps("Pre-clear");
556 if (cap_set_proc(caps)) {
557 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
559 print_caps("Post-clear");
565 get_capture_device_open_failure_messages(const char *open_err_str,
567 char *errmsg, size_t errmsg_len,
568 char *secondary_errmsg,
569 size_t secondary_errmsg_len)
572 const char *libpcap_warn;
573 static const char ppamsg[] = "can't find PPA for ";
576 g_snprintf(errmsg, (gulong) errmsg_len,
577 "The capture session could not be initiated on interface '%s' (%s).",
578 iface, open_err_str);
581 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
583 "In order to capture packets, WinPcap must be installed; see\n"
585 " https://www.winpcap.org/\n"
587 "for a downloadable version of WinPcap and for instructions on how to install\n"
590 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
592 "Please check that \"%s\" is the proper interface.\n"
595 "Help can be found on the following pages:\n"
597 " https://wiki.wireshark.org/WinPcap\n"
598 " https://wiki.wireshark.org/CaptureSetup\n",
602 /* If we got a "can't find PPA for X" message, warn the user (who
603 is running dumpcap on HP-UX) that they don't have a version of
604 libpcap that properly handles HP-UX (libpcap 0.6.x and later
605 versions, which properly handle HP-UX, say "can't find /dev/dlpi
606 PPA for X" rather than "can't find PPA for X"). */
607 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
610 "You are running (T)Wireshark with a version of the libpcap library\n"
611 "that doesn't handle HP-UX network devices well; this means that\n"
612 "(T)Wireshark may not be able to capture packets.\n"
614 "To fix this, you should install libpcap 0.6.2, or a later version\n"
615 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
616 "packaged binary form from the Software Porting And Archive Centre\n"
617 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
618 "at the URL lists a number of mirror sites.";
622 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
623 "Please check to make sure you have sufficient permissions, and that you have "
624 "the proper interface or pipe specified.%s", libpcap_warn);
629 compile_capture_filter(const char *iface, pcap_t *pcap_h,
630 struct bpf_program *fcode, const char *cfilter)
632 bpf_u_int32 netnum, netmask;
633 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
635 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
637 * Well, we can't get the netmask for this interface; it's used
638 * only for filters that check for broadcast IP addresses, so
639 * we just punt and use 0. It might be nice to warn the user,
640 * but that's a pain in a GUI application, as it'd involve popping
641 * up a message box, and it's not clear how often this would make
642 * a difference (only filters that check for IP broadcast addresses
646 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
651 * Sigh. Older versions of libpcap don't properly declare the
652 * third argument to pcap_compile() as a const pointer. Cast
656 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
662 #ifdef HAVE_BPF_IMAGE
664 show_filter_code(capture_options *capture_opts)
666 interface_options *interface_opts;
668 gchar open_err_str[PCAP_ERRBUF_SIZE];
669 char errmsg[MSG_MAX_LENGTH+1];
670 char secondary_errmsg[MSG_MAX_LENGTH+1];
671 struct bpf_program fcode;
672 struct bpf_insn *insn;
676 for (j = 0; j < capture_opts->ifaces->len; j++) {
677 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, j);
678 pcap_h = open_capture_device(capture_opts, interface_opts,
679 CAP_READ_TIMEOUT, &open_err_str);
680 if (pcap_h == NULL) {
681 /* Open failed; get messages */
682 get_capture_device_open_failure_messages(open_err_str,
683 interface_opts->name,
684 errmsg, sizeof errmsg,
686 sizeof secondary_errmsg);
687 /* And report them */
688 report_capture_error(errmsg, secondary_errmsg);
692 /* Set the link-layer type. */
693 if (!set_pcap_datalink(pcap_h, interface_opts->linktype, interface_opts->name,
694 errmsg, sizeof errmsg,
695 secondary_errmsg, sizeof secondary_errmsg)) {
697 report_capture_error(errmsg, secondary_errmsg);
701 /* OK, try to compile the capture filter. */
702 if (!compile_capture_filter(interface_opts->name, pcap_h, &fcode,
703 interface_opts->cfilter)) {
705 report_cfilter_error(capture_opts, j, errmsg);
710 /* Now print the filter code. */
711 insn = fcode.bf_insns;
713 for (i = 0; i < fcode.bf_len; insn++, i++)
714 printf("%s\n", bpf_image(insn, i));
716 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
717 /* to remove any suid privileges. */
718 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
719 /* (euid/egid have already previously been set to ruid/rgid. */
720 /* (See comment in main() for details) */
722 relinquish_special_privs_perm();
724 relinquish_all_capabilities();
727 /* Let our parent know we succeeded. */
728 pipe_write_block(2, SP_SUCCESS, NULL);
735 * capture_interface_list() is expected to do the right thing to get
736 * a list of interfaces.
738 * In most of the programs in the Wireshark suite, "the right thing"
739 * is to run dumpcap and ask it for the list, because dumpcap may
740 * be the only program in the suite with enough privileges to get
743 * In dumpcap itself, however, we obviously can't run dumpcap to
744 * ask for the list. Therefore, our capture_interface_list() should
745 * just call get_interface_list().
748 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
750 return get_interface_list(err, err_str);
754 * Output a machine readable list of the interfaces
755 * This list is retrieved by the sync_interface_list_open() function
756 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
759 print_machine_readable_interfaces(GList *if_list)
766 char addr_str[WS_INET6_ADDRSTRLEN];
769 /* Let our parent know we succeeded. */
770 pipe_write_block(2, SP_SUCCESS, NULL);
773 i = 1; /* Interface id number */
774 for (if_entry = g_list_first(if_list); if_entry != NULL;
775 if_entry = g_list_next(if_entry)) {
776 if_info = (if_info_t *)if_entry->data;
777 printf("%d. %s\t", i++, if_info->name);
780 * Print the contents of the if_entry struct in a parseable format.
781 * Each if_entry element is tab-separated. Addresses are comma-
784 /* XXX - Make sure our description doesn't contain a tab */
785 if (if_info->vendor_description != NULL)
786 printf("%s\t", if_info->vendor_description);
790 /* XXX - Make sure our friendly name doesn't contain a tab */
791 if (if_info->friendly_name != NULL)
792 printf("%s\t", if_info->friendly_name);
796 printf("%i\t", if_info->type);
798 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
799 addr = g_slist_next(addr)) {
800 if (addr != g_slist_nth(if_info->addrs, 0))
803 if_addr = (if_addr_t *)addr->data;
804 switch(if_addr->ifat_type) {
806 printf("%s", ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str, sizeof(addr_str)));
809 printf("%s", ws_inet_ntop6(&if_addr->addr.ip6_addr, addr_str, sizeof(addr_str)));
812 printf("<type unknown %i>", if_addr->ifat_type);
816 if (if_info->loopback)
817 printf("\tloopback");
820 printf("\t%s", if_info->extcap);
826 * If you change the machine-readable output format of this function,
827 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
830 print_machine_readable_if_capabilities(if_capabilities_t *caps, int queries)
832 GList *lt_entry, *ts_entry;
833 const gchar *desc_str;
836 /* Let our parent know we succeeded. */
837 pipe_write_block(2, SP_SUCCESS, NULL);
840 if (queries & CAPS_QUERY_LINK_TYPES) {
841 if (caps->can_set_rfmon)
845 for (lt_entry = caps->data_link_types; lt_entry != NULL;
846 lt_entry = g_list_next(lt_entry)) {
847 data_link_info_t *data_link_info = (data_link_info_t *)lt_entry->data;
848 if (data_link_info->description != NULL)
849 desc_str = data_link_info->description;
851 desc_str = "(not supported)";
852 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
857 if (queries & CAPS_QUERY_TIMESTAMP_TYPES) {
858 for (ts_entry = caps->timestamp_types; ts_entry != NULL;
859 ts_entry = g_list_next(ts_entry)) {
860 timestamp_info_t *timestamp = (timestamp_info_t *)ts_entry->data;
861 if (timestamp->description != NULL)
862 desc_str = timestamp->description;
865 printf("%s\t%s\n", timestamp->name, desc_str);
875 /* Print the number of packets captured for each interface until we're killed. */
877 print_statistics_loop(gboolean machine_readable)
879 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
885 char errbuf[PCAP_ERRBUF_SIZE];
888 if_list = get_interface_list(&err, &err_str);
889 if (if_list == NULL) {
891 cmdarg_err("There are no interfaces on which a capture can be done");
893 cmdarg_err("%s", err_str);
899 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
900 if_info = (if_info_t *)if_entry->data;
903 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
904 * connections. We avoid collecting stats on them.
906 if (!strncmp(if_info->name, "nf", 2)) {
907 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
913 #ifdef HAVE_PCAP_OPEN
914 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
916 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
920 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
921 if_stat->name = g_strdup(if_info->name);
923 stat_list = g_list_append(stat_list, if_stat);
928 cmdarg_err("There are no interfaces on which a capture can be done");
933 /* Let our parent know we succeeded. */
934 pipe_write_block(2, SP_SUCCESS, NULL);
937 if (!machine_readable) {
938 printf("%-15s %10s %10s\n", "Interface", "Received",
943 while (global_ld.go) {
944 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
945 if_stat = (if_stat_t *)stat_entry->data;
946 pcap_stats(if_stat->pch, &ps);
948 if (!machine_readable) {
949 printf("%-15s %10u %10u\n", if_stat->name,
950 ps.ps_recv, ps.ps_drop);
952 printf("%s\t%u\t%u\n", if_stat->name,
953 ps.ps_recv, ps.ps_drop);
958 /* If we have a dummy signal pipe check it */
959 if (!signal_pipe_check_running()) {
960 global_ld.go = FALSE;
968 /* XXX - Not reached. Should we look for 'q' in stdin? */
969 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
970 if_stat = (if_stat_t *)stat_entry->data;
971 pcap_close(if_stat->pch);
972 g_free(if_stat->name);
975 g_list_free(stat_list);
976 free_interface_list(if_list);
984 capture_cleanup_handler(DWORD dwCtrlType)
986 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
987 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
988 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
989 like SIGTERM at least when the machine's shutting down.
991 For now, if we're running as a command rather than a capture child,
992 we handle all but CTRL_LOGOFF_EVENT as indications that we should
993 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
996 If we're not running as a capture child, we might be running as
997 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
998 user logs out. (XXX - can we explicitly check whether we're
999 running as a service?) */
1001 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1002 "Console: Control signal");
1003 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1004 "Console: Control signal, CtrlType: %u", dwCtrlType);
1006 /* Keep capture running if we're a service and a user logs off */
1007 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1008 capture_loop_stop();
1016 capture_cleanup_handler(int signum _U_)
1018 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1019 SIGTERM. We assume that if the user wanted it to keep running
1020 after they logged out, they'd have nohupped it. */
1022 /* Note: don't call g_log() in the signal handler: if we happened to be in
1023 * g_log() in process context when the signal came in, g_log will detect
1024 * the "recursion" and abort.
1027 capture_loop_stop();
1033 report_capture_count(gboolean reportit)
1035 /* Don't print this if we're a capture child. */
1036 if (!capture_child && reportit) {
1037 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packet_count);
1038 /* stderr could be line buffered */
1046 report_counts_for_siginfo(void)
1048 report_capture_count(quiet);
1049 infoprint = FALSE; /* we just reported it */
1053 report_counts_siginfo(int signum _U_)
1055 int sav_errno = errno;
1057 /* If we've been told to delay printing, just set a flag asking
1058 that we print counts (if we're supposed to), otherwise print
1059 the count of packets captured (if we're supposed to). */
1063 report_counts_for_siginfo();
1066 #endif /* SIGINFO */
1069 exit_main(int status)
1072 /* Shutdown windows sockets */
1075 /* can be helpful for debugging */
1076 #ifdef DEBUG_DUMPCAP
1077 printf("Press any key\n");
1083 capture_opts_cleanup(&global_capture_opts);
1089 * If we were linked with libcap (not related to libpcap), make sure we have
1090 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1091 * (See comment in main() for details)
1094 relinquish_privs_except_capture(void)
1096 /* If 'started_with_special_privs' (ie: suid) then enable for
1097 * ourself the NET_ADMIN and NET_RAW capabilities and then
1098 * drop our suid privileges.
1100 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1101 * stuff we don't need (and shouldn't have).
1102 * CAP_NET_RAW: Packet capture (raw sockets).
1105 if (started_with_special_privs()) {
1106 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1107 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1109 cap_t caps = cap_init(); /* all capabilities initialized to off */
1111 print_caps("Pre drop, pre set");
1113 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1114 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1117 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1118 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1120 if (cap_set_proc(caps)) {
1121 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1123 print_caps("Pre drop, post set");
1125 relinquish_special_privs_perm();
1127 print_caps("Post drop, pre set");
1128 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1129 if (cap_set_proc(caps)) {
1130 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1132 print_caps("Post drop, post set");
1138 #endif /* HAVE_LIBCAP */
1140 /* Take care of byte order in the libpcap headers read from pipes.
1141 * (function taken from wiretap/libpcap.c) */
1143 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1146 /* Byte-swap the record header fields. */
1147 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1148 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1149 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1150 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1153 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1154 swapped, in order to match the BPF header layout.
1156 Unfortunately, some files were, according to a comment in the "libpcap"
1157 source, written with version 2.3 in their headers but without the
1158 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1159 would make no sense - we assume that we need to swap them. */
1160 if (hdr->version_major == 2 &&
1161 (hdr->version_minor < 3 ||
1162 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1165 temp = rechdr->orig_len;
1166 rechdr->orig_len = rechdr->incl_len;
1167 rechdr->incl_len = temp;
1171 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1175 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1179 return recv(pipe_fd, buf, (int)sz, 0);
1184 return ws_read(pipe_fd, buf, sz);
1190 * Thread function that reads from a pipe and pushes the data
1191 * to the main application thread.
1194 * XXX Right now we use async queues for basic signaling. The main thread
1195 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1196 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1197 * Iff the read is successful cap_pipe_read pushes an item onto
1198 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1199 * the queues themselves (yet).
1201 * We might want to move some of the cap_pipe_dispatch logic here so that
1202 * we can let cap_thread_read run independently, queuing up multiple reads
1203 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1205 static void *cap_thread_read(void *arg)
1207 capture_src *pcap_src;
1210 DWORD last_err, bytes_read;
1216 pcap_src = (capture_src *)arg;
1217 while (pcap_src->cap_pipe_err == PIPOK) {
1218 g_async_queue_pop(pcap_src->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1219 g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1221 while (bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1222 if ((pcap_src->from_cap_socket)
1228 b = cap_pipe_read(pcap_src->cap_pipe_fd, pcap_src->cap_pipe_buf+bytes_read,
1229 pcap_src->cap_pipe_bytes_to_read - bytes_read, pcap_src->from_cap_socket);
1232 pcap_src->cap_pipe_err = PIPEOF;
1236 pcap_src->cap_pipe_err = PIPERR;
1247 /* If we try to use read() on a named pipe on Windows with partial
1248 * data it appears to return EOF.
1250 res = ReadFile(pcap_src->cap_pipe_h, pcap_src->cap_pipe_buf+bytes_read,
1251 pcap_src->cap_pipe_bytes_to_read - bytes_read,
1256 last_err = GetLastError();
1257 if (last_err == ERROR_MORE_DATA) {
1259 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1260 pcap_src->cap_pipe_err = PIPEOF;
1264 pcap_src->cap_pipe_err = PIPERR;
1267 } else if (b == 0 && pcap_src->cap_pipe_bytes_to_read > 0) {
1268 pcap_src->cap_pipe_err = PIPEOF;
1275 pcap_src->cap_pipe_bytes_read = bytes_read;
1276 if (pcap_src->cap_pipe_bytes_read >= pcap_src->cap_pipe_bytes_to_read) {
1277 g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1279 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1285 /* Provide select() functionality for a single file descriptor
1286 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1288 * Returns the same values as select.
1291 cap_pipe_select(int pipe_fd)
1294 struct timeval timeout;
1297 FD_SET(pipe_fd, &rfds);
1299 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1300 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1302 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1305 #define DEF_TCP_PORT 19000
1308 cap_open_socket(char *pipename, capture_src *pcap_src, char *errmsg, int errmsgl)
1310 char *sockname = pipename + 4;
1311 struct sockaddr_in sa;
1318 memset(&sa, 0, sizeof(sa));
1320 p = strchr(sockname, ':');
1322 len = strlen(sockname);
1323 port = DEF_TCP_PORT;
1327 port = strtoul(p + 1, &p, 10);
1328 if (*p || port > 65535) {
1337 g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
1339 if (!ws_inet_pton4(buf, (guint32 *)&sa.sin_addr)) {
1343 sa.sin_family = AF_INET;
1344 sa.sin_port = g_htons((u_short)port);
1346 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1347 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1349 LPTSTR errorText = NULL;
1352 lastError = WSAGetLastError();
1353 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1354 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1355 FORMAT_MESSAGE_IGNORE_INSERTS,
1356 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1357 (LPTSTR)&errorText, 0, NULL);
1359 g_snprintf(errmsg, errmsgl,
1360 "The capture session could not be initiated due to the socket error: \n"
1362 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
1364 LocalFree(errorText);
1366 " %d: %s", errno, g_strerror(errno));
1368 pcap_src->cap_pipe_err = PIPERR;
1371 cap_pipe_close(fd, TRUE);
1375 pcap_src->from_cap_socket = TRUE;
1379 g_snprintf(errmsg, errmsgl,
1380 "The capture session could not be initiated because\n"
1381 "\"%s\" is not a valid socket specification", pipename);
1382 pcap_src->cap_pipe_err = PIPERR;
1386 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1390 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1394 closesocket(pipe_fd);
1402 cap_pipe_read_data_bytes(capture_src *pcap_src, char *errmsg, int errmsgl)
1405 int fd = pcap_src->cap_pipe_fd;
1407 DWORD sz, bytes_read = 0;
1409 size_t sz, bytes_read = 0;
1413 sz = pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read;
1414 while (bytes_read < sz) {
1416 g_snprintf(errmsg, errmsgl, "Invalid file descriptor.");
1420 sel_ret = cap_pipe_select(fd);
1422 g_snprintf(errmsg, errmsgl,
1423 "Unexpected error from select: %s.", g_strerror(errno));
1425 } else if (sel_ret > 0) {
1426 b = cap_pipe_read(fd, pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read+bytes_read,
1427 sz-bytes_read, pcap_src->from_cap_socket);
1430 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1432 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1439 pcap_src->cap_pipe_bytes_read += bytes_read;
1443 /* Some forward declarations for breaking up cap_pipe_open_live for pcap and pcapng formats */
1444 static void pcap_pipe_open_live(int fd, capture_src *pcap_src, struct pcap_hdr *hdr, char *errmsg, int errmsgl);
1445 static void pcapng_pipe_open_live(int fd, capture_src *pcap_src, char *errmsg, int errmsgl);
1446 static int pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, int errmsgl);
1448 /* Mimic pcap_open_live() for pipe captures
1450 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1451 * open it, and read the header.
1453 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1454 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1456 cap_pipe_open_live(char *pipename,
1457 capture_src *pcap_src,
1459 char *errmsg, int errmsgl)
1462 ws_statb64 pipe_stat;
1463 struct sockaddr_un sa;
1467 char* extcap_pipe_name;
1469 gboolean extcap_pipe = FALSE;
1471 int fd = -1, sel_ret;
1474 pcap_src->cap_pipe_fd = -1;
1476 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1479 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1482 * XXX - this blocks until a pcap per-file header has been written to
1483 * the pipe, so it could block indefinitely.
1485 if (strcmp(pipename, "-") == 0) {
1487 fd = 0; /* read from stdin */
1489 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1491 } else if (!strncmp(pipename, "TCP@", 4)) {
1492 if ((fd = cap_open_socket(pipename, pcap_src, errmsg, errmsgl)) < 0) {
1497 if ( g_strrstr(pipename, EXTCAP_PIPE_PREFIX) != NULL )
1500 if (ws_stat64(pipename, &pipe_stat) < 0) {
1501 if (errno == ENOENT || errno == ENOTDIR)
1502 pcap_src->cap_pipe_err = PIPNEXIST;
1504 g_snprintf(errmsg, errmsgl,
1505 "The capture session could not be initiated "
1506 "due to error getting information on pipe/socket: %s.", g_strerror(errno));
1507 pcap_src->cap_pipe_err = PIPERR;
1511 if (S_ISFIFO(pipe_stat.st_mode)) {
1512 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1514 g_snprintf(errmsg, errmsgl,
1515 "The capture session could not be initiated "
1516 "due to error on pipe open: %s.", g_strerror(errno));
1517 pcap_src->cap_pipe_err = PIPERR;
1520 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1521 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1523 g_snprintf(errmsg, errmsgl,
1524 "The capture session could not be initiated "
1525 "due to error on socket create: %s.", g_strerror(errno));
1526 pcap_src->cap_pipe_err = PIPERR;
1529 sa.sun_family = AF_UNIX;
1531 * The Single UNIX Specification says:
1533 * The size of sun_path has intentionally been left undefined.
1534 * This is because different implementations use different sizes.
1535 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1536 * of 104. Since most implementations originate from BSD versions,
1537 * the size is typically in the range 92 to 108.
1539 * Applications should not assume a particular length for sun_path
1540 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1544 * The <sys/un.h> header shall define the sockaddr_un structure,
1545 * which shall include at least the following members:
1547 * sa_family_t sun_family Address family.
1548 * char sun_path[] Socket pathname.
1550 * so we assume that it's an array, with a specified size,
1551 * and that the size reflects the maximum path length.
1553 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1554 /* Path name too long */
1555 g_snprintf(errmsg, errmsgl,
1556 "The capture session coud not be initiated "
1557 "due to error on socket connect: Path name too long.");
1558 pcap_src->cap_pipe_err = PIPERR;
1562 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1564 g_snprintf(errmsg, errmsgl,
1565 "The capture session coud not be initiated "
1566 "due to error on socket connect: %s.", g_strerror(errno));
1567 pcap_src->cap_pipe_err = PIPERR;
1572 if (S_ISCHR(pipe_stat.st_mode)) {
1574 * Assume the user specified an interface on a system where
1575 * interfaces are in /dev. Pretend we haven't seen it.
1577 pcap_src->cap_pipe_err = PIPNEXIST;
1579 g_snprintf(errmsg, errmsgl,
1580 "The capture session could not be initiated because\n"
1581 "\"%s\" is neither an interface nor a socket nor a pipe.", pipename);
1582 pcap_src->cap_pipe_err = PIPERR;
1588 #define PIPE_STR "\\pipe\\"
1589 /* Under Windows, named pipes _must_ have the form
1590 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1592 pncopy = g_strdup(pipename);
1593 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1594 pos = strchr(pncopy + 3, '\\');
1595 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1602 g_snprintf(errmsg, errmsgl,
1603 "The capture session could not be initiated because\n"
1604 "\"%s\" is neither an interface nor a pipe.", pipename);
1605 pcap_src->cap_pipe_err = PIPNEXIST;
1608 extcap_pipe_name = g_strconcat("\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, NULL);
1609 extcap_pipe = strstr(pipename, extcap_pipe_name) ? TRUE : FALSE;
1610 g_free(extcap_pipe_name);
1612 /* Wait for the pipe to appear */
1615 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1617 pcap_src->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1618 OPEN_EXISTING, 0, NULL);
1620 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE)
1623 if (GetLastError() != ERROR_PIPE_BUSY) {
1624 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1625 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1626 g_snprintf(errmsg, errmsgl,
1627 "The capture session on \"%s\" could not be started "
1628 "due to error on pipe open: %s (error %d).",
1629 pipename, utf_16to8(err_str), GetLastError());
1631 pcap_src->cap_pipe_err = PIPERR;
1635 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1636 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1637 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1638 g_snprintf(errmsg, errmsgl,
1639 "The capture session on \"%s\" timed out during "
1640 "pipe open: %s (error %d).",
1641 pipename, utf_16to8(err_str), GetLastError());
1643 pcap_src->cap_pipe_err = PIPERR;
1650 pcap_src->from_cap_pipe = TRUE;
1653 * We start with a 2KB buffer for packet data, which should be
1654 * large enough for most regular network packets. We increase it,
1655 * up to the maximum size we allow, as necessary.
1657 pcap_src->cap_pipe_databuf = (guchar*)g_malloc(2048);
1658 pcap_src->cap_pipe_databuf_size = 2048;
1661 if (pcap_src->from_cap_socket)
1664 /* read the pcap header */
1666 while (bytes_read < sizeof magic) {
1667 sel_ret = cap_pipe_select(fd);
1669 g_snprintf(errmsg, errmsgl,
1670 "Unexpected error from select: %s.", g_strerror(errno));
1672 } else if (sel_ret > 0) {
1673 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
1674 sizeof magic-bytes_read,
1675 pcap_src->from_cap_socket);
1676 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1677 if (extcap_pipe && b <= 0)
1682 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1684 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1694 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
1696 pcap_src->cap_pipe_buf = (char *) &magic;
1697 pcap_src->cap_pipe_bytes_read = 0;
1698 pcap_src->cap_pipe_bytes_to_read = sizeof(magic);
1699 /* We don't have to worry about cap_pipe_read_mtx here */
1700 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1701 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1702 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1703 if (pcap_src->cap_pipe_bytes_read <= 0 && extcap_pipe)
1706 if (pcap_src->cap_pipe_bytes_read <= 0) {
1707 if (pcap_src->cap_pipe_bytes_read == 0)
1708 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open.");
1710 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s.",
1719 case PCAP_NSEC_MAGIC:
1720 /* Host that wrote it has our byte order, and was running
1721 a program using either standard or ss990417 libpcap. */
1722 pcap_src->cap_pipe_byte_swapped = FALSE;
1723 pcap_src->cap_pipe_modified = FALSE;
1724 pcap_src->ts_nsec = magic == PCAP_NSEC_MAGIC;
1726 case PCAP_MODIFIED_MAGIC:
1727 /* Host that wrote it has our byte order, but was running
1728 a program using either ss990915 or ss991029 libpcap. */
1729 pcap_src->cap_pipe_byte_swapped = FALSE;
1730 pcap_src->cap_pipe_modified = TRUE;
1732 case PCAP_SWAPPED_MAGIC:
1733 case PCAP_SWAPPED_NSEC_MAGIC:
1734 /* Host that wrote it has a byte order opposite to ours,
1735 and was running a program using either standard or
1736 ss990417 libpcap. */
1737 pcap_src->cap_pipe_byte_swapped = TRUE;
1738 pcap_src->cap_pipe_modified = FALSE;
1739 pcap_src->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
1741 case PCAP_SWAPPED_MODIFIED_MAGIC:
1742 /* Host that wrote it out has a byte order opposite to
1743 ours, and was running a program using either ss990915
1744 or ss991029 libpcap. */
1745 pcap_src->cap_pipe_byte_swapped = TRUE;
1746 pcap_src->cap_pipe_modified = TRUE;
1748 case BLOCK_TYPE_SHB:
1749 /* This isn't pcap, it's pcapng. */
1750 pcap_src->from_pcapng = TRUE;
1751 pcap_src->cap_pipe_dispatch = pcapng_pipe_dispatch;
1752 global_capture_opts.use_pcapng = TRUE; /* we can only output in pcapng format */
1753 pcapng_pipe_open_live(fd, pcap_src, errmsg, errmsgl);
1756 /* Not a pcap type we know about, or not pcap at all. */
1757 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format or not libpcap data.");
1761 pcap_pipe_open_live(fd, pcap_src, (struct pcap_hdr *) hdr, errmsg, errmsgl);
1765 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1766 pcap_src->cap_pipe_err = PIPERR;
1767 cap_pipe_close(fd, pcap_src->from_cap_socket);
1768 pcap_src->cap_pipe_fd = -1;
1770 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1775 pcap_pipe_open_live(int fd,
1776 capture_src *pcap_src,
1777 struct pcap_hdr *hdr,
1778 char *errmsg, int errmsgl)
1784 if (pcap_src->from_cap_socket)
1787 /* Read the rest of the header */
1789 while (bytes_read < sizeof(struct pcap_hdr)) {
1790 sel_ret = cap_pipe_select(fd);
1792 g_snprintf(errmsg, errmsgl,
1793 "Unexpected error from select: %s.", g_strerror(errno));
1795 } else if (sel_ret > 0) {
1796 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
1797 sizeof(struct pcap_hdr) - bytes_read,
1798 pcap_src->from_cap_socket);
1801 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open.");
1803 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s.",
1813 pcap_src->cap_pipe_buf = (char *) hdr;
1814 pcap_src->cap_pipe_bytes_read = 0;
1815 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1816 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1817 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1818 if (pcap_src->cap_pipe_bytes_read <= 0) {
1819 if (pcap_src->cap_pipe_bytes_read == 0)
1820 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open.");
1822 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s.",
1829 if (pcap_src->cap_pipe_byte_swapped) {
1830 /* Byte-swap the header fields about which we care. */
1831 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
1832 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
1833 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
1834 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
1836 pcap_src->linktype = hdr->network;
1838 if (pcap_src->linktype == DLT_DBUS) {
1840 * The maximum D-Bus message size is 128MB, so allow packets up
1843 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_DBUS;
1846 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
1848 if (hdr->version_major < 2) {
1849 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format version %d.%d",
1850 hdr->version_major, hdr->version_minor);
1854 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
1855 pcap_src->cap_pipe_err = PIPOK;
1856 pcap_src->cap_pipe_fd = fd;
1860 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcap_pipe_open_live: error %s", errmsg);
1861 pcap_src->cap_pipe_err = PIPERR;
1862 cap_pipe_close(fd, pcap_src->from_cap_socket);
1863 pcap_src->cap_pipe_fd = -1;
1865 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1869 /* Read the pcapng section header block */
1871 pcapng_read_shb(capture_src *pcap_src,
1875 struct pcapng_block_header_s *bh = &pcap_src->cap_pipe_info.pcapng.bh;
1876 struct pcapng_section_header_block_s *shb = &pcap_src->cap_pipe_info.pcapng.shb;
1879 if (pcap_src->from_cap_socket)
1882 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_block_header_s) + sizeof(struct pcapng_section_header_block_s);
1883 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl)) {
1889 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf + sizeof(struct pcapng_block_header_s);
1890 pcap_src->cap_pipe_bytes_read = 0;
1891 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_section_header_block_s);
1892 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1893 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1894 if (pcap_src->cap_pipe_bytes_read <= 0) {
1895 if (pcap_src->cap_pipe_bytes_read == 0)
1896 g_snprintf(errmsg, errmsgl, "End of file on pipe section header during open.");
1898 g_snprintf(errmsg, errmsgl, "Error on pipe section header during open: %s.",
1902 pcap_src->cap_pipe_bytes_read = sizeof(struct pcapng_block_header_s) + sizeof(struct pcapng_section_header_block_s);
1905 memcpy(shb, pcap_src->cap_pipe_databuf + sizeof(struct pcapng_block_header_s), sizeof(struct pcapng_section_header_block_s));
1909 pcap_src->cap_pipe_byte_swapped = FALSE;
1911 case PCAPNG_SWAPPED_MAGIC:
1912 pcap_src->cap_pipe_byte_swapped = TRUE;
1915 /* Not a pcapng type we know about, or not pcapng at all. */
1916 g_snprintf(errmsg, errmsgl, "Unrecognized pcapng format or not pcapng data.");
1920 if (pcap_src->cap_pipe_byte_swapped) {
1921 /* Byte-swap the header fields about which we care. */
1922 shb->version_major = GUINT16_SWAP_LE_BE(shb->version_major);
1923 shb->version_minor = GUINT16_SWAP_LE_BE(shb->version_minor);
1924 shb->section_length = GUINT64_SWAP_LE_BE(shb->section_length);
1925 bh->block_total_length = GUINT32_SWAP_LE_BE(bh->block_total_length);
1928 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
1930 /* Setup state to capture the rest of the section header block */
1931 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
1937 pcapng_write_saved_block(capture_src *pcap_src, struct pcapng_block_header_s *bh)
1939 guint32 length = bh->block_total_length;
1941 if (pcap_src->cap_pipe_byte_swapped) {
1942 length = GUINT32_SWAP_LE_BE(length);
1945 return pcapng_write_block(global_ld.pdh,
1946 (const guint8 *) bh,
1948 &global_ld.bytes_written, &global_ld.err);
1951 /* Save SHB and IDB blocks to playback whenever we change output files. */
1952 /* The list is saved in reverse order of blocks added */
1954 pcapng_block_save(capture_src *pcap_src)
1956 pcapng_pipe_info_t *pcapng = &pcap_src->cap_pipe_info.pcapng;
1957 struct pcapng_block_header_s *bh = &pcapng->bh;
1959 /* Delete all the old blocks first whenever we get a SHB */
1960 if (bh->block_type == BLOCK_TYPE_SHB) {
1961 g_list_free_full(pcapng->saved_blocks, g_free);
1962 pcapng->saved_blocks = NULL;
1963 } else if (bh->block_type != BLOCK_TYPE_IDB) {
1967 gpointer data = g_malloc(bh->block_total_length);
1971 memcpy(data, pcap_src->cap_pipe_databuf, bh->block_total_length);
1973 pcapng->saved_blocks = g_list_prepend(pcapng->saved_blocks, data);
1979 pcapng_pipe_open_live(int fd,
1980 capture_src *pcap_src,
1984 guint32 type = BLOCK_TYPE_SHB;
1985 struct pcapng_block_header_s *bh = &pcap_src->cap_pipe_info.pcapng.bh;
1988 if (pcap_src->from_cap_socket)
1991 memcpy(pcap_src->cap_pipe_databuf, &type, sizeof(guint32));
1992 /* read the rest of the pcapng general block header */
1993 pcap_src->cap_pipe_bytes_read = sizeof(guint32);
1994 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_block_header_s);
1995 pcap_src->cap_pipe_err = PIPOK;
1996 pcap_src->cap_pipe_fd = fd;
1997 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl)) {
2000 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(struct pcapng_block_header_s));
2004 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
2006 bh->block_type = type;
2007 pcap_src->cap_pipe_buf = (char *) &bh->block_total_length;
2008 pcap_src->cap_pipe_bytes_read = 0;
2009 pcap_src->cap_pipe_bytes_to_read = sizeof(bh->block_total_length);
2010 /* We don't have to worry about cap_pipe_read_mtx here */
2011 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2012 g_async_queue_pop(pcap_src->cap_pipe_done_q);
2013 if (pcap_src->cap_pipe_bytes_read <= 0) {
2014 if (pcap_src->cap_pipe_bytes_read == 0)
2015 g_snprintf(errmsg, errmsgl, "End of file on pipe block_total_length during open.");
2017 g_snprintf(errmsg, errmsgl, "Error on pipe block_total_length during open: %s.",
2021 pcap_src->cap_pipe_bytes_read = sizeof(struct pcapng_block_header_s);
2022 memcpy(pcap_src->cap_pipe_databuf, bh, sizeof(struct pcapng_block_header_s));
2023 pcap_src->cap_pipe_err = PIPOK;
2024 pcap_src->cap_pipe_fd = fd;
2027 if (pcapng_read_shb(pcap_src, errmsg, errmsgl)) {
2034 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_open_live: error %s", errmsg);
2035 pcap_src->cap_pipe_err = PIPERR;
2036 cap_pipe_close(fd, pcap_src->from_cap_socket);
2037 pcap_src->cap_pipe_fd = -1;
2039 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2043 /* We read one record from the pipe, take care of byte order in the record
2044 * header, write the record to the capture file, and update capture statistics. */
2046 pcap_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, int errmsgl)
2048 struct pcap_pkthdr phdr;
2049 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2052 #if !GLIB_CHECK_VERSION(2,31,18)
2060 pcap_pipe_info_t *pcap_info = &pcap_src->cap_pipe_info.pcap;
2062 #ifdef LOG_CAPTURE_VERBOSE
2063 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcap_pipe_dispatch");
2066 switch (pcap_src->cap_pipe_state) {
2068 case STATE_EXPECT_REC_HDR:
2070 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2073 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2074 pcap_src->cap_pipe_bytes_to_read = pcap_src->cap_pipe_modified ?
2075 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2076 pcap_src->cap_pipe_bytes_read = 0;
2079 pcap_src->cap_pipe_buf = (char *) &pcap_info->rechdr;
2080 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2081 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2086 case STATE_READ_REC_HDR:
2088 if (pcap_src->from_cap_socket)
2091 b = cap_pipe_read(pcap_src->cap_pipe_fd, ((char *)&pcap_info->rechdr)+pcap_src->cap_pipe_bytes_read,
2092 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read, pcap_src->from_cap_socket);
2095 result = PD_PIPE_EOF;
2097 result = PD_PIPE_ERR;
2100 pcap_src->cap_pipe_bytes_read += b;
2104 #if GLIB_CHECK_VERSION(2,31,18)
2105 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2107 g_get_current_time(&wait_time);
2108 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2109 q_status = g_async_queue_timed_pop(pcap_src->cap_pipe_done_q, &wait_time);
2111 if (pcap_src->cap_pipe_err == PIPEOF) {
2112 result = PD_PIPE_EOF;
2114 } else if (pcap_src->cap_pipe_err == PIPERR) {
2115 result = PD_PIPE_ERR;
2123 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2125 result = PD_REC_HDR_READ;
2128 case STATE_EXPECT_DATA:
2130 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2133 pcap_src->cap_pipe_state = STATE_READ_DATA;
2134 pcap_src->cap_pipe_bytes_to_read = pcap_info->rechdr.hdr.incl_len;
2135 pcap_src->cap_pipe_bytes_read = 0;
2138 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2139 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2140 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2145 case STATE_READ_DATA:
2147 if (pcap_src->from_cap_socket)
2150 b = cap_pipe_read(pcap_src->cap_pipe_fd,
2151 pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read,
2152 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read,
2153 pcap_src->from_cap_socket);
2156 result = PD_PIPE_EOF;
2158 result = PD_PIPE_ERR;
2161 pcap_src->cap_pipe_bytes_read += b;
2166 #if GLIB_CHECK_VERSION(2,31,18)
2167 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2169 g_get_current_time(&wait_time);
2170 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2171 q_status = g_async_queue_timed_pop(pcap_src->cap_pipe_done_q, &wait_time);
2172 #endif /* GLIB_CHECK_VERSION(2,31,18) */
2173 if (pcap_src->cap_pipe_err == PIPEOF) {
2174 result = PD_PIPE_EOF;
2176 } else if (pcap_src->cap_pipe_err == PIPERR) {
2177 result = PD_PIPE_ERR;
2185 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2187 result = PD_DATA_READ;
2191 g_snprintf(errmsg, errmsgl, "pcap_pipe_dispatch: invalid state");
2194 } /* switch (pcap_src->cap_pipe_state) */
2197 * We've now read as much data as we were expecting, so process it.
2201 case PD_REC_HDR_READ:
2202 /* We've read the header. Take care of byte order. */
2203 cap_pipe_adjust_header(pcap_src->cap_pipe_byte_swapped, &pcap_info->hdr,
2204 &pcap_info->rechdr.hdr);
2205 if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_max_pkt_size) {
2207 * The record contains more data than the advertised/allowed in the
2208 * pcap header, do not try to read more data (do not change to
2209 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2210 * instead stop with an error.
2212 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2213 ld->packet_count+1, pcap_info->rechdr.hdr.incl_len);
2217 if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_databuf_size) {
2219 * Grow the buffer to the packet size, rounded up to a power of
2222 new_bufsize = pcap_info->rechdr.hdr.incl_len;
2224 * http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2227 new_bufsize |= new_bufsize >> 1;
2228 new_bufsize |= new_bufsize >> 2;
2229 new_bufsize |= new_bufsize >> 4;
2230 new_bufsize |= new_bufsize >> 8;
2231 new_bufsize |= new_bufsize >> 16;
2233 pcap_src->cap_pipe_databuf = (guchar*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2234 pcap_src->cap_pipe_databuf_size = new_bufsize;
2238 * The record has some data following the header, try to read it next
2241 if (pcap_info->rechdr.hdr.incl_len) {
2242 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2247 * No data following the record header? Then no more data needs to be
2248 * read and we will fallthrough and emit an empty packet.
2252 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2253 phdr.ts.tv_sec = pcap_info->rechdr.hdr.ts_sec;
2254 phdr.ts.tv_usec = pcap_info->rechdr.hdr.ts_usec;
2255 phdr.caplen = pcap_info->rechdr.hdr.incl_len;
2256 phdr.len = pcap_info->rechdr.hdr.orig_len;
2259 capture_loop_queue_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2261 capture_loop_write_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2263 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2267 pcap_src->cap_pipe_err = PIPEOF;
2272 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2273 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2274 g_snprintf(errmsg, errmsgl,
2275 "Error reading from pipe: %s (error %d)",
2276 utf_16to8(err_str), GetLastError());
2279 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2287 pcap_src->cap_pipe_err = PIPERR;
2288 /* Return here rather than inside the switch to prevent GCC warning */
2293 pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, int errmsgl)
2295 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2298 #if !GLIB_CHECK_VERSION(2,31,18)
2305 struct pcapng_block_header_s *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2307 #ifdef LOG_CAPTURE_VERBOSE
2308 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch");
2311 switch (pcap_src->cap_pipe_state) {
2313 case STATE_EXPECT_REC_HDR:
2315 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2318 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2319 pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_block_header_s);
2320 pcap_src->cap_pipe_bytes_read = 0;
2323 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2324 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2325 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2330 case STATE_READ_REC_HDR:
2332 if (pcap_src->from_cap_socket)
2335 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl)) {
2341 #if GLIB_CHECK_VERSION(2,31,18)
2342 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2344 g_get_current_time(&wait_time);
2345 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2346 q_status = g_async_queue_timed_pop(pcap_src->cap_pipe_done_q, &wait_time);
2348 if (pcap_src->cap_pipe_err == PIPEOF) {
2349 result = PD_PIPE_EOF;
2351 } else if (pcap_src->cap_pipe_err == PIPERR) {
2352 result = PD_PIPE_ERR;
2360 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2362 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(struct pcapng_block_header_s));
2363 result = PD_REC_HDR_READ;
2366 case STATE_EXPECT_DATA:
2368 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2370 pcap_src->cap_pipe_state = STATE_READ_DATA;
2371 pcap_src->cap_pipe_bytes_to_read = bh->block_total_length;
2375 pcap_src->cap_pipe_bytes_to_read -= pcap_src->cap_pipe_bytes_read;
2376 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf + pcap_src->cap_pipe_bytes_read;
2377 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2378 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2383 case STATE_READ_DATA:
2385 if (pcap_src->from_cap_socket)
2388 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl)) {
2391 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2397 #if GLIB_CHECK_VERSION(2,31,18)
2398 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2400 g_get_current_time(&wait_time);
2401 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2402 q_status = g_async_queue_timed_pop(pcap_src->cap_pipe_done_q, &wait_time);
2403 #endif /* GLIB_CHECK_VERSION(2,31,18) */
2404 if (pcap_src->cap_pipe_err == PIPEOF) {
2405 result = PD_PIPE_EOF;
2407 } else if (pcap_src->cap_pipe_err == PIPERR) {
2408 result = PD_PIPE_ERR;
2414 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2417 pcap_src->cap_pipe_bytes_read = bh->block_total_length;
2420 result = PD_DATA_READ;
2424 g_snprintf(errmsg, errmsgl, "pcapng_pipe_dispatch: invalid state");
2427 } /* switch (pcap_src->cap_pipe_state) */
2430 * We've now read as much data as we were expecting, so process it.
2434 case PD_REC_HDR_READ:
2435 if (bh->block_type == BLOCK_TYPE_SHB) {
2436 /* we need to read ahead to get the endianess before getting the block type and length */
2437 pcapng_read_shb(pcap_src, errmsg, errmsgl);
2441 /* We've read the header. Take care of byte order. */
2442 if (pcap_src->cap_pipe_byte_swapped) {
2443 /* Byte-swap the record header fields. */
2444 bh->block_type = GUINT32_SWAP_LE_BE(bh->block_type);
2445 bh->block_total_length = GUINT32_SWAP_LE_BE(bh->block_total_length);
2447 if (bh->block_total_length > pcap_src->cap_pipe_max_pkt_size) {
2449 * The record contains more data than the advertised/allowed in the
2450 * pcapng header, do not try to read more data (do not change to
2451 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2452 * instead stop with an error.
2454 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2455 ld->packet_count+1, bh->block_total_length);
2459 if (bh->block_total_length > pcap_src->cap_pipe_databuf_size) {
2461 * Grow the buffer to the packet size, rounded up to a power of
2464 new_bufsize = bh->block_total_length;
2466 * http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2469 new_bufsize |= new_bufsize >> 1;
2470 new_bufsize |= new_bufsize >> 2;
2471 new_bufsize |= new_bufsize >> 4;
2472 new_bufsize |= new_bufsize >> 8;
2473 new_bufsize |= new_bufsize >> 16;
2475 pcap_src->cap_pipe_databuf = (guchar*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2476 pcap_src->cap_pipe_databuf_size = new_bufsize;
2479 /* The record always has at least the block total length following the header */
2480 if (bh->block_total_length < sizeof(struct pcapng_block_header_s)+sizeof(guint32)) {
2481 g_snprintf(errmsg, errmsgl, "malformed pcapng block_total_length < minimum");
2482 pcap_src->cap_pipe_err = PIPEOF;
2485 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2489 if (!pcapng_block_save(pcap_src)) {
2493 capture_loop_queue_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
2495 capture_loop_write_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
2497 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2501 pcap_src->cap_pipe_err = PIPEOF;
2506 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2507 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2508 g_snprintf(errmsg, errmsgl,
2509 "Error reading from pipe: %s (error %d)",
2510 utf_16to8(err_str), GetLastError());
2513 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2521 pcap_src->cap_pipe_err = PIPERR;
2522 /* Return here rather than inside the switch to prevent GCC warning */
2526 /** Open the capture input file (pcap or capture pipe).
2527 * Returns TRUE if it succeeds, FALSE otherwise. */
2529 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2530 char *errmsg, size_t errmsg_len,
2531 char *secondary_errmsg, size_t secondary_errmsg_len)
2533 gchar open_err_str[PCAP_ERRBUF_SIZE];
2534 gchar *sync_msg_str;
2535 interface_options *interface_opts;
2536 capture_src *pcap_src;
2540 WORD wVersionRequested;
2544 /* XXX - opening Winsock on tshark? */
2546 /* Initialize Windows Socket if we are in a Win32 OS
2547 This needs to be done before querying the interface for network/netmask */
2549 /* XXX - do we really require 1.1 or earlier?
2550 Are there any versions that support only 2.0 or higher? */
2551 wVersionRequested = MAKEWORD(1, 1);
2552 err = WSAStartup(wVersionRequested, &wsaData);
2556 case WSASYSNOTREADY:
2557 g_snprintf(errmsg, (gulong) errmsg_len,
2558 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2561 case WSAVERNOTSUPPORTED:
2562 g_snprintf(errmsg, (gulong) errmsg_len,
2563 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2564 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2567 case WSAEINPROGRESS:
2568 g_snprintf(errmsg, (gulong) errmsg_len,
2569 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2573 g_snprintf(errmsg, (gulong) errmsg_len,
2574 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2578 g_snprintf(errmsg, (gulong) errmsg_len,
2579 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2583 g_snprintf(errmsg, (gulong) errmsg_len,
2584 "Couldn't initialize Windows Sockets: error %d", err);
2587 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2591 if ((use_threads == FALSE) &&
2592 (capture_opts->ifaces->len > 1)) {
2593 g_snprintf(errmsg, (gulong) errmsg_len,
2594 "Using threads is required for capturing on multiple interfaces.");
2598 for (i = 0; i < capture_opts->ifaces->len; i++) {
2599 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
2600 pcap_src = (capture_src *)g_malloc(sizeof (capture_src));
2601 if (pcap_src == NULL) {
2602 g_snprintf(errmsg, (gulong) errmsg_len,
2603 "Could not allocate memory.");
2606 memset(pcap_src, 0, sizeof(capture_src));
2607 #ifdef MUST_DO_SELECT
2608 pcap_src->pcap_fd = -1;
2610 pcap_src->interface_id = i;
2611 pcap_src->linktype = -1;
2613 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2615 pcap_src->cap_pipe_fd = -1;
2616 pcap_src->cap_pipe_dispatch = pcap_pipe_dispatch;
2617 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2618 pcap_src->cap_pipe_err = PIPOK;
2620 #if GLIB_CHECK_VERSION(2,31,0)
2621 pcap_src->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2622 g_mutex_init(pcap_src->cap_pipe_read_mtx);
2624 pcap_src->cap_pipe_read_mtx = g_mutex_new();
2626 pcap_src->cap_pipe_pending_q = g_async_queue_new();
2627 pcap_src->cap_pipe_done_q = g_async_queue_new();
2629 g_array_append_val(ld->pcaps, pcap_src);
2631 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts->name);
2632 pcap_src->pcap_h = open_capture_device(capture_opts, interface_opts,
2633 CAP_READ_TIMEOUT, &open_err_str);
2635 if (pcap_src->pcap_h != NULL) {
2636 /* we've opened "iface" as a network device */
2638 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2639 /* Find out if we're getting nanosecond-precision time stamps */
2640 pcap_src->ts_nsec = have_high_resolution_timestamp(pcap_src->pcap_h);
2643 #if defined(HAVE_PCAP_SETSAMPLING)
2644 if (interface_opts->sampling_method != CAPTURE_SAMP_NONE) {
2645 struct pcap_samp *samp;
2647 if ((samp = pcap_setsampling(pcap_src->pcap_h)) != NULL) {
2648 switch (interface_opts->sampling_method) {
2649 case CAPTURE_SAMP_BY_COUNT:
2650 samp->method = PCAP_SAMP_1_EVERY_N;
2653 case CAPTURE_SAMP_BY_TIMER:
2654 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2658 sync_msg_str = g_strdup_printf(
2659 "Unknown sampling method %d specified,\n"
2660 "continue without packet sampling",
2661 interface_opts->sampling_method);
2662 report_capture_error("Couldn't set the capture "
2663 "sampling", sync_msg_str);
2664 g_free(sync_msg_str);
2666 samp->value = interface_opts->sampling_param;
2668 report_capture_error("Couldn't set the capture sampling",
2669 "Cannot get packet sampling data structure");
2674 /* setting the data link type only works on real interfaces */
2675 if (!set_pcap_datalink(pcap_src->pcap_h, interface_opts->linktype,
2676 interface_opts->name,
2678 secondary_errmsg, secondary_errmsg_len)) {
2681 pcap_src->linktype = get_pcap_datalink(pcap_src->pcap_h, interface_opts->name);
2683 /* We couldn't open "iface" as a network device. */
2684 /* Try to open it as a pipe */
2685 cap_pipe_open_live(interface_opts->name, pcap_src, &pcap_src->cap_pipe_info.pcap.hdr, errmsg, (int) errmsg_len);
2688 if (pcap_src->cap_pipe_fd == -1) {
2690 if (pcap_src->cap_pipe_h == INVALID_HANDLE_VALUE) {
2692 if (pcap_src->cap_pipe_err == PIPNEXIST) {
2694 * We tried opening as an interface, and that failed,
2695 * so we tried to open it as a pipe, but the pipe
2696 * doesn't exist. Report the error message for
2699 get_capture_device_open_failure_messages(open_err_str,
2700 interface_opts->name,
2704 secondary_errmsg_len);
2707 * Else pipe (or file) does exist and cap_pipe_open_live() has
2712 /* cap_pipe_open_live() succeeded; don't want
2713 error message from pcap_open_live() */
2714 open_err_str[0] = '\0';
2718 /* XXX - will this work for tshark? */
2719 #ifdef MUST_DO_SELECT
2720 if (!pcap_src->from_cap_pipe) {
2721 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2722 pcap_src->pcap_fd = pcap_get_selectable_fd(pcap_src->pcap_h);
2724 pcap_src->pcap_fd = pcap_fileno(pcap_src->pcap_h);
2729 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2730 returned a warning; print it, but keep capturing. */
2731 if (open_err_str[0] != '\0') {
2732 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2733 report_capture_error(sync_msg_str, "");
2734 g_free(sync_msg_str);
2738 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2739 /* to remove any suid privileges. */
2740 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2741 /* (euid/egid have already previously been set to ruid/rgid. */
2742 /* (See comment in main() for details) */
2744 relinquish_special_privs_perm();
2746 relinquish_all_capabilities();
2751 /* close the capture input file (pcap or capture pipe) */
2752 static void capture_loop_close_input(loop_data *ld)
2755 capture_src *pcap_src;
2757 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2759 for (i = 0; i < ld->pcaps->len; i++) {
2760 pcap_src = g_array_index(ld->pcaps, capture_src *, i);
2761 /* Pipe, or capture device? */
2762 if (pcap_src->from_cap_pipe) {
2763 /* Pipe. If open, close the capture pipe "input file". */
2764 if (pcap_src->cap_pipe_fd >= 0) {
2765 cap_pipe_close(pcap_src->cap_pipe_fd, pcap_src->from_cap_socket);
2766 pcap_src->cap_pipe_fd = -1;
2769 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE) {
2770 CloseHandle(pcap_src->cap_pipe_h);
2771 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2774 if (pcap_src->cap_pipe_databuf != NULL) {
2775 /* Free the buffer. */
2776 g_free(pcap_src->cap_pipe_databuf);
2777 pcap_src->cap_pipe_databuf = NULL;
2779 if (pcap_src->from_pcapng) {
2780 g_list_free_full(pcap_src->cap_pipe_info.pcapng.saved_blocks, g_free);
2781 pcap_src->cap_pipe_info.pcapng.saved_blocks = NULL;
2784 /* Capture device. If open, close the pcap_t. */
2785 if (pcap_src->pcap_h != NULL) {
2786 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_src->pcap_h);
2787 pcap_close(pcap_src->pcap_h);
2788 pcap_src->pcap_h = NULL;
2796 /* Shut down windows sockets */
2802 /* init the capture filter */
2803 static initfilter_status_t
2804 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2805 const gchar * name, const gchar * cfilter)
2807 struct bpf_program fcode;
2809 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2811 /* capture filters only work on real interfaces */
2812 if (cfilter && !from_cap_pipe) {
2813 /* A capture filter was specified; set it up. */
2814 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2815 /* Treat this specially - our caller might try to compile this
2816 as a display filter and, if that succeeds, warn the user that
2817 the display and capture filter syntaxes are different. */
2818 return INITFILTER_BAD_FILTER;
2820 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2821 #ifdef HAVE_PCAP_FREECODE
2822 pcap_freecode(&fcode);
2824 return INITFILTER_OTHER_ERROR;
2826 #ifdef HAVE_PCAP_FREECODE
2827 pcap_freecode(&fcode);
2831 return INITFILTER_NO_ERROR;
2835 /* set up to write to the already-opened capture output file/files */
2837 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2841 capture_src *pcap_src;
2842 interface_options *interface_opts;
2843 gboolean successful;
2845 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2847 if ((capture_opts->use_pcapng == FALSE) &&
2848 (capture_opts->ifaces->len > 1)) {
2849 g_snprintf(errmsg, errmsg_len,
2850 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
2854 /* Set up to write to the capture file. */
2855 if (capture_opts->multi_files_on) {
2856 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2858 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2859 if (ld->pdh == NULL) {
2864 pcap_src = g_array_index(ld->pcaps, capture_src *, 0);
2865 if (pcap_src->from_pcapng) {
2866 /* We are just going to rewrite the source SHB and IDB blocks */
2869 if (capture_opts->use_pcapng) {
2871 GString *cpu_info_str;
2872 GString *os_info_str;
2874 cpu_info_str = g_string_new("");
2875 os_info_str = g_string_new("");
2876 get_cpu_info(cpu_info_str);
2877 get_os_version_info(os_info_str);
2879 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2880 successful = pcapng_write_session_header_block(ld->pdh,
2881 (const char *)capture_opts->capture_comment, /* Comment */
2882 cpu_info_str->str, /* HW */
2883 os_info_str->str, /* OS */
2885 -1, /* section_length */
2888 g_string_free(cpu_info_str, TRUE);
2891 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2892 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
2893 pcap_src = g_array_index(ld->pcaps, capture_src *, i);
2894 if (pcap_src->from_cap_pipe) {
2895 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
2897 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
2899 successful = pcapng_write_interface_description_block(global_ld.pdh,
2900 NULL, /* OPT_COMMENT 1 */
2901 interface_opts->name, /* IDB_NAME 2 */
2902 interface_opts->descr, /* IDB_DESCRIPTION 3 */
2903 interface_opts->cfilter, /* IDB_FILTER 11 */
2904 os_info_str->str, /* IDB_OS 12 */
2907 &(global_ld.bytes_written),
2908 0, /* IDB_IF_SPEED 8 */
2909 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2913 g_string_free(os_info_str, TRUE);
2916 pcap_src = g_array_index(ld->pcaps, capture_src *, 0);
2917 if (pcap_src->from_cap_pipe) {
2918 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
2920 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
2922 successful = libpcap_write_file_header(ld->pdh, pcap_src->linktype, pcap_src->snaplen,
2923 pcap_src->ts_nsec, &ld->bytes_written, &err);
2931 if (ld->pdh == NULL) {
2932 /* We couldn't set up to write to the capture file. */
2933 /* XXX - use cf_open_error_message from tshark instead? */
2938 g_snprintf(errmsg, errmsg_len,
2939 "The file to which the capture would be"
2940 " saved (\"%s\") could not be opened: Error %d.",
2941 capture_opts->save_file, err);
2943 g_snprintf(errmsg, errmsg_len,
2944 "The file to which the capture would be"
2945 " saved (\"%s\") could not be opened: %s.",
2946 capture_opts->save_file, g_strerror(err));
2958 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2962 capture_src *pcap_src;
2963 guint64 end_time = create_timestamp();
2965 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2967 if (capture_opts->multi_files_on) {
2968 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2970 if (capture_opts->use_pcapng) {
2971 for (i = 0; i < global_ld.pcaps->len; i++) {
2972 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
2973 if (!pcap_src->from_cap_pipe) {
2974 guint64 isb_ifrecv, isb_ifdrop;
2975 struct pcap_stat stats;
2977 if (pcap_stats(pcap_src->pcap_h, &stats) >= 0) {
2978 isb_ifrecv = pcap_src->received;
2979 isb_ifdrop = stats.ps_drop + pcap_src->dropped + pcap_src->flushed;
2981 isb_ifrecv = G_MAXUINT64;
2982 isb_ifdrop = G_MAXUINT64;
2984 pcapng_write_interface_statistics_block(ld->pdh,
2987 "Counters provided by dumpcap",
2996 if (fclose(ld->pdh) == EOF) {
2997 if (err_close != NULL) {
3007 /* dispatch incoming packets (pcap or capture pipe)
3009 * Waits for incoming packets to be available, and calls pcap_dispatch()
3010 * to cause them to be processed.
3012 * Returns the number of packets which were processed.
3014 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3015 * packet-batching behaviour does not cause packets to get held back
3019 capture_loop_dispatch(loop_data *ld,
3020 char *errmsg, int errmsg_len, capture_src *pcap_src)
3023 gint packet_count_before;
3028 packet_count_before = ld->packet_count;
3029 if (pcap_src->from_cap_pipe) {
3030 /* dispatch from capture pipe */
3031 #ifdef LOG_CAPTURE_VERBOSE
3032 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
3035 sel_ret = cap_pipe_select(pcap_src->cap_pipe_fd);
3037 if (sel_ret < 0 && errno != EINTR) {
3038 g_snprintf(errmsg, errmsg_len,
3039 "Unexpected error from select: %s", g_strerror(errno));
3040 report_capture_error(errmsg, please_report);
3045 * "select()" says we can read from the pipe without blocking
3048 inpkts = pcap_src->cap_pipe_dispatch(ld, pcap_src, errmsg, errmsg_len);
3058 /* dispatch from pcap */
3059 #ifdef MUST_DO_SELECT
3061 * If we have "pcap_get_selectable_fd()", we use it to get the
3062 * descriptor on which to select; if that's -1, it means there
3063 * is no descriptor on which you can do a "select()" (perhaps
3064 * because you're capturing on a special device, and that device's
3065 * driver unfortunately doesn't support "select()", in which case
3066 * we don't do the select - which means it might not be possible
3067 * to stop a capture until a packet arrives. If that's unacceptable,
3068 * plead with whoever supplies the software for that device to add
3069 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3070 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3071 * later, so it can use pcap_breakloop().
3073 #ifdef LOG_CAPTURE_VERBOSE
3074 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3076 if (pcap_src->pcap_fd != -1) {
3077 sel_ret = cap_pipe_select(pcap_src->pcap_fd);
3080 * "select()" says we can read from it without blocking; go for
3083 * We don't have pcap_breakloop(), so we only process one packet
3084 * per pcap_dispatch() call, to allow a signal to stop the
3085 * processing immediately, rather than processing all packets
3086 * in a batch before quitting.
3089 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3091 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3095 /* Error, rather than pcap_breakloop(). */
3096 pcap_src->pcap_err = TRUE;
3098 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3101 if (sel_ret < 0 && errno != EINTR) {
3102 g_snprintf(errmsg, errmsg_len,
3103 "Unexpected error from select: %s", g_strerror(errno));
3104 report_capture_error(errmsg, please_report);
3110 #endif /* MUST_DO_SELECT */
3112 /* dispatch from pcap without select */
3114 #ifdef LOG_CAPTURE_VERBOSE
3115 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3119 * On Windows, we don't support asynchronously telling a process to
3120 * stop capturing; instead, we check for an indication on a pipe
3121 * after processing packets. We therefore process only one packet
3122 * at a time, so that we can check the pipe after every packet.
3125 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3127 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3131 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3133 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3138 /* Error, rather than pcap_breakloop(). */
3139 pcap_src->pcap_err = TRUE;
3141 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3143 #else /* pcap_next_ex */
3144 #ifdef LOG_CAPTURE_VERBOSE
3145 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3147 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3150 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3151 * see https://wiki.wireshark.org/CaptureSetup/WinPcapRemote
3152 * This should be fixed in the WinPcap 4.0 alpha release.
3154 * For reference, an example remote interface:
3155 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3158 /* emulate dispatch from pcap */
3161 struct pcap_pkthdr *pkt_header;
3166 (in = pcap_next_ex(pcap_src->pcap_h, &pkt_header, &pkt_data)) == 1) {
3168 capture_loop_queue_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
3170 capture_loop_write_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
3175 pcap_src->pcap_err = TRUE;
3179 #endif /* pcap_next_ex */
3183 #ifdef LOG_CAPTURE_VERBOSE
3184 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3187 return ld->packet_count - packet_count_before;
3191 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3192 * want to grab only the characters between the '{' and '}' delimiters.
3194 * Returns a GString that must be freed with g_string_free(). */
3196 isolate_uuid(const char *iface)
3201 ptr = strchr(iface, '{');
3203 return g_string_new(iface);
3204 gstr = g_string_new(ptr + 1);
3206 ptr = strchr(gstr->str, '}');
3210 gstr = g_string_truncate(gstr, ptr - gstr->str);
3215 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3216 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3218 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3219 char *errmsg, int errmsg_len)
3222 gchar *capfile_name;
3223 gchar *prefix, *suffix;
3224 gboolean is_tempfile;
3226 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3227 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3229 if (capture_opts->save_file != NULL) {
3230 /* We return to the caller while the capture is in progress.
3231 * Therefore we need to take a copy of save_file in
3232 * case the caller destroys it after we return.
3234 capfile_name = g_strdup(capture_opts->save_file);
3236 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3237 if (capture_opts->multi_files_on) {
3238 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3239 g_snprintf(errmsg, errmsg_len,
3240 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3241 g_free(capfile_name);
3244 if (strcmp(capfile_name, "-") == 0) {
3245 /* write to stdout */
3248 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3249 _setmode(1, O_BINARY);
3252 /* Try to open the specified FIFO for use as a capture buffer.
3253 Do *not* create it if it doesn't exist. There's nothing
3254 to truncate. If we need to read it, We Have A Problem. */
3255 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY, 0);
3257 } /* if (...output_to_pipe ... */
3260 if (capture_opts->multi_files_on) {
3261 /* ringbuffer is enabled */
3262 *save_file_fd = ringbuf_init(capfile_name,
3263 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3264 capture_opts->group_read_access);
3266 /* we need the ringbuf name */
3267 if (*save_file_fd != -1) {
3268 g_free(capfile_name);
3269 capfile_name = g_strdup(ringbuf_current_filename());
3272 /* Try to open/create the specified file for use as a capture buffer. */
3273 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY|O_TRUNC|O_CREAT,
3274 (capture_opts->group_read_access) ? 0640 : 0600);
3277 is_tempfile = FALSE;
3279 /* Choose a random name for the temporary capture buffer */
3280 if (global_capture_opts.ifaces->len > 1) {
3281 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3282 if (capture_opts->use_pcapng) {
3289 basename = g_path_get_basename((&g_array_index(global_capture_opts.ifaces, interface_options, 0))->console_display_name);
3291 /* use the generic portion of the interface guid to form the basis of the filename */
3292 if (strncmp("NPF_{", basename, 5)==0)
3294 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
3296 iface = isolate_uuid(basename);
3298 basename = g_strdup(iface->str);
3299 g_string_free(iface, TRUE);
3302 /* generate the temp file name prefix and suffix */
3303 if (capture_opts->use_pcapng) {
3304 prefix = g_strconcat("wireshark_", basename, NULL);
3307 prefix = g_strconcat("wireshark_", basename, NULL);
3312 *save_file_fd = create_tempfile(&tmpname, prefix, suffix);
3314 capfile_name = g_strdup(tmpname);
3318 /* did we fail to open the output file? */
3319 if (*save_file_fd == -1) {
3321 g_snprintf(errmsg, errmsg_len,
3322 "The temporary file to which the capture would be saved (\"%s\") "
3323 "could not be opened: %s.", capfile_name, g_strerror(errno));
3325 if (capture_opts->multi_files_on) {
3326 ringbuf_error_cleanup();
3329 g_snprintf(errmsg, errmsg_len,
3330 "The file to which the capture would be saved (\"%s\") "
3331 "could not be opened: %s.", capfile_name,
3334 g_free(capfile_name);
3338 if (capture_opts->save_file != NULL) {
3339 g_free(capture_opts->save_file);
3341 capture_opts->save_file = capfile_name;
3342 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3343 "g_free(capfile_name)". */
3349 /* Do the work of handling either the file size or file duration capture
3350 conditions being reached, and switching files or stopping. */
3352 do_file_switch_or_stop(capture_options *capture_opts,
3353 condition *cnd_autostop_files,
3354 condition *cnd_autostop_size,
3355 condition *cnd_file_duration,
3356 condition *cnd_file_interval)
3359 capture_src *pcap_src;
3360 interface_options *interface_opts;
3361 gboolean successful;
3363 if (capture_opts->multi_files_on) {
3364 if (cnd_autostop_files != NULL &&
3365 cnd_eval(cnd_autostop_files, (guint64)++global_ld.autostop_files)) {
3366 /* no files left: stop here */
3367 global_ld.go = FALSE;
3371 /* Switch to the next ringbuffer file */
3372 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3373 &global_ld.save_file_fd, &global_ld.err)) {
3375 /* File switch succeeded: reset the conditions */
3376 global_ld.bytes_written = 0;
3377 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3378 if (pcap_src->from_pcapng) {
3379 /* Write the saved SHB and all IDBs to start of next file */
3380 /* The blocks were saved in reverse so reverse it before iterating */
3381 GList *rlist = g_list_reverse(pcap_src->cap_pipe_info.pcapng.saved_blocks);
3382 GList *list = rlist;
3384 while (list && successful) {
3385 successful = pcapng_write_saved_block(pcap_src, (struct pcapng_block_header_s *) list->data);
3386 list = g_list_next(list);
3388 pcap_src->cap_pipe_info.pcapng.saved_blocks = g_list_reverse(rlist);
3390 if (capture_opts->use_pcapng) {
3392 GString *cpu_info_str;
3393 GString *os_info_str;
3395 cpu_info_str = g_string_new("");
3396 os_info_str = g_string_new("");
3397 get_cpu_info(cpu_info_str);
3398 get_os_version_info(os_info_str);
3400 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
3401 successful = pcapng_write_session_header_block(global_ld.pdh,
3402 (const char *)capture_opts->capture_comment, /* Comment */
3403 cpu_info_str->str, /* HW */
3404 os_info_str->str, /* OS */
3406 -1, /* section_length */
3407 &(global_ld.bytes_written),
3409 g_string_free(cpu_info_str, TRUE);
3412 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3413 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
3414 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3415 successful = pcapng_write_interface_description_block(global_ld.pdh,
3416 NULL, /* OPT_COMMENT 1 */
3417 interface_opts->name, /* IDB_NAME 2 */
3418 interface_opts->descr, /* IDB_DESCRIPTION 3 */
3419 interface_opts->cfilter, /* IDB_FILTER 11 */
3420 os_info_str->str, /* IDB_OS 12 */
3423 &(global_ld.bytes_written),
3424 0, /* IDB_IF_SPEED 8 */
3425 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3429 g_string_free(os_info_str, TRUE);
3432 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3433 successful = libpcap_write_file_header(global_ld.pdh, pcap_src->linktype, pcap_src->snaplen,
3434 pcap_src->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3438 fclose(global_ld.pdh);
3439 global_ld.pdh = NULL;
3440 global_ld.go = FALSE;
3443 if (cnd_autostop_size)
3444 cnd_reset(cnd_autostop_size);
3445 if (cnd_file_duration)
3446 cnd_reset(cnd_file_duration);
3447 if (cnd_file_interval)
3448 cnd_reset(cnd_file_interval);
3449 fflush(global_ld.pdh);
3451 report_packet_count(global_ld.inpkts_to_sync_pipe);
3452 global_ld.inpkts_to_sync_pipe = 0;
3453 report_new_capture_file(capture_opts->save_file);
3455 /* File switch failed: stop here */
3456 global_ld.go = FALSE;
3460 /* single file, stop now */
3461 global_ld.go = FALSE;
3468 pcap_read_handler(void* arg)
3470 capture_src *pcap_src;
3471 char errmsg[MSG_MAX_LENGTH+1];
3473 pcap_src = (capture_src *)arg;
3475 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3476 pcap_src->interface_id);
3478 while (global_ld.go) {
3479 /* dispatch incoming packets */
3480 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_src);
3482 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3483 pcap_src->interface_id);
3484 g_thread_exit(NULL);
3488 /* Do the low-level work of a capture.
3489 Returns TRUE if it succeeds, FALSE otherwise. */
3491 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3494 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3496 struct timeval upd_time, cur_time;
3500 condition *cnd_file_duration = NULL;
3501 condition *cnd_file_interval = NULL;
3502 condition *cnd_autostop_files = NULL;
3503 condition *cnd_autostop_size = NULL;
3504 condition *cnd_autostop_duration = NULL;
3507 gboolean cfilter_error = FALSE;
3508 char errmsg[MSG_MAX_LENGTH+1];
3509 char secondary_errmsg[MSG_MAX_LENGTH+1];
3510 capture_src *pcap_src;
3511 interface_options *interface_opts;
3512 guint i, error_index = 0;
3515 *secondary_errmsg = '\0';
3517 /* init the loop data */
3518 global_ld.go = TRUE;
3519 global_ld.packet_count = 0;
3521 global_ld.report_packet_count = FALSE;
3523 if (capture_opts->has_autostop_packets)
3524 global_ld.packet_max = capture_opts->autostop_packets;
3526 global_ld.packet_max = 0; /* no limit */
3527 global_ld.inpkts_to_sync_pipe = 0;
3528 global_ld.err = 0; /* no error seen yet */
3529 global_ld.pdh = NULL;
3530 global_ld.autostop_files = 0;
3531 global_ld.save_file_fd = -1;
3533 /* We haven't yet gotten the capture statistics. */
3534 *stats_known = FALSE;
3536 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3537 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3539 /* open the "input file" from network interface or capture pipe */
3540 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3541 secondary_errmsg, sizeof(secondary_errmsg))) {
3544 for (i = 0; i < capture_opts->ifaces->len; i++) {
3545 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3546 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
3547 /* init the input filter from the network interface (capture pipe will do nothing) */
3549 * When remote capturing WinPCap crashes when the capture filter
3550 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3553 switch (capture_loop_init_filter(pcap_src->pcap_h, pcap_src->from_cap_pipe,
3554 interface_opts->name,
3555 interface_opts->cfilter?interface_opts->cfilter:"")) {
3557 case INITFILTER_NO_ERROR:
3560 case INITFILTER_BAD_FILTER:
3561 cfilter_error = TRUE;
3563 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_src->pcap_h));
3566 case INITFILTER_OTHER_ERROR:
3567 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3568 pcap_geterr(pcap_src->pcap_h));
3569 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3574 /* If we're supposed to write to a capture file, open it for output
3575 (temporary/specified name/ringbuffer) */
3576 if (capture_opts->saving_to_file) {
3577 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3578 errmsg, sizeof(errmsg))) {
3582 /* set up to write to the already-opened capture output file/files */
3583 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3588 /* XXX - capture SIGTERM and close the capture, in case we're on a
3589 Linux 2.0[.x] system and you have to explicitly close the capture
3590 stream in order to turn promiscuous mode off? We need to do that
3591 in other places as well - and I don't think that works all the
3592 time in any case, due to libpcap bugs. */
3594 /* Well, we should be able to start capturing.
3596 Sync out the capture file, so the header makes it to the file system,
3597 and send a "capture started successfully and capture file created"
3598 message to our parent so that they'll open the capture file and
3599 update its windows to indicate that we have a live capture in
3601 fflush(global_ld.pdh);
3602 report_new_capture_file(capture_opts->save_file);
3605 /* initialize capture stop (and alike) conditions */
3606 init_capture_stop_conditions();
3607 /* create stop conditions */
3608 if (capture_opts->has_autostop_filesize) {
3609 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3610 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3613 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1000);
3615 if (capture_opts->has_autostop_duration)
3616 cnd_autostop_duration =
3617 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3619 if (capture_opts->multi_files_on) {
3620 if (capture_opts->has_file_duration)
3622 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3624 if (capture_opts->has_autostop_files)
3625 cnd_autostop_files =
3626 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_files);
3628 if (capture_opts->has_file_interval)
3630 cnd_new(CND_CLASS_INTERVAL, capture_opts->file_interval);
3633 /* init the time values */
3635 upd_time = GetTickCount();
3637 gettimeofday(&upd_time, NULL);
3639 start_time = create_timestamp();
3640 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3641 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3643 /* WOW, everything is prepared! */
3644 /* please fasten your seat belts, we will enter now the actual capture loop */
3646 pcap_queue = g_async_queue_new();
3647 pcap_queue_bytes = 0;
3648 pcap_queue_packets = 0;
3649 for (i = 0; i < global_ld.pcaps->len; i++) {
3650 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3651 /* XXX - Add an interface name here? */
3652 pcap_src->tid = g_thread_new("Capture read", pcap_read_handler, pcap_src);
3655 while (global_ld.go) {
3656 /* dispatch incoming packets */
3658 pcap_queue_element *queue_element;
3659 #if GLIB_CHECK_VERSION(2,31,18)
3661 g_async_queue_lock(pcap_queue);
3662 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3664 GTimeVal write_thread_time;
3666 g_get_current_time(&write_thread_time);
3667 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3668 g_async_queue_lock(pcap_queue);
3669 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3671 if (queue_element) {
3672 if (queue_element->pcap_src->from_pcapng) {
3673 pcap_queue_bytes -= queue_element->u.bh.block_total_length;
3674 pcap_queue_packets -= 1;
3676 pcap_queue_bytes -= queue_element->u.phdr.caplen;
3677 pcap_queue_packets -= 1;
3680 g_async_queue_unlock(pcap_queue);
3681 if (queue_element) {
3682 if (queue_element->pcap_src->from_pcapng) {
3683 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3684 "Dequeued a block of length %d captured on interface %d.",
3685 queue_element->u.bh.block_total_length, queue_element->pcap_src->interface_id);
3687 capture_loop_write_pcapng_cb(queue_element->pcap_src,
3688 &queue_element->u.bh,
3691 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3692 "Dequeued a packet of length %d captured on interface %d.",
3693 queue_element->u.phdr.caplen, queue_element->pcap_src->interface_id);
3695 capture_loop_write_packet_cb((u_char *) queue_element->pcap_src,
3696 &queue_element->u.phdr,
3699 g_free(queue_element->pd);
3700 g_free(queue_element);
3706 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3707 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3708 sizeof(errmsg), pcap_src);
3711 /* Were we asked to print packet counts by the SIGINFO handler? */
3712 if (global_ld.report_packet_count) {
3713 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3714 plurality(global_ld.packet_count, "", "s"));
3715 global_ld.report_packet_count = FALSE;
3720 /* any news from our parent (signal pipe)? -> just stop the capture */
3721 if (!signal_pipe_check_running()) {
3722 global_ld.go = FALSE;
3727 global_ld.inpkts_to_sync_pipe += inpkts;
3729 /* check capture size condition */
3730 if (cnd_autostop_size != NULL &&
3731 cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
3732 /* Capture size limit reached, do we have another file? */
3733 if (!do_file_switch_or_stop(capture_opts,
3739 } /* cnd_autostop_size */
3740 if (capture_opts->output_to_pipe) {
3741 fflush(global_ld.pdh);
3745 /* Only update once every 500ms so as not to overload slow displays.
3746 * This also prevents too much context-switching between the dumpcap
3747 * and wireshark processes.
3749 #define DUMPCAP_UPD_TIME 500
3752 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3753 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3755 gettimeofday(&cur_time, NULL);
3756 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3757 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3760 upd_time = cur_time;
3763 if (pcap_stats(pch, stats) >= 0) {
3764 *stats_known = TRUE;
3767 /* Let the parent process know. */
3768 if (global_ld.inpkts_to_sync_pipe) {
3770 fflush(global_ld.pdh);
3772 /* Send our parent a message saying we've written out
3773 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3775 report_packet_count(global_ld.inpkts_to_sync_pipe);
3777 global_ld.inpkts_to_sync_pipe = 0;
3780 /* check capture duration condition */
3781 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3782 /* The maximum capture time has elapsed; stop the capture. */
3783 global_ld.go = FALSE;
3787 /* check capture file duration condition */
3788 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3789 /* duration limit reached, do we have another file? */
3790 if (!do_file_switch_or_stop(capture_opts,
3796 } /* cnd_file_duration */
3798 /* check capture file interval condition */
3799 if (cnd_file_interval != NULL && cnd_eval(cnd_file_interval)) {
3800 /* end of interval reached, do we have another file? */
3801 if (!do_file_switch_or_stop(capture_opts,
3807 } /* cnd_file_interval */
3811 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3813 pcap_queue_element *queue_element;
3815 for (i = 0; i < global_ld.pcaps->len; i++) {
3816 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3817 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3818 pcap_src->interface_id);
3819 g_thread_join(pcap_src->tid);
3820 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3821 pcap_src->interface_id);
3824 g_async_queue_lock(pcap_queue);
3825 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3826 if (queue_element) {
3827 pcap_queue_bytes -= queue_element->u.phdr.caplen;
3828 pcap_queue_packets -= 1;
3830 g_async_queue_unlock(pcap_queue);
3831 if (queue_element == NULL) {
3834 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3835 "Dequeued a packet of length %d captured on interface %d.",
3836 queue_element->u.phdr.caplen, queue_element->pcap_src->interface_id);
3837 capture_loop_write_packet_cb((u_char *)queue_element->pcap_src,
3838 &queue_element->u.phdr,
3840 g_free(queue_element->pd);
3841 g_free(queue_element);
3842 global_ld.inpkts_to_sync_pipe += 1;
3843 if (capture_opts->output_to_pipe) {
3844 fflush(global_ld.pdh);
3850 /* delete stop conditions */
3851 if (cnd_file_duration != NULL)
3852 cnd_delete(cnd_file_duration);
3853 if (cnd_file_interval != NULL)
3854 cnd_delete(cnd_file_interval);
3855 if (cnd_autostop_files != NULL)
3856 cnd_delete(cnd_autostop_files);
3857 if (cnd_autostop_size != NULL)
3858 cnd_delete(cnd_autostop_size);
3859 if (cnd_autostop_duration != NULL)
3860 cnd_delete(cnd_autostop_duration);
3862 /* did we have a pcap (input) error? */
3863 for (i = 0; i < capture_opts->ifaces->len; i++) {
3864 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3865 if (pcap_src->pcap_err) {
3866 /* On Linux, if an interface goes down while you're capturing on it,
3867 you'll get a "recvfrom: Network is down" or
3868 "The interface went down" error (ENETDOWN).
3869 (At least you will if g_strerror() doesn't show a local translation
3872 On FreeBSD, DragonFly BSD, and macOS, if a network adapter
3873 disappears while you're capturing on it, you'll get a
3874 "read: Device not configured" error (ENXIO). (See previous
3875 parenthetical note.)
3877 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3879 These should *not* be reported to the Wireshark developers. */
3882 cap_err_str = pcap_geterr(pcap_src->pcap_h);
3883 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3884 strcmp(cap_err_str, "The interface went down") == 0 ||
3885 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3886 strcmp(cap_err_str, "read: I/O error") == 0 ||
3887 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3888 report_capture_error("The network adapter on which the capture was being done "
3889 "is no longer running; the capture has stopped.",
3892 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3894 report_capture_error(errmsg, please_report);
3897 } else if (pcap_src->from_cap_pipe && pcap_src->cap_pipe_err == PIPERR) {
3898 report_capture_error(errmsg, "");
3902 /* did we have an output error while capturing? */
3903 if (global_ld.err == 0) {
3906 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3907 global_ld.err, FALSE);
3908 report_capture_error(errmsg, please_report);
3912 if (capture_opts->saving_to_file) {
3913 /* close the output file */
3914 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3918 /* there might be packets not yet notified to the parent */
3919 /* (do this after closing the file, so all packets are already flushed) */
3920 if (global_ld.inpkts_to_sync_pipe) {
3922 report_packet_count(global_ld.inpkts_to_sync_pipe);
3923 global_ld.inpkts_to_sync_pipe = 0;
3926 /* If we've displayed a message about a write error, there's no point
3927 in displaying another message about an error on close. */
3928 if (!close_ok && write_ok) {
3929 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3931 report_capture_error(errmsg, "");
3935 * XXX We exhibit different behaviour between normal mode and sync mode
3936 * when the pipe is stdin and not already at EOF. If we're a child, the
3937 * parent's stdin isn't closed, so if the user starts another capture,
3938 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3939 * will say "Unrecognized libpcap format". On the other hand, in normal
3940 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3943 report_capture_count(TRUE);
3945 /* get packet drop statistics from pcap */
3946 for (i = 0; i < capture_opts->ifaces->len; i++) {
3948 guint32 pcap_dropped = 0;
3950 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3951 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
3952 received = pcap_src->received;
3953 if (pcap_src->pcap_h != NULL) {
3954 g_assert(!pcap_src->from_cap_pipe);
3955 /* Get the capture statistics, so we know how many packets were dropped. */
3957 * Older versions of libpcap didn't set ps_ifdrop on some
3958 * platforms; initialize it to 0 to handle that.
3960 stats->ps_ifdrop = 0;
3961 if (pcap_stats(pcap_src->pcap_h, stats) >= 0) {
3962 *stats_known = TRUE;
3963 /* Let the parent process know. */
3964 pcap_dropped += stats->ps_drop;
3966 g_snprintf(errmsg, sizeof(errmsg),
3967 "Can't get packet-drop statistics: %s",
3968 pcap_geterr(pcap_src->pcap_h));
3969 report_capture_error(errmsg, please_report);
3972 report_packet_drops(received, pcap_dropped, pcap_src->dropped, pcap_src->flushed, stats->ps_ifdrop, interface_opts->console_display_name);
3975 /* close the input file (pcap or capture pipe) */
3976 capture_loop_close_input(&global_ld);
3978 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
3980 /* ok, if the write and the close were successful. */
3981 return write_ok && close_ok;
3984 if (capture_opts->multi_files_on) {
3985 /* cleanup ringbuffer */
3986 ringbuf_error_cleanup();
3988 /* We can't use the save file, and we have no FILE * for the stream
3989 to close in order to close it, so close the FD directly. */
3990 if (global_ld.save_file_fd != -1) {
3991 ws_close(global_ld.save_file_fd);
3994 /* We couldn't even start the capture, so get rid of the capture
3996 if (capture_opts->save_file != NULL) {
3997 ws_unlink(capture_opts->save_file);
3998 g_free(capture_opts->save_file);
4001 capture_opts->save_file = NULL;
4003 report_cfilter_error(capture_opts, error_index, errmsg);
4005 report_capture_error(errmsg, secondary_errmsg);
4007 /* close the input file (pcap or cap_pipe) */
4008 capture_loop_close_input(&global_ld);
4010 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
4017 capture_loop_stop(void)
4019 #ifdef HAVE_PCAP_BREAKLOOP
4021 capture_src *pcap_src;
4023 for (i = 0; i < global_ld.pcaps->len; i++) {
4024 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4025 if (pcap_src->pcap_h != NULL)
4026 pcap_breakloop(pcap_src->pcap_h);
4029 global_ld.go = FALSE;
4034 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
4035 int err, gboolean is_close)
4040 g_snprintf(errmsg, errmsglen,
4041 "Not all the packets could be written to the file"
4042 " to which the capture was being saved\n"
4043 "(\"%s\") because there is no space left on the file system\n"
4044 "on which that file resides.",
4050 g_snprintf(errmsg, errmsglen,
4051 "Not all the packets could be written to the file"
4052 " to which the capture was being saved\n"
4053 "(\"%s\") because you are too close to, or over,"
4054 " your disk quota\n"
4055 "on the file system on which that file resides.",
4062 g_snprintf(errmsg, errmsglen,
4063 "The file to which the capture was being saved\n"
4064 "(\"%s\") could not be closed: %s.",
4065 fname, g_strerror(err));
4067 g_snprintf(errmsg, errmsglen,
4068 "An error occurred while writing to the file"
4069 " to which the capture was being saved\n"
4071 fname, g_strerror(err));
4077 /* one pcapng block was captured, process it */
4079 capture_loop_write_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, const u_char *pd)
4083 if (!global_capture_opts.use_pcapng) {
4086 /* We may be called multiple times from pcap_dispatch(); if we've set
4087 the "stop capturing" flag, ignore this packet, as we're not
4088 supposed to be saving any more packets. */
4089 if (!global_ld.go) {
4090 pcap_src->flushed++;
4094 if (global_ld.pdh) {
4095 gboolean successful;
4097 /* We're supposed to write the packet to a file; do so.
4098 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4099 "ld->err" to the error. */
4100 successful = pcapng_write_block(global_ld.pdh,
4102 bh->block_total_length,
4103 &global_ld.bytes_written, &err);
4105 fflush(global_ld.pdh);
4107 global_ld.go = FALSE;
4108 global_ld.err = err;
4109 pcap_src->dropped++;
4110 } else if (bh->block_type == BLOCK_TYPE_EPB || bh->block_type == BLOCK_TYPE_SPB) {
4111 /* count packet only if we actually have an EPB or SPB */
4112 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4113 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4114 "Wrote a packet of length %d captured on interface %u.",
4115 phdr->caplen, pcap_src->interface_id);
4117 global_ld.packet_count++;
4118 pcap_src->received++;
4119 /* if the user told us to stop after x packets, do we already have enough? */
4120 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
4121 global_ld.go = FALSE;
4127 /* one packet was captured, process it */
4129 capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
4132 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4134 guint ts_mul = pcap_src->ts_nsec ? 1000000000 : 1000000;
4136 /* We may be called multiple times from pcap_dispatch(); if we've set
4137 the "stop capturing" flag, ignore this packet, as we're not
4138 supposed to be saving any more packets. */
4139 if (!global_ld.go) {
4140 pcap_src->flushed++;
4144 if (global_ld.pdh) {
4145 gboolean successful;
4147 /* We're supposed to write the packet to a file; do so.
4148 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4149 "ld->err" to the error. */
4150 if (global_capture_opts.use_pcapng) {
4151 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
4153 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4154 phdr->caplen, phdr->len,
4155 pcap_src->interface_id,
4158 &global_ld.bytes_written, &err);
4160 successful = libpcap_write_packet(global_ld.pdh,
4161 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4162 phdr->caplen, phdr->len,
4164 &global_ld.bytes_written, &err);
4167 global_ld.go = FALSE;
4168 global_ld.err = err;
4169 pcap_src->dropped++;
4171 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4172 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4173 "Wrote a packet of length %d captured on interface %u.",
4174 phdr->caplen, pcap_src->interface_id);
4176 global_ld.packet_count++;
4177 pcap_src->received++;
4178 /* if the user told us to stop after x packets, do we already have enough? */
4179 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
4180 global_ld.go = FALSE;
4186 /* one packet was captured, queue it */
4188 capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
4191 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4192 pcap_queue_element *queue_element;
4193 gboolean limit_reached;
4195 /* We may be called multiple times from pcap_dispatch(); if we've set
4196 the "stop capturing" flag, ignore this packet, as we're not
4197 supposed to be saving any more packets. */
4198 if (!global_ld.go) {
4199 pcap_src->flushed++;
4203 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4204 if (queue_element == NULL) {
4205 pcap_src->dropped++;
4208 queue_element->pcap_src = pcap_src;
4209 queue_element->u.phdr = *phdr;
4210 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4211 if (queue_element->pd == NULL) {
4212 pcap_src->dropped++;
4213 g_free(queue_element);
4216 memcpy(queue_element->pd, pd, phdr->caplen);
4217 g_async_queue_lock(pcap_queue);
4218 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4219 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4220 limit_reached = FALSE;
4221 g_async_queue_push_unlocked(pcap_queue, queue_element);
4222 pcap_queue_bytes += phdr->caplen;
4223 pcap_queue_packets += 1;
4225 limit_reached = TRUE;
4227 g_async_queue_unlock(pcap_queue);
4228 if (limit_reached) {
4229 pcap_src->dropped++;
4230 g_free(queue_element->pd);
4231 g_free(queue_element);
4232 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4233 "Dropped a packet of length %d captured on interface %u.",
4234 phdr->caplen, pcap_src->interface_id);
4236 pcap_src->received++;
4237 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4238 "Queued a packet of length %d captured on interface %u.",
4239 phdr->caplen, pcap_src->interface_id);
4241 /* I don't want to hold the mutex over the debug output. So the
4242 output may be wrong */
4243 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4244 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4245 pcap_queue_bytes, pcap_queue_packets);
4248 /* one pcapng block was captured, queue it */
4250 capture_loop_queue_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, const u_char *pd)
4252 pcap_queue_element *queue_element;
4253 gboolean limit_reached;
4255 /* We may be called multiple times from pcap_dispatch(); if we've set
4256 the "stop capturing" flag, ignore this packet, as we're not
4257 supposed to be saving any more packets. */
4258 if (!global_ld.go) {
4259 pcap_src->flushed++;
4263 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4264 if (queue_element == NULL) {
4265 pcap_src->dropped++;
4268 queue_element->pcap_src = pcap_src;
4269 queue_element->u.bh = *bh;
4270 queue_element->pd = (u_char *)g_malloc(bh->block_total_length);
4271 if (queue_element->pd == NULL) {
4272 pcap_src->dropped++;
4273 g_free(queue_element);
4276 memcpy(queue_element->pd, pd, bh->block_total_length);
4277 g_async_queue_lock(pcap_queue);
4278 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4279 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4280 limit_reached = FALSE;
4281 g_async_queue_push_unlocked(pcap_queue, queue_element);
4282 pcap_queue_bytes += bh->block_total_length;
4283 pcap_queue_packets += 1;
4285 limit_reached = TRUE;
4287 g_async_queue_unlock(pcap_queue);
4288 if (limit_reached) {
4289 pcap_src->dropped++;
4290 g_free(queue_element->pd);
4291 g_free(queue_element);
4292 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4293 "Dropped a packet of length %d captured on interface %u.",
4294 bh->block_total_length, pcap_src->interface_id);
4296 pcap_src->received++;
4297 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4298 "Queued a packet of length %d captured on interface %u.",
4299 bh->block_total_length, pcap_src->interface_id);
4301 /* I don't want to hold the mutex over the debug output. So the
4302 output may be wrong */
4303 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4304 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4305 pcap_queue_bytes, pcap_queue_packets);
4309 set_80211_channel(const char *iface, const char *opt)
4313 guint32 center_freq1 = 0;
4314 guint32 center_freq2 = 0;
4317 gchar **options = NULL;
4319 options = g_strsplit_set(opt, ",", 4);
4320 for (args = 0; options[args]; args++);
4323 freq = get_nonzero_guint32(options[0], "802.11 channel frequency");
4325 if (args >= 1 && options[1]) {
4326 type = ws80211_str_to_chan_type(options[1]);
4328 cmdarg_err("\"%s\" is not a valid 802.11 channel type", options[1]);
4334 if (args >= 2 && options[2])
4335 center_freq1 = get_nonzero_guint32(options[2], "VHT center frequency");
4337 if (args >= 3 && options[3])
4338 center_freq2 = get_nonzero_guint32(options[3], "VHT center frequency 2");
4340 ret = ws80211_init();
4342 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4346 ret = ws80211_set_freq(iface, freq, type, center_freq1, center_freq2);
4349 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4355 pipe_write_block(2, SP_SUCCESS, NULL);
4358 g_strfreev(options);
4363 get_dumpcap_compiled_info(GString *str)
4365 /* Capture libraries */
4366 g_string_append(str, ", ");
4367 get_compiled_caplibs_version(str);
4371 get_dumpcap_runtime_info(GString *str)
4373 /* Capture libraries */
4374 g_string_append(str, ", ");
4375 get_runtime_caplibs_version(str);
4378 /* And now our feature presentation... [ fade to music ] */
4380 main(int argc, char *argv[])
4382 GString *comp_info_str;
4383 GString *runtime_info_str;
4385 static const struct option long_options[] = {
4386 {"help", no_argument, NULL, 'h'},
4387 {"version", no_argument, NULL, 'v'},
4388 LONGOPT_CAPTURE_COMMON
4392 gboolean arg_error = FALSE;
4398 struct sigaction action, oldaction;
4401 gboolean start_capture = TRUE;
4402 gboolean stats_known;
4403 struct pcap_stat stats;
4404 GLogLevelFlags log_flags;
4405 gboolean list_interfaces = FALSE;
4406 int caps_queries = 0;
4407 #ifdef HAVE_BPF_IMAGE
4408 gboolean print_bpf_code = FALSE;
4410 gboolean set_chan = FALSE;
4411 gchar *set_chan_arg = NULL;
4412 gboolean machine_readable = FALSE;
4413 gboolean print_statistics = FALSE;
4414 int status, run_once_args = 0;
4417 #if defined(__APPLE__) && defined(__LP64__)
4418 struct utsname osinfo;
4422 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
4424 /* Get the compile-time version information string */
4425 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
4427 /* Get the run-time version information string */
4428 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
4430 /* Add it to the information to be reported on a crash. */
4431 ws_add_crash_info("Dumpcap (Wireshark) %s\n"
4436 get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
4437 g_string_free(comp_info_str, TRUE);
4438 g_string_free(runtime_info_str, TRUE);
4441 arg_list_utf_16to8(argc, argv);
4442 create_app_running_mutex();
4445 * Initialize our DLL search path. MUST be called before LoadLibrary
4448 ws_init_dll_search_path();
4451 #ifdef HAVE_BPF_IMAGE
4452 #define OPTSTRING_d "d"
4454 #define OPTSTRING_d ""
4457 #ifdef HAVE_PCAP_REMOTE
4458 #define OPTSTRING_r "r"
4459 #define OPTSTRING_u "u"
4461 #define OPTSTRING_r ""
4462 #define OPTSTRING_u ""
4465 #ifdef HAVE_PCAP_SETSAMPLING
4466 #define OPTSTRING_m "m:"
4468 #define OPTSTRING_m ""
4471 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
4473 #ifdef DEBUG_CHILD_DUMPCAP
4474 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4475 fprintf (stderr, "Unable to open debug log file .\n");
4480 #if defined(__APPLE__) && defined(__LP64__)
4482 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
4483 * a bug workaround - timeouts less than 1 second don't work with libpcap
4484 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
4485 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4486 * The problem is extremely unlikely to be reintroduced in a future
4489 if (uname(&osinfo) == 0) {
4491 * {Mac} OS X/macOS 10.x uses Darwin {x+4}.0.0; 10.x.y uses Darwin
4492 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4493 * number of 10.0.0, not 10.1.0 - go figure).
4495 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
4496 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
4497 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
4498 need_timeout_workaround = TRUE;
4503 * Determine if dumpcap is being requested to run in a special
4504 * capture_child mode by going thru the command line args to see if
4505 * a -Z is present. (-Z is a hidden option).
4507 * The primary result of running in capture_child mode is that
4508 * all messages sent out on stderr are in a special type/len/string
4509 * format to allow message processing by type. These messages include
4510 * error messages if dumpcap fails to start the operation it was
4511 * requested to do, as well as various "status" messages which are sent
4512 * when an actual capture is in progress, and a "success" message sent
4513 * if dumpcap was requested to perform an operation other than a
4516 * Capture_child mode would normally be requested by a parent process
4517 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4518 * to which dumpcap stderr has been redirected. It might also have
4519 * another pipe to obtain dumpcap stdout output; for operations other
4520 * than a capture, that information is formatted specially for easier
4521 * parsing by the parent process.
4523 * Capture_child mode needs to be determined immediately upon
4524 * startup so that any messages generated by dumpcap in this mode
4525 * (eg: during initialization) will be formatted properly.
4528 for (i=1; i<argc; i++) {
4529 if (strcmp("-Z", argv[i]) == 0) {
4530 capture_child = TRUE;
4531 machine_readable = TRUE; /* request machine-readable output */
4533 /* set output pipe to binary mode, to avoid ugly text conversions */
4534 _setmode(2, O_BINARY);
4539 /* The default_log_handler will use stdout, which makes trouble in */
4540 /* capture child mode, as it uses stdout for its sync_pipe. */
4541 /* So: the filtering is done in the console_log_handler and not here.*/
4542 /* We set the log handlers right up front to make sure that any log */
4543 /* messages when running as child will be sent back to the parent */
4544 /* with the correct format. */
4549 G_LOG_LEVEL_CRITICAL|
4550 G_LOG_LEVEL_WARNING|
4551 G_LOG_LEVEL_MESSAGE|
4555 G_LOG_FLAG_RECURSION);
4557 g_log_set_handler(NULL,
4559 console_log_handler, NULL /* user_data */);
4560 g_log_set_handler(LOG_DOMAIN_MAIN,
4562 console_log_handler, NULL /* user_data */);
4563 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4565 console_log_handler, NULL /* user_data */);
4566 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4568 console_log_handler, NULL /* user_data */);
4570 /* Initialize the pcaps list */
4571 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(capture_src *));
4573 #if !GLIB_CHECK_VERSION(2,31,0)
4574 /* Initialize the thread system */
4575 g_thread_init(NULL);
4579 /* Load wpcap if possible. Do this before collecting the run-time version information */
4582 /* ... and also load the packet.dll from wpcap */
4583 /* XXX - currently not required, may change later. */
4584 /*wpcap_packet_load();*/
4586 /* Start windows sockets */
4587 result = WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4590 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_ERROR,
4591 "ERROR: WSAStartup failed with error: %d", result);
4595 /* Set handler for Ctrl+C key */
4596 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4598 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4599 and exit. Do the same with SIGPIPE, in case, for example,
4600 we're writing to our standard output and it's a pipe.
4601 Do the same with SIGHUP if it's not being ignored (if we're
4602 being run under nohup, it might be ignored, in which case we
4603 should leave it ignored).
4605 XXX - apparently, Coverity complained that part of action
4606 wasn't initialized. Perhaps it's running on Linux, where
4607 struct sigaction has an ignored "sa_restorer" element and
4608 where "sa_handler" and "sa_sigaction" might not be two
4609 members of a union. */
4610 memset(&action, 0, sizeof(action));
4611 action.sa_handler = capture_cleanup_handler;
4613 * Arrange that system calls not get restarted, because when
4614 * our signal handler returns we don't want to restart
4615 * a call that was waiting for packets to arrive.
4617 action.sa_flags = 0;
4618 sigemptyset(&action.sa_mask);
4619 sigaction(SIGTERM, &action, NULL);
4620 sigaction(SIGINT, &action, NULL);
4621 sigaction(SIGPIPE, &action, NULL);
4622 sigaction(SIGHUP, NULL, &oldaction);
4623 if (oldaction.sa_handler == SIG_DFL)
4624 sigaction(SIGHUP, &action, NULL);
4627 /* Catch SIGINFO and, if we get it and we're capturing in
4628 quiet mode, report the number of packets we've captured. */
4629 action.sa_handler = report_counts_siginfo;
4630 action.sa_flags = SA_RESTART;
4631 sigemptyset(&action.sa_mask);
4632 sigaction(SIGINFO, &action, NULL);
4633 #endif /* SIGINFO */
4636 /* ----------------------------------------------------------------- */
4637 /* Privilege and capability handling */
4639 /* 1. Running not as root or suid root; no special capabilities. */
4642 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4645 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4647 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4648 /* capabilities; Drop all other capabilities; */
4649 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4650 /* else: after pcap_open_live() in capture_loop_open_input() */
4651 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4652 /* (Note: this means that the process, although logged in */
4653 /* as root, does not have various permissions such as the */
4654 /* ability to bypass file access permissions). */
4655 /* XXX: Should we just leave capabilities alone in this case */
4656 /* so that user gets expected effect that root can do */
4659 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4661 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4662 /* else: after pcap_open_live() in capture_loop_open_input() */
4663 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4664 /* pcap_open_live). */
4666 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4668 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4669 /* capabilities; Drop all other capabilities; */
4670 /* Drop suid privileges (euid=ruid); */
4671 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4672 /* else: after pcap_open_live() in capture_loop_open_input() */
4673 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4675 /* XXX: For some Linux versions/distros with capabilities */
4676 /* a 'normal' process with any capabilities cannot be */
4677 /* 'killed' (signaled) from another (same uid) non-privileged */
4679 /* For example: If (non-suid) Wireshark forks a */
4680 /* child suid dumpcap which acts as described here (case 5), */
4681 /* Wireshark will be unable to kill (signal) the child */
4682 /* dumpcap process until the capabilities have been dropped */
4683 /* (after pcap_open_live()). */
4684 /* This behaviour will apparently be changed in the kernel */
4685 /* to allow the kill (signal) in this case. */
4686 /* See the following for details: */
4687 /* https://www.mail-archive.com/ [wrapped] */
4688 /* linux-security-module@vger.kernel.org/msg02913.html */
4690 /* It is therefore conceivable that if dumpcap somehow hangs */
4691 /* in pcap_open_live or before that wireshark will not */
4692 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4693 /* In this case, exiting wireshark will kill the child */
4694 /* dumpcap process. */
4696 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4697 /* capabilities; Using libcap. Note: capset cmd (which see) */
4698 /* used to assign capabilities to file. */
4700 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4701 /* else: after pcap_open_live() in capture_loop_open_input() */
4702 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4704 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4705 /* longer required (similar to capture). */
4707 /* ----------------------------------------------------------------- */
4709 init_process_policies();
4712 /* If 'started with special privileges' (and using libcap) */
4713 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4714 /* Set euid/egid = ruid/rgid to remove suid privileges */
4715 relinquish_privs_except_capture();
4718 /* Set the initial values in the capture options. This might be overwritten
4719 by the command line parameters. */
4720 capture_opts_init(&global_capture_opts);
4721 /* We always save to a file - if no file was specified, we save to a
4723 global_capture_opts.saving_to_file = TRUE;
4724 global_capture_opts.has_ring_num_files = TRUE;
4726 /* Pass on capture_child mode for capture_opts */
4727 global_capture_opts.capture_child = capture_child;
4729 /* Now get our args */
4730 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4732 case 'h': /* Print help and exit */
4733 printf("Dumpcap (Wireshark) %s\n"
4734 "Capture network packets and dump them into a pcapng or pcap file.\n"
4735 "See https://www.wireshark.org for more information.\n",
4736 get_ws_vcs_version_info());
4737 print_usage(stdout);
4740 case 'v': /* Show version and exit */
4741 comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
4742 runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
4743 show_version("Dumpcap (Wireshark)", comp_info_str, runtime_info_str);
4744 g_string_free(comp_info_str, TRUE);
4745 g_string_free(runtime_info_str, TRUE);
4748 /*** capture option specific ***/
4749 case 'a': /* autostop criteria */
4750 case 'b': /* Ringbuffer option */
4751 case 'c': /* Capture x packets */
4752 case 'f': /* capture filter */
4753 case 'g': /* enable group read access on file(s) */
4754 case 'i': /* Use interface x */
4755 case LONGOPT_SET_TSTAMP_TYPE: /* Set capture timestamp type */
4756 case 'n': /* Use pcapng format */
4757 case 'p': /* Don't capture in promiscuous mode */
4758 case 'P': /* Use pcap format */
4759 case 's': /* Set the snapshot (capture) length */
4760 case 'w': /* Write to capture file x */
4761 case 'y': /* Set the pcap data link type */
4762 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4763 #ifdef HAVE_PCAP_REMOTE
4764 case 'u': /* Use UDP for data transfer */
4765 case 'r': /* Capture own RPCAP traffic too */
4766 case 'A': /* Authentication */
4768 #ifdef HAVE_PCAP_SETSAMPLING
4769 case 'm': /* Sampling */
4771 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
4772 case 'B': /* Buffer size */
4774 #ifdef HAVE_PCAP_CREATE
4775 case 'I': /* Monitor mode */
4777 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4782 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4784 capture_child = TRUE;
4786 /* set output pipe to binary mode, to avoid ugly text conversions */
4787 _setmode(2, O_BINARY);
4789 * optarg = the control ID, aka the PPID, currently used for the
4792 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4793 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4794 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4795 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4797 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4798 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4799 "Signal pipe: Unable to open %s. Dead parent?",
4807 case 'q': /* Quiet */
4813 /*** all non capture option specific ***/
4814 case 'D': /* Print a list of capture devices and exit */
4815 if (!list_interfaces) {
4816 list_interfaces = TRUE;
4820 case 'L': /* Print list of link-layer types and exit */
4821 if (!(caps_queries & CAPS_QUERY_LINK_TYPES)) {
4822 caps_queries |= CAPS_QUERY_LINK_TYPES;
4826 case LONGOPT_LIST_TSTAMP_TYPES:
4827 caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
4829 #ifdef HAVE_BPF_IMAGE
4830 case 'd': /* Print BPF code for capture filter and exit */
4831 if (!print_bpf_code) {
4832 print_bpf_code = TRUE;
4837 case 'S': /* Print interface statistics once a second */
4838 if (!print_statistics) {
4839 print_statistics = TRUE;
4843 case 'k': /* Set wireless channel */
4846 set_chan_arg = optarg;
4849 cmdarg_err("Only one -k flag may be specified");
4853 case 'M': /* For -D, -L, and -S, print machine-readable output */
4854 machine_readable = TRUE;
4857 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4860 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4863 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4865 case '?': /* Bad flag - print usage message */
4874 /* user specified file name as regular command-line argument */
4875 /* XXX - use it as the capture file name (or something else)? */
4881 * Extra command line arguments were specified; complain.
4882 * XXX - interpret as capture filter, as tcpdump and tshark do?
4884 cmdarg_err("Invalid argument: %s", argv[0]);
4889 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4892 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4893 /* Use some default if the user hasn't specified some */
4894 /* XXX: Are these defaults good enough? */
4895 pcap_queue_byte_limit = 1000 * 1000;
4896 pcap_queue_packet_limit = 1000;
4899 print_usage(stderr);
4903 if (run_once_args > 1) {
4904 #ifdef HAVE_BPF_IMAGE
4905 cmdarg_err("Only one of -D, -L, -d, -k or -S may be supplied.");
4907 cmdarg_err("Only one of -D, -L, -k or -S may be supplied.");
4910 } else if (run_once_args == 1) {
4911 /* We're supposed to print some information, rather than
4912 to capture traffic; did they specify a ring buffer option? */
4913 if (global_capture_opts.multi_files_on) {
4914 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4918 /* We're supposed to capture traffic; */
4920 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4921 if (global_capture_opts.ifaces->len > 1) {
4923 global_capture_opts.use_pcapng = TRUE;
4926 if (global_capture_opts.capture_comment &&
4927 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4928 /* XXX - for ringbuffer, should we apply the comment to each file? */
4929 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4933 /* Was the ring buffer option specified and, if so, does it make sense? */
4934 if (global_capture_opts.multi_files_on) {
4935 /* Ring buffer works only under certain conditions:
4936 a) ring buffer does not work with temporary files;
4937 b) it makes no sense to enable the ring buffer if the maximum
4938 file size is set to "infinite". */
4939 if (global_capture_opts.save_file == NULL) {
4940 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4941 global_capture_opts.multi_files_on = FALSE;
4943 if (!global_capture_opts.has_autostop_filesize &&
4944 !global_capture_opts.has_file_duration &&
4945 !global_capture_opts.has_file_interval) {
4946 cmdarg_err("Ring buffer requested, but no maximum capture file size, duration"
4947 "or interval were specified.");
4949 /* XXX - this must be redesigned as the conditions changed */
4950 global_capture_opts.multi_files_on = FALSE;
4953 if (global_capture_opts.has_file_duration && global_capture_opts.has_file_interval) {
4954 cmdarg_err("Ring buffer file duration and interval can't be used at the same time.");
4961 * "-D" requires no interface to be selected; it's supposed to list
4964 if (list_interfaces) {
4965 /* Get the list of interfaces */
4970 if_list = capture_interface_list(&err, &err_str, NULL);
4971 if (if_list == NULL) {
4974 * If we're being run by another program, just give them
4975 * an empty list of interfaces, don't report this as
4976 * an error; that lets them decide whether to report
4977 * this as an error or not.
4979 if (!machine_readable) {
4980 cmdarg_err("There are no interfaces on which a capture can be done");
4984 cmdarg_err("%s", err_str);
4990 if (machine_readable) /* tab-separated values to stdout */
4991 print_machine_readable_interfaces(if_list);
4993 capture_opts_print_interfaces(if_list);
4994 free_interface_list(if_list);
4999 * "-S" requires no interface to be selected; it gives statistics
5000 * for all interfaces.
5002 if (print_statistics) {
5003 status = print_statistics_loop(machine_readable);
5008 interface_options *interface_opts;
5010 if (global_capture_opts.ifaces->len != 1) {
5011 cmdarg_err("Need one interface");
5015 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
5016 status = set_80211_channel(interface_opts->name, set_chan_arg);
5021 * "-L", "-d", and capturing act on a particular interface, so we have to
5022 * have an interface; if none was specified, pick a default.
5024 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
5026 /* cmdarg_err() already called .... */
5031 /* Get the list of link-layer and/or timestamp types for the capture device. */
5032 if_capabilities_t *caps;
5036 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
5037 int if_caps_queries = caps_queries;
5038 interface_options *interface_opts;
5040 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, ii);
5042 caps = get_if_capabilities(interface_opts, &err_str);
5044 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
5045 "Please check to make sure you have sufficient permissions, and that\n"
5046 "you have the proper interface or pipe specified.", interface_opts->name, err_str);
5050 if ((if_caps_queries & CAPS_QUERY_LINK_TYPES) && caps->data_link_types == NULL) {
5051 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts->name);
5053 } /* No timestamp types is no big deal. So we will just ignore it */
5055 if (interface_opts->monitor_mode)
5056 if_caps_queries |= CAPS_MONITOR_MODE;
5058 if (machine_readable) /* tab-separated values to stdout */
5059 /* XXX: We need to change the format and adapt consumers */
5060 print_machine_readable_if_capabilities(caps, if_caps_queries);
5062 /* XXX: We might want to print also the interface name */
5063 capture_opts_print_if_capabilities(caps, interface_opts->name, if_caps_queries);
5064 free_if_capabilities(caps);
5069 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
5070 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5071 interface_options *interface_opts;
5073 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5074 if (interface_opts->timestamp_type) {
5075 interface_opts->timestamp_type_id = pcap_tstamp_type_name_to_val(interface_opts->timestamp_type);
5076 if (interface_opts->timestamp_type_id < 0) {
5077 cmdarg_err("Invalid argument to option: --time-stamp-type=%s", interface_opts->timestamp_type);
5084 /* We're supposed to do a capture, or print the BPF code for a filter. */
5086 /* Let the user know what interfaces were chosen. */
5087 if (capture_child) {
5088 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5089 interface_options *interface_opts;
5091 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5092 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
5093 interface_opts->name);
5096 str = g_string_new("");
5098 if (global_capture_opts.ifaces->len < 2)
5100 if (global_capture_opts.ifaces->len < 4)
5103 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5104 interface_options *interface_opts;
5106 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5108 if (global_capture_opts.ifaces->len > 2) {
5109 g_string_append_printf(str, ",");
5111 g_string_append_printf(str, " ");
5112 if (j == global_capture_opts.ifaces->len - 1) {
5113 g_string_append_printf(str, "and ");
5116 g_string_append_printf(str, "'%s'", interface_opts->console_display_name);
5119 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
5121 fprintf(stderr, "Capturing on %s\n", str->str);
5122 g_string_free(str, TRUE);
5125 /* Process the snapshot length, as that affects the generated BPF code. */
5126 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
5128 #ifdef HAVE_BPF_IMAGE
5129 if (print_bpf_code) {
5130 show_filter_code(&global_capture_opts);
5135 /* We're supposed to do a capture. Process the ring buffer arguments. */
5136 capture_opts_trim_ring_num_files(&global_capture_opts);
5138 /* flush stderr prior to starting the main capture loop */
5141 /* Now start the capture. */
5142 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
5146 /* capture failed */
5149 return 0; /* never here, make compiler happy */
5154 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
5155 const char *message, gpointer user_data _U_)
5162 /* ignore log message, if log_level isn't interesting */
5163 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5164 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
5169 switch(log_level & G_LOG_LEVEL_MASK) {
5170 case G_LOG_LEVEL_ERROR:
5173 case G_LOG_LEVEL_CRITICAL:
5176 case G_LOG_LEVEL_WARNING:
5179 case G_LOG_LEVEL_MESSAGE:
5182 case G_LOG_LEVEL_INFO:
5185 case G_LOG_LEVEL_DEBUG:
5189 fprintf(stderr, "unknown log_level %d\n", log_level);
5191 g_assert_not_reached();
5194 /* Generate the output message */
5195 if (log_level & G_LOG_LEVEL_MESSAGE) {
5196 /* normal user messages without additional infos */
5197 msg = g_strdup_printf("%s\n", message);
5199 /* create a "timestamp" */
5201 today = localtime(&curr);
5203 /* info/debug messages with additional infos */
5205 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
5206 today->tm_hour, today->tm_min, today->tm_sec,
5207 log_domain != NULL ? log_domain : "",
5210 msg = g_strdup_printf("Time not representable %8s %s %s\n",
5211 log_domain != NULL ? log_domain : "",
5215 /* DEBUG & INFO msgs (if we're debugging today) */
5216 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
5217 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5218 #ifdef DEBUG_DUMPCAP
5219 fprintf(stderr, "%s", msg);
5222 #ifdef DEBUG_CHILD_DUMPCAP
5223 fprintf(debug_log, "%s", msg);
5231 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
5232 /* to parent especially formatted if dumpcap running as child. */
5233 if (capture_child) {
5234 sync_pipe_errmsg_to_parent(2, msg, "");
5236 fprintf(stderr, "%s", msg);
5243 /****************************************************************************************************************/
5244 /* indication report routines */
5248 report_packet_count(unsigned int packet_count)
5250 char tmp[SP_DECISIZE+1+1];
5251 static unsigned int count = 0;
5253 if (capture_child) {
5254 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
5255 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
5256 pipe_write_block(2, SP_PACKET_COUNT, tmp);
5258 count += packet_count;
5259 fprintf(stderr, "\rPackets: %u ", count);
5260 /* stderr could be line buffered */
5266 report_new_capture_file(const char *filename)
5268 if (capture_child) {
5269 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
5270 pipe_write_block(2, SP_FILE, filename);
5274 * Prevent a SIGINFO handler from writing to the standard error
5275 * while we're doing so; instead, have it just set a flag telling
5276 * us to print that information when we're done.
5279 #endif /* SIGINFO */
5280 fprintf(stderr, "File: %s\n", filename);
5281 /* stderr could be line buffered */
5286 * Allow SIGINFO handlers to write.
5291 * If a SIGINFO handler asked us to write out capture counts, do so.
5294 report_counts_for_siginfo();
5295 #endif /* SIGINFO */
5300 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
5302 interface_options *interface_opts;
5303 char tmp[MSG_MAX_LENGTH+1+6];
5305 if (i < capture_opts->ifaces->len) {
5306 if (capture_child) {
5307 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
5308 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
5309 pipe_write_block(2, SP_BAD_FILTER, tmp);
5312 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5313 * the error message below.
5315 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
5317 "Invalid capture filter \"%s\" for interface '%s'.\n"
5319 "That string isn't a valid capture filter (%s).\n"
5320 "See the User's Guide for a description of the capture filter syntax.",
5321 interface_opts->cfilter, interface_opts->name, errmsg);
5327 report_capture_error(const char *error_msg, const char *secondary_error_msg)
5329 if (capture_child) {
5330 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5331 "Primary Error: %s", error_msg);
5332 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5333 "Secondary Error: %s", secondary_error_msg);
5334 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5336 cmdarg_err("%s", error_msg);
5337 if (secondary_error_msg[0] != '\0')
5338 cmdarg_err_cont("%s", secondary_error_msg);
5343 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
5345 char tmp[SP_DECISIZE+1+1];
5346 guint32 total_drops = pcap_drops + drops + flushed;
5348 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
5350 if (capture_child) {
5351 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5352 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
5353 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
5354 /* XXX: Need to provide interface id, changes to consumers required. */
5355 pipe_write_block(2, SP_DROPS, tmp);
5358 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
5359 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
5360 received ? 100.0 * received / (received + total_drops) : 0.0);
5361 /* stderr could be line buffered */
5367 /************************************************************************************************/
5368 /* signal_pipe handling */
5373 signal_pipe_check_running(void)
5375 /* any news from our parent? -> just stop the capture */
5379 /* if we are running standalone, no check required */
5380 if (!capture_child) {
5384 if (!sig_pipe_name || !sig_pipe_handle) {
5385 /* This shouldn't happen */
5386 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5387 "Signal pipe: No name or handle");
5392 * XXX - We should have the process ID of the parent (from the "-Z" flag)
5393 * at this point. Should we check to see if the parent is still alive,
5394 * e.g. by using OpenProcess?
5397 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5399 if (!result || avail > 0) {
5400 /* peek failed or some bytes really available */
5401 /* (if not piping from stdin this would fail) */
5402 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5403 "Signal pipe: Stop capture: %s", sig_pipe_name);
5404 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5405 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
5406 sig_pipe_handle, result, avail);
5409 /* pipe ok and no bytes available */
5416 * Editor modelines - https://www.wireshark.org/tools/modelines.html
5421 * indent-tabs-mode: nil
5424 * vi: set shiftwidth=4 tabstop=8 expandtab:
5425 * :indentSize=4:tabSize=8:noTabs=true: