5 * Wireshark - Network traffic analyzer
6 * By Gerald Combs <gerald@wireshark.org>
7 * Copyright 1998 Gerald Combs
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 #include <stdlib.h> /* for exit() */
33 #ifdef HAVE_SYS_TYPES_H
34 # include <sys/types.h>
37 #ifdef HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
41 #ifdef HAVE_NETINET_IN_H
42 #include <netinet/in.h>
45 #ifdef HAVE_SYS_STAT_H
46 # include <sys/stat.h>
61 #ifdef HAVE_ARPA_INET_H
62 #include <arpa/inet.h>
65 #if defined(__APPLE__) && defined(__LP64__)
66 #include <sys/utsname.h>
72 #include <wsutil/crash_info.h>
75 #include "wsutil/wsgetopt.h"
83 # include <sys/prctl.h>
84 # include <sys/capability.h>
87 #include "ringbuffer.h"
88 #include "clopts_common.h"
89 #include "cmdarg_err.h"
90 #include "version_info.h"
92 #include "capture-pcap-util.h"
94 #include "capture-wpcap.h"
100 #include "capture-wpcap.h"
101 #include <wsutil/unicode-utils.h>
108 #ifdef NEED_INET_V6DEFS_H
109 # include "wsutil/inet_v6defs.h"
112 #include <wsutil/privileges.h>
114 #include "sync_pipe.h"
116 #include "capture_opts.h"
117 #include "capture_session.h"
118 #include "capture_ifinfo.h"
119 #include "capture_sync.h"
121 #include "conditions.h"
122 #include "capture_stop_conditions.h"
124 #include "wsutil/tempfile.h"
126 #include "wsutil/file_util.h"
128 #include "ws80211_utils.h"
131 * Get information about libpcap format from "wiretap/libpcap.h".
132 * XXX - can we just use pcap_open_offline() to read the pipe?
134 #include "wiretap/libpcap.h"
136 /**#define DEBUG_DUMPCAP**/
137 /**#define DEBUG_CHILD_DUMPCAP**/
141 #include <conio.h> /* _getch() */
145 #ifdef DEBUG_CHILD_DUMPCAP
146 FILE *debug_log; /* for logging debug messages to */
147 /* a file if DEBUG_CHILD_DUMPCAP */
151 static GAsyncQueue *pcap_queue;
152 static gint64 pcap_queue_bytes;
153 static gint64 pcap_queue_packets;
154 static gint64 pcap_queue_byte_limit = 0;
155 static gint64 pcap_queue_packet_limit = 0;
157 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
159 static gchar *sig_pipe_name = NULL;
160 static HANDLE sig_pipe_handle = NULL;
161 static gboolean signal_pipe_check_running(void);
165 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
166 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
169 /** Stop a low-level capture (stops the capture child). */
170 static void capture_loop_stop(void);
171 /** Close a pipe, or socket if \a from_socket is TRUE */
172 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
174 /* Enable kernel BPF jit compiler if available */
175 int enable_kernel_bpf_jit_compiler(void)
180 const char *file = "/proc/sys/net/core/bpf_jit_enable";
182 fd = open(file, O_WRONLY);
186 ret = write(fd, "1", (unsigned int)strlen("1"));
193 #if !defined (__linux__)
194 #ifndef HAVE_PCAP_BREAKLOOP
196 * We don't have pcap_breakloop(), which is the only way to ensure that
197 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
198 * won't, if the call to read the next packet or batch of packets is
199 * is interrupted by a signal on UN*X, just go back and try again to
202 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
203 * the signal handler, set a flag to stop capturing; however, without
204 * a guarantee of that sort, we can't guarantee that we'll stop capturing
205 * if the read will be retried and won't time out if no packets arrive.
207 * Therefore, on at least some platforms, we work around the lack of
208 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
209 * to wait for packets to arrive, so that we're probably going to be
210 * blocked in the select() when the signal arrives, and can just bail
211 * out of the loop at that point.
213 * However, we don't want to do that on BSD (because "select()" doesn't work
214 * correctly on BPF devices on at least some releases of some flavors of
215 * BSD), and we don't want to do it on Windows (because "select()" is
216 * something for sockets, not for arbitrary handles). (Note that "Windows"
217 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
218 * using WinPcap, not a UNIX libpcap.)
220 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
221 * on BSD times out even if no packets have arrived, so we'll eventually
222 * exit pcap_dispatch() with an indication that no packets have arrived,
223 * and will break out of the capture loop at that point.
225 * On Windows, we can't send a SIGINT to stop capturing, so none of this
226 * applies in any case.
228 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
229 * want to include it if it's not present on this platform, however.
231 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
232 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
234 # define MUST_DO_SELECT
235 # endif /* avoid select */
236 #endif /* HAVE_PCAP_BREAKLOOP */
238 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
239 * in pcap_dispatch(); on the other hand, select() works just fine there.
240 * Hence we use a select for that come what may.
242 #define MUST_DO_SELECT
245 /** init the capture filter */
248 INITFILTER_BAD_FILTER,
249 INITFILTER_OTHER_ERROR
250 } initfilter_status_t;
253 STATE_EXPECT_REC_HDR,
266 typedef struct _pcap_options {
271 #ifdef MUST_DO_SELECT
272 int pcap_fd; /**< pcap file descriptor */
279 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
280 /**< capture pipe (unix only "input file") */
281 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
282 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
283 struct pcap_hdr cap_pipe_hdr; /**< Pcap header when capturing from a pipe */
284 struct pcaprec_modified_hdr cap_pipe_rechdr; /**< Pcap record header when capturing from a pipe */
286 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
288 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
289 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
290 gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
292 char * cap_pipe_buf; /**< Pointer to the data buffer we read into */
293 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
294 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
296 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
297 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
299 cap_pipe_state_t cap_pipe_state;
300 cap_pipe_err_t cap_pipe_err;
303 GMutex *cap_pipe_read_mtx;
304 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
308 typedef struct _loop_data {
310 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
311 int err; /**< if non-zero, error seen while capturing */
312 gint packet_count; /**< Number of packets we have already captured */
313 gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
314 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
316 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
322 guint64 bytes_written;
323 guint32 autostop_files;
326 typedef struct _pcap_queue_element {
327 pcap_options *pcap_opts;
328 struct pcap_pkthdr phdr;
330 } pcap_queue_element;
333 * Standard secondary message for unexpected errors.
335 static const char please_report[] =
336 "Please report this to the Wireshark developers.\n"
337 "http://bugs.wireshark.org/\n"
338 "(This is not a crash; please do not report it as such.)";
341 * This needs to be static, so that the SIGINT handler can clear the "go"
344 static loop_data global_ld;
348 * Timeout, in milliseconds, for reads from the stream of captured packets
349 * from a capture device.
351 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
352 * 64-bit applications, with sub-second timeouts not to work. The bug is
353 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
355 #if defined(__APPLE__) && defined(__LP64__)
356 static gboolean need_timeout_workaround;
358 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
360 #define CAP_READ_TIMEOUT 250
364 * Timeout, in microseconds, for reads from the stream of captured packets
365 * from a pipe. Pipes don't have the same problem that BPF devices do
366 * in OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
367 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
368 * of the offending versions of Snow Leopard.
370 * On Windows this value is converted to milliseconds and passed to
371 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
372 * will return immediately.
375 #define PIPE_READ_TIMEOUT 100000
377 #define PIPE_READ_TIMEOUT 250000
380 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
383 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
384 const char *message, gpointer user_data _U_);
386 /* capture related options */
387 static capture_options global_capture_opts;
388 static gboolean quiet = FALSE;
389 static gboolean use_threads = FALSE;
390 static guint64 start_time;
392 static void capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
394 static void capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
396 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
397 int err, gboolean is_close);
399 static void WS_MSVC_NORETURN exit_main(int err) G_GNUC_NORETURN;
401 static void report_new_capture_file(const char *filename);
402 static void report_packet_count(unsigned int packet_count);
403 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, gchar *name);
404 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
405 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
407 #define MSG_MAX_LENGTH 4096
409 /* Copied from pcapio.c libpcap_write_interface_statistics_block()*/
411 create_timestamp(void) {
421 * Current time, represented as 100-nanosecond intervals since
422 * January 1, 1601, 00:00:00 UTC.
424 * I think DWORD might be signed, so cast both parts of "now"
425 * to guint32 so that the sign bit doesn't get treated specially.
427 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
428 * might want to use instead.
430 GetSystemTimeAsFileTime(&now);
431 timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
432 (guint32)now.dwLowDateTime;
435 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
441 * Subtract difference, in microseconds, between January 1, 1601
442 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
444 timestamp -= G_GINT64_CONSTANT(11644473600000000U);
447 * Current time, represented as seconds and microseconds since
448 * January 1, 1970, 00:00:00 UTC.
450 gettimeofday(&now, NULL);
453 * Convert to delta in microseconds.
455 timestamp = (guint64)(now.tv_sec) * 1000000 +
456 (guint64)(now.tv_usec);
462 print_usage(gboolean print_ver)
469 "Dumpcap " VERSION "%s\n"
470 "Capture network packets and dump them into a pcapng file.\n"
471 "See http://www.wireshark.org for more information.\n",
472 wireshark_svnversion);
476 fprintf(output, "\nUsage: dumpcap [options] ...\n");
477 fprintf(output, "\n");
478 fprintf(output, "Capture interface:\n");
479 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
480 " or for remote capturing, use one of these formats:\n"
481 " rpcap://<host>/<interface>\n"
482 " TCP@<host>:<port>\n");
483 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
484 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
485 fprintf(output, " -p don't capture in promiscuous mode\n");
486 #ifdef HAVE_PCAP_CREATE
487 fprintf(output, " -I capture in monitor mode, if available\n");
489 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
490 fprintf(output, " -B <buffer size> size of kernel buffer in MB (def: %dMB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
492 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
493 fprintf(output, " -D print list of interfaces and exit\n");
494 fprintf(output, " -L print list of link-layer types of iface and exit\n");
495 #ifdef HAVE_BPF_IMAGE
496 fprintf(output, " -d print generated BPF code for capture filter\n");
498 fprintf(output, " -k set channel on wifi interface <freq>,[<type>]\n");
499 fprintf(output, " -S print statistics for each interface once per second\n");
500 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
501 fprintf(output, "\n");
502 #ifdef HAVE_PCAP_REMOTE
503 fprintf(output, "RPCAP options:\n");
504 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
505 fprintf(output, " -u use UDP for RPCAP data transfer\n");
506 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
507 #ifdef HAVE_PCAP_SETSAMPLING
508 fprintf(output, " -m <sampling type> use packet sampling\n");
509 fprintf(output, " count:NUM - capture one packet of every NUM\n");
510 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
513 fprintf(output, "Stop conditions:\n");
514 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
515 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
516 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
517 fprintf(output, " files:NUM - stop after NUM files\n");
518 /*fprintf(output, "\n");*/
519 fprintf(output, "Output (files):\n");
520 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
521 fprintf(output, " -g enable group read access on the output file(s)\n");
522 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
523 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
524 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
525 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
526 fprintf(output, " -P use libpcap format instead of pcapng\n");
527 fprintf(output, " --capture-comment <comment>\n");
528 fprintf(output, " add a capture comment to the output file\n");
529 fprintf(output, " (only for pcapng)\n");
530 fprintf(output, "\n");
531 fprintf(output, "Miscellaneous:\n");
532 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
533 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
534 fprintf(output, " within dumpcap\n");
535 fprintf(output, " -t use a separate thread per interface\n");
536 fprintf(output, " -q don't report packet capture counts\n");
537 fprintf(output, " -v print version information and exit\n");
538 fprintf(output, " -h display this help and exit\n");
539 fprintf(output, "\n");
540 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
541 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
542 fprintf(output, "\n");
543 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
547 show_version(GString *comp_info_str, GString *runtime_info_str)
550 "Dumpcap " VERSION "%s\n"
555 "See http://www.wireshark.org for more information.\n",
556 wireshark_svnversion, get_copyright_info(), comp_info_str->str, runtime_info_str->str);
560 * Report an error in command-line arguments.
563 cmdarg_err(const char *fmt, ...)
569 /* Generate a 'special format' message back to parent */
571 msg = g_strdup_vprintf(fmt, ap);
572 sync_pipe_errmsg_to_parent(2, msg, "");
577 fprintf(stderr, "dumpcap: ");
578 vfprintf(stderr, fmt, ap);
579 fprintf(stderr, "\n");
585 * Report additional information for an error in command-line arguments.
588 cmdarg_err_cont(const char *fmt, ...)
595 msg = g_strdup_vprintf(fmt, ap);
596 sync_pipe_errmsg_to_parent(2, msg, "");
601 vfprintf(stderr, fmt, ap);
602 fprintf(stderr, "\n");
609 #if 0 /* Set to enable capability debugging */
610 /* see 'man cap_to_text()' for explanation of output */
611 /* '=' means 'all= ' ie: no capabilities */
612 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
614 print_caps(const char *pfx) {
615 cap_t caps = cap_get_proc();
616 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
617 "%s: EUID: %d Capabilities: %s", pfx,
618 geteuid(), cap_to_text(caps, NULL));
621 print_caps(const char *pfx _U_) {
626 relinquish_all_capabilities(void)
628 /* Drop any and all capabilities this process may have. */
629 /* Allowed whether or not process has any privileges. */
630 cap_t caps = cap_init(); /* all capabilities initialized to off */
631 print_caps("Pre-clear");
632 if (cap_set_proc(caps)) {
633 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
635 print_caps("Post-clear");
641 open_capture_device(interface_options *interface_opts,
642 char (*open_err_str)[PCAP_ERRBUF_SIZE])
645 #ifdef HAVE_PCAP_CREATE
648 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
649 struct pcap_rmtauth auth;
652 /* Open the network interface to capture from it.
653 Some versions of libpcap may put warnings into the error buffer
654 if they succeed; to tell if that's happened, we have to clear
655 the error buffer, and check if it's still a null string. */
656 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Entering open_capture_device().");
657 (*open_err_str)[0] = '\0';
658 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
660 * If we're opening a remote device, use pcap_open(); that's currently
661 * the only open routine that supports remote devices.
663 if (strncmp (interface_opts->name, "rpcap://", 8) == 0) {
664 auth.type = interface_opts->auth_type == CAPTURE_AUTH_PWD ?
665 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
666 auth.username = interface_opts->auth_username;
667 auth.password = interface_opts->auth_password;
669 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
670 "Calling pcap_open() using name %s, snaplen %d, promisc_mode %d, datatx_udp %d, nocap_rpcap %d.",
671 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode,
672 interface_opts->datatx_udp, interface_opts->nocap_rpcap);
673 pcap_h = pcap_open(interface_opts->name, interface_opts->snaplen,
675 (interface_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
676 (interface_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
677 (interface_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
678 CAP_READ_TIMEOUT, &auth, *open_err_str);
679 if (pcap_h == NULL) {
680 /* Error - did pcap actually supply an error message? */
681 if ((*open_err_str)[0] == '\0') {
682 /* Work around known WinPcap bug wherein no error message is
683 filled in on a failure to open an rpcap: URL. */
684 g_strlcpy(*open_err_str,
685 "Unknown error (pcap bug; actual error cause not reported)",
686 sizeof *open_err_str);
689 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
690 "pcap_open() returned %p.", (void *)pcap_h);
695 * If we're not opening a remote device, use pcap_create() and
696 * pcap_activate() if we have them, so that we can set the buffer
697 * size, otherwise use pcap_open_live().
699 #ifdef HAVE_PCAP_CREATE
700 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
701 "Calling pcap_create() using %s.", interface_opts->name);
702 pcap_h = pcap_create(interface_opts->name, *open_err_str);
703 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
704 "pcap_create() returned %p.", (void *)pcap_h);
705 if (pcap_h != NULL) {
706 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
707 "Calling pcap_set_snaplen() with snaplen %d.", interface_opts->snaplen);
708 pcap_set_snaplen(pcap_h, interface_opts->snaplen);
709 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
710 "Calling pcap_set_promisc() with promisc_mode %d.", interface_opts->promisc_mode);
711 pcap_set_promisc(pcap_h, interface_opts->promisc_mode);
712 pcap_set_timeout(pcap_h, CAP_READ_TIMEOUT);
714 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
715 "buffersize %d.", interface_opts->buffer_size);
716 if (interface_opts->buffer_size != 0) {
717 pcap_set_buffer_size(pcap_h, interface_opts->buffer_size * 1024 * 1024);
719 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
720 "monitor_mode %d.", interface_opts->monitor_mode);
721 if (interface_opts->monitor_mode)
722 pcap_set_rfmon(pcap_h, 1);
723 err = pcap_activate(pcap_h);
724 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
725 "pcap_activate() returned %d.", err);
727 /* Failed to activate, set to NULL */
728 if (err == PCAP_ERROR)
729 g_strlcpy(*open_err_str, pcap_geterr(pcap_h), sizeof *open_err_str);
731 g_strlcpy(*open_err_str, pcap_statustostr(err), sizeof *open_err_str);
737 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
738 "pcap_open_live() calling using name %s, snaplen %d, promisc_mode %d.",
739 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode);
740 pcap_h = pcap_open_live(interface_opts->name, interface_opts->snaplen,
741 interface_opts->promisc_mode, CAP_READ_TIMEOUT,
743 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
744 "pcap_open_live() returned %p.", (void *)pcap_h);
747 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "open_capture_device %s : %s", pcap_h ? "SUCCESS" : "FAILURE", interface_opts->name);
752 get_capture_device_open_failure_messages(const char *open_err_str,
758 char *errmsg, size_t errmsg_len,
759 char *secondary_errmsg,
760 size_t secondary_errmsg_len)
763 const char *libpcap_warn;
764 static const char ppamsg[] = "can't find PPA for ";
767 g_snprintf(errmsg, (gulong) errmsg_len,
768 "The capture session could not be initiated (%s).", open_err_str);
771 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
773 "In order to capture packets, WinPcap must be installed; see\n"
775 " http://www.winpcap.org/\n"
779 " http://www.mirrors.wiretapped.net/security/packet-capture/winpcap/\n"
783 " http://winpcap.cs.pu.edu.tw/\n"
785 "for a downloadable version of WinPcap and for instructions on how to install\n"
788 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
790 "Please check that \"%s\" is the proper interface.\n"
793 "Help can be found at:\n"
795 " http://wiki.wireshark.org/WinPcap\n"
796 " http://wiki.wireshark.org/CaptureSetup\n",
800 /* If we got a "can't find PPA for X" message, warn the user (who
801 is running dumpcap on HP-UX) that they don't have a version of
802 libpcap that properly handles HP-UX (libpcap 0.6.x and later
803 versions, which properly handle HP-UX, say "can't find /dev/dlpi
804 PPA for X" rather than "can't find PPA for X"). */
805 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
808 "You are running (T)Wireshark with a version of the libpcap library\n"
809 "that doesn't handle HP-UX network devices well; this means that\n"
810 "(T)Wireshark may not be able to capture packets.\n"
812 "To fix this, you should install libpcap 0.6.2, or a later version\n"
813 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
814 "packaged binary form from the Software Porting And Archive Centre\n"
815 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
816 "at the URL lists a number of mirror sites.";
820 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
821 "Please check to make sure you have sufficient permissions, and that you have "
822 "the proper interface or pipe specified.%s", libpcap_warn);
826 /* Set the data link type on a pcap. */
828 set_pcap_linktype(pcap_t *pcap_h, int linktype,
829 #ifdef HAVE_PCAP_SET_DATALINK
834 char *errmsg, size_t errmsg_len,
835 char *secondary_errmsg, size_t secondary_errmsg_len)
837 char *set_linktype_err_str;
840 return TRUE; /* just use the default */
841 #ifdef HAVE_PCAP_SET_DATALINK
842 if (pcap_set_datalink(pcap_h, linktype) == 0)
843 return TRUE; /* no error */
844 set_linktype_err_str = pcap_geterr(pcap_h);
846 /* Let them set it to the type it is; reject any other request. */
847 if (get_pcap_linktype(pcap_h, name) == linktype)
848 return TRUE; /* no error */
849 set_linktype_err_str =
850 "That DLT isn't one of the DLTs supported by this device";
852 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
853 set_linktype_err_str);
855 * If the error isn't "XXX is not one of the DLTs supported by this device",
856 * tell the user to tell the Wireshark developers about it.
858 if (strstr(set_linktype_err_str, "is not one of the DLTs supported by this device") == NULL)
859 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
861 secondary_errmsg[0] = '\0';
866 compile_capture_filter(const char *iface, pcap_t *pcap_h,
867 struct bpf_program *fcode, const char *cfilter)
869 bpf_u_int32 netnum, netmask;
870 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
872 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
874 * Well, we can't get the netmask for this interface; it's used
875 * only for filters that check for broadcast IP addresses, so
876 * we just punt and use 0. It might be nice to warn the user,
877 * but that's a pain in a GUI application, as it'd involve popping
878 * up a message box, and it's not clear how often this would make
879 * a difference (only filters that check for IP broadcast addresses
883 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
888 * Sigh. Older versions of libpcap don't properly declare the
889 * third argument to pcap_compile() as a const pointer. Cast
892 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
897 #ifdef HAVE_BPF_IMAGE
899 show_filter_code(capture_options *capture_opts)
901 interface_options interface_opts;
903 gchar open_err_str[PCAP_ERRBUF_SIZE];
904 char errmsg[MSG_MAX_LENGTH+1];
905 char secondary_errmsg[MSG_MAX_LENGTH+1];
906 struct bpf_program fcode;
907 struct bpf_insn *insn;
911 for (j = 0; j < capture_opts->ifaces->len; j++) {
912 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
913 pcap_h = open_capture_device(&interface_opts, &open_err_str);
914 if (pcap_h == NULL) {
915 /* Open failed; get messages */
916 get_capture_device_open_failure_messages(open_err_str,
918 errmsg, sizeof errmsg,
920 sizeof secondary_errmsg);
921 /* And report them */
922 report_capture_error(errmsg, secondary_errmsg);
926 /* Set the link-layer type. */
927 if (!set_pcap_linktype(pcap_h, interface_opts.linktype, interface_opts.name,
928 errmsg, sizeof errmsg,
929 secondary_errmsg, sizeof secondary_errmsg)) {
931 report_capture_error(errmsg, secondary_errmsg);
935 /* OK, try to compile the capture filter. */
936 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
937 interface_opts.cfilter)) {
939 report_cfilter_error(capture_opts, j, errmsg);
944 /* Now print the filter code. */
945 insn = fcode.bf_insns;
947 for (i = 0; i < fcode.bf_len; insn++, i++)
948 printf("%s\n", bpf_image(insn, i));
950 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
951 /* to remove any suid privileges. */
952 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
953 /* (euid/egid have already previously been set to ruid/rgid. */
954 /* (See comment in main() for details) */
956 relinquish_special_privs_perm();
958 relinquish_all_capabilities();
961 /* Let our parent know we succeeded. */
962 pipe_write_block(2, SP_SUCCESS, NULL);
969 * capture_interface_list() is expected to do the right thing to get
970 * a list of interfaces.
972 * In most of the programs in the Wireshark suite, "the right thing"
973 * is to run dumpcap and ask it for the list, because dumpcap may
974 * be the only program in the suite with enough privileges to get
977 * In dumpcap itself, however, we obviously can't run dumpcap to
978 * ask for the list. Therefore, our capture_interface_list() should
979 * just call get_interface_list().
982 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
984 return get_interface_list(err, err_str);
988 * Get the data-link type for a libpcap device.
989 * This works around AIX 5.x's non-standard and incompatible-with-the-
990 * rest-of-the-universe libpcap.
993 get_pcap_linktype(pcap_t *pch, const char *devicename
1001 const char *ifacename;
1004 linktype = pcap_datalink(pch);
1008 * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
1009 * rather than DLT_ values for link-layer types; the ifType values
1010 * for LAN devices are:
1017 * and the ifType value for a loopback device is 24.
1019 * The AIX names for LAN devices begin with:
1026 * and the AIX names for loopback devices begin with "lo".
1028 * (The difference between "Ethernet" and "802.3" is presumably
1029 * whether packets have an Ethernet header, with a packet type,
1030 * or an 802.3 header, with a packet length, followed by an 802.2
1031 * header and possibly a SNAP header.)
1033 * If the device name matches "linktype" interpreted as an ifType
1034 * value, rather than as a DLT_ value, we will assume this is AIX's
1035 * non-standard, incompatible libpcap, rather than a standard libpcap,
1036 * and will map the link-layer type to the standard DLT_ value for
1037 * that link-layer type, as that's what the rest of Wireshark expects.
1039 * (This means the capture files won't be readable by a tcpdump
1040 * linked with AIX's non-standard libpcap, but so it goes. They
1041 * *will* be readable by standard versions of tcpdump, Wireshark,
1044 * XXX - if we conclude we're using AIX libpcap, should we also
1045 * set a flag to cause us to assume the time stamps are in
1046 * seconds-and-nanoseconds form, and to convert them to
1047 * seconds-and-microseconds form before processing them and
1052 * Find the last component of the device name, which is the
1055 ifacename = strchr(devicename, '/');
1056 if (ifacename == NULL)
1057 ifacename = devicename;
1059 /* See if it matches any of the LAN device names. */
1060 if (strncmp(ifacename, "en", 2) == 0) {
1061 if (linktype == 6) {
1063 * That's the RFC 1573 value for Ethernet; map it to DLT_EN10MB.
1067 } else if (strncmp(ifacename, "et", 2) == 0) {
1068 if (linktype == 7) {
1070 * That's the RFC 1573 value for 802.3; map it to DLT_EN10MB.
1071 * (libpcap, tcpdump, Wireshark, etc. don't care if it's Ethernet
1076 } else if (strncmp(ifacename, "tr", 2) == 0) {
1077 if (linktype == 9) {
1079 * That's the RFC 1573 value for 802.5 (Token Ring); map it to
1080 * DLT_IEEE802, which is what's used for Token Ring.
1084 } else if (strncmp(ifacename, "fi", 2) == 0) {
1085 if (linktype == 15) {
1087 * That's the RFC 1573 value for FDDI; map it to DLT_FDDI.
1091 } else if (strncmp(ifacename, "lo", 2) == 0) {
1092 if (linktype == 24) {
1094 * That's the RFC 1573 value for "software loopback" devices; map it
1095 * to DLT_NULL, which is what's used for loopback devices on BSD.
1105 static data_link_info_t *
1106 create_data_link_info(int dlt)
1108 data_link_info_t *data_link_info;
1111 data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
1112 data_link_info->dlt = dlt;
1113 text = pcap_datalink_val_to_name(dlt);
1115 data_link_info->name = g_strdup(text);
1117 data_link_info->name = g_strdup_printf("DLT %d", dlt);
1118 text = pcap_datalink_val_to_description(dlt);
1120 data_link_info->description = g_strdup(text);
1122 data_link_info->description = NULL;
1123 return data_link_info;
1127 * Get the capabilities of a network device.
1129 static if_capabilities_t *
1130 get_if_capabilities(const char *devicename, gboolean monitor_mode
1131 #ifndef HAVE_PCAP_CREATE
1136 if_capabilities_t *caps;
1137 char errbuf[PCAP_ERRBUF_SIZE];
1139 #ifdef HAVE_PCAP_CREATE
1143 #ifdef HAVE_PCAP_LIST_DATALINKS
1147 data_link_info_t *data_link_info;
1150 * Allocate the interface capabilities structure.
1152 caps = (if_capabilities_t *)g_malloc(sizeof *caps);
1155 * WinPcap 4.1.2, and possibly earlier versions, have a bug
1156 * wherein, when an open with an rpcap: URL fails, the error
1157 * message for the error is not copied to errbuf and whatever
1158 * on-the-stack junk is in errbuf is treated as the error
1161 * To work around that (and any other bugs of that sort, we
1162 * initialize errbuf to an empty string. If we get an error
1163 * and the string is empty, we report it as an unknown error.
1164 * (If we *don't* get an error, and the string is *non*-empty,
1165 * that could be a warning returned, such as "can't turn
1166 * promiscuous mode on"; we currently don't do so.)
1169 #ifdef HAVE_PCAP_OPEN
1170 pch = pcap_open(devicename, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1171 caps->can_set_rfmon = FALSE;
1173 if (err_str != NULL)
1174 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1178 #elif defined(HAVE_PCAP_CREATE)
1179 pch = pcap_create(devicename, errbuf);
1181 if (err_str != NULL)
1182 *err_str = g_strdup(errbuf);
1186 status = pcap_can_set_rfmon(pch);
1189 if (status == PCAP_ERROR)
1190 *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
1193 *err_str = g_strdup(pcap_statustostr(status));
1199 caps->can_set_rfmon = FALSE;
1200 else if (status == 1) {
1201 caps->can_set_rfmon = TRUE;
1203 pcap_set_rfmon(pch, 1);
1205 if (err_str != NULL) {
1206 *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
1214 status = pcap_activate(pch);
1216 /* Error. We ignore warnings (status > 0). */
1217 if (err_str != NULL) {
1218 if (status == PCAP_ERROR)
1219 *err_str = g_strdup_printf("pcap_activate() failed: %s",
1222 *err_str = g_strdup(pcap_statustostr(status));
1229 pch = pcap_open_live(devicename, MIN_PACKET_SIZE, 0, 0, errbuf);
1230 caps->can_set_rfmon = FALSE;
1232 if (err_str != NULL)
1233 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1238 deflt = get_pcap_linktype(pch, devicename);
1239 #ifdef HAVE_PCAP_LIST_DATALINKS
1240 nlt = pcap_list_datalinks(pch, &linktypes);
1241 if (nlt == 0 || linktypes == NULL) {
1243 if (err_str != NULL)
1244 *err_str = NULL; /* an empty list doesn't mean an error */
1248 caps->data_link_types = NULL;
1249 for (i = 0; i < nlt; i++) {
1250 data_link_info = create_data_link_info(linktypes[i]);
1253 * XXX - for 802.11, make the most detailed 802.11
1254 * version the default, rather than the one the
1255 * device has as the default?
1257 if (linktypes[i] == deflt)
1258 caps->data_link_types = g_list_prepend(caps->data_link_types,
1261 caps->data_link_types = g_list_append(caps->data_link_types,
1264 #ifdef HAVE_PCAP_FREE_DATALINKS
1265 pcap_free_datalinks(linktypes);
1268 * In Windows, there's no guarantee that if you have a library
1269 * built with one version of the MSVC++ run-time library, and
1270 * it returns a pointer to allocated data, you can free that
1271 * data from a program linked with another version of the
1272 * MSVC++ run-time library.
1274 * This is not an issue on UN*X.
1276 * See the mail threads starting at
1278 * http://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
1282 * http://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
1285 #define xx_free free /* hack so checkAPIs doesn't complain */
1288 #endif /* HAVE_PCAP_FREE_DATALINKS */
1289 #else /* HAVE_PCAP_LIST_DATALINKS */
1291 data_link_info = create_data_link_info(deflt);
1292 caps->data_link_types = g_list_append(caps->data_link_types,
1294 #endif /* HAVE_PCAP_LIST_DATALINKS */
1298 if (err_str != NULL)
1303 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
1305 * Output a machine readable list of the interfaces
1306 * This list is retrieved by the sync_interface_list_open() function
1307 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
1310 print_machine_readable_interfaces(GList *if_list)
1317 char addr_str[ADDRSTRLEN];
1319 if (capture_child) {
1320 /* Let our parent know we succeeded. */
1321 pipe_write_block(2, SP_SUCCESS, NULL);
1324 i = 1; /* Interface id number */
1325 for (if_entry = g_list_first(if_list); if_entry != NULL;
1326 if_entry = g_list_next(if_entry)) {
1327 if_info = (if_info_t *)if_entry->data;
1328 printf("%d. %s\t", i++, if_info->name);
1331 * Print the contents of the if_entry struct in a parseable format.
1332 * Each if_entry element is tab-separated. Addresses are comma-
1335 /* XXX - Make sure our description doesn't contain a tab */
1336 if (if_info->vendor_description != NULL)
1337 printf("%s\t", if_info->vendor_description);
1341 /* XXX - Make sure our friendly name doesn't contain a tab */
1342 if (if_info->friendly_name != NULL)
1343 printf("%s\t", if_info->friendly_name);
1347 printf("%u\t", if_info->type);
1349 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
1350 addr = g_slist_next(addr)) {
1351 if (addr != g_slist_nth(if_info->addrs, 0))
1354 if_addr = (if_addr_t *)addr->data;
1355 switch(if_addr->ifat_type) {
1357 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
1359 printf("%s", addr_str);
1361 printf("<unknown IPv4>");
1365 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
1366 addr_str, ADDRSTRLEN)) {
1367 printf("%s", addr_str);
1369 printf("<unknown IPv6>");
1373 printf("<type unknown %u>", if_addr->ifat_type);
1377 if (if_info->loopback)
1378 printf("\tloopback");
1380 printf("\tnetwork");
1387 * If you change the machine-readable output format of this function,
1388 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
1391 print_machine_readable_if_capabilities(if_capabilities_t *caps)
1394 data_link_info_t *data_link_info;
1395 const gchar *desc_str;
1397 if (capture_child) {
1398 /* Let our parent know we succeeded. */
1399 pipe_write_block(2, SP_SUCCESS, NULL);
1402 if (caps->can_set_rfmon)
1406 for (lt_entry = caps->data_link_types; lt_entry != NULL;
1407 lt_entry = g_list_next(lt_entry)) {
1408 data_link_info = (data_link_info_t *)lt_entry->data;
1409 if (data_link_info->description != NULL)
1410 desc_str = data_link_info->description;
1412 desc_str = "(not supported)";
1413 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
1423 /* Print the number of packets captured for each interface until we're killed. */
1425 print_statistics_loop(gboolean machine_readable)
1427 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1433 char errbuf[PCAP_ERRBUF_SIZE];
1434 struct pcap_stat ps;
1436 if_list = get_interface_list(&err, &err_str);
1437 if (if_list == NULL) {
1439 case CANT_GET_INTERFACE_LIST:
1440 case DONT_HAVE_PCAP:
1441 cmdarg_err("%s", err_str);
1445 case NO_INTERFACES_FOUND:
1446 cmdarg_err("There are no interfaces on which a capture can be done");
1452 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1453 if_info = (if_info_t *)if_entry->data;
1454 #ifdef HAVE_PCAP_OPEN
1455 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1457 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1461 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
1462 if_stat->name = g_strdup(if_info->name);
1464 stat_list = g_list_append(stat_list, if_stat);
1469 cmdarg_err("There are no interfaces on which a capture can be done");
1473 if (capture_child) {
1474 /* Let our parent know we succeeded. */
1475 pipe_write_block(2, SP_SUCCESS, NULL);
1478 if (!machine_readable) {
1479 printf("%-15s %10s %10s\n", "Interface", "Received",
1483 global_ld.go = TRUE;
1484 while (global_ld.go) {
1485 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1486 if_stat = (if_stat_t *)stat_entry->data;
1487 pcap_stats(if_stat->pch, &ps);
1489 if (!machine_readable) {
1490 printf("%-15s %10u %10u\n", if_stat->name,
1491 ps.ps_recv, ps.ps_drop);
1493 printf("%s\t%u\t%u\n", if_stat->name,
1494 ps.ps_recv, ps.ps_drop);
1505 /* XXX - Not reached. Should we look for 'q' in stdin? */
1506 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1507 if_stat = (if_stat_t *)stat_entry->data;
1508 pcap_close(if_stat->pch);
1509 g_free(if_stat->name);
1512 g_list_free(stat_list);
1513 free_interface_list(if_list);
1521 capture_cleanup_handler(DWORD dwCtrlType)
1523 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1524 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1525 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1526 like SIGTERM at least when the machine's shutting down.
1528 For now, if we're running as a command rather than a capture child,
1529 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1530 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1531 in that way on UN*X.
1533 If we're not running as a capture child, we might be running as
1534 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1535 user logs out. (XXX - can we explicitly check whether we're
1536 running as a service?) */
1538 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1539 "Console: Control signal");
1540 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1541 "Console: Control signal, CtrlType: %u", dwCtrlType);
1543 /* Keep capture running if we're a service and a user logs off */
1544 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1545 capture_loop_stop();
1553 capture_cleanup_handler(int signum _U_)
1555 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1556 SIGTERM. We assume that if the user wanted it to keep running
1557 after they logged out, they'd have nohupped it. */
1559 /* Note: don't call g_log() in the signal handler: if we happened to be in
1560 * g_log() in process context when the signal came in, g_log will detect
1561 * the "recursion" and abort.
1564 capture_loop_stop();
1570 report_capture_count(gboolean reportit)
1572 /* Don't print this if we're a capture child. */
1573 if (!capture_child && reportit) {
1574 fprintf(stderr, "\rPackets captured: %u\n", global_ld.packet_count);
1575 /* stderr could be line buffered */
1583 report_counts_for_siginfo(void)
1585 report_capture_count(quiet);
1586 infoprint = FALSE; /* we just reported it */
1590 report_counts_siginfo(int signum _U_)
1592 int sav_errno = errno;
1594 /* If we've been told to delay printing, just set a flag asking
1595 that we print counts (if we're supposed to), otherwise print
1596 the count of packets captured (if we're supposed to). */
1600 report_counts_for_siginfo();
1603 #endif /* SIGINFO */
1606 exit_main(int status)
1609 /* Shutdown windows sockets */
1612 /* can be helpful for debugging */
1613 #ifdef DEBUG_DUMPCAP
1614 printf("Press any key\n");
1625 * If we were linked with libcap (not related to libpcap), make sure we have
1626 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1627 * (See comment in main() for details)
1630 relinquish_privs_except_capture(void)
1632 /* If 'started_with_special_privs' (ie: suid) then enable for
1633 * ourself the NET_ADMIN and NET_RAW capabilities and then
1634 * drop our suid privileges.
1636 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1637 * stuff we don't need (and shouldn't have).
1638 * CAP_NET_RAW: Packet capture (raw sockets).
1641 if (started_with_special_privs()) {
1642 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1643 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1645 cap_t caps = cap_init(); /* all capabilities initialized to off */
1647 print_caps("Pre drop, pre set");
1649 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1650 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1653 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1654 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1656 if (cap_set_proc(caps)) {
1657 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1659 print_caps("Pre drop, post set");
1661 relinquish_special_privs_perm();
1663 print_caps("Post drop, pre set");
1664 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1665 if (cap_set_proc(caps)) {
1666 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1668 print_caps("Post drop, post set");
1674 #endif /* HAVE_LIBCAP */
1676 /* Take care of byte order in the libpcap headers read from pipes.
1677 * (function taken from wiretap/libpcap.c) */
1679 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1682 /* Byte-swap the record header fields. */
1683 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
1684 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
1685 rechdr->incl_len = BSWAP32(rechdr->incl_len);
1686 rechdr->orig_len = BSWAP32(rechdr->orig_len);
1689 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1690 swapped, in order to match the BPF header layout.
1692 Unfortunately, some files were, according to a comment in the "libpcap"
1693 source, written with version 2.3 in their headers but without the
1694 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1695 would make no sense - we assume that we need to swap them. */
1696 if (hdr->version_major == 2 &&
1697 (hdr->version_minor < 3 ||
1698 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1701 temp = rechdr->orig_len;
1702 rechdr->orig_len = rechdr->incl_len;
1703 rechdr->incl_len = temp;
1707 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1711 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1715 return recv(pipe_fd, buf, (int)sz, 0);
1720 return ws_read(pipe_fd, buf, sz);
1726 * Thread function that reads from a pipe and pushes the data
1727 * to the main application thread.
1730 * XXX Right now we use async queues for basic signaling. The main thread
1731 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1732 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1733 * Iff the read is successful cap_pipe_read pushes an item onto
1734 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1735 * the queues themselves (yet).
1737 * We might want to move some of the cap_pipe_dispatch logic here so that
1738 * we can let cap_thread_read run independently, queuing up multiple reads
1739 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1741 static void *cap_thread_read(void *arg)
1743 pcap_options *pcap_opts;
1746 DWORD b, last_err, bytes_read;
1752 pcap_opts = (pcap_options *)arg;
1753 while (pcap_opts->cap_pipe_err == PIPOK) {
1754 g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1755 g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1757 while (bytes_read < pcap_opts->cap_pipe_bytes_to_read) {
1758 if ((pcap_opts->from_cap_socket)
1764 b = cap_pipe_read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1765 pcap_opts->cap_pipe_bytes_to_read - bytes_read, pcap_opts->from_cap_socket);
1768 pcap_opts->cap_pipe_err = PIPEOF;
1772 pcap_opts->cap_pipe_err = PIPERR;
1783 /* If we try to use read() on a named pipe on Windows with partial
1784 * data it appears to return EOF.
1786 res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1787 pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1792 last_err = GetLastError();
1793 if (last_err == ERROR_MORE_DATA) {
1795 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1796 pcap_opts->cap_pipe_err = PIPEOF;
1800 pcap_opts->cap_pipe_err = PIPERR;
1803 } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1804 pcap_opts->cap_pipe_err = PIPEOF;
1811 pcap_opts->cap_pipe_bytes_read = bytes_read;
1812 if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1813 g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1815 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1821 /* Provide select() functionality for a single file descriptor
1822 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1824 * Returns the same values as select.
1827 cap_pipe_select(int pipe_fd)
1830 struct timeval timeout;
1833 FD_SET(pipe_fd, &rfds);
1835 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1836 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1838 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1841 #define DEF_TCP_PORT 19000
1844 cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errmsgl)
1846 char *sockname = pipename + 4;
1847 struct sockaddr_in sa;
1854 memset(&sa, 0, sizeof(sa));
1856 p = strchr(sockname, ':');
1858 len = strlen(sockname);
1859 port = DEF_TCP_PORT;
1863 port = strtoul(p + 1, &p, 10);
1864 if (*p || port > 65535) {
1873 strncpy(buf, sockname, len);
1875 if (inet_pton(AF_INET, buf, &sa.sin_addr) <= 0) {
1879 sa.sin_family = AF_INET;
1880 sa.sin_port = htons((u_short)port);
1882 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1883 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1885 LPTSTR errorText = NULL;
1888 lastError = WSAGetLastError();
1889 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1890 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1891 FORMAT_MESSAGE_IGNORE_INSERTS,
1892 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1893 (LPTSTR)&errorText, 0, NULL);
1895 g_snprintf(errmsg, errmsgl,
1896 "The capture session could not be initiated due to the socket error: \n"
1898 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
1900 LocalFree(errorText);
1902 " %d: %s", errno, strerror(errno));
1904 pcap_opts->cap_pipe_err = PIPERR;
1907 cap_pipe_close(fd, TRUE);
1911 pcap_opts->from_cap_socket = TRUE;
1915 g_snprintf(errmsg, errmsgl,
1916 "The capture session could not be initiated because\n"
1917 "\"%s\" is not a valid socket specification", pipename);
1918 pcap_opts->cap_pipe_err = PIPERR;
1922 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1926 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1930 closesocket(pipe_fd);
1937 /* Mimic pcap_open_live() for pipe captures
1939 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1940 * open it, and read the header.
1942 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1943 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1945 cap_pipe_open_live(char *pipename,
1946 pcap_options *pcap_opts,
1947 struct pcap_hdr *hdr,
1948 char *errmsg, int errmsgl)
1951 ws_statb64 pipe_stat;
1952 struct sockaddr_un sa;
1962 pcap_opts->cap_pipe_fd = -1;
1964 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
1966 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1969 * XXX - this blocks until a pcap per-file header has been written to
1970 * the pipe, so it could block indefinitely.
1972 if (strcmp(pipename, "-") == 0) {
1974 fd = 0; /* read from stdin */
1976 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1978 } else if (!strncmp(pipename, "TCP@", 4)) {
1979 if ((fd = cap_open_socket(pipename, pcap_opts, errmsg, errmsgl)) < 0) {
1984 if (ws_stat64(pipename, &pipe_stat) < 0) {
1985 if (errno == ENOENT || errno == ENOTDIR)
1986 pcap_opts->cap_pipe_err = PIPNEXIST;
1988 g_snprintf(errmsg, errmsgl,
1989 "The capture session could not be initiated "
1990 "due to error getting information on pipe/socket: %s", g_strerror(errno));
1991 pcap_opts->cap_pipe_err = PIPERR;
1995 if (S_ISFIFO(pipe_stat.st_mode)) {
1996 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1998 g_snprintf(errmsg, errmsgl,
1999 "The capture session could not be initiated "
2000 "due to error on pipe open: %s", g_strerror(errno));
2001 pcap_opts->cap_pipe_err = PIPERR;
2004 } else if (S_ISSOCK(pipe_stat.st_mode)) {
2005 fd = socket(AF_UNIX, SOCK_STREAM, 0);
2007 g_snprintf(errmsg, errmsgl,
2008 "The capture session could not be initiated "
2009 "due to error on socket create: %s", g_strerror(errno));
2010 pcap_opts->cap_pipe_err = PIPERR;
2013 sa.sun_family = AF_UNIX;
2015 * The Single UNIX Specification says:
2017 * The size of sun_path has intentionally been left undefined.
2018 * This is because different implementations use different sizes.
2019 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
2020 * of 104. Since most implementations originate from BSD versions,
2021 * the size is typically in the range 92 to 108.
2023 * Applications should not assume a particular length for sun_path
2024 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
2028 * The <sys/un.h> header shall define the sockaddr_un structure,
2029 * which shall include at least the following members:
2031 * sa_family_t sun_family Address family.
2032 * char sun_path[] Socket pathname.
2034 * so we assume that it's an array, with a specified size,
2035 * and that the size reflects the maximum path length.
2037 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
2038 /* Path name too long */
2039 g_snprintf(errmsg, errmsgl,
2040 "The capture session coud not be initiated "
2041 "due to error on socket connect: Path name too long");
2042 pcap_opts->cap_pipe_err = PIPERR;
2046 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
2048 g_snprintf(errmsg, errmsgl,
2049 "The capture session coud not be initiated "
2050 "due to error on socket connect: %s", g_strerror(errno));
2051 pcap_opts->cap_pipe_err = PIPERR;
2056 if (S_ISCHR(pipe_stat.st_mode)) {
2058 * Assume the user specified an interface on a system where
2059 * interfaces are in /dev. Pretend we haven't seen it.
2061 pcap_opts->cap_pipe_err = PIPNEXIST;
2063 g_snprintf(errmsg, errmsgl,
2064 "The capture session could not be initiated because\n"
2065 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
2066 pcap_opts->cap_pipe_err = PIPERR;
2071 #define PIPE_STR "\\pipe\\"
2072 /* Under Windows, named pipes _must_ have the form
2073 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
2075 pncopy = g_strdup(pipename);
2076 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
2077 pos = strchr(pncopy + 3, '\\');
2078 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
2085 g_snprintf(errmsg, errmsgl,
2086 "The capture session could not be initiated because\n"
2087 "\"%s\" is neither an interface nor a pipe", pipename);
2088 pcap_opts->cap_pipe_err = PIPNEXIST;
2092 /* Wait for the pipe to appear */
2094 pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
2095 OPEN_EXISTING, 0, NULL);
2097 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
2100 if (GetLastError() != ERROR_PIPE_BUSY) {
2101 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2102 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2103 g_snprintf(errmsg, errmsgl,
2104 "The capture session on \"%s\" could not be started "
2105 "due to error on pipe open: %s (error %d)",
2106 pipename, utf_16to8(err_str), GetLastError());
2108 pcap_opts->cap_pipe_err = PIPERR;
2112 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
2113 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2114 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2115 g_snprintf(errmsg, errmsgl,
2116 "The capture session on \"%s\" timed out during "
2117 "pipe open: %s (error %d)",
2118 pipename, utf_16to8(err_str), GetLastError());
2120 pcap_opts->cap_pipe_err = PIPERR;
2127 pcap_opts->from_cap_pipe = TRUE;
2130 if (pcap_opts->from_cap_socket)
2133 /* read the pcap header */
2135 while (bytes_read < sizeof magic) {
2136 sel_ret = cap_pipe_select(fd);
2138 g_snprintf(errmsg, errmsgl,
2139 "Unexpected error from select: %s", g_strerror(errno));
2141 } else if (sel_ret > 0) {
2142 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
2143 sizeof magic-bytes_read,
2144 pcap_opts->from_cap_socket);
2147 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2149 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2159 #if GLIB_CHECK_VERSION(2,31,0)
2160 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_opts);
2162 g_thread_create(&cap_thread_read, pcap_opts, FALSE, NULL);
2165 pcap_opts->cap_pipe_buf = (char *) &magic;
2166 pcap_opts->cap_pipe_bytes_read = 0;
2167 pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
2168 /* We don't have to worry about cap_pipe_read_mtx here */
2169 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2170 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2171 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2172 if (pcap_opts->cap_pipe_bytes_read == 0)
2173 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2175 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2184 case PCAP_NSEC_MAGIC:
2185 /* Host that wrote it has our byte order, and was running
2186 a program using either standard or ss990417 libpcap. */
2187 pcap_opts->cap_pipe_byte_swapped = FALSE;
2188 pcap_opts->cap_pipe_modified = FALSE;
2189 pcap_opts->ts_nsec = magic == PCAP_NSEC_MAGIC;
2191 case PCAP_MODIFIED_MAGIC:
2192 /* Host that wrote it has our byte order, but was running
2193 a program using either ss990915 or ss991029 libpcap. */
2194 pcap_opts->cap_pipe_byte_swapped = FALSE;
2195 pcap_opts->cap_pipe_modified = TRUE;
2197 case PCAP_SWAPPED_MAGIC:
2198 case PCAP_SWAPPED_NSEC_MAGIC:
2199 /* Host that wrote it has a byte order opposite to ours,
2200 and was running a program using either standard or
2201 ss990417 libpcap. */
2202 pcap_opts->cap_pipe_byte_swapped = TRUE;
2203 pcap_opts->cap_pipe_modified = FALSE;
2204 pcap_opts->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
2206 case PCAP_SWAPPED_MODIFIED_MAGIC:
2207 /* Host that wrote it out has a byte order opposite to
2208 ours, and was running a program using either ss990915
2209 or ss991029 libpcap. */
2210 pcap_opts->cap_pipe_byte_swapped = TRUE;
2211 pcap_opts->cap_pipe_modified = TRUE;
2214 /* Not a "libpcap" type we know about. */
2215 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
2220 if (pcap_opts->from_cap_socket)
2223 /* Read the rest of the header */
2225 while (bytes_read < sizeof(struct pcap_hdr)) {
2226 sel_ret = cap_pipe_select(fd);
2228 g_snprintf(errmsg, errmsgl,
2229 "Unexpected error from select: %s", g_strerror(errno));
2231 } else if (sel_ret > 0) {
2232 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
2233 sizeof(struct pcap_hdr) - bytes_read,
2234 pcap_opts->from_cap_socket);
2237 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2239 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
2249 pcap_opts->cap_pipe_buf = (char *) hdr;
2250 pcap_opts->cap_pipe_bytes_read = 0;
2251 pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
2252 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2253 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2254 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2255 if (pcap_opts->cap_pipe_bytes_read == 0)
2256 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2258 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
2265 if (pcap_opts->cap_pipe_byte_swapped) {
2266 /* Byte-swap the header fields about which we care. */
2267 hdr->version_major = BSWAP16(hdr->version_major);
2268 hdr->version_minor = BSWAP16(hdr->version_minor);
2269 hdr->snaplen = BSWAP32(hdr->snaplen);
2270 hdr->network = BSWAP32(hdr->network);
2272 pcap_opts->linktype = hdr->network;
2274 if (hdr->version_major < 2) {
2275 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
2279 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2280 pcap_opts->cap_pipe_err = PIPOK;
2281 pcap_opts->cap_pipe_fd = fd;
2285 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
2286 pcap_opts->cap_pipe_err = PIPERR;
2287 cap_pipe_close(fd, pcap_opts->from_cap_socket);
2288 pcap_opts->cap_pipe_fd = -1;
2292 /* We read one record from the pipe, take care of byte order in the record
2293 * header, write the record to the capture file, and update capture statistics. */
2295 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
2297 struct pcap_pkthdr phdr;
2298 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2301 #if !GLIB_CHECK_VERSION(2,31,18)
2309 #ifdef LOG_CAPTURE_VERBOSE
2310 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
2313 switch (pcap_opts->cap_pipe_state) {
2315 case STATE_EXPECT_REC_HDR:
2317 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2320 pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
2321 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
2322 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2323 pcap_opts->cap_pipe_bytes_read = 0;
2326 pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
2327 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2328 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2333 case STATE_READ_REC_HDR:
2335 if (pcap_opts->from_cap_socket)
2338 b = cap_pipe_read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
2339 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
2342 result = PD_PIPE_EOF;
2344 result = PD_PIPE_ERR;
2347 pcap_opts->cap_pipe_bytes_read += b;
2351 #if GLIB_CHECK_VERSION(2,31,18)
2352 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2354 g_get_current_time(&wait_time);
2355 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2356 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2358 if (pcap_opts->cap_pipe_err == PIPEOF) {
2359 result = PD_PIPE_EOF;
2361 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2362 result = PD_PIPE_ERR;
2370 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2372 result = PD_REC_HDR_READ;
2375 case STATE_EXPECT_DATA:
2377 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2380 pcap_opts->cap_pipe_state = STATE_READ_DATA;
2381 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2382 pcap_opts->cap_pipe_bytes_read = 0;
2385 pcap_opts->cap_pipe_buf = (char *) data;
2386 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2387 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2392 case STATE_READ_DATA:
2394 if (pcap_opts->from_cap_socket)
2397 b = cap_pipe_read(pcap_opts->cap_pipe_fd,
2398 data+pcap_opts->cap_pipe_bytes_read,
2399 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read,
2400 pcap_opts->from_cap_socket);
2403 result = PD_PIPE_EOF;
2405 result = PD_PIPE_ERR;
2408 pcap_opts->cap_pipe_bytes_read += b;
2413 #if GLIB_CHECK_VERSION(2,31,18)
2414 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2416 g_get_current_time(&wait_time);
2417 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2418 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2419 #endif /* GLIB_CHECK_VERSION(2,31,18) */
2420 if (pcap_opts->cap_pipe_err == PIPEOF) {
2421 result = PD_PIPE_EOF;
2423 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2424 result = PD_PIPE_ERR;
2432 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2434 result = PD_DATA_READ;
2438 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2441 } /* switch (pcap_opts->cap_pipe_state) */
2444 * We've now read as much data as we were expecting, so process it.
2448 case PD_REC_HDR_READ:
2449 /* We've read the header. Take care of byte order. */
2450 cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
2451 &pcap_opts->cap_pipe_rechdr.hdr);
2452 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2453 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2454 ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
2458 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2459 pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2462 /* no data to read? fall through */
2465 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2466 phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2467 phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2468 phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2469 phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2472 capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2474 capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2476 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2480 pcap_opts->cap_pipe_err = PIPEOF;
2485 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2486 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2487 g_snprintf(errmsg, errmsgl,
2488 "Error reading from pipe: %s (error %d)",
2489 utf_16to8(err_str), GetLastError());
2492 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2500 pcap_opts->cap_pipe_err = PIPERR;
2501 /* Return here rather than inside the switch to prevent GCC warning */
2506 /** Open the capture input file (pcap or capture pipe).
2507 * Returns TRUE if it succeeds, FALSE otherwise. */
2509 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2510 char *errmsg, size_t errmsg_len,
2511 char *secondary_errmsg, size_t secondary_errmsg_len)
2513 gchar open_err_str[PCAP_ERRBUF_SIZE];
2514 gchar *sync_msg_str;
2515 interface_options interface_opts;
2516 pcap_options *pcap_opts;
2520 gchar *sync_secondary_msg_str;
2521 WORD wVersionRequested;
2525 /* XXX - opening Winsock on tshark? */
2527 /* Initialize Windows Socket if we are in a WIN32 OS
2528 This needs to be done before querying the interface for network/netmask */
2530 /* XXX - do we really require 1.1 or earlier?
2531 Are there any versions that support only 2.0 or higher? */
2532 wVersionRequested = MAKEWORD(1, 1);
2533 err = WSAStartup(wVersionRequested, &wsaData);
2537 case WSASYSNOTREADY:
2538 g_snprintf(errmsg, (gulong) errmsg_len,
2539 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2542 case WSAVERNOTSUPPORTED:
2543 g_snprintf(errmsg, (gulong) errmsg_len,
2544 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2545 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2548 case WSAEINPROGRESS:
2549 g_snprintf(errmsg, (gulong) errmsg_len,
2550 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2554 g_snprintf(errmsg, (gulong) errmsg_len,
2555 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2559 g_snprintf(errmsg, (gulong) errmsg_len,
2560 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2564 g_snprintf(errmsg, (gulong) errmsg_len,
2565 "Couldn't initialize Windows Sockets: error %d", err);
2568 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2572 if ((use_threads == FALSE) &&
2573 (capture_opts->ifaces->len > 1)) {
2574 g_snprintf(errmsg, (gulong) errmsg_len,
2575 "Using threads is required for capturing on multiple interfaces!");
2579 for (i = 0; i < capture_opts->ifaces->len; i++) {
2580 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2581 pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2582 if (pcap_opts == NULL) {
2583 g_snprintf(errmsg, (gulong) errmsg_len,
2584 "Could not allocate memory.");
2587 pcap_opts->received = 0;
2588 pcap_opts->dropped = 0;
2589 pcap_opts->flushed = 0;
2590 pcap_opts->pcap_h = NULL;
2591 #ifdef MUST_DO_SELECT
2592 pcap_opts->pcap_fd = -1;
2594 pcap_opts->pcap_err = FALSE;
2595 pcap_opts->interface_id = i;
2596 pcap_opts->tid = NULL;
2597 pcap_opts->snaplen = 0;
2598 pcap_opts->linktype = -1;
2599 pcap_opts->ts_nsec = FALSE;
2600 pcap_opts->from_cap_pipe = FALSE;
2601 pcap_opts->from_cap_socket = FALSE;
2602 memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2603 memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2605 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2607 pcap_opts->cap_pipe_fd = -1;
2608 pcap_opts->cap_pipe_modified = FALSE;
2609 pcap_opts->cap_pipe_byte_swapped = FALSE;
2611 pcap_opts->cap_pipe_buf = NULL;
2613 pcap_opts->cap_pipe_bytes_to_read = 0;
2614 pcap_opts->cap_pipe_bytes_read = 0;
2615 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2616 pcap_opts->cap_pipe_err = PIPOK;
2618 #if GLIB_CHECK_VERSION(2,31,0)
2619 pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2620 g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2622 pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2624 pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2625 pcap_opts->cap_pipe_done_q = g_async_queue_new();
2627 g_array_append_val(ld->pcaps, pcap_opts);
2629 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2630 pcap_opts->pcap_h = open_capture_device(&interface_opts, &open_err_str);
2632 if (pcap_opts->pcap_h != NULL) {
2633 /* we've opened "iface" as a network device */
2635 /* try to set the capture buffer size */
2636 if (interface_opts.buffer_size > 1 &&
2637 pcap_setbuff(pcap_opts->pcap_h, interface_opts.buffer_size * 1024 * 1024) != 0) {
2638 sync_secondary_msg_str = g_strdup_printf(
2639 "The capture buffer size of %dMB seems to be too high for your machine,\n"
2640 "the default of 1MB will be used.\n"
2642 "Nonetheless, the capture is started.\n",
2643 interface_opts.buffer_size);
2644 report_capture_error("Couldn't set the capture buffer size!",
2645 sync_secondary_msg_str);
2646 g_free(sync_secondary_msg_str);
2650 #if defined(HAVE_PCAP_SETSAMPLING)
2651 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2652 struct pcap_samp *samp;
2654 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2655 switch (interface_opts.sampling_method) {
2656 case CAPTURE_SAMP_BY_COUNT:
2657 samp->method = PCAP_SAMP_1_EVERY_N;
2660 case CAPTURE_SAMP_BY_TIMER:
2661 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2665 sync_msg_str = g_strdup_printf(
2666 "Unknown sampling method %d specified,\n"
2667 "continue without packet sampling",
2668 interface_opts.sampling_method);
2669 report_capture_error("Couldn't set the capture "
2670 "sampling", sync_msg_str);
2671 g_free(sync_msg_str);
2673 samp->value = interface_opts.sampling_param;
2675 report_capture_error("Couldn't set the capture sampling",
2676 "Cannot get packet sampling data structure");
2681 /* setting the data link type only works on real interfaces */
2682 if (!set_pcap_linktype(pcap_opts->pcap_h, interface_opts.linktype, interface_opts.name,
2684 secondary_errmsg, secondary_errmsg_len)) {
2687 pcap_opts->linktype = get_pcap_linktype(pcap_opts->pcap_h, interface_opts.name);
2689 /* We couldn't open "iface" as a network device. */
2690 /* Try to open it as a pipe */
2691 cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2694 if (pcap_opts->cap_pipe_fd == -1) {
2696 if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2698 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2699 /* Pipe doesn't exist, so output message for interface */
2700 get_capture_device_open_failure_messages(open_err_str,
2701 interface_opts.name,
2705 secondary_errmsg_len);
2708 * Else pipe (or file) does exist and cap_pipe_open_live() has
2713 /* cap_pipe_open_live() succeeded; don't want
2714 error message from pcap_open_live() */
2715 open_err_str[0] = '\0';
2719 /* XXX - will this work for tshark? */
2720 #ifdef MUST_DO_SELECT
2721 if (!pcap_opts->from_cap_pipe) {
2722 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2723 pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2725 pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2730 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2731 returned a warning; print it, but keep capturing. */
2732 if (open_err_str[0] != '\0') {
2733 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2734 report_capture_error(sync_msg_str, "");
2735 g_free(sync_msg_str);
2737 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2738 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2741 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2742 /* to remove any suid privileges. */
2743 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2744 /* (euid/egid have already previously been set to ruid/rgid. */
2745 /* (See comment in main() for details) */
2747 relinquish_special_privs_perm();
2749 relinquish_all_capabilities();
2754 /* close the capture input file (pcap or capture pipe) */
2755 static void capture_loop_close_input(loop_data *ld)
2758 pcap_options *pcap_opts;
2760 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2762 for (i = 0; i < ld->pcaps->len; i++) {
2763 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2764 /* if open, close the capture pipe "input file" */
2765 if (pcap_opts->cap_pipe_fd >= 0) {
2766 g_assert(pcap_opts->from_cap_pipe);
2767 cap_pipe_close(pcap_opts->cap_pipe_fd, pcap_opts->from_cap_socket);
2768 pcap_opts->cap_pipe_fd = -1;
2771 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2772 CloseHandle(pcap_opts->cap_pipe_h);
2773 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2776 /* if open, close the pcap "input file" */
2777 if (pcap_opts->pcap_h != NULL) {
2778 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2779 pcap_close(pcap_opts->pcap_h);
2780 pcap_opts->pcap_h = NULL;
2787 /* Shut down windows sockets */
2793 /* init the capture filter */
2794 static initfilter_status_t
2795 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2796 const gchar * name, const gchar * cfilter)
2798 struct bpf_program fcode;
2800 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2802 /* capture filters only work on real interfaces */
2803 if (cfilter && !from_cap_pipe) {
2804 /* A capture filter was specified; set it up. */
2805 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2806 /* Treat this specially - our caller might try to compile this
2807 as a display filter and, if that succeeds, warn the user that
2808 the display and capture filter syntaxes are different. */
2809 return INITFILTER_BAD_FILTER;
2811 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2812 #ifdef HAVE_PCAP_FREECODE
2813 pcap_freecode(&fcode);
2815 return INITFILTER_OTHER_ERROR;
2817 #ifdef HAVE_PCAP_FREECODE
2818 pcap_freecode(&fcode);
2822 return INITFILTER_NO_ERROR;
2826 /* set up to write to the already-opened capture output file/files */
2828 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2832 pcap_options *pcap_opts;
2833 interface_options interface_opts;
2834 gboolean successful;
2836 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2838 if ((capture_opts->use_pcapng == FALSE) &&
2839 (capture_opts->ifaces->len > 1)) {
2840 g_snprintf(errmsg, errmsg_len,
2841 "Using PCAPNG is required for capturing on multiple interfaces! Use the -n option.");
2845 /* Set up to write to the capture file. */
2846 if (capture_opts->multi_files_on) {
2847 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2849 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2850 if (ld->pdh == NULL) {
2855 if (capture_opts->use_pcapng) {
2857 GString *os_info_str;
2859 os_info_str = g_string_new("");
2860 get_os_version_info(os_info_str);
2862 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2863 successful = libpcap_write_session_header_block(libpcap_write_to_file, ld->pdh,
2864 (const char *)capture_opts->capture_comment, /* Comment*/
2866 os_info_str->str, /* OS*/
2868 -1, /* section_length */
2872 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2873 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2874 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2875 if (pcap_opts->from_cap_pipe) {
2876 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2878 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2880 successful = libpcap_write_interface_description_block(libpcap_write_to_file, global_ld.pdh,
2881 NULL, /* OPT_COMMENT 1 */
2882 interface_opts.name, /* IDB_NAME 2 */
2883 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2884 interface_opts.cfilter, /* IDB_FILTER 11 */
2885 os_info_str->str, /* IDB_OS 12 */
2886 pcap_opts->linktype,
2888 &(global_ld.bytes_written),
2889 0, /* IDB_IF_SPEED 8 */
2890 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2894 g_string_free(os_info_str, TRUE);
2897 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
2898 if (pcap_opts->from_cap_pipe) {
2899 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2901 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2903 successful = libpcap_write_file_header(libpcap_write_to_file, ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
2904 pcap_opts->ts_nsec, &ld->bytes_written, &err);
2912 if (ld->pdh == NULL) {
2913 /* We couldn't set up to write to the capture file. */
2914 /* XXX - use cf_open_error_message from tshark instead? */
2919 g_snprintf(errmsg, errmsg_len,
2920 "The file to which the capture would be"
2921 " saved (\"%s\") could not be opened: Error %d.",
2922 capture_opts->save_file, err);
2924 g_snprintf(errmsg, errmsg_len,
2925 "The file to which the capture would be"
2926 " saved (\"%s\") could not be opened: %s.",
2927 capture_opts->save_file, g_strerror(err));
2939 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2943 pcap_options *pcap_opts;
2944 guint64 end_time = create_timestamp();
2946 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2948 if (capture_opts->multi_files_on) {
2949 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2951 if (capture_opts->use_pcapng) {
2952 for (i = 0; i < global_ld.pcaps->len; i++) {
2953 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2954 if (!pcap_opts->from_cap_pipe) {
2955 guint64 isb_ifrecv, isb_ifdrop;
2956 struct pcap_stat stats;
2958 if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
2959 isb_ifrecv = pcap_opts->received;
2960 isb_ifdrop = stats.ps_drop + pcap_opts->dropped + pcap_opts->flushed;
2962 isb_ifrecv = G_MAXUINT64;
2963 isb_ifdrop = G_MAXUINT64;
2965 libpcap_write_interface_statistics_block(libpcap_write_to_file, ld->pdh,
2968 "Counters provided by dumpcap",
2977 if (fclose(ld->pdh) == EOF) {
2978 if (err_close != NULL) {
2988 /* dispatch incoming packets (pcap or capture pipe)
2990 * Waits for incoming packets to be available, and calls pcap_dispatch()
2991 * to cause them to be processed.
2993 * Returns the number of packets which were processed.
2995 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2996 * packet-batching behaviour does not cause packets to get held back
3000 capture_loop_dispatch(loop_data *ld,
3001 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
3004 gint packet_count_before;
3005 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
3010 packet_count_before = ld->packet_count;
3011 if (pcap_opts->from_cap_pipe) {
3012 /* dispatch from capture pipe */
3013 #ifdef LOG_CAPTURE_VERBOSE
3014 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
3017 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
3019 if (sel_ret < 0 && errno != EINTR) {
3020 g_snprintf(errmsg, errmsg_len,
3021 "Unexpected error from select: %s", g_strerror(errno));
3022 report_capture_error(errmsg, please_report);
3027 * "select()" says we can read from the pipe without blocking
3030 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
3040 /* dispatch from pcap */
3041 #ifdef MUST_DO_SELECT
3043 * If we have "pcap_get_selectable_fd()", we use it to get the
3044 * descriptor on which to select; if that's -1, it means there
3045 * is no descriptor on which you can do a "select()" (perhaps
3046 * because you're capturing on a special device, and that device's
3047 * driver unfortunately doesn't support "select()", in which case
3048 * we don't do the select - which means it might not be possible
3049 * to stop a capture until a packet arrives. If that's unacceptable,
3050 * plead with whoever supplies the software for that device to add
3051 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3052 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3053 * later, so it can use pcap_breakloop().
3055 #ifdef LOG_CAPTURE_VERBOSE
3056 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3058 if (pcap_opts->pcap_fd != -1) {
3059 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
3062 * "select()" says we can read from it without blocking; go for
3065 * We don't have pcap_breakloop(), so we only process one packet
3066 * per pcap_dispatch() call, to allow a signal to stop the
3067 * processing immediately, rather than processing all packets
3068 * in a batch before quitting.
3071 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3073 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3077 /* Error, rather than pcap_breakloop(). */
3078 pcap_opts->pcap_err = TRUE;
3080 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3083 if (sel_ret < 0 && errno != EINTR) {
3084 g_snprintf(errmsg, errmsg_len,
3085 "Unexpected error from select: %s", g_strerror(errno));
3086 report_capture_error(errmsg, please_report);
3092 #endif /* MUST_DO_SELECT */
3094 /* dispatch from pcap without select */
3096 #ifdef LOG_CAPTURE_VERBOSE
3097 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3101 * On Windows, we don't support asynchronously telling a process to
3102 * stop capturing; instead, we check for an indication on a pipe
3103 * after processing packets. We therefore process only one packet
3104 * at a time, so that we can check the pipe after every packet.
3107 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3109 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3113 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3115 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3120 /* Error, rather than pcap_breakloop(). */
3121 pcap_opts->pcap_err = TRUE;
3123 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3125 #else /* pcap_next_ex */
3126 #ifdef LOG_CAPTURE_VERBOSE
3127 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3129 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3132 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3133 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
3134 * This should be fixed in the WinPcap 4.0 alpha release.
3136 * For reference, an example remote interface:
3137 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3140 /* emulate dispatch from pcap */
3143 struct pcap_pkthdr *pkt_header;
3148 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
3150 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3152 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3157 pcap_opts->pcap_err = TRUE;
3161 #endif /* pcap_next_ex */
3165 #ifdef LOG_CAPTURE_VERBOSE
3166 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3169 return ld->packet_count - packet_count_before;
3173 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3174 * want to grab only the characters between the '{' and '}' delimiters.
3176 * Returns a GString that must be freed with g_string_free(). */
3178 isolate_uuid(const char *iface)
3183 ptr = strchr(iface, '{');
3185 return g_string_new(iface);
3186 gstr = g_string_new(ptr + 1);
3188 ptr = strchr(gstr->str, '}');
3192 gstr = g_string_truncate(gstr, ptr - gstr->str);
3197 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3198 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3200 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3201 char *errmsg, int errmsg_len)
3204 gchar *capfile_name;
3206 gboolean is_tempfile;
3208 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3209 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3211 if (capture_opts->save_file != NULL) {
3212 /* We return to the caller while the capture is in progress.
3213 * Therefore we need to take a copy of save_file in
3214 * case the caller destroys it after we return.
3216 capfile_name = g_strdup(capture_opts->save_file);
3218 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3219 if (capture_opts->multi_files_on) {
3220 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3221 g_snprintf(errmsg, errmsg_len,
3222 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3223 g_free(capfile_name);
3226 if (strcmp(capfile_name, "-") == 0) {
3227 /* write to stdout */
3230 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3231 _setmode(1, O_BINARY);
3234 } /* if (...output_to_pipe ... */
3237 if (capture_opts->multi_files_on) {
3238 /* ringbuffer is enabled */
3239 *save_file_fd = ringbuf_init(capfile_name,
3240 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3241 capture_opts->group_read_access);
3243 /* we need the ringbuf name */
3244 if (*save_file_fd != -1) {
3245 g_free(capfile_name);
3246 capfile_name = g_strdup(ringbuf_current_filename());
3249 /* Try to open/create the specified file for use as a capture buffer. */
3250 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
3251 (capture_opts->group_read_access) ? 0640 : 0600);
3254 is_tempfile = FALSE;
3256 /* Choose a random name for the temporary capture buffer */
3257 if (global_capture_opts.ifaces->len > 1) {
3258 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3261 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
3263 /* use the generic portion of the interface guid to form the basis of the filename */
3264 if (strncmp("NPF_{", basename, 5)==0)
3266 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
3268 iface = isolate_uuid(basename);
3270 basename = g_strdup(iface->str);
3271 g_string_free(iface, TRUE);
3274 /* generate the temp file name prefix...
3275 * It would be nice if we could specify a pcapng/pcap filename suffix,
3276 * create_tempfile() however currently uses mkstemp() which doesn't allow this - one day perhaps*/
3277 if (capture_opts->use_pcapng) {
3278 prefix = g_strconcat("wireshark_pcapng_", basename, NULL);
3280 prefix = g_strconcat("wireshark_pcap_", basename, NULL);
3284 *save_file_fd = create_tempfile(&tmpname, prefix);
3286 capfile_name = g_strdup(tmpname);
3290 /* did we fail to open the output file? */
3291 if (*save_file_fd == -1) {
3293 g_snprintf(errmsg, errmsg_len,
3294 "The temporary file to which the capture would be saved (\"%s\") "
3295 "could not be opened: %s.", capfile_name, g_strerror(errno));
3297 if (capture_opts->multi_files_on) {
3298 ringbuf_error_cleanup();
3301 g_snprintf(errmsg, errmsg_len,
3302 "The file to which the capture would be saved (\"%s\") "
3303 "could not be opened: %s.", capfile_name,
3306 g_free(capfile_name);
3310 if (capture_opts->save_file != NULL) {
3311 g_free(capture_opts->save_file);
3313 capture_opts->save_file = capfile_name;
3314 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3315 "g_free(capfile_name)". */
3321 /* Do the work of handling either the file size or file duration capture
3322 conditions being reached, and switching files or stopping. */
3324 do_file_switch_or_stop(capture_options *capture_opts,
3325 condition *cnd_autostop_files,
3326 condition *cnd_autostop_size,
3327 condition *cnd_file_duration)
3330 pcap_options *pcap_opts;
3331 interface_options interface_opts;
3332 gboolean successful;
3334 if (capture_opts->multi_files_on) {
3335 if (cnd_autostop_files != NULL &&
3336 cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
3337 /* no files left: stop here */
3338 global_ld.go = FALSE;
3342 /* Switch to the next ringbuffer file */
3343 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3344 &global_ld.save_file_fd, &global_ld.err)) {
3346 /* File switch succeeded: reset the conditions */
3347 global_ld.bytes_written = 0;
3348 if (capture_opts->use_pcapng) {
3350 GString *os_info_str;
3352 os_info_str = g_string_new("");
3353 get_os_version_info(os_info_str);
3355 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
3356 successful = libpcap_write_session_header_block(libpcap_write_to_file, global_ld.pdh,
3359 os_info_str->str, /* OS */
3361 -1, /* section_length */
3362 &(global_ld.bytes_written),
3365 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3366 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3367 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3368 successful = libpcap_write_interface_description_block(libpcap_write_to_file, global_ld.pdh,
3369 NULL, /* OPT_COMMENT 1 */
3370 interface_opts.name, /* IDB_NAME 2 */
3371 interface_opts.descr, /* IDB_DESCRIPTION 3 */
3372 interface_opts.cfilter, /* IDB_FILTER 11 */
3373 os_info_str->str, /* IDB_OS 12 */
3374 pcap_opts->linktype,
3376 &(global_ld.bytes_written),
3377 0, /* IDB_IF_SPEED 8 */
3378 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3382 g_string_free(os_info_str, TRUE);
3385 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3386 successful = libpcap_write_file_header(libpcap_write_to_file, global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
3387 pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3390 fclose(global_ld.pdh);
3391 global_ld.pdh = NULL;
3392 global_ld.go = FALSE;
3395 if (cnd_autostop_size)
3396 cnd_reset(cnd_autostop_size);
3397 if (cnd_file_duration)
3398 cnd_reset(cnd_file_duration);
3399 fflush(global_ld.pdh);
3401 report_packet_count(global_ld.inpkts_to_sync_pipe);
3402 global_ld.inpkts_to_sync_pipe = 0;
3403 report_new_capture_file(capture_opts->save_file);
3405 /* File switch failed: stop here */
3406 global_ld.go = FALSE;
3410 /* single file, stop now */
3411 global_ld.go = FALSE;
3418 pcap_read_handler(void* arg)
3420 pcap_options *pcap_opts;
3421 char errmsg[MSG_MAX_LENGTH+1];
3423 pcap_opts = (pcap_options *)arg;
3425 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3426 pcap_opts->interface_id);
3428 while (global_ld.go) {
3429 /* dispatch incoming packets */
3430 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3432 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3433 pcap_opts->interface_id);
3434 g_thread_exit(NULL);
3438 /* Do the low-level work of a capture.
3439 Returns TRUE if it succeeds, FALSE otherwise. */
3441 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3444 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3446 struct timeval upd_time, cur_time;
3450 condition *cnd_file_duration = NULL;
3451 condition *cnd_autostop_files = NULL;
3452 condition *cnd_autostop_size = NULL;
3453 condition *cnd_autostop_duration = NULL;
3456 gboolean cfilter_error = FALSE;
3457 char errmsg[MSG_MAX_LENGTH+1];
3458 char secondary_errmsg[MSG_MAX_LENGTH+1];
3459 pcap_options *pcap_opts;
3460 interface_options interface_opts;
3461 guint i, error_index = 0;
3464 *secondary_errmsg = '\0';
3466 /* init the loop data */
3467 global_ld.go = TRUE;
3468 global_ld.packet_count = 0;
3470 global_ld.report_packet_count = FALSE;
3472 if (capture_opts->has_autostop_packets)
3473 global_ld.packet_max = capture_opts->autostop_packets;
3475 global_ld.packet_max = 0; /* no limit */
3476 global_ld.inpkts_to_sync_pipe = 0;
3477 global_ld.err = 0; /* no error seen yet */
3478 global_ld.pdh = NULL;
3479 global_ld.autostop_files = 0;
3480 global_ld.save_file_fd = -1;
3482 /* We haven't yet gotten the capture statistics. */
3483 *stats_known = FALSE;
3485 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3486 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3488 /* open the "input file" from network interface or capture pipe */
3489 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3490 secondary_errmsg, sizeof(secondary_errmsg))) {
3493 for (i = 0; i < capture_opts->ifaces->len; i++) {
3494 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3495 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3496 /* init the input filter from the network interface (capture pipe will do nothing) */
3498 * When remote capturing WinPCap crashes when the capture filter
3499 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3502 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3503 interface_opts.name,
3504 interface_opts.cfilter?interface_opts.cfilter:"")) {
3506 case INITFILTER_NO_ERROR:
3509 case INITFILTER_BAD_FILTER:
3510 cfilter_error = TRUE;
3512 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3515 case INITFILTER_OTHER_ERROR:
3516 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3517 pcap_geterr(pcap_opts->pcap_h));
3518 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3523 /* If we're supposed to write to a capture file, open it for output
3524 (temporary/specified name/ringbuffer) */
3525 if (capture_opts->saving_to_file) {
3526 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3527 errmsg, sizeof(errmsg))) {
3531 /* set up to write to the already-opened capture output file/files */
3532 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3537 /* XXX - capture SIGTERM and close the capture, in case we're on a
3538 Linux 2.0[.x] system and you have to explicitly close the capture
3539 stream in order to turn promiscuous mode off? We need to do that
3540 in other places as well - and I don't think that works all the
3541 time in any case, due to libpcap bugs. */
3543 /* Well, we should be able to start capturing.
3545 Sync out the capture file, so the header makes it to the file system,
3546 and send a "capture started successfully and capture file created"
3547 message to our parent so that they'll open the capture file and
3548 update its windows to indicate that we have a live capture in
3550 fflush(global_ld.pdh);
3551 report_new_capture_file(capture_opts->save_file);
3554 /* initialize capture stop (and alike) conditions */
3555 init_capture_stop_conditions();
3556 /* create stop conditions */
3557 if (capture_opts->has_autostop_filesize)
3559 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
3560 if (capture_opts->has_autostop_duration)
3561 cnd_autostop_duration =
3562 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3564 if (capture_opts->multi_files_on) {
3565 if (capture_opts->has_file_duration)
3567 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3569 if (capture_opts->has_autostop_files)
3570 cnd_autostop_files =
3571 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
3574 /* init the time values */
3576 upd_time = GetTickCount();
3578 gettimeofday(&upd_time, NULL);
3580 start_time = create_timestamp();
3581 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
3583 /* WOW, everything is prepared! */
3584 /* please fasten your seat belts, we will enter now the actual capture loop */
3586 pcap_queue = g_async_queue_new();
3587 pcap_queue_bytes = 0;
3588 pcap_queue_packets = 0;
3589 for (i = 0; i < global_ld.pcaps->len; i++) {
3590 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3591 #if GLIB_CHECK_VERSION(2,31,0)
3592 /* XXX - Add an interface name here? */
3593 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3595 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3599 while (global_ld.go) {
3600 /* dispatch incoming packets */
3602 pcap_queue_element *queue_element;
3603 #if GLIB_CHECK_VERSION(2,31,18)
3605 g_async_queue_lock(pcap_queue);
3606 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3608 GTimeVal write_thread_time;
3610 g_get_current_time(&write_thread_time);
3611 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3612 g_async_queue_lock(pcap_queue);
3613 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3615 if (queue_element) {
3616 pcap_queue_bytes -= queue_element->phdr.caplen;
3617 pcap_queue_packets -= 1;
3619 g_async_queue_unlock(pcap_queue);
3620 if (queue_element) {
3621 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3622 "Dequeued a packet of length %d captured on interface %d.",
3623 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3625 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3626 &queue_element->phdr,
3628 g_free(queue_element->pd);
3629 g_free(queue_element);
3635 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3636 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3637 sizeof(errmsg), pcap_opts);
3640 /* Were we asked to print packet counts by the SIGINFO handler? */
3641 if (global_ld.report_packet_count) {
3642 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3643 plurality(global_ld.packet_count, "", "s"));
3644 global_ld.report_packet_count = FALSE;
3649 /* any news from our parent (signal pipe)? -> just stop the capture */
3650 if (!signal_pipe_check_running()) {
3651 global_ld.go = FALSE;
3656 global_ld.inpkts_to_sync_pipe += inpkts;
3658 /* check capture size condition */
3659 if (cnd_autostop_size != NULL &&
3660 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)) {
3661 /* Capture size limit reached, do we have another file? */
3662 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3663 cnd_autostop_size, cnd_file_duration))
3665 } /* cnd_autostop_size */
3666 if (capture_opts->output_to_pipe) {
3667 fflush(global_ld.pdh);
3671 /* Only update once every 500ms so as not to overload slow displays.
3672 * This also prevents too much context-switching between the dumpcap
3673 * and wireshark processes.
3675 #define DUMPCAP_UPD_TIME 500
3678 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3679 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3681 gettimeofday(&cur_time, NULL);
3682 if ((cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3683 (upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3686 upd_time = cur_time;
3689 if (pcap_stats(pch, stats) >= 0) {
3690 *stats_known = TRUE;
3693 /* Let the parent process know. */
3694 if (global_ld.inpkts_to_sync_pipe) {
3696 fflush(global_ld.pdh);
3698 /* Send our parent a message saying we've written out
3699 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3701 report_packet_count(global_ld.inpkts_to_sync_pipe);
3703 global_ld.inpkts_to_sync_pipe = 0;
3706 /* check capture duration condition */
3707 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3708 /* The maximum capture time has elapsed; stop the capture. */
3709 global_ld.go = FALSE;
3713 /* check capture file duration condition */
3714 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3715 /* duration limit reached, do we have another file? */
3716 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3717 cnd_autostop_size, cnd_file_duration))
3719 } /* cnd_file_duration */
3723 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3725 pcap_queue_element *queue_element;
3727 for (i = 0; i < global_ld.pcaps->len; i++) {
3728 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3729 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3730 pcap_opts->interface_id);
3731 g_thread_join(pcap_opts->tid);
3732 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3733 pcap_opts->interface_id);
3736 g_async_queue_lock(pcap_queue);
3737 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3738 if (queue_element) {
3739 pcap_queue_bytes -= queue_element->phdr.caplen;
3740 pcap_queue_packets -= 1;
3742 g_async_queue_unlock(pcap_queue);
3743 if (queue_element == NULL) {
3746 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3747 "Dequeued a packet of length %d captured on interface %d.",
3748 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3749 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3750 &queue_element->phdr,
3752 g_free(queue_element->pd);
3753 g_free(queue_element);
3754 global_ld.inpkts_to_sync_pipe += 1;
3755 if (capture_opts->output_to_pipe) {
3756 fflush(global_ld.pdh);
3762 /* delete stop conditions */
3763 if (cnd_file_duration != NULL)
3764 cnd_delete(cnd_file_duration);
3765 if (cnd_autostop_files != NULL)
3766 cnd_delete(cnd_autostop_files);
3767 if (cnd_autostop_size != NULL)
3768 cnd_delete(cnd_autostop_size);
3769 if (cnd_autostop_duration != NULL)
3770 cnd_delete(cnd_autostop_duration);
3772 /* did we have a pcap (input) error? */
3773 for (i = 0; i < capture_opts->ifaces->len; i++) {
3774 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3775 if (pcap_opts->pcap_err) {
3776 /* On Linux, if an interface goes down while you're capturing on it,
3777 you'll get a "recvfrom: Network is down" or
3778 "The interface went down" error (ENETDOWN).
3779 (At least you will if g_strerror() doesn't show a local translation
3782 On FreeBSD and OS X, if a network adapter disappears while
3783 you're capturing on it, you'll get a "read: Device not configured"
3784 error (ENXIO). (See previous parenthetical note.)
3786 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3788 These should *not* be reported to the Wireshark developers. */
3791 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3792 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3793 strcmp(cap_err_str, "The interface went down") == 0 ||
3794 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3795 strcmp(cap_err_str, "read: I/O error") == 0 ||
3796 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3797 report_capture_error("The network adapter on which the capture was being done "
3798 "is no longer running; the capture has stopped.",
3801 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3803 report_capture_error(errmsg, please_report);
3806 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3807 report_capture_error(errmsg, "");
3811 /* did we have an output error while capturing? */
3812 if (global_ld.err == 0) {
3815 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3816 global_ld.err, FALSE);
3817 report_capture_error(errmsg, please_report);
3821 if (capture_opts->saving_to_file) {
3822 /* close the output file */
3823 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3827 /* there might be packets not yet notified to the parent */
3828 /* (do this after closing the file, so all packets are already flushed) */
3829 if (global_ld.inpkts_to_sync_pipe) {
3831 report_packet_count(global_ld.inpkts_to_sync_pipe);
3832 global_ld.inpkts_to_sync_pipe = 0;
3835 /* If we've displayed a message about a write error, there's no point
3836 in displaying another message about an error on close. */
3837 if (!close_ok && write_ok) {
3838 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3840 report_capture_error(errmsg, "");
3844 * XXX We exhibit different behaviour between normal mode and sync mode
3845 * when the pipe is stdin and not already at EOF. If we're a child, the
3846 * parent's stdin isn't closed, so if the user starts another capture,
3847 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3848 * will say "Unrecognized libpcap format". On the other hand, in normal
3849 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3852 report_capture_count(TRUE);
3854 /* get packet drop statistics from pcap */
3855 for (i = 0; i < capture_opts->ifaces->len; i++) {
3857 guint32 pcap_dropped = 0;
3859 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3860 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3861 received = pcap_opts->received;
3862 if (pcap_opts->pcap_h != NULL) {
3863 g_assert(!pcap_opts->from_cap_pipe);
3864 /* Get the capture statistics, so we know how many packets were dropped. */
3865 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3866 *stats_known = TRUE;
3867 /* Let the parent process know. */
3868 pcap_dropped += stats->ps_drop;
3870 g_snprintf(errmsg, sizeof(errmsg),
3871 "Can't get packet-drop statistics: %s",
3872 pcap_geterr(pcap_opts->pcap_h));
3873 report_capture_error(errmsg, please_report);
3876 report_packet_drops(received, pcap_dropped, pcap_opts->dropped, pcap_opts->flushed, interface_opts.console_display_name);
3879 /* close the input file (pcap or capture pipe) */
3880 capture_loop_close_input(&global_ld);
3882 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
3884 /* ok, if the write and the close were successful. */
3885 return write_ok && close_ok;
3888 if (capture_opts->multi_files_on) {
3889 /* cleanup ringbuffer */
3890 ringbuf_error_cleanup();
3892 /* We can't use the save file, and we have no FILE * for the stream
3893 to close in order to close it, so close the FD directly. */
3894 if (global_ld.save_file_fd != -1) {
3895 ws_close(global_ld.save_file_fd);
3898 /* We couldn't even start the capture, so get rid of the capture
3900 if (capture_opts->save_file != NULL) {
3901 ws_unlink(capture_opts->save_file);
3902 g_free(capture_opts->save_file);
3905 capture_opts->save_file = NULL;
3907 report_cfilter_error(capture_opts, error_index, errmsg);
3909 report_capture_error(errmsg, secondary_errmsg);
3911 /* close the input file (pcap or cap_pipe) */
3912 capture_loop_close_input(&global_ld);
3914 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3921 capture_loop_stop(void)
3923 #ifdef HAVE_PCAP_BREAKLOOP
3925 pcap_options *pcap_opts;
3927 for (i = 0; i < global_ld.pcaps->len; i++) {
3928 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3929 if (pcap_opts->pcap_h != NULL)
3930 pcap_breakloop(pcap_opts->pcap_h);
3933 global_ld.go = FALSE;
3938 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3939 int err, gboolean is_close)
3944 g_snprintf(errmsg, errmsglen,
3945 "Not all the packets could be written to the file"
3946 " to which the capture was being saved\n"
3947 "(\"%s\") because there is no space left on the file system\n"
3948 "on which that file resides.",
3954 g_snprintf(errmsg, errmsglen,
3955 "Not all the packets could be written to the file"
3956 " to which the capture was being saved\n"
3957 "(\"%s\") because you are too close to, or over,"
3958 " your disk quota\n"
3959 "on the file system on which that file resides.",
3966 g_snprintf(errmsg, errmsglen,
3967 "The file to which the capture was being saved\n"
3968 "(\"%s\") could not be closed: %s.",
3969 fname, g_strerror(err));
3971 g_snprintf(errmsg, errmsglen,
3972 "An error occurred while writing to the file"
3973 " to which the capture was being saved\n"
3975 fname, g_strerror(err));
3982 /* one packet was captured, process it */
3984 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3987 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3989 guint ts_mul = pcap_opts->ts_nsec ? 1000000000 : 1000000;
3991 /* We may be called multiple times from pcap_dispatch(); if we've set
3992 the "stop capturing" flag, ignore this packet, as we're not
3993 supposed to be saving any more packets. */
3994 if (!global_ld.go) {
3995 pcap_opts->flushed++;
3999 if (global_ld.pdh) {
4000 gboolean successful;
4002 /* We're supposed to write the packet to a file; do so.
4003 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4004 "ld->err" to the error. */
4005 if (global_capture_opts.use_pcapng) {
4006 successful = libpcap_write_enhanced_packet_block(libpcap_write_to_file, global_ld.pdh,
4008 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4009 phdr->caplen, phdr->len,
4010 pcap_opts->interface_id,
4013 &global_ld.bytes_written, &err);
4015 successful = libpcap_write_packet(libpcap_write_to_file, global_ld.pdh,
4016 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4017 phdr->caplen, phdr->len,
4019 &global_ld.bytes_written, &err);
4022 global_ld.go = FALSE;
4023 global_ld.err = err;
4024 pcap_opts->dropped++;
4026 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4027 "Wrote a packet of length %d captured on interface %u.",
4028 phdr->caplen, pcap_opts->interface_id);
4029 global_ld.packet_count++;
4030 pcap_opts->received++;
4031 /* if the user told us to stop after x packets, do we already have enough? */
4032 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
4033 global_ld.go = FALSE;
4039 /* one packet was captured, queue it */
4041 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4044 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4045 pcap_queue_element *queue_element;
4046 gboolean limit_reached;
4048 /* We may be called multiple times from pcap_dispatch(); if we've set
4049 the "stop capturing" flag, ignore this packet, as we're not
4050 supposed to be saving any more packets. */
4051 if (!global_ld.go) {
4052 pcap_opts->flushed++;
4056 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4057 if (queue_element == NULL) {
4058 pcap_opts->dropped++;
4061 queue_element->pcap_opts = pcap_opts;
4062 queue_element->phdr = *phdr;
4063 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4064 if (queue_element->pd == NULL) {
4065 pcap_opts->dropped++;
4066 g_free(queue_element);
4069 memcpy(queue_element->pd, pd, phdr->caplen);
4070 g_async_queue_lock(pcap_queue);
4071 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4072 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4073 limit_reached = FALSE;
4074 g_async_queue_push_unlocked(pcap_queue, queue_element);
4075 pcap_queue_bytes += phdr->caplen;
4076 pcap_queue_packets += 1;
4078 limit_reached = TRUE;
4080 g_async_queue_unlock(pcap_queue);
4081 if (limit_reached) {
4082 pcap_opts->dropped++;
4083 g_free(queue_element->pd);
4084 g_free(queue_element);
4085 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4086 "Dropped a packet of length %d captured on interface %u.",
4087 phdr->caplen, pcap_opts->interface_id);
4089 pcap_opts->received++;
4090 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4091 "Queued a packet of length %d captured on interface %u.",
4092 phdr->caplen, pcap_opts->interface_id);
4094 /* I don't want to hold the mutex over the debug output. So the
4095 output may be wrong */
4096 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4097 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4098 pcap_queue_bytes, pcap_queue_packets);
4102 set_80211_channel(const char *iface, const char *opt)
4104 int freq = 0, type, ret;
4105 gchar **options = NULL;
4107 options = g_strsplit_set(opt, ",", 2);
4110 freq = atoi(options[0]);
4113 type = ws80211_str_to_chan_type(options[1]);
4122 ret = ws80211_init();
4124 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4128 ret = ws80211_set_freq(iface, freq, type);
4131 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4137 pipe_write_block(2, SP_SUCCESS, NULL);
4141 g_strfreev(options);
4145 /* And now our feature presentation... [ fade to music ] */
4147 main(int argc, char *argv[])
4149 GString *comp_info_str;
4150 GString *runtime_info_str;
4152 struct option long_options[] = {
4153 {(char *)"capture-comment", required_argument, NULL, LONGOPT_NUM_CAP_COMMENT },
4157 gboolean arg_error = FALSE;
4162 struct sigaction action, oldaction;
4165 gboolean start_capture = TRUE;
4166 gboolean stats_known;
4167 struct pcap_stat stats;
4168 GLogLevelFlags log_flags;
4169 gboolean list_interfaces = FALSE;
4170 gboolean list_link_layer_types = FALSE;
4171 #ifdef HAVE_BPF_IMAGE
4172 gboolean print_bpf_code = FALSE;
4174 gboolean set_chan = FALSE;
4175 gchar *set_chan_arg = NULL;
4176 gboolean machine_readable = FALSE;
4177 gboolean print_statistics = FALSE;
4178 int status, run_once_args = 0;
4181 #if defined(__APPLE__) && defined(__LP64__)
4182 struct utsname osinfo;
4186 /* Assemble the compile-time version information string */
4187 comp_info_str = g_string_new("Compiled ");
4188 get_compiled_version_info(comp_info_str, NULL, NULL);
4190 /* Assemble the run-time version information string */
4191 runtime_info_str = g_string_new("Running ");
4192 get_runtime_version_info(runtime_info_str, NULL);
4194 /* Add it to the information to be reported on a crash. */
4195 ws_add_crash_info("Dumpcap " VERSION "%s\n"
4200 wireshark_svnversion, comp_info_str->str, runtime_info_str->str);
4203 arg_list_utf_16to8(argc, argv);
4204 create_app_running_mutex();
4207 * Initialize our DLL search path. MUST be called before LoadLibrary
4210 ws_init_dll_search_path();
4213 #ifdef HAVE_PCAP_REMOTE
4214 #define OPTSTRING_A "A:"
4215 #define OPTSTRING_r "r"
4216 #define OPTSTRING_u "u"
4218 #define OPTSTRING_A ""
4219 #define OPTSTRING_r ""
4220 #define OPTSTRING_u ""
4223 #ifdef HAVE_PCAP_SETSAMPLING
4224 #define OPTSTRING_m "m:"
4226 #define OPTSTRING_m ""
4229 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4230 #define OPTSTRING_B "B:"
4232 #define OPTSTRING_B ""
4233 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4235 #ifdef HAVE_PCAP_CREATE
4236 #define OPTSTRING_I "I"
4238 #define OPTSTRING_I ""
4241 #ifdef HAVE_BPF_IMAGE
4242 #define OPTSTRING_d "d"
4244 #define OPTSTRING_d ""
4247 #define OPTSTRING "a:" OPTSTRING_A "b:" OPTSTRING_B "C:c:" OPTSTRING_d "Df:ghi:" OPTSTRING_I "k:L" OPTSTRING_m "MN:npPq" OPTSTRING_r "Ss:t" OPTSTRING_u "vw:y:Z:"
4249 #ifdef DEBUG_CHILD_DUMPCAP
4250 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4251 fprintf (stderr, "Unable to open debug log file !\n");
4256 #if defined(__APPLE__) && defined(__LP64__)
4258 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
4259 * a bug workaround - timeouts less than 1 second don't work with libpcap
4260 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
4261 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4262 * The problem is extremely unlikely to be reintroduced in a future
4265 if (uname(&osinfo) == 0) {
4267 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
4268 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4269 * number of 10.0.0, not 10.1.0 - go figure).
4271 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
4272 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
4273 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
4274 need_timeout_workaround = TRUE;
4279 * Determine if dumpcap is being requested to run in a special
4280 * capture_child mode by going thru the command line args to see if
4281 * a -Z is present. (-Z is a hidden option).
4283 * The primary result of running in capture_child mode is that
4284 * all messages sent out on stderr are in a special type/len/string
4285 * format to allow message processing by type. These messages include
4286 * error messages if dumpcap fails to start the operation it was
4287 * requested to do, as well as various "status" messages which are sent
4288 * when an actual capture is in progress, and a "success" message sent
4289 * if dumpcap was requested to perform an operation other than a
4292 * Capture_child mode would normally be requested by a parent process
4293 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4294 * to which dumpcap stderr has been redirected. It might also have
4295 * another pipe to obtain dumpcap stdout output; for operations other
4296 * than a capture, that information is formatted specially for easier
4297 * parsing by the parent process.
4299 * Capture_child mode needs to be determined immediately upon
4300 * startup so that any messages generated by dumpcap in this mode
4301 * (eg: during initialization) will be formatted properly.
4304 for (i=1; i<argc; i++) {
4305 if (strcmp("-Z", argv[i]) == 0) {
4306 capture_child = TRUE;
4307 machine_readable = TRUE; /* request machine-readable output */
4309 /* set output pipe to binary mode, to avoid ugly text conversions */
4310 _setmode(2, O_BINARY);
4315 /* The default_log_handler will use stdout, which makes trouble in */
4316 /* capture child mode, as it uses stdout for its sync_pipe. */
4317 /* So: the filtering is done in the console_log_handler and not here.*/
4318 /* We set the log handlers right up front to make sure that any log */
4319 /* messages when running as child will be sent back to the parent */
4320 /* with the correct format. */
4325 G_LOG_LEVEL_CRITICAL|
4326 G_LOG_LEVEL_WARNING|
4327 G_LOG_LEVEL_MESSAGE|
4331 G_LOG_FLAG_RECURSION);
4333 g_log_set_handler(NULL,
4335 console_log_handler, NULL /* user_data */);
4336 g_log_set_handler(LOG_DOMAIN_MAIN,
4338 console_log_handler, NULL /* user_data */);
4339 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4341 console_log_handler, NULL /* user_data */);
4342 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4344 console_log_handler, NULL /* user_data */);
4346 /* Initialize the pcaps list */
4347 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
4349 #if !GLIB_CHECK_VERSION(2,31,0)
4350 /* Initialize the thread system */
4351 g_thread_init(NULL);
4355 /* Load wpcap if possible. Do this before collecting the run-time version information */
4358 /* ... and also load the packet.dll from wpcap */
4359 /* XXX - currently not required, may change later. */
4360 /*wpcap_packet_load();*/
4362 /* Start windows sockets */
4363 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4365 /* Set handler for Ctrl+C key */
4366 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4368 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4369 and exit. Do the same with SIGPIPE, in case, for example,
4370 we're writing to our standard output and it's a pipe.
4371 Do the same with SIGHUP if it's not being ignored (if we're
4372 being run under nohup, it might be ignored, in which case we
4373 should leave it ignored).
4375 XXX - apparently, Coverity complained that part of action
4376 wasn't initialized. Perhaps it's running on Linux, where
4377 struct sigaction has an ignored "sa_restorer" element and
4378 where "sa_handler" and "sa_sigaction" might not be two
4379 members of a union. */
4380 memset(&action, 0, sizeof(action));
4381 action.sa_handler = capture_cleanup_handler;
4383 * Arrange that system calls not get restarted, because when
4384 * our signal handler returns we don't want to restart
4385 * a call that was waiting for packets to arrive.
4387 action.sa_flags = 0;
4388 sigemptyset(&action.sa_mask);
4389 sigaction(SIGTERM, &action, NULL);
4390 sigaction(SIGINT, &action, NULL);
4391 sigaction(SIGPIPE, &action, NULL);
4392 sigaction(SIGHUP, NULL, &oldaction);
4393 if (oldaction.sa_handler == SIG_DFL)
4394 sigaction(SIGHUP, &action, NULL);
4397 /* Catch SIGINFO and, if we get it and we're capturing in
4398 quiet mode, report the number of packets we've captured. */
4399 action.sa_handler = report_counts_siginfo;
4400 action.sa_flags = SA_RESTART;
4401 sigemptyset(&action.sa_mask);
4402 sigaction(SIGINFO, &action, NULL);
4403 #endif /* SIGINFO */
4406 enable_kernel_bpf_jit_compiler();
4408 /* ----------------------------------------------------------------- */
4409 /* Privilege and capability handling */
4411 /* 1. Running not as root or suid root; no special capabilities. */
4414 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4417 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4419 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4420 /* capabilities; Drop all other capabilities; */
4421 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4422 /* else: after pcap_open_live() in capture_loop_open_input() */
4423 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4424 /* (Note: this means that the process, although logged in */
4425 /* as root, does not have various permissions such as the */
4426 /* ability to bypass file access permissions). */
4427 /* XXX: Should we just leave capabilities alone in this case */
4428 /* so that user gets expected effect that root can do */
4431 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4433 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4434 /* else: after pcap_open_live() in capture_loop_open_input() */
4435 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4436 /* pcap_open_live). */
4438 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4440 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4441 /* capabilities; Drop all other capabilities; */
4442 /* Drop suid privileges (euid=ruid); */
4443 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4444 /* else: after pcap_open_live() in capture_loop_open_input() */
4445 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4447 /* XXX: For some Linux versions/distros with capabilities */
4448 /* a 'normal' process with any capabilities cannot be */
4449 /* 'killed' (signaled) from another (same uid) non-privileged */
4451 /* For example: If (non-suid) Wireshark forks a */
4452 /* child suid dumpcap which acts as described here (case 5), */
4453 /* Wireshark will be unable to kill (signal) the child */
4454 /* dumpcap process until the capabilities have been dropped */
4455 /* (after pcap_open_live()). */
4456 /* This behaviour will apparently be changed in the kernel */
4457 /* to allow the kill (signal) in this case. */
4458 /* See the following for details: */
4459 /* http://www.mail-archive.com/ [wrapped] */
4460 /* linux-security-module@vger.kernel.org/msg02913.html */
4462 /* It is therefore conceivable that if dumpcap somehow hangs */
4463 /* in pcap_open_live or before that wireshark will not */
4464 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4465 /* In this case, exiting wireshark will kill the child */
4466 /* dumpcap process. */
4468 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4469 /* capabilities; Using libcap. Note: capset cmd (which see) */
4470 /* used to assign capabilities to file. */
4472 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4473 /* else: after pcap_open_live() in capture_loop_open_input() */
4474 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4476 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4477 /* longer required (similar to capture). */
4479 /* ----------------------------------------------------------------- */
4481 init_process_policies();
4484 /* If 'started with special privileges' (and using libcap) */
4485 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4486 /* Set euid/egid = ruid/rgid to remove suid privileges */
4487 relinquish_privs_except_capture();
4490 /* Set the initial values in the capture options. This might be overwritten
4491 by the command line parameters. */
4492 capture_opts_init(&global_capture_opts);
4494 /* We always save to a file - if no file was specified, we save to a
4496 global_capture_opts.saving_to_file = TRUE;
4497 global_capture_opts.has_ring_num_files = TRUE;
4499 /* Pass on capture_child mode for capture_opts */
4500 global_capture_opts.capture_child = capture_child;
4502 /* Now get our args */
4503 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4505 case 'h': /* Print help and exit */
4509 case 'v': /* Show version and exit */
4511 show_version(comp_info_str, runtime_info_str);
4512 g_string_free(comp_info_str, TRUE);
4513 g_string_free(runtime_info_str, TRUE);
4517 /*** capture option specific ***/
4518 case 'a': /* autostop criteria */
4519 case 'b': /* Ringbuffer option */
4520 case 'c': /* Capture x packets */
4521 case 'f': /* capture filter */
4522 case 'g': /* enable group read access on file(s) */
4523 case 'i': /* Use interface x */
4524 case 'n': /* Use pcapng format */
4525 case 'p': /* Don't capture in promiscuous mode */
4526 case 'P': /* Use pcap format */
4527 case 's': /* Set the snapshot (capture) length */
4528 case 'w': /* Write to capture file x */
4529 case 'y': /* Set the pcap data link type */
4530 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4531 #ifdef HAVE_PCAP_REMOTE
4532 case 'u': /* Use UDP for data transfer */
4533 case 'r': /* Capture own RPCAP traffic too */
4534 case 'A': /* Authentication */
4536 #ifdef HAVE_PCAP_SETSAMPLING
4537 case 'm': /* Sampling */
4539 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4540 case 'B': /* Buffer size */
4541 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4542 #ifdef HAVE_PCAP_CREATE
4543 case 'I': /* Monitor mode */
4545 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4550 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4552 capture_child = TRUE;
4554 /* set output pipe to binary mode, to avoid ugly text conversions */
4555 _setmode(2, O_BINARY);
4557 * optarg = the control ID, aka the PPID, currently used for the
4560 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4561 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4562 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4563 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4565 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4566 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4567 "Signal pipe: Unable to open %s. Dead parent?",
4575 case 'q': /* Quiet */
4581 /*** all non capture option specific ***/
4582 case 'D': /* Print a list of capture devices and exit */
4583 list_interfaces = TRUE;
4586 case 'L': /* Print list of link-layer types and exit */
4587 list_link_layer_types = TRUE;
4590 #ifdef HAVE_BPF_IMAGE
4591 case 'd': /* Print BPF code for capture filter and exit */
4592 print_bpf_code = TRUE;
4596 case 'S': /* Print interface statistics once a second */
4597 print_statistics = TRUE;
4600 case 'k': /* Set wireless channel */
4602 set_chan_arg = optarg;
4605 case 'M': /* For -D, -L, and -S, print machine-readable output */
4606 machine_readable = TRUE;
4609 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4612 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4615 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4617 case '?': /* Bad flag - print usage message */
4626 /* user specified file name as regular command-line argument */
4627 /* XXX - use it as the capture file name (or something else)? */
4633 * Extra command line arguments were specified; complain.
4634 * XXX - interpret as capture filter, as tcpdump and tshark do?
4636 cmdarg_err("Invalid argument: %s", argv[0]);
4641 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4644 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4645 /* Use some default if the user hasn't specified some */
4646 /* XXX: Are these defaults good enough? */
4647 pcap_queue_byte_limit = 1000 * 1000;
4648 pcap_queue_packet_limit = 1000;
4655 if (run_once_args > 1) {
4656 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
4658 } else if (run_once_args == 1) {
4659 /* We're supposed to print some information, rather than
4660 to capture traffic; did they specify a ring buffer option? */
4661 if (global_capture_opts.multi_files_on) {
4662 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4666 /* We're supposed to capture traffic; */
4668 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4669 if (global_capture_opts.ifaces->len > 1) {
4671 global_capture_opts.use_pcapng = TRUE;
4674 if (global_capture_opts.capture_comment &&
4675 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4676 /* XXX - for ringbuffer, should we apply the comment to each file? */
4677 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4681 /* Was the ring buffer option specified and, if so, does it make sense? */
4682 if (global_capture_opts.multi_files_on) {
4683 /* Ring buffer works only under certain conditions:
4684 a) ring buffer does not work with temporary files;
4685 b) it makes no sense to enable the ring buffer if the maximum
4686 file size is set to "infinite". */
4687 if (global_capture_opts.save_file == NULL) {
4688 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4689 global_capture_opts.multi_files_on = FALSE;
4691 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4692 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4694 /* XXX - this must be redesigned as the conditions changed */
4695 global_capture_opts.multi_files_on = FALSE;
4702 * "-D" requires no interface to be selected; it's supposed to list
4705 if (list_interfaces) {
4706 /* Get the list of interfaces */
4711 if_list = capture_interface_list(&err, &err_str,NULL);
4712 if (if_list == NULL) {
4714 case CANT_GET_INTERFACE_LIST:
4715 case DONT_HAVE_PCAP:
4716 cmdarg_err("%s", err_str);
4721 case NO_INTERFACES_FOUND:
4723 * If we're being run by another program, just give them
4724 * an empty list of interfaces, don't report this as
4725 * an error; that lets them decide whether to report
4726 * this as an error or not.
4728 if (!machine_readable) {
4729 cmdarg_err("There are no interfaces on which a capture can be done");
4736 if (machine_readable) /* tab-separated values to stdout */
4737 print_machine_readable_interfaces(if_list);
4739 capture_opts_print_interfaces(if_list);
4740 free_interface_list(if_list);
4745 * "-S" requires no interface to be selected; it gives statistics
4746 * for all interfaces.
4748 if (print_statistics) {
4749 status = print_statistics_loop(machine_readable);
4754 interface_options interface_opts;
4756 if (global_capture_opts.ifaces->len != 1) {
4757 cmdarg_err("Need one interface");
4761 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4762 status = set_80211_channel(interface_opts.name, set_chan_arg);
4767 * "-L", "-d", and capturing act on a particular interface, so we have to
4768 * have an interface; if none was specified, pick a default.
4770 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4772 /* cmdarg_err() already called .... */
4776 /* Let the user know what interfaces were chosen. */
4777 if (capture_child) {
4778 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4779 interface_options interface_opts;
4781 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4782 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4783 interface_opts.name);
4786 str = g_string_new("");
4788 if (global_capture_opts.ifaces->len < 2)
4790 if (global_capture_opts.ifaces->len < 4)
4793 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4794 interface_options interface_opts;
4796 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4798 if (global_capture_opts.ifaces->len > 2) {
4799 g_string_append_printf(str, ",");
4801 g_string_append_printf(str, " ");
4802 if (j == global_capture_opts.ifaces->len - 1) {
4803 g_string_append_printf(str, "and ");
4806 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
4809 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4811 fprintf(stderr, "Capturing on %s\n", str->str);
4812 g_string_free(str, TRUE);
4815 if (list_link_layer_types) {
4816 /* Get the list of link-layer types for the capture device. */
4817 if_capabilities_t *caps;
4821 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4822 interface_options interface_opts;
4824 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4825 caps = get_if_capabilities(interface_opts.name,
4826 interface_opts.monitor_mode, &err_str);
4828 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4829 "Please check to make sure you have sufficient permissions, and that\n"
4830 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4834 if (caps->data_link_types == NULL) {
4835 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4838 if (machine_readable) /* tab-separated values to stdout */
4839 /* XXX: We need to change the format and adopt consumers */
4840 print_machine_readable_if_capabilities(caps);
4842 /* XXX: We might want to print also the interface name */
4843 capture_opts_print_if_capabilities(caps, interface_opts.name,
4844 interface_opts.monitor_mode);
4845 free_if_capabilities(caps);
4850 /* We're supposed to do a capture, or print the BPF code for a filter.
4851 Process the snapshot length, as that affects the generated BPF code. */
4852 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4854 #ifdef HAVE_BPF_IMAGE
4855 if (print_bpf_code) {
4856 show_filter_code(&global_capture_opts);
4861 /* We're supposed to do a capture. Process the ring buffer arguments. */
4862 capture_opts_trim_ring_num_files(&global_capture_opts);
4864 /* flush stderr prior to starting the main capture loop */
4867 /* Now start the capture. */
4869 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4873 /* capture failed */
4876 return 0; /* never here, make compiler happy */
4881 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4882 const char *message, gpointer user_data _U_)
4889 /* ignore log message, if log_level isn't interesting */
4890 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4891 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4896 /* create a "timestamp" */
4898 today = localtime(&curr);
4900 switch(log_level & G_LOG_LEVEL_MASK) {
4901 case G_LOG_LEVEL_ERROR:
4904 case G_LOG_LEVEL_CRITICAL:
4907 case G_LOG_LEVEL_WARNING:
4910 case G_LOG_LEVEL_MESSAGE:
4913 case G_LOG_LEVEL_INFO:
4916 case G_LOG_LEVEL_DEBUG:
4920 fprintf(stderr, "unknown log_level %u\n", log_level);
4922 g_assert_not_reached();
4925 /* Generate the output message */
4926 if (log_level & G_LOG_LEVEL_MESSAGE) {
4927 /* normal user messages without additional infos */
4928 msg = g_strdup_printf("%s\n", message);
4930 /* info/debug messages with additional infos */
4931 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4932 today->tm_hour, today->tm_min, today->tm_sec,
4933 log_domain != NULL ? log_domain : "",
4937 /* DEBUG & INFO msgs (if we're debugging today) */
4938 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4939 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4940 #ifdef DEBUG_DUMPCAP
4941 fprintf(stderr, "%s", msg);
4944 #ifdef DEBUG_CHILD_DUMPCAP
4945 fprintf(debug_log, "%s", msg);
4953 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4954 /* to parent especially formatted if dumpcap running as child. */
4955 if (capture_child) {
4956 sync_pipe_errmsg_to_parent(2, msg, "");
4958 fprintf(stderr, "%s", msg);
4965 /****************************************************************************************************************/
4966 /* indication report routines */
4970 report_packet_count(unsigned int packet_count)
4972 char tmp[SP_DECISIZE+1+1];
4973 static unsigned int count = 0;
4975 if (capture_child) {
4976 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
4977 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
4978 pipe_write_block(2, SP_PACKET_COUNT, tmp);
4980 count += packet_count;
4981 fprintf(stderr, "\rPackets: %u ", count);
4982 /* stderr could be line buffered */
4988 report_new_capture_file(const char *filename)
4990 if (capture_child) {
4991 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
4992 pipe_write_block(2, SP_FILE, filename);
4996 * Prevent a SIGINFO handler from writing to the standard error
4997 * while we're doing so; instead, have it just set a flag telling
4998 * us to print that information when we're done.
5001 #endif /* SIGINFO */
5002 fprintf(stderr, "File: %s\n", filename);
5003 /* stderr could be line buffered */
5008 * Allow SIGINFO handlers to write.
5013 * If a SIGINFO handler asked us to write out capture counts, do so.
5016 report_counts_for_siginfo();
5017 #endif /* SIGINFO */
5022 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
5024 interface_options interface_opts;
5025 char tmp[MSG_MAX_LENGTH+1+6];
5027 if (i < capture_opts->ifaces->len) {
5028 if (capture_child) {
5029 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
5030 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
5031 pipe_write_block(2, SP_BAD_FILTER, tmp);
5034 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5035 * the error message below.
5037 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
5039 "Invalid capture filter \"%s\" for interface %s!\n"
5041 "That string isn't a valid capture filter (%s).\n"
5042 "See the User's Guide for a description of the capture filter syntax.",
5043 interface_opts.cfilter, interface_opts.name, errmsg);
5049 report_capture_error(const char *error_msg, const char *secondary_error_msg)
5051 if (capture_child) {
5052 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5053 "Primary Error: %s", error_msg);
5054 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5055 "Secondary Error: %s", secondary_error_msg);
5056 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5058 cmdarg_err("%s", error_msg);
5059 if (secondary_error_msg[0] != '\0')
5060 cmdarg_err_cont("%s", secondary_error_msg);
5065 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, gchar *name)
5067 char tmp[SP_DECISIZE+1+1];
5068 guint32 total_drops = pcap_drops + drops + flushed;
5070 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
5072 if (capture_child) {
5073 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5074 "Packets received/dropped on interface %s: %u/%u (pcap:%u/dumpcap:%u/flushed:%u)",
5075 name, received, total_drops, pcap_drops, drops, flushed);
5076 /* XXX: Need to provide interface id, changes to consumers required. */
5077 pipe_write_block(2, SP_DROPS, tmp);
5080 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u) (%.1f%%)\n",
5081 name, received, total_drops, pcap_drops, drops, flushed,
5082 received ? 100.0 * received / (received + total_drops) : 0.0);
5083 /* stderr could be line buffered */
5089 /************************************************************************************************/
5090 /* signal_pipe handling */
5095 signal_pipe_check_running(void)
5097 /* any news from our parent? -> just stop the capture */
5101 /* if we are running standalone, no check required */
5102 if (!capture_child) {
5106 if (!sig_pipe_name || !sig_pipe_handle) {
5107 /* This shouldn't happen */
5108 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5109 "Signal pipe: No name or handle");
5114 * XXX - We should have the process ID of the parent (from the "-Z" flag)
5115 * at this point. Should we check to see if the parent is still alive,
5116 * e.g. by using OpenProcess?
5119 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5121 if (!result || avail > 0) {
5122 /* peek failed or some bytes really available */
5123 /* (if not piping from stdin this would fail) */
5124 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5125 "Signal pipe: Stop capture: %s", sig_pipe_name);
5126 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5127 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
5128 sig_pipe_handle, result, avail);
5131 /* pipe ok and no bytes available */
5142 * Editor modelines - http://www.wireshark.org/tools/modelines.html
5147 * indent-tabs-mode: nil
5150 * vi: set shiftwidth=4 tabstop=8 expandtab:
5151 * :indentSize=4:tabSize=8:noTabs=true: