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>
57 #ifdef HAVE_ARPA_INET_H
58 #include <arpa/inet.h>
61 #if defined(__APPLE__) && defined(__LP64__)
62 #include <sys/utsname.h>
68 #include <wsutil/crash_info.h>
71 #include "wsutil/wsgetopt.h"
79 # include <sys/prctl.h>
80 # include <sys/capability.h>
83 #include "ringbuffer.h"
84 #include "clopts_common.h"
85 #include "console_io.h"
86 #include "cmdarg_err.h"
87 #include "version_info.h"
89 #include "capture-pcap-util.h"
91 #include "capture-wpcap.h"
97 #include "capture-wpcap.h"
98 #include <wsutil/unicode-utils.h>
105 #ifdef NEED_INET_V6DEFS_H
106 # include "wsutil/inet_v6defs.h"
109 #include <wsutil/privileges.h>
111 #include "sync_pipe.h"
113 #include "capture_opts.h"
114 #include "capture_ifinfo.h"
115 #include "capture_sync.h"
117 #include "conditions.h"
118 #include "capture_stop_conditions.h"
120 #include "tempfile.h"
122 #include "wsutil/file_util.h"
124 #include "ws80211_utils.h"
127 * Get information about libpcap format from "wiretap/libpcap.h".
128 * XXX - can we just use pcap_open_offline() to read the pipe?
130 #include "wiretap/libpcap.h"
132 /**#define DEBUG_DUMPCAP**/
133 /**#define DEBUG_CHILD_DUMPCAP**/
137 #include <conio.h> /* _getch() */
141 #ifdef DEBUG_CHILD_DUMPCAP
142 FILE *debug_log; /* for logging debug messages to */
143 /* a file if DEBUG_CHILD_DUMPCAP */
147 static GAsyncQueue *pcap_queue;
148 static gint64 pcap_queue_bytes;
149 static gint64 pcap_queue_packets;
150 static gint64 pcap_queue_byte_limit = 0;
151 static gint64 pcap_queue_packet_limit = 0;
153 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
155 static gchar *sig_pipe_name = NULL;
156 static HANDLE sig_pipe_handle = NULL;
157 static gboolean signal_pipe_check_running(void);
161 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
162 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
165 /** Stop a low-level capture (stops the capture child). */
166 static void capture_loop_stop(void);
167 /** Close a pipe, or socket if \a from_socket is TRUE */
168 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
170 #if !defined (__linux__)
171 #ifndef HAVE_PCAP_BREAKLOOP
173 * We don't have pcap_breakloop(), which is the only way to ensure that
174 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
175 * won't, if the call to read the next packet or batch of packets is
176 * is interrupted by a signal on UN*X, just go back and try again to
179 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
180 * the signal handler, set a flag to stop capturing; however, without
181 * a guarantee of that sort, we can't guarantee that we'll stop capturing
182 * if the read will be retried and won't time out if no packets arrive.
184 * Therefore, on at least some platforms, we work around the lack of
185 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
186 * to wait for packets to arrive, so that we're probably going to be
187 * blocked in the select() when the signal arrives, and can just bail
188 * out of the loop at that point.
190 * However, we don't want to do that on BSD (because "select()" doesn't work
191 * correctly on BPF devices on at least some releases of some flavors of
192 * BSD), and we don't want to do it on Windows (because "select()" is
193 * something for sockets, not for arbitrary handles). (Note that "Windows"
194 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
195 * using WinPcap, not a UNIX libpcap.)
197 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
198 * on BSD times out even if no packets have arrived, so we'll eventually
199 * exit pcap_dispatch() with an indication that no packets have arrived,
200 * and will break out of the capture loop at that point.
202 * On Windows, we can't send a SIGINT to stop capturing, so none of this
203 * applies in any case.
205 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
206 * want to include it if it's not present on this platform, however.
208 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
209 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
211 # define MUST_DO_SELECT
212 # endif /* avoid select */
213 #endif /* HAVE_PCAP_BREAKLOOP */
215 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
216 * in pcap_dispatch(); on the other hand, select() works just fine there.
217 * Hence we use a select for that come what may.
219 #define MUST_DO_SELECT
222 /** init the capture filter */
225 INITFILTER_BAD_FILTER,
226 INITFILTER_OTHER_ERROR
227 } initfilter_status_t;
230 STATE_EXPECT_REC_HDR,
241 typedef struct _pcap_options {
246 #ifdef MUST_DO_SELECT
247 int pcap_fd; /**< pcap file descriptor */
254 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
255 /**< capture pipe (unix only "input file") */
256 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
257 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
258 struct pcap_hdr cap_pipe_hdr; /**< Pcap header when capturing from a pipe */
259 struct pcaprec_modified_hdr cap_pipe_rechdr; /**< Pcap record header when capturing from a pipe */
261 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
263 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
264 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
265 gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
267 char * cap_pipe_buf; /**< Pointer to the data buffer we read into */
268 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
269 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
271 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
272 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
274 cap_pipe_state_t cap_pipe_state;
275 cap_pipe_err_t cap_pipe_err;
278 GMutex *cap_pipe_read_mtx;
279 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
283 typedef struct _loop_data {
285 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
286 int err; /**< if non-zero, error seen while capturing */
287 gint packet_count; /**< Number of packets we have already captured */
288 gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
289 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
291 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
297 guint64 bytes_written;
298 guint32 autostop_files;
301 typedef struct _pcap_queue_element {
302 pcap_options *pcap_opts;
303 struct pcap_pkthdr phdr;
305 } pcap_queue_element;
308 * Standard secondary message for unexpected errors.
310 static const char please_report[] =
311 "Please report this to the Wireshark developers.\n"
312 "(This is not a crash; please do not report it as such.)";
315 * This needs to be static, so that the SIGINT handler can clear the "go"
318 static loop_data global_ld;
322 * Timeout, in milliseconds, for reads from the stream of captured packets
323 * from a capture device.
325 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
326 * 64-bit applications, with sub-second timeouts not to work. The bug is
327 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
329 #if defined(__APPLE__) && defined(__LP64__)
330 static gboolean need_timeout_workaround;
332 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
334 #define CAP_READ_TIMEOUT 250
338 * Timeout, in microseconds, for reads from the stream of captured packets
339 * from a pipe. Pipes don't have the same problem that BPF devices do
340 * in OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
341 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
342 * of the offending versions of Snow Leopard.
344 * On Windows this value is converted to milliseconds and passed to
345 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
346 * will return immediately.
349 #define PIPE_READ_TIMEOUT 100000
351 #define PIPE_READ_TIMEOUT 250000
354 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
357 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
358 const char *message, gpointer user_data _U_);
360 /* capture related options */
361 static capture_options global_capture_opts;
362 static gboolean quiet = FALSE;
363 static gboolean use_threads = FALSE;
364 static guint64 start_time;
366 static void capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
368 static void capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
370 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
371 int err, gboolean is_close);
373 static void WS_MSVC_NORETURN exit_main(int err) G_GNUC_NORETURN;
375 static void report_new_capture_file(const char *filename);
376 static void report_packet_count(unsigned int packet_count);
377 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, gchar *name);
378 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
379 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
381 #define MSG_MAX_LENGTH 4096
383 /* Copied from pcapio.c libpcap_write_interface_statistics_block()*/
385 create_timestamp(void) {
395 * Current time, represented as 100-nanosecond intervals since
396 * January 1, 1601, 00:00:00 UTC.
398 * I think DWORD might be signed, so cast both parts of "now"
399 * to guint32 so that the sign bit doesn't get treated specially.
401 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
402 * might want to use instead.
404 GetSystemTimeAsFileTime(&now);
405 timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
406 (guint32)now.dwLowDateTime;
409 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
415 * Subtract difference, in microseconds, between January 1, 1601
416 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
418 timestamp -= G_GINT64_CONSTANT(11644473600000000U);
421 * Current time, represented as seconds and microseconds since
422 * January 1, 1970, 00:00:00 UTC.
424 gettimeofday(&now, NULL);
427 * Convert to delta in microseconds.
429 timestamp = (guint64)(now.tv_sec) * 1000000 +
430 (guint64)(now.tv_usec);
436 print_usage(gboolean print_ver)
443 "Dumpcap " VERSION "%s\n"
444 "Capture network packets and dump them into a pcapng file.\n"
445 "See http://www.wireshark.org for more information.\n",
446 wireshark_svnversion);
450 fprintf(output, "\nUsage: dumpcap [options] ...\n");
451 fprintf(output, "\n");
452 fprintf(output, "Capture interface:\n");
453 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
454 " or for remote capturing, use one of these formats:\n"
455 " rpcap://<host>/<interface>\n"
456 " TCP@<host>:<port>\n");
457 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
458 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
459 fprintf(output, " -p don't capture in promiscuous mode\n");
460 #ifdef HAVE_PCAP_CREATE
461 fprintf(output, " -I capture in monitor mode, if available\n");
463 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
464 fprintf(output, " -B <buffer size> size of kernel buffer in MB (def: %dMB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
466 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
467 fprintf(output, " -D print list of interfaces and exit\n");
468 fprintf(output, " -L print list of link-layer types of iface and exit\n");
469 #ifdef HAVE_BPF_IMAGE
470 fprintf(output, " -d print generated BPF code for capture filter\n");
472 fprintf(output, " -k set channel on wifi interface <freq>,[<type>]\n");
473 fprintf(output, " -S print statistics for each interface once per second\n");
474 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
475 fprintf(output, "\n");
476 #ifdef HAVE_PCAP_REMOTE
477 fprintf(output, "RPCAP options:\n");
478 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
479 fprintf(output, " -u use UDP for RPCAP data transfer\n");
480 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
481 #ifdef HAVE_PCAP_SETSAMPLING
482 fprintf(output, " -m <sampling type> use packet sampling\n");
483 fprintf(output, " count:NUM - capture one packet of every NUM\n");
484 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
487 fprintf(output, "Stop conditions:\n");
488 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
489 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
490 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
491 fprintf(output, " files:NUM - stop after NUM files\n");
492 /*fprintf(output, "\n");*/
493 fprintf(output, "Output (files):\n");
494 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
495 fprintf(output, " -g enable group read access on the output file(s)\n");
496 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
497 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
498 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
499 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
500 fprintf(output, " -P use libpcap format instead of pcapng\n");
501 fprintf(output, "\n");
502 fprintf(output, "Miscellaneous:\n");
503 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
504 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets within dumpcap\n");
505 fprintf(output, " -t use a separate thread per interface\n");
506 fprintf(output, " -q don't report packet capture counts\n");
507 fprintf(output, " -v print version information and exit\n");
508 fprintf(output, " -h display this help and exit\n");
509 fprintf(output, "\n");
510 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
511 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
512 fprintf(output, "\n");
513 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
517 show_version(GString *comp_info_str, GString *runtime_info_str)
520 "Dumpcap " VERSION "%s\n"
525 "See http://www.wireshark.org for more information.\n",
526 wireshark_svnversion, get_copyright_info(), comp_info_str->str, runtime_info_str->str);
530 * Print to the standard error. This is a command-line tool, so there's
531 * no need to pop up a console.
534 vfprintf_stderr(const char *fmt, va_list ap)
536 vfprintf(stderr, fmt, ap);
540 fprintf_stderr(const char *fmt, ...)
545 vfprintf_stderr(fmt, ap);
550 * Report an error in command-line arguments.
553 cmdarg_err(const char *fmt, ...)
559 /* Generate a 'special format' message back to parent */
561 msg = g_strdup_vprintf(fmt, ap);
562 sync_pipe_errmsg_to_parent(2, msg, "");
567 fprintf(stderr, "dumpcap: ");
568 vfprintf(stderr, fmt, ap);
569 fprintf(stderr, "\n");
575 * Report additional information for an error in command-line arguments.
578 cmdarg_err_cont(const char *fmt, ...)
585 msg = g_strdup_vprintf(fmt, ap);
586 sync_pipe_errmsg_to_parent(2, msg, "");
591 vfprintf(stderr, fmt, ap);
592 fprintf(stderr, "\n");
599 #if 0 /* Set to enable capability debugging */
600 /* see 'man cap_to_text()' for explanation of output */
601 /* '=' means 'all= ' ie: no capabilities */
602 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
604 print_caps(const char *pfx) {
605 cap_t caps = cap_get_proc();
606 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
607 "%s: EUID: %d Capabilities: %s", pfx,
608 geteuid(), cap_to_text(caps, NULL));
611 print_caps(const char *pfx _U_) {
616 relinquish_all_capabilities(void)
618 /* Drop any and all capabilities this process may have. */
619 /* Allowed whether or not process has any privileges. */
620 cap_t caps = cap_init(); /* all capabilities initialized to off */
621 print_caps("Pre-clear");
622 if (cap_set_proc(caps)) {
623 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
625 print_caps("Post-clear");
631 open_capture_device(interface_options *interface_opts,
632 char (*open_err_str)[PCAP_ERRBUF_SIZE])
635 #ifdef HAVE_PCAP_CREATE
638 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
639 struct pcap_rmtauth auth;
642 /* Open the network interface to capture from it.
643 Some versions of libpcap may put warnings into the error buffer
644 if they succeed; to tell if that's happened, we have to clear
645 the error buffer, and check if it's still a null string. */
646 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Entering open_capture_device().");
647 (*open_err_str)[0] = '\0';
648 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
650 * If we're opening a remote device, use pcap_open(); that's currently
651 * the only open routine that supports remote devices.
653 if (strncmp (interface_opts->name, "rpcap://", 8) == 0) {
654 auth.type = interface_opts->auth_type == CAPTURE_AUTH_PWD ?
655 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
656 auth.username = interface_opts->auth_username;
657 auth.password = interface_opts->auth_password;
659 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
660 "Calling pcap_open() using name %s, snaplen %d, promisc_mode %d, datatx_udp %d, nocap_rpcap %d.",
661 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode,
662 interface_opts->datatx_udp, interface_opts->nocap_rpcap);
663 pcap_h = pcap_open(interface_opts->name, interface_opts->snaplen,
665 (interface_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
666 (interface_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
667 (interface_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
668 CAP_READ_TIMEOUT, &auth, *open_err_str);
669 if (pcap_h == NULL) {
670 /* Error - did pcap actually supply an error message? */
671 if ((*open_err_str)[0] == '\0') {
672 /* Work around known WinPcap bug wherein no error message is
673 filled in on a failure to open an rpcap: URL. */
674 g_strlcpy(*open_err_str,
675 "Unknown error (pcap bug; actual error cause not reported)",
676 sizeof *open_err_str);
679 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
680 "pcap_open() returned %p.", (void *)pcap_h);
685 * If we're not opening a remote device, use pcap_create() and
686 * pcap_activate() if we have them, so that we can set the buffer
687 * size, otherwise use pcap_open_live().
689 #ifdef HAVE_PCAP_CREATE
690 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
691 "Calling pcap_create() using %s.", interface_opts->name);
692 pcap_h = pcap_create(interface_opts->name, *open_err_str);
693 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
694 "pcap_create() returned %p.", (void *)pcap_h);
695 if (pcap_h != NULL) {
696 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
697 "Calling pcap_set_snaplen() with snaplen %d.", interface_opts->snaplen);
698 pcap_set_snaplen(pcap_h, interface_opts->snaplen);
699 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
700 "Calling pcap_set_promisc() with promisc_mode %d.", interface_opts->promisc_mode);
701 pcap_set_promisc(pcap_h, interface_opts->promisc_mode);
702 pcap_set_timeout(pcap_h, CAP_READ_TIMEOUT);
704 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
705 "buffersize %d.", interface_opts->buffer_size);
706 if (interface_opts->buffer_size != 0) {
707 pcap_set_buffer_size(pcap_h, interface_opts->buffer_size * 1024 * 1024);
709 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
710 "monitor_mode %d.", interface_opts->monitor_mode);
711 if (interface_opts->monitor_mode)
712 pcap_set_rfmon(pcap_h, 1);
713 err = pcap_activate(pcap_h);
714 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
715 "pcap_activate() returned %d.", err);
717 /* Failed to activate, set to NULL */
718 if (err == PCAP_ERROR)
719 g_strlcpy(*open_err_str, pcap_geterr(pcap_h), sizeof *open_err_str);
721 g_strlcpy(*open_err_str, pcap_statustostr(err), sizeof *open_err_str);
727 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
728 "pcap_open_live() calling using name %s, snaplen %d, promisc_mode %d.",
729 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode);
730 pcap_h = pcap_open_live(interface_opts->name, interface_opts->snaplen,
731 interface_opts->promisc_mode, CAP_READ_TIMEOUT,
733 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
734 "pcap_open_live() returned %p.", (void *)pcap_h);
737 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "open_capture_device %s : %s", pcap_h ? "SUCCESS" : "FAILURE", interface_opts->name);
742 get_capture_device_open_failure_messages(const char *open_err_str,
748 char *errmsg, size_t errmsg_len,
749 char *secondary_errmsg,
750 size_t secondary_errmsg_len)
753 const char *libpcap_warn;
754 static const char ppamsg[] = "can't find PPA for ";
757 g_snprintf(errmsg, (gulong) errmsg_len,
758 "The capture session could not be initiated (%s).", open_err_str);
761 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
763 "In order to capture packets, WinPcap must be installed; see\n"
765 " http://www.winpcap.org/\n"
769 " http://www.mirrors.wiretapped.net/security/packet-capture/winpcap/\n"
773 " http://winpcap.cs.pu.edu.tw/\n"
775 "for a downloadable version of WinPcap and for instructions on how to install\n"
778 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
780 "Please check that \"%s\" is the proper interface.\n"
783 "Help can be found at:\n"
785 " http://wiki.wireshark.org/WinPcap\n"
786 " http://wiki.wireshark.org/CaptureSetup\n",
790 /* If we got a "can't find PPA for X" message, warn the user (who
791 is running dumpcap on HP-UX) that they don't have a version of
792 libpcap that properly handles HP-UX (libpcap 0.6.x and later
793 versions, which properly handle HP-UX, say "can't find /dev/dlpi
794 PPA for X" rather than "can't find PPA for X"). */
795 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
798 "You are running (T)Wireshark with a version of the libpcap library\n"
799 "that doesn't handle HP-UX network devices well; this means that\n"
800 "(T)Wireshark may not be able to capture packets.\n"
802 "To fix this, you should install libpcap 0.6.2, or a later version\n"
803 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
804 "packaged binary form from the Software Porting And Archive Centre\n"
805 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
806 "at the URL lists a number of mirror sites.";
810 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
811 "Please check to make sure you have sufficient permissions, and that you have "
812 "the proper interface or pipe specified.%s", libpcap_warn);
816 /* Set the data link type on a pcap. */
818 set_pcap_linktype(pcap_t *pcap_h, int linktype,
819 #ifdef HAVE_PCAP_SET_DATALINK
824 char *errmsg, size_t errmsg_len,
825 char *secondary_errmsg, size_t secondary_errmsg_len)
827 char *set_linktype_err_str;
830 return TRUE; /* just use the default */
831 #ifdef HAVE_PCAP_SET_DATALINK
832 if (pcap_set_datalink(pcap_h, linktype) == 0)
833 return TRUE; /* no error */
834 set_linktype_err_str = pcap_geterr(pcap_h);
836 /* Let them set it to the type it is; reject any other request. */
837 if (get_pcap_linktype(pcap_h, name) == linktype)
838 return TRUE; /* no error */
839 set_linktype_err_str =
840 "That DLT isn't one of the DLTs supported by this device";
842 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
843 set_linktype_err_str);
845 * If the error isn't "XXX is not one of the DLTs supported by this device",
846 * tell the user to tell the Wireshark developers about it.
848 if (strstr(set_linktype_err_str, "is not one of the DLTs supported by this device") == NULL)
849 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
851 secondary_errmsg[0] = '\0';
856 compile_capture_filter(const char *iface, pcap_t *pcap_h,
857 struct bpf_program *fcode, const char *cfilter)
859 bpf_u_int32 netnum, netmask;
860 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
862 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
864 * Well, we can't get the netmask for this interface; it's used
865 * only for filters that check for broadcast IP addresses, so
866 * we just punt and use 0. It might be nice to warn the user,
867 * but that's a pain in a GUI application, as it'd involve popping
868 * up a message box, and it's not clear how often this would make
869 * a difference (only filters that check for IP broadcast addresses
873 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
878 * Sigh. Older versions of libpcap don't properly declare the
879 * third argument to pcap_compile() as a const pointer. Cast
882 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
887 #ifdef HAVE_BPF_IMAGE
889 show_filter_code(capture_options *capture_opts)
891 interface_options interface_opts;
893 gchar open_err_str[PCAP_ERRBUF_SIZE];
894 char errmsg[MSG_MAX_LENGTH+1];
895 char secondary_errmsg[MSG_MAX_LENGTH+1];
896 struct bpf_program fcode;
897 struct bpf_insn *insn;
901 for (j = 0; j < capture_opts->ifaces->len; j++) {
902 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
903 pcap_h = open_capture_device(&interface_opts, &open_err_str);
904 if (pcap_h == NULL) {
905 /* Open failed; get messages */
906 get_capture_device_open_failure_messages(open_err_str,
908 errmsg, sizeof errmsg,
910 sizeof secondary_errmsg);
911 /* And report them */
912 report_capture_error(errmsg, secondary_errmsg);
916 /* Set the link-layer type. */
917 if (!set_pcap_linktype(pcap_h, interface_opts.linktype, interface_opts.name,
918 errmsg, sizeof errmsg,
919 secondary_errmsg, sizeof secondary_errmsg)) {
921 report_capture_error(errmsg, secondary_errmsg);
925 /* OK, try to compile the capture filter. */
926 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
927 interface_opts.cfilter)) {
929 report_cfilter_error(capture_opts, j, errmsg);
934 /* Now print the filter code. */
935 insn = fcode.bf_insns;
937 for (i = 0; i < fcode.bf_len; insn++, i++)
938 printf("%s\n", bpf_image(insn, i));
940 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
941 /* to remove any suid privileges. */
942 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
943 /* (euid/egid have already previously been set to ruid/rgid. */
944 /* (See comment in main() for details) */
946 relinquish_special_privs_perm();
948 relinquish_all_capabilities();
951 /* Let our parent know we succeeded. */
952 pipe_write_block(2, SP_SUCCESS, NULL);
959 * capture_interface_list() is expected to do the right thing to get
960 * a list of interfaces.
962 * In most of the programs in the Wireshark suite, "the right thing"
963 * is to run dumpcap and ask it for the list, because dumpcap may
964 * be the only program in the suite with enough privileges to get
967 * In dumpcap itself, however, we obviously can't run dumpcap to
968 * ask for the list. Therefore, our capture_interface_list() should
969 * just call get_interface_list().
972 capture_interface_list(int *err, char **err_str)
974 return get_interface_list(err, err_str);
978 * Get the data-link type for a libpcap device.
979 * This works around AIX 5.x's non-standard and incompatible-with-the-
980 * rest-of-the-universe libpcap.
983 get_pcap_linktype(pcap_t *pch, const char *devicename
991 const char *ifacename;
994 linktype = pcap_datalink(pch);
998 * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
999 * rather than DLT_ values for link-layer types; the ifType values
1000 * for LAN devices are:
1007 * and the ifType value for a loopback device is 24.
1009 * The AIX names for LAN devices begin with:
1016 * and the AIX names for loopback devices begin with "lo".
1018 * (The difference between "Ethernet" and "802.3" is presumably
1019 * whether packets have an Ethernet header, with a packet type,
1020 * or an 802.3 header, with a packet length, followed by an 802.2
1021 * header and possibly a SNAP header.)
1023 * If the device name matches "linktype" interpreted as an ifType
1024 * value, rather than as a DLT_ value, we will assume this is AIX's
1025 * non-standard, incompatible libpcap, rather than a standard libpcap,
1026 * and will map the link-layer type to the standard DLT_ value for
1027 * that link-layer type, as that's what the rest of Wireshark expects.
1029 * (This means the capture files won't be readable by a tcpdump
1030 * linked with AIX's non-standard libpcap, but so it goes. They
1031 * *will* be readable by standard versions of tcpdump, Wireshark,
1034 * XXX - if we conclude we're using AIX libpcap, should we also
1035 * set a flag to cause us to assume the time stamps are in
1036 * seconds-and-nanoseconds form, and to convert them to
1037 * seconds-and-microseconds form before processing them and
1042 * Find the last component of the device name, which is the
1045 ifacename = strchr(devicename, '/');
1046 if (ifacename == NULL)
1047 ifacename = devicename;
1049 /* See if it matches any of the LAN device names. */
1050 if (strncmp(ifacename, "en", 2) == 0) {
1051 if (linktype == 6) {
1053 * That's the RFC 1573 value for Ethernet; map it to DLT_EN10MB.
1057 } else if (strncmp(ifacename, "et", 2) == 0) {
1058 if (linktype == 7) {
1060 * That's the RFC 1573 value for 802.3; map it to DLT_EN10MB.
1061 * (libpcap, tcpdump, Wireshark, etc. don't care if it's Ethernet
1066 } else if (strncmp(ifacename, "tr", 2) == 0) {
1067 if (linktype == 9) {
1069 * That's the RFC 1573 value for 802.5 (Token Ring); map it to
1070 * DLT_IEEE802, which is what's used for Token Ring.
1074 } else if (strncmp(ifacename, "fi", 2) == 0) {
1075 if (linktype == 15) {
1077 * That's the RFC 1573 value for FDDI; map it to DLT_FDDI.
1081 } else if (strncmp(ifacename, "lo", 2) == 0) {
1082 if (linktype == 24) {
1084 * That's the RFC 1573 value for "software loopback" devices; map it
1085 * to DLT_NULL, which is what's used for loopback devices on BSD.
1095 static data_link_info_t *
1096 create_data_link_info(int dlt)
1098 data_link_info_t *data_link_info;
1101 data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
1102 data_link_info->dlt = dlt;
1103 text = pcap_datalink_val_to_name(dlt);
1105 data_link_info->name = g_strdup(text);
1107 data_link_info->name = g_strdup_printf("DLT %d", dlt);
1108 text = pcap_datalink_val_to_description(dlt);
1110 data_link_info->description = g_strdup(text);
1112 data_link_info->description = NULL;
1113 return data_link_info;
1117 * Get the capabilities of a network device.
1119 static if_capabilities_t *
1120 get_if_capabilities(const char *devicename, gboolean monitor_mode
1121 #ifndef HAVE_PCAP_CREATE
1126 if_capabilities_t *caps;
1127 char errbuf[PCAP_ERRBUF_SIZE];
1129 #ifdef HAVE_PCAP_CREATE
1133 #ifdef HAVE_PCAP_LIST_DATALINKS
1137 data_link_info_t *data_link_info;
1140 * Allocate the interface capabilities structure.
1142 caps = (if_capabilities_t *)g_malloc(sizeof *caps);
1145 * WinPcap 4.1.2, and possibly earlier versions, have a bug
1146 * wherein, when an open with an rpcap: URL fails, the error
1147 * message for the error is not copied to errbuf and whatever
1148 * on-the-stack junk is in errbuf is treated as the error
1151 * To work around that (and any other bugs of that sort, we
1152 * initialize errbuf to an empty string. If we get an error
1153 * and the string is empty, we report it as an unknown error.
1154 * (If we *don't* get an error, and the string is *non*-empty,
1155 * that could be a warning returned, such as "can't turn
1156 * promiscuous mode on"; we currently don't do so.)
1159 #ifdef HAVE_PCAP_OPEN
1160 pch = pcap_open(devicename, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1161 caps->can_set_rfmon = FALSE;
1163 if (err_str != NULL)
1164 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1168 #elif defined(HAVE_PCAP_CREATE)
1169 pch = pcap_create(devicename, errbuf);
1171 if (err_str != NULL)
1172 *err_str = g_strdup(errbuf);
1176 status = pcap_can_set_rfmon(pch);
1179 if (status == PCAP_ERROR)
1180 *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
1183 *err_str = g_strdup(pcap_statustostr(status));
1189 caps->can_set_rfmon = FALSE;
1190 else if (status == 1) {
1191 caps->can_set_rfmon = TRUE;
1193 pcap_set_rfmon(pch, 1);
1195 if (err_str != NULL) {
1196 *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
1204 status = pcap_activate(pch);
1206 /* Error. We ignore warnings (status > 0). */
1207 if (err_str != NULL) {
1208 if (status == PCAP_ERROR)
1209 *err_str = g_strdup_printf("pcap_activate() failed: %s",
1212 *err_str = g_strdup(pcap_statustostr(status));
1219 pch = pcap_open_live(devicename, MIN_PACKET_SIZE, 0, 0, errbuf);
1220 caps->can_set_rfmon = FALSE;
1222 if (err_str != NULL)
1223 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1228 deflt = get_pcap_linktype(pch, devicename);
1229 #ifdef HAVE_PCAP_LIST_DATALINKS
1230 nlt = pcap_list_datalinks(pch, &linktypes);
1231 if (nlt == 0 || linktypes == NULL) {
1233 if (err_str != NULL)
1234 *err_str = NULL; /* an empty list doesn't mean an error */
1238 caps->data_link_types = NULL;
1239 for (i = 0; i < nlt; i++) {
1240 data_link_info = create_data_link_info(linktypes[i]);
1243 * XXX - for 802.11, make the most detailed 802.11
1244 * version the default, rather than the one the
1245 * device has as the default?
1247 if (linktypes[i] == deflt)
1248 caps->data_link_types = g_list_prepend(caps->data_link_types,
1251 caps->data_link_types = g_list_append(caps->data_link_types,
1254 #ifdef HAVE_PCAP_FREE_DATALINKS
1255 pcap_free_datalinks(linktypes);
1258 * In Windows, there's no guarantee that if you have a library
1259 * built with one version of the MSVC++ run-time library, and
1260 * it returns a pointer to allocated data, you can free that
1261 * data from a program linked with another version of the
1262 * MSVC++ run-time library.
1264 * This is not an issue on UN*X.
1266 * See the mail threads starting at
1268 * http://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
1272 * http://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
1275 #define xx_free free /* hack so checkAPIs doesn't complain */
1278 #endif /* HAVE_PCAP_FREE_DATALINKS */
1279 #else /* HAVE_PCAP_LIST_DATALINKS */
1281 data_link_info = create_data_link_info(deflt);
1282 caps->data_link_types = g_list_append(caps->data_link_types,
1284 #endif /* HAVE_PCAP_LIST_DATALINKS */
1288 if (err_str != NULL)
1293 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
1295 * Output a machine readable list of the interfaces
1296 * This list is retrieved by the sync_interface_list_open() function
1297 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
1300 print_machine_readable_interfaces(GList *if_list)
1307 char addr_str[ADDRSTRLEN];
1309 if (capture_child) {
1310 /* Let our parent know we succeeded. */
1311 pipe_write_block(2, SP_SUCCESS, NULL);
1314 i = 1; /* Interface id number */
1315 for (if_entry = g_list_first(if_list); if_entry != NULL;
1316 if_entry = g_list_next(if_entry)) {
1317 if_info = (if_info_t *)if_entry->data;
1318 printf("%d. %s", i++, if_info->name);
1321 * Print the contents of the if_entry struct in a parseable format.
1322 * Each if_entry element is tab-separated. Addresses are comma-
1325 /* XXX - Make sure our description doesn't contain a tab */
1326 if (if_info->vendor_description != NULL)
1327 printf("\t%s\t", if_info->vendor_description);
1331 /* XXX - Make sure our friendly name doesn't contain a tab */
1332 if (if_info->friendly_name != NULL)
1333 printf("%s\t", if_info->friendly_name);
1337 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
1338 addr = g_slist_next(addr)) {
1339 if (addr != g_slist_nth(if_info->addrs, 0))
1342 if_addr = (if_addr_t *)addr->data;
1343 switch(if_addr->ifat_type) {
1345 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
1347 printf("%s", addr_str);
1349 printf("<unknown IPv4>");
1353 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
1354 addr_str, ADDRSTRLEN)) {
1355 printf("%s", addr_str);
1357 printf("<unknown IPv6>");
1361 printf("<type unknown %u>", if_addr->ifat_type);
1365 if (if_info->loopback)
1366 printf("\tloopback");
1368 printf("\tnetwork");
1375 * If you change the machine-readable output format of this function,
1376 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
1379 print_machine_readable_if_capabilities(if_capabilities_t *caps)
1382 data_link_info_t *data_link_info;
1383 const gchar *desc_str;
1385 if (capture_child) {
1386 /* Let our parent know we succeeded. */
1387 pipe_write_block(2, SP_SUCCESS, NULL);
1390 if (caps->can_set_rfmon)
1394 for (lt_entry = caps->data_link_types; lt_entry != NULL;
1395 lt_entry = g_list_next(lt_entry)) {
1396 data_link_info = (data_link_info_t *)lt_entry->data;
1397 if (data_link_info->description != NULL)
1398 desc_str = data_link_info->description;
1400 desc_str = "(not supported)";
1401 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
1411 /* Print the number of packets captured for each interface until we're killed. */
1413 print_statistics_loop(gboolean machine_readable)
1415 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1421 char errbuf[PCAP_ERRBUF_SIZE];
1422 struct pcap_stat ps;
1424 if_list = get_interface_list(&err, &err_str);
1425 if (if_list == NULL) {
1427 case CANT_GET_INTERFACE_LIST:
1428 case DONT_HAVE_PCAP:
1429 cmdarg_err("%s", err_str);
1433 case NO_INTERFACES_FOUND:
1434 cmdarg_err("There are no interfaces on which a capture can be done");
1440 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1441 if_info = (if_info_t *)if_entry->data;
1442 #ifdef HAVE_PCAP_OPEN
1443 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1445 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1449 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
1450 if_stat->name = g_strdup(if_info->name);
1452 stat_list = g_list_append(stat_list, if_stat);
1457 cmdarg_err("There are no interfaces on which a capture can be done");
1461 if (capture_child) {
1462 /* Let our parent know we succeeded. */
1463 pipe_write_block(2, SP_SUCCESS, NULL);
1466 if (!machine_readable) {
1467 printf("%-15s %10s %10s\n", "Interface", "Received",
1471 global_ld.go = TRUE;
1472 while (global_ld.go) {
1473 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1474 if_stat = (if_stat_t *)stat_entry->data;
1475 pcap_stats(if_stat->pch, &ps);
1477 if (!machine_readable) {
1478 printf("%-15s %10u %10u\n", if_stat->name,
1479 ps.ps_recv, ps.ps_drop);
1481 printf("%s\t%u\t%u\n", if_stat->name,
1482 ps.ps_recv, ps.ps_drop);
1493 /* XXX - Not reached. Should we look for 'q' in stdin? */
1494 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1495 if_stat = (if_stat_t *)stat_entry->data;
1496 pcap_close(if_stat->pch);
1497 g_free(if_stat->name);
1500 g_list_free(stat_list);
1501 free_interface_list(if_list);
1509 capture_cleanup_handler(DWORD dwCtrlType)
1511 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1512 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1513 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1514 like SIGTERM at least when the machine's shutting down.
1516 For now, if we're running as a command rather than a capture child,
1517 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1518 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1519 in that way on UN*X.
1521 If we're not running as a capture child, we might be running as
1522 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1523 user logs out. (XXX - can we explicitly check whether we're
1524 running as a service?) */
1526 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1527 "Console: Control signal");
1528 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1529 "Console: Control signal, CtrlType: %u", dwCtrlType);
1531 /* Keep capture running if we're a service and a user logs off */
1532 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1533 capture_loop_stop();
1541 capture_cleanup_handler(int signum _U_)
1543 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1544 SIGTERM. We assume that if the user wanted it to keep running
1545 after they logged out, they'd have nohupped it. */
1547 /* Note: don't call g_log() in the signal handler: if we happened to be in
1548 * g_log() in process context when the signal came in, g_log will detect
1549 * the "recursion" and abort.
1552 capture_loop_stop();
1558 report_capture_count(gboolean reportit)
1560 /* Don't print this if we're a capture child. */
1561 if (!capture_child && reportit) {
1562 fprintf(stderr, "\rPackets captured: %u\n", global_ld.packet_count);
1563 /* stderr could be line buffered */
1571 report_counts_for_siginfo(void)
1573 report_capture_count(quiet);
1574 infoprint = FALSE; /* we just reported it */
1578 report_counts_siginfo(int signum _U_)
1580 int sav_errno = errno;
1582 /* If we've been told to delay printing, just set a flag asking
1583 that we print counts (if we're supposed to), otherwise print
1584 the count of packets captured (if we're supposed to). */
1588 report_counts_for_siginfo();
1591 #endif /* SIGINFO */
1594 exit_main(int status)
1597 /* Shutdown windows sockets */
1600 /* can be helpful for debugging */
1601 #ifdef DEBUG_DUMPCAP
1602 printf("Press any key\n");
1613 * If we were linked with libcap (not related to libpcap), make sure we have
1614 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1615 * (See comment in main() for details)
1618 relinquish_privs_except_capture(void)
1620 /* If 'started_with_special_privs' (ie: suid) then enable for
1621 * ourself the NET_ADMIN and NET_RAW capabilities and then
1622 * drop our suid privileges.
1624 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1625 * stuff we don't need (and shouldn't have).
1626 * CAP_NET_RAW: Packet capture (raw sockets).
1629 if (started_with_special_privs()) {
1630 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1631 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1633 cap_t caps = cap_init(); /* all capabilities initialized to off */
1635 print_caps("Pre drop, pre set");
1637 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1638 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1641 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1642 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1644 if (cap_set_proc(caps)) {
1645 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1647 print_caps("Pre drop, post set");
1649 relinquish_special_privs_perm();
1651 print_caps("Post drop, pre set");
1652 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1653 if (cap_set_proc(caps)) {
1654 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1656 print_caps("Post drop, post set");
1662 #endif /* HAVE_LIBCAP */
1664 /* Take care of byte order in the libpcap headers read from pipes.
1665 * (function taken from wiretap/libpcap.c) */
1667 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1670 /* Byte-swap the record header fields. */
1671 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
1672 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
1673 rechdr->incl_len = BSWAP32(rechdr->incl_len);
1674 rechdr->orig_len = BSWAP32(rechdr->orig_len);
1677 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1678 swapped, in order to match the BPF header layout.
1680 Unfortunately, some files were, according to a comment in the "libpcap"
1681 source, written with version 2.3 in their headers but without the
1682 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1683 would make no sense - we assume that we need to swap them. */
1684 if (hdr->version_major == 2 &&
1685 (hdr->version_minor < 3 ||
1686 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1689 temp = rechdr->orig_len;
1690 rechdr->orig_len = rechdr->incl_len;
1691 rechdr->incl_len = temp;
1695 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1699 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1703 return recv(pipe_fd, buf, (int)sz, 0);
1708 return ws_read(pipe_fd, buf, sz);
1714 * Thread function that reads from a pipe and pushes the data
1715 * to the main application thread.
1718 * XXX Right now we use async queues for basic signaling. The main thread
1719 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1720 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1721 * Iff the read is successful cap_pipe_read pushes an item onto
1722 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1723 * the queues themselves (yet).
1725 * We might want to move some of the cap_pipe_dispatch logic here so that
1726 * we can let cap_thread_read run independently, queuing up multiple reads
1727 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1729 static void *cap_thread_read(void *arg)
1731 pcap_options *pcap_opts;
1734 DWORD b, last_err, bytes_read;
1740 pcap_opts = (pcap_options *)arg;
1741 while (pcap_opts->cap_pipe_err == PIPOK) {
1742 g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1743 g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1745 while (bytes_read < pcap_opts->cap_pipe_bytes_to_read) {
1746 if ((pcap_opts->from_cap_socket)
1752 b = cap_pipe_read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1753 pcap_opts->cap_pipe_bytes_to_read - bytes_read, pcap_opts->from_cap_socket);
1756 pcap_opts->cap_pipe_err = PIPEOF;
1760 pcap_opts->cap_pipe_err = PIPERR;
1771 /* If we try to use read() on a named pipe on Windows with partial
1772 * data it appears to return EOF.
1774 res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1775 pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1780 last_err = GetLastError();
1781 if (last_err == ERROR_MORE_DATA) {
1783 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1784 pcap_opts->cap_pipe_err = PIPEOF;
1788 pcap_opts->cap_pipe_err = PIPERR;
1791 } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1792 pcap_opts->cap_pipe_err = PIPEOF;
1799 pcap_opts->cap_pipe_bytes_read = bytes_read;
1800 if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1801 g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1803 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1809 /* Provide select() functionality for a single file descriptor
1810 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1812 * Returns the same values as select.
1815 cap_pipe_select(int pipe_fd)
1818 struct timeval timeout;
1821 FD_SET(pipe_fd, &rfds);
1823 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1824 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1826 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1829 #define DEF_TCP_PORT 19000
1832 cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errmsgl)
1834 char *sockname = pipename + 4;
1835 struct sockaddr_in sa;
1842 memset(&sa, 0, sizeof(sa));
1844 p = strchr(sockname, ':');
1846 len = strlen(sockname);
1847 port = DEF_TCP_PORT;
1851 port = strtoul(p + 1, &p, 10);
1852 if (*p || port > 65535) {
1861 strncpy(buf, sockname, len);
1863 if (!inet_pton(AF_INET, buf, &sa.sin_addr)) {
1867 sa.sin_family = AF_INET;
1868 sa.sin_port = htons((u_short)port);
1870 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1871 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1873 LPTSTR errorText = NULL;
1876 lastError = WSAGetLastError();
1877 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1878 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1879 FORMAT_MESSAGE_IGNORE_INSERTS,
1880 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1881 (LPTSTR)&errorText, 0, NULL);
1883 g_snprintf(errmsg, errmsgl,
1884 "The capture session could not be initiated due to the socket error: \n"
1886 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
1888 LocalFree(errorText);
1890 " %d: %s", errno, strerror(errno));
1892 pcap_opts->cap_pipe_err = PIPERR;
1895 cap_pipe_close(fd, TRUE);
1899 pcap_opts->from_cap_socket = TRUE;
1903 g_snprintf(errmsg, errmsgl,
1904 "The capture session could not be initiated because\n"
1905 "\"%s\" is not a valid socket specification", pipename);
1906 pcap_opts->cap_pipe_err = PIPERR;
1910 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1914 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1918 closesocket(pipe_fd);
1925 /* Mimic pcap_open_live() for pipe captures
1927 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1928 * open it, and read the header.
1930 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1931 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1933 cap_pipe_open_live(char *pipename,
1934 pcap_options *pcap_opts,
1935 struct pcap_hdr *hdr,
1936 char *errmsg, int errmsgl)
1939 ws_statb64 pipe_stat;
1940 struct sockaddr_un sa;
1950 pcap_opts->cap_pipe_fd = -1;
1952 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
1954 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1957 * XXX - this blocks until a pcap per-file header has been written to
1958 * the pipe, so it could block indefinitely.
1960 if (strcmp(pipename, "-") == 0) {
1962 fd = 0; /* read from stdin */
1964 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1966 } else if (!strncmp(pipename, "TCP@", 4)) {
1967 if ((fd = cap_open_socket(pipename, pcap_opts, errmsg, errmsgl)) < 0) {
1972 if (ws_stat64(pipename, &pipe_stat) < 0) {
1973 if (errno == ENOENT || errno == ENOTDIR)
1974 pcap_opts->cap_pipe_err = PIPNEXIST;
1976 g_snprintf(errmsg, errmsgl,
1977 "The capture session could not be initiated "
1978 "due to error getting information on pipe/socket: %s", g_strerror(errno));
1979 pcap_opts->cap_pipe_err = PIPERR;
1983 if (S_ISFIFO(pipe_stat.st_mode)) {
1984 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1986 g_snprintf(errmsg, errmsgl,
1987 "The capture session could not be initiated "
1988 "due to error on pipe open: %s", g_strerror(errno));
1989 pcap_opts->cap_pipe_err = PIPERR;
1992 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1993 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1995 g_snprintf(errmsg, errmsgl,
1996 "The capture session could not be initiated "
1997 "due to error on socket create: %s", g_strerror(errno));
1998 pcap_opts->cap_pipe_err = PIPERR;
2001 sa.sun_family = AF_UNIX;
2003 * The Single UNIX Specification says:
2005 * The size of sun_path has intentionally been left undefined.
2006 * This is because different implementations use different sizes.
2007 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
2008 * of 104. Since most implementations originate from BSD versions,
2009 * the size is typically in the range 92 to 108.
2011 * Applications should not assume a particular length for sun_path
2012 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
2016 * The <sys/un.h> header shall define the sockaddr_un structure,
2017 * which shall include at least the following members:
2019 * sa_family_t sun_family Address family.
2020 * char sun_path[] Socket pathname.
2022 * so we assume that it's an array, with a specified size,
2023 * and that the size reflects the maximum path length.
2025 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
2026 /* Path name too long */
2027 g_snprintf(errmsg, errmsgl,
2028 "The capture session coud not be initiated "
2029 "due to error on socket connect: Path name too long");
2030 pcap_opts->cap_pipe_err = PIPERR;
2034 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
2036 g_snprintf(errmsg, errmsgl,
2037 "The capture session coud not be initiated "
2038 "due to error on socket connect: %s", g_strerror(errno));
2039 pcap_opts->cap_pipe_err = PIPERR;
2044 if (S_ISCHR(pipe_stat.st_mode)) {
2046 * Assume the user specified an interface on a system where
2047 * interfaces are in /dev. Pretend we haven't seen it.
2049 pcap_opts->cap_pipe_err = PIPNEXIST;
2051 g_snprintf(errmsg, errmsgl,
2052 "The capture session could not be initiated because\n"
2053 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
2054 pcap_opts->cap_pipe_err = PIPERR;
2059 #define PIPE_STR "\\pipe\\"
2060 /* Under Windows, named pipes _must_ have the form
2061 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
2063 pncopy = g_strdup(pipename);
2064 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
2065 pos = strchr(pncopy + 3, '\\');
2066 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
2073 g_snprintf(errmsg, errmsgl,
2074 "The capture session could not be initiated because\n"
2075 "\"%s\" is neither an interface nor a pipe", pipename);
2076 pcap_opts->cap_pipe_err = PIPNEXIST;
2080 /* Wait for the pipe to appear */
2082 pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
2083 OPEN_EXISTING, 0, NULL);
2085 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
2088 if (GetLastError() != ERROR_PIPE_BUSY) {
2089 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2090 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2091 g_snprintf(errmsg, errmsgl,
2092 "The capture session on \"%s\" could not be started "
2093 "due to error on pipe open: %s (error %d)",
2094 pipename, utf_16to8(err_str), GetLastError());
2096 pcap_opts->cap_pipe_err = PIPERR;
2100 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
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\" timed out during "
2105 "pipe open: %s (error %d)",
2106 pipename, utf_16to8(err_str), GetLastError());
2108 pcap_opts->cap_pipe_err = PIPERR;
2115 pcap_opts->from_cap_pipe = TRUE;
2118 if (pcap_opts->from_cap_socket)
2121 /* read the pcap header */
2123 while (bytes_read < sizeof magic) {
2124 sel_ret = cap_pipe_select(fd);
2126 g_snprintf(errmsg, errmsgl,
2127 "Unexpected error from select: %s", g_strerror(errno));
2129 } else if (sel_ret > 0) {
2130 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
2131 sizeof magic-bytes_read,
2132 pcap_opts->from_cap_socket);
2135 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2137 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2147 #if GLIB_CHECK_VERSION(2,31,0)
2148 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_opts);
2150 g_thread_create(&cap_thread_read, pcap_opts, FALSE, NULL);
2153 pcap_opts->cap_pipe_buf = (char *) &magic;
2154 pcap_opts->cap_pipe_bytes_read = 0;
2155 pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
2156 /* We don't have to worry about cap_pipe_read_mtx here */
2157 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2158 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2159 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2160 if (pcap_opts->cap_pipe_bytes_read == 0)
2161 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2163 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2172 case PCAP_NSEC_MAGIC:
2173 /* Host that wrote it has our byte order, and was running
2174 a program using either standard or ss990417 libpcap. */
2175 pcap_opts->cap_pipe_byte_swapped = FALSE;
2176 pcap_opts->cap_pipe_modified = FALSE;
2177 pcap_opts->ts_nsec = magic == PCAP_NSEC_MAGIC;
2179 case PCAP_MODIFIED_MAGIC:
2180 /* Host that wrote it has our byte order, but was running
2181 a program using either ss990915 or ss991029 libpcap. */
2182 pcap_opts->cap_pipe_byte_swapped = FALSE;
2183 pcap_opts->cap_pipe_modified = TRUE;
2185 case PCAP_SWAPPED_MAGIC:
2186 case PCAP_SWAPPED_NSEC_MAGIC:
2187 /* Host that wrote it has a byte order opposite to ours,
2188 and was running a program using either standard or
2189 ss990417 libpcap. */
2190 pcap_opts->cap_pipe_byte_swapped = TRUE;
2191 pcap_opts->cap_pipe_modified = FALSE;
2192 pcap_opts->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
2194 case PCAP_SWAPPED_MODIFIED_MAGIC:
2195 /* Host that wrote it out has a byte order opposite to
2196 ours, and was running a program using either ss990915
2197 or ss991029 libpcap. */
2198 pcap_opts->cap_pipe_byte_swapped = TRUE;
2199 pcap_opts->cap_pipe_modified = TRUE;
2202 /* Not a "libpcap" type we know about. */
2203 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
2208 if (pcap_opts->from_cap_socket)
2211 /* Read the rest of the header */
2213 while (bytes_read < sizeof(struct pcap_hdr)) {
2214 sel_ret = cap_pipe_select(fd);
2216 g_snprintf(errmsg, errmsgl,
2217 "Unexpected error from select: %s", g_strerror(errno));
2219 } else if (sel_ret > 0) {
2220 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
2221 sizeof(struct pcap_hdr) - bytes_read,
2222 pcap_opts->from_cap_socket);
2225 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2227 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
2237 pcap_opts->cap_pipe_buf = (char *) hdr;
2238 pcap_opts->cap_pipe_bytes_read = 0;
2239 pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
2240 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2241 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2242 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2243 if (pcap_opts->cap_pipe_bytes_read == 0)
2244 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2246 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
2253 if (pcap_opts->cap_pipe_byte_swapped) {
2254 /* Byte-swap the header fields about which we care. */
2255 hdr->version_major = BSWAP16(hdr->version_major);
2256 hdr->version_minor = BSWAP16(hdr->version_minor);
2257 hdr->snaplen = BSWAP32(hdr->snaplen);
2258 hdr->network = BSWAP32(hdr->network);
2260 pcap_opts->linktype = hdr->network;
2262 if (hdr->version_major < 2) {
2263 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
2267 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2268 pcap_opts->cap_pipe_err = PIPOK;
2269 pcap_opts->cap_pipe_fd = fd;
2273 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
2274 pcap_opts->cap_pipe_err = PIPERR;
2275 cap_pipe_close(fd, pcap_opts->from_cap_socket);
2276 pcap_opts->cap_pipe_fd = -1;
2280 /* We read one record from the pipe, take care of byte order in the record
2281 * header, write the record to the capture file, and update capture statistics. */
2283 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
2285 struct pcap_pkthdr phdr;
2286 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2289 #if !GLIB_CHECK_VERSION(2,31,18)
2297 #ifdef LOG_CAPTURE_VERBOSE
2298 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
2301 switch (pcap_opts->cap_pipe_state) {
2303 case STATE_EXPECT_REC_HDR:
2305 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2308 pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
2309 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
2310 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2311 pcap_opts->cap_pipe_bytes_read = 0;
2314 pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
2315 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2316 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2321 case STATE_READ_REC_HDR:
2323 if (pcap_opts->from_cap_socket)
2326 b = cap_pipe_read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
2327 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
2330 result = PD_PIPE_EOF;
2332 result = PD_PIPE_ERR;
2335 pcap_opts->cap_pipe_bytes_read += b;
2339 #if GLIB_CHECK_VERSION(2,31,18)
2340 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2342 g_get_current_time(&wait_time);
2343 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2344 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2346 if (pcap_opts->cap_pipe_err == PIPEOF) {
2347 result = PD_PIPE_EOF;
2349 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2350 result = PD_PIPE_ERR;
2358 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2360 result = PD_REC_HDR_READ;
2363 case STATE_EXPECT_DATA:
2365 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2368 pcap_opts->cap_pipe_state = STATE_READ_DATA;
2369 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2370 pcap_opts->cap_pipe_bytes_read = 0;
2373 pcap_opts->cap_pipe_buf = (char *) data;
2374 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2375 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2380 case STATE_READ_DATA:
2382 if (pcap_opts->from_cap_socket)
2385 b = cap_pipe_read(pcap_opts->cap_pipe_fd,
2386 data+pcap_opts->cap_pipe_bytes_read,
2387 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read,
2388 pcap_opts->from_cap_socket);
2391 result = PD_PIPE_EOF;
2393 result = PD_PIPE_ERR;
2396 pcap_opts->cap_pipe_bytes_read += b;
2401 #if GLIB_CHECK_VERSION(2,31,18)
2402 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2404 g_get_current_time(&wait_time);
2405 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2406 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2407 #endif /* GLIB_CHECK_VERSION(2,31,18) */
2408 if (pcap_opts->cap_pipe_err == PIPEOF) {
2409 result = PD_PIPE_EOF;
2411 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2412 result = PD_PIPE_ERR;
2420 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2422 result = PD_DATA_READ;
2426 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2429 } /* switch (pcap_opts->cap_pipe_state) */
2432 * We've now read as much data as we were expecting, so process it.
2436 case PD_REC_HDR_READ:
2437 /* We've read the header. Take care of byte order. */
2438 cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
2439 &pcap_opts->cap_pipe_rechdr.hdr);
2440 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2441 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2442 ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
2446 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2447 pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2450 /* no data to read? fall through */
2453 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2454 phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2455 phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2456 phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2457 phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2460 capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2462 capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2464 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2468 pcap_opts->cap_pipe_err = PIPEOF;
2473 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2474 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2475 g_snprintf(errmsg, errmsgl,
2476 "Error reading from pipe: %s (error %d)",
2477 utf_16to8(err_str), GetLastError());
2480 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2488 pcap_opts->cap_pipe_err = PIPERR;
2489 /* Return here rather than inside the switch to prevent GCC warning */
2494 /** Open the capture input file (pcap or capture pipe).
2495 * Returns TRUE if it succeeds, FALSE otherwise. */
2497 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2498 char *errmsg, size_t errmsg_len,
2499 char *secondary_errmsg, size_t secondary_errmsg_len)
2501 gchar open_err_str[PCAP_ERRBUF_SIZE];
2502 gchar *sync_msg_str;
2503 interface_options interface_opts;
2504 pcap_options *pcap_opts;
2508 gchar *sync_secondary_msg_str;
2509 WORD wVersionRequested;
2513 /* XXX - opening Winsock on tshark? */
2515 /* Initialize Windows Socket if we are in a WIN32 OS
2516 This needs to be done before querying the interface for network/netmask */
2518 /* XXX - do we really require 1.1 or earlier?
2519 Are there any versions that support only 2.0 or higher? */
2520 wVersionRequested = MAKEWORD(1, 1);
2521 err = WSAStartup(wVersionRequested, &wsaData);
2525 case WSASYSNOTREADY:
2526 g_snprintf(errmsg, (gulong) errmsg_len,
2527 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2530 case WSAVERNOTSUPPORTED:
2531 g_snprintf(errmsg, (gulong) errmsg_len,
2532 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2533 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2536 case WSAEINPROGRESS:
2537 g_snprintf(errmsg, (gulong) errmsg_len,
2538 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2542 g_snprintf(errmsg, (gulong) errmsg_len,
2543 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2547 g_snprintf(errmsg, (gulong) errmsg_len,
2548 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2552 g_snprintf(errmsg, (gulong) errmsg_len,
2553 "Couldn't initialize Windows Sockets: error %d", err);
2556 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2560 if ((use_threads == FALSE) &&
2561 (capture_opts->ifaces->len > 1)) {
2562 g_snprintf(errmsg, (gulong) errmsg_len,
2563 "Using threads is required for capturing on multiple interfaces!");
2567 for (i = 0; i < capture_opts->ifaces->len; i++) {
2568 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2569 pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2570 if (pcap_opts == NULL) {
2571 g_snprintf(errmsg, (gulong) errmsg_len,
2572 "Could not allocate memory.");
2575 pcap_opts->received = 0;
2576 pcap_opts->dropped = 0;
2577 pcap_opts->flushed = 0;
2578 pcap_opts->pcap_h = NULL;
2579 #ifdef MUST_DO_SELECT
2580 pcap_opts->pcap_fd = -1;
2582 pcap_opts->pcap_err = FALSE;
2583 pcap_opts->interface_id = i;
2584 pcap_opts->tid = NULL;
2585 pcap_opts->snaplen = 0;
2586 pcap_opts->linktype = -1;
2587 pcap_opts->ts_nsec = FALSE;
2588 pcap_opts->from_cap_pipe = FALSE;
2589 pcap_opts->from_cap_socket = FALSE;
2590 memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2591 memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2593 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2595 pcap_opts->cap_pipe_fd = -1;
2596 pcap_opts->cap_pipe_modified = FALSE;
2597 pcap_opts->cap_pipe_byte_swapped = FALSE;
2599 pcap_opts->cap_pipe_buf = NULL;
2601 pcap_opts->cap_pipe_bytes_to_read = 0;
2602 pcap_opts->cap_pipe_bytes_read = 0;
2603 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2604 pcap_opts->cap_pipe_err = PIPOK;
2606 #if GLIB_CHECK_VERSION(2,31,0)
2607 pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2608 g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2610 pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2612 pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2613 pcap_opts->cap_pipe_done_q = g_async_queue_new();
2615 g_array_append_val(ld->pcaps, pcap_opts);
2617 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2618 pcap_opts->pcap_h = open_capture_device(&interface_opts, &open_err_str);
2620 if (pcap_opts->pcap_h != NULL) {
2621 /* we've opened "iface" as a network device */
2623 /* try to set the capture buffer size */
2624 if (interface_opts.buffer_size > 1 &&
2625 pcap_setbuff(pcap_opts->pcap_h, interface_opts.buffer_size * 1024 * 1024) != 0) {
2626 sync_secondary_msg_str = g_strdup_printf(
2627 "The capture buffer size of %dMB seems to be too high for your machine,\n"
2628 "the default of 1MB will be used.\n"
2630 "Nonetheless, the capture is started.\n",
2631 interface_opts.buffer_size);
2632 report_capture_error("Couldn't set the capture buffer size!",
2633 sync_secondary_msg_str);
2634 g_free(sync_secondary_msg_str);
2638 #if defined(HAVE_PCAP_SETSAMPLING)
2639 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2640 struct pcap_samp *samp;
2642 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2643 switch (interface_opts.sampling_method) {
2644 case CAPTURE_SAMP_BY_COUNT:
2645 samp->method = PCAP_SAMP_1_EVERY_N;
2648 case CAPTURE_SAMP_BY_TIMER:
2649 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2653 sync_msg_str = g_strdup_printf(
2654 "Unknown sampling method %d specified,\n"
2655 "continue without packet sampling",
2656 interface_opts.sampling_method);
2657 report_capture_error("Couldn't set the capture "
2658 "sampling", sync_msg_str);
2659 g_free(sync_msg_str);
2661 samp->value = interface_opts.sampling_param;
2663 report_capture_error("Couldn't set the capture sampling",
2664 "Cannot get packet sampling data structure");
2669 /* setting the data link type only works on real interfaces */
2670 if (!set_pcap_linktype(pcap_opts->pcap_h, interface_opts.linktype, interface_opts.name,
2672 secondary_errmsg, secondary_errmsg_len)) {
2675 pcap_opts->linktype = get_pcap_linktype(pcap_opts->pcap_h, interface_opts.name);
2677 /* We couldn't open "iface" as a network device. */
2678 /* Try to open it as a pipe */
2679 cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2682 if (pcap_opts->cap_pipe_fd == -1) {
2684 if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2686 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2687 /* Pipe doesn't exist, so output message for interface */
2688 get_capture_device_open_failure_messages(open_err_str,
2689 interface_opts.name,
2693 secondary_errmsg_len);
2696 * Else pipe (or file) does exist and cap_pipe_open_live() has
2701 /* cap_pipe_open_live() succeeded; don't want
2702 error message from pcap_open_live() */
2703 open_err_str[0] = '\0';
2707 /* XXX - will this work for tshark? */
2708 #ifdef MUST_DO_SELECT
2709 if (!pcap_opts->from_cap_pipe) {
2710 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2711 pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2713 pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2718 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2719 returned a warning; print it, but keep capturing. */
2720 if (open_err_str[0] != '\0') {
2721 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2722 report_capture_error(sync_msg_str, "");
2723 g_free(sync_msg_str);
2725 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2726 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2729 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2730 /* to remove any suid privileges. */
2731 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2732 /* (euid/egid have already previously been set to ruid/rgid. */
2733 /* (See comment in main() for details) */
2735 relinquish_special_privs_perm();
2737 relinquish_all_capabilities();
2742 /* close the capture input file (pcap or capture pipe) */
2743 static void capture_loop_close_input(loop_data *ld)
2746 pcap_options *pcap_opts;
2748 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2750 for (i = 0; i < ld->pcaps->len; i++) {
2751 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2752 /* if open, close the capture pipe "input file" */
2753 if (pcap_opts->cap_pipe_fd >= 0) {
2754 g_assert(pcap_opts->from_cap_pipe);
2755 cap_pipe_close(pcap_opts->cap_pipe_fd, pcap_opts->from_cap_socket);
2756 pcap_opts->cap_pipe_fd = -1;
2759 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2760 CloseHandle(pcap_opts->cap_pipe_h);
2761 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2764 /* if open, close the pcap "input file" */
2765 if (pcap_opts->pcap_h != NULL) {
2766 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2767 pcap_close(pcap_opts->pcap_h);
2768 pcap_opts->pcap_h = NULL;
2775 /* Shut down windows sockets */
2781 /* init the capture filter */
2782 static initfilter_status_t
2783 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2784 const gchar * name, const gchar * cfilter)
2786 struct bpf_program fcode;
2788 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2790 /* capture filters only work on real interfaces */
2791 if (cfilter && !from_cap_pipe) {
2792 /* A capture filter was specified; set it up. */
2793 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2794 /* Treat this specially - our caller might try to compile this
2795 as a display filter and, if that succeeds, warn the user that
2796 the display and capture filter syntaxes are different. */
2797 return INITFILTER_BAD_FILTER;
2799 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2800 #ifdef HAVE_PCAP_FREECODE
2801 pcap_freecode(&fcode);
2803 return INITFILTER_OTHER_ERROR;
2805 #ifdef HAVE_PCAP_FREECODE
2806 pcap_freecode(&fcode);
2810 return INITFILTER_NO_ERROR;
2814 /* set up to write to the already-opened capture output file/files */
2816 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2820 pcap_options *pcap_opts;
2821 interface_options interface_opts;
2822 gboolean successful;
2824 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2826 if ((capture_opts->use_pcapng == FALSE) &&
2827 (capture_opts->ifaces->len > 1)) {
2828 g_snprintf(errmsg, errmsg_len,
2829 "Using PCAPNG is required for capturing on multiple interfaces! Use the -n option.");
2833 /* Set up to write to the capture file. */
2834 if (capture_opts->multi_files_on) {
2835 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2837 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2838 if (ld->pdh == NULL) {
2843 if (capture_opts->use_pcapng) {
2845 GString *os_info_str;
2847 os_info_str = g_string_new("");
2848 get_os_version_info(os_info_str);
2850 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2851 successful = libpcap_write_session_header_block(libpcap_write_to_file, ld->pdh,
2854 os_info_str->str, /* OS*/
2856 -1, /* section_length */
2860 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2861 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2862 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2863 if (pcap_opts->from_cap_pipe) {
2864 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2866 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2868 successful = libpcap_write_interface_description_block(libpcap_write_to_file, global_ld.pdh,
2869 NULL, /* OPT_COMMENT 1 */
2870 interface_opts.name, /* IDB_NAME 2 */
2871 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2872 interface_opts.cfilter, /* IDB_FILTER 11 */
2873 os_info_str->str, /* IDB_OS 12 */
2874 pcap_opts->linktype,
2876 &(global_ld.bytes_written),
2877 0, /* IDB_IF_SPEED 8 */
2878 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2882 g_string_free(os_info_str, TRUE);
2885 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
2886 if (pcap_opts->from_cap_pipe) {
2887 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2889 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2891 successful = libpcap_write_file_header(libpcap_write_to_file, ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
2892 pcap_opts->ts_nsec, &ld->bytes_written, &err);
2900 if (ld->pdh == NULL) {
2901 /* We couldn't set up to write to the capture file. */
2902 /* XXX - use cf_open_error_message from tshark instead? */
2907 g_snprintf(errmsg, errmsg_len,
2908 "The file to which the capture would be"
2909 " saved (\"%s\") could not be opened: Error %d.",
2910 capture_opts->save_file, err);
2912 g_snprintf(errmsg, errmsg_len,
2913 "The file to which the capture would be"
2914 " saved (\"%s\") could not be opened: %s.",
2915 capture_opts->save_file, g_strerror(err));
2927 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2931 pcap_options *pcap_opts;
2932 guint64 end_time = create_timestamp();
2934 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2936 if (capture_opts->multi_files_on) {
2937 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2939 if (capture_opts->use_pcapng) {
2940 for (i = 0; i < global_ld.pcaps->len; i++) {
2941 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2942 if (!pcap_opts->from_cap_pipe) {
2943 guint64 isb_ifrecv, isb_ifdrop;
2944 struct pcap_stat stats;
2946 if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
2947 isb_ifrecv = pcap_opts->received;
2948 isb_ifdrop = stats.ps_drop + pcap_opts->dropped + pcap_opts->flushed;
2950 isb_ifrecv = G_MAXUINT64;
2951 isb_ifdrop = G_MAXUINT64;
2953 libpcap_write_interface_statistics_block(libpcap_write_to_file, ld->pdh,
2956 "Counters provided by dumpcap",
2965 if (fclose(ld->pdh) == EOF) {
2966 if (err_close != NULL) {
2976 /* dispatch incoming packets (pcap or capture pipe)
2978 * Waits for incoming packets to be available, and calls pcap_dispatch()
2979 * to cause them to be processed.
2981 * Returns the number of packets which were processed.
2983 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2984 * packet-batching behaviour does not cause packets to get held back
2988 capture_loop_dispatch(loop_data *ld,
2989 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
2992 gint packet_count_before;
2993 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
2998 packet_count_before = ld->packet_count;
2999 if (pcap_opts->from_cap_pipe) {
3000 /* dispatch from capture pipe */
3001 #ifdef LOG_CAPTURE_VERBOSE
3002 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
3005 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
3007 if (sel_ret < 0 && errno != EINTR) {
3008 g_snprintf(errmsg, errmsg_len,
3009 "Unexpected error from select: %s", g_strerror(errno));
3010 report_capture_error(errmsg, please_report);
3015 * "select()" says we can read from the pipe without blocking
3018 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
3028 /* dispatch from pcap */
3029 #ifdef MUST_DO_SELECT
3031 * If we have "pcap_get_selectable_fd()", we use it to get the
3032 * descriptor on which to select; if that's -1, it means there
3033 * is no descriptor on which you can do a "select()" (perhaps
3034 * because you're capturing on a special device, and that device's
3035 * driver unfortunately doesn't support "select()", in which case
3036 * we don't do the select - which means it might not be possible
3037 * to stop a capture until a packet arrives. If that's unacceptable,
3038 * plead with whoever supplies the software for that device to add
3039 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3040 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3041 * later, so it can use pcap_breakloop().
3043 #ifdef LOG_CAPTURE_VERBOSE
3044 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3046 if (pcap_opts->pcap_fd != -1) {
3047 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
3050 * "select()" says we can read from it without blocking; go for
3053 * We don't have pcap_breakloop(), so we only process one packet
3054 * per pcap_dispatch() call, to allow a signal to stop the
3055 * processing immediately, rather than processing all packets
3056 * in a batch before quitting.
3059 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3061 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3065 /* Error, rather than pcap_breakloop(). */
3066 pcap_opts->pcap_err = TRUE;
3068 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3071 if (sel_ret < 0 && errno != EINTR) {
3072 g_snprintf(errmsg, errmsg_len,
3073 "Unexpected error from select: %s", g_strerror(errno));
3074 report_capture_error(errmsg, please_report);
3080 #endif /* MUST_DO_SELECT */
3082 /* dispatch from pcap without select */
3084 #ifdef LOG_CAPTURE_VERBOSE
3085 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3089 * On Windows, we don't support asynchronously telling a process to
3090 * stop capturing; instead, we check for an indication on a pipe
3091 * after processing packets. We therefore process only one packet
3092 * at a time, so that we can check the pipe after every packet.
3095 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3097 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3101 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3103 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3108 /* Error, rather than pcap_breakloop(). */
3109 pcap_opts->pcap_err = TRUE;
3111 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3113 #else /* pcap_next_ex */
3114 #ifdef LOG_CAPTURE_VERBOSE
3115 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3117 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3120 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3121 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
3122 * This should be fixed in the WinPcap 4.0 alpha release.
3124 * For reference, an example remote interface:
3125 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3128 /* emulate dispatch from pcap */
3131 struct pcap_pkthdr *pkt_header;
3136 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
3138 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3140 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3145 pcap_opts->pcap_err = TRUE;
3149 #endif /* pcap_next_ex */
3153 #ifdef LOG_CAPTURE_VERBOSE
3154 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3157 return ld->packet_count - packet_count_before;
3161 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3162 * want to grab only the characters between the '{' and '}' delimiters.
3164 * Returns a GString that must be freed with g_string_free(). */
3166 isolate_uuid(const char *iface)
3171 ptr = strchr(iface, '{');
3173 return g_string_new(iface);
3174 gstr = g_string_new(ptr + 1);
3176 ptr = strchr(gstr->str, '}');
3180 gstr = g_string_truncate(gstr, ptr - gstr->str);
3185 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3186 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3188 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3189 char *errmsg, int errmsg_len)
3192 gchar *capfile_name;
3194 gboolean is_tempfile;
3196 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3197 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3199 if (capture_opts->save_file != NULL) {
3200 /* We return to the caller while the capture is in progress.
3201 * Therefore we need to take a copy of save_file in
3202 * case the caller destroys it after we return.
3204 capfile_name = g_strdup(capture_opts->save_file);
3206 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3207 if (capture_opts->multi_files_on) {
3208 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3209 g_snprintf(errmsg, errmsg_len,
3210 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3211 g_free(capfile_name);
3214 if (strcmp(capfile_name, "-") == 0) {
3215 /* write to stdout */
3218 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3219 _setmode(1, O_BINARY);
3222 } /* if (...output_to_pipe ... */
3225 if (capture_opts->multi_files_on) {
3226 /* ringbuffer is enabled */
3227 *save_file_fd = ringbuf_init(capfile_name,
3228 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3229 capture_opts->group_read_access);
3231 /* we need the ringbuf name */
3232 if (*save_file_fd != -1) {
3233 g_free(capfile_name);
3234 capfile_name = g_strdup(ringbuf_current_filename());
3237 /* Try to open/create the specified file for use as a capture buffer. */
3238 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
3239 (capture_opts->group_read_access) ? 0640 : 0600);
3242 is_tempfile = FALSE;
3244 /* Choose a random name for the temporary capture buffer */
3245 if (global_capture_opts.ifaces->len > 1) {
3246 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3249 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
3251 /* use the generic portion of the interface guid to form the basis of the filename */
3252 if (strncmp("NPF_{", basename, 5)==0)
3254 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
3256 iface = isolate_uuid(basename);
3258 basename = g_strdup(iface->str);
3259 g_string_free(iface, TRUE);
3262 /* generate the temp file name prefix...
3263 * It would be nice if we could specify a pcapng/pcap filename suffix,
3264 * create_tempfile() however currently uses mkstemp() which doesn't allow this - one day perhaps*/
3265 if (capture_opts->use_pcapng) {
3266 prefix = g_strconcat("wireshark_pcapng_", basename, NULL);
3268 prefix = g_strconcat("wireshark_pcap_", basename, NULL);
3272 *save_file_fd = create_tempfile(&tmpname, prefix);
3274 capfile_name = g_strdup(tmpname);
3278 /* did we fail to open the output file? */
3279 if (*save_file_fd == -1) {
3281 g_snprintf(errmsg, errmsg_len,
3282 "The temporary file to which the capture would be saved (\"%s\") "
3283 "could not be opened: %s.", capfile_name, g_strerror(errno));
3285 if (capture_opts->multi_files_on) {
3286 ringbuf_error_cleanup();
3289 g_snprintf(errmsg, errmsg_len,
3290 "The file to which the capture would be saved (\"%s\") "
3291 "could not be opened: %s.", capfile_name,
3294 g_free(capfile_name);
3298 if (capture_opts->save_file != NULL) {
3299 g_free(capture_opts->save_file);
3301 capture_opts->save_file = capfile_name;
3302 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3303 "g_free(capfile_name)". */
3309 /* Do the work of handling either the file size or file duration capture
3310 conditions being reached, and switching files or stopping. */
3312 do_file_switch_or_stop(capture_options *capture_opts,
3313 condition *cnd_autostop_files,
3314 condition *cnd_autostop_size,
3315 condition *cnd_file_duration)
3318 pcap_options *pcap_opts;
3319 interface_options interface_opts;
3320 gboolean successful;
3322 if (capture_opts->multi_files_on) {
3323 if (cnd_autostop_files != NULL &&
3324 cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
3325 /* no files left: stop here */
3326 global_ld.go = FALSE;
3330 /* Switch to the next ringbuffer file */
3331 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3332 &global_ld.save_file_fd, &global_ld.err)) {
3334 /* File switch succeeded: reset the conditions */
3335 global_ld.bytes_written = 0;
3336 if (capture_opts->use_pcapng) {
3338 GString *os_info_str;
3340 os_info_str = g_string_new("");
3341 get_os_version_info(os_info_str);
3343 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
3344 successful = libpcap_write_session_header_block(libpcap_write_to_file, global_ld.pdh,
3347 os_info_str->str, /* OS */
3349 -1, /* section_length */
3350 &(global_ld.bytes_written),
3353 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3354 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3355 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3356 successful = libpcap_write_interface_description_block(libpcap_write_to_file, global_ld.pdh,
3357 NULL, /* OPT_COMMENT 1 */
3358 interface_opts.name, /* IDB_NAME 2 */
3359 interface_opts.descr, /* IDB_DESCRIPTION 3 */
3360 interface_opts.cfilter, /* IDB_FILTER 11 */
3361 os_info_str->str, /* IDB_OS 12 */
3362 pcap_opts->linktype,
3364 &(global_ld.bytes_written),
3365 0, /* IDB_IF_SPEED 8 */
3366 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3370 g_string_free(os_info_str, TRUE);
3373 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3374 successful = libpcap_write_file_header(libpcap_write_to_file, global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
3375 pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3378 fclose(global_ld.pdh);
3379 global_ld.pdh = NULL;
3380 global_ld.go = FALSE;
3383 if (cnd_autostop_size)
3384 cnd_reset(cnd_autostop_size);
3385 if (cnd_file_duration)
3386 cnd_reset(cnd_file_duration);
3387 fflush(global_ld.pdh);
3389 report_packet_count(global_ld.inpkts_to_sync_pipe);
3390 global_ld.inpkts_to_sync_pipe = 0;
3391 report_new_capture_file(capture_opts->save_file);
3393 /* File switch failed: stop here */
3394 global_ld.go = FALSE;
3398 /* single file, stop now */
3399 global_ld.go = FALSE;
3406 pcap_read_handler(void* arg)
3408 pcap_options *pcap_opts;
3409 char errmsg[MSG_MAX_LENGTH+1];
3411 pcap_opts = (pcap_options *)arg;
3413 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3414 pcap_opts->interface_id);
3416 while (global_ld.go) {
3417 /* dispatch incoming packets */
3418 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3420 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3421 pcap_opts->interface_id);
3422 g_thread_exit(NULL);
3426 /* Do the low-level work of a capture.
3427 Returns TRUE if it succeeds, FALSE otherwise. */
3429 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3432 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3434 struct timeval upd_time, cur_time;
3438 condition *cnd_file_duration = NULL;
3439 condition *cnd_autostop_files = NULL;
3440 condition *cnd_autostop_size = NULL;
3441 condition *cnd_autostop_duration = NULL;
3444 gboolean cfilter_error = FALSE;
3445 char errmsg[MSG_MAX_LENGTH+1];
3446 char secondary_errmsg[MSG_MAX_LENGTH+1];
3447 pcap_options *pcap_opts;
3448 interface_options interface_opts;
3449 guint i, error_index = 0;
3452 *secondary_errmsg = '\0';
3454 /* init the loop data */
3455 global_ld.go = TRUE;
3456 global_ld.packet_count = 0;
3458 global_ld.report_packet_count = FALSE;
3460 if (capture_opts->has_autostop_packets)
3461 global_ld.packet_max = capture_opts->autostop_packets;
3463 global_ld.packet_max = 0; /* no limit */
3464 global_ld.inpkts_to_sync_pipe = 0;
3465 global_ld.err = 0; /* no error seen yet */
3466 global_ld.pdh = NULL;
3467 global_ld.autostop_files = 0;
3468 global_ld.save_file_fd = -1;
3470 /* We haven't yet gotten the capture statistics. */
3471 *stats_known = FALSE;
3473 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3474 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3476 /* open the "input file" from network interface or capture pipe */
3477 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3478 secondary_errmsg, sizeof(secondary_errmsg))) {
3481 for (i = 0; i < capture_opts->ifaces->len; i++) {
3482 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3483 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3484 /* init the input filter from the network interface (capture pipe will do nothing) */
3486 * When remote capturing WinPCap crashes when the capture filter
3487 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3490 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3491 interface_opts.name,
3492 interface_opts.cfilter?interface_opts.cfilter:"")) {
3494 case INITFILTER_NO_ERROR:
3497 case INITFILTER_BAD_FILTER:
3498 cfilter_error = TRUE;
3500 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3503 case INITFILTER_OTHER_ERROR:
3504 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3505 pcap_geterr(pcap_opts->pcap_h));
3506 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3511 /* If we're supposed to write to a capture file, open it for output
3512 (temporary/specified name/ringbuffer) */
3513 if (capture_opts->saving_to_file) {
3514 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3515 errmsg, sizeof(errmsg))) {
3519 /* set up to write to the already-opened capture output file/files */
3520 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3525 /* XXX - capture SIGTERM and close the capture, in case we're on a
3526 Linux 2.0[.x] system and you have to explicitly close the capture
3527 stream in order to turn promiscuous mode off? We need to do that
3528 in other places as well - and I don't think that works all the
3529 time in any case, due to libpcap bugs. */
3531 /* Well, we should be able to start capturing.
3533 Sync out the capture file, so the header makes it to the file system,
3534 and send a "capture started successfully and capture file created"
3535 message to our parent so that they'll open the capture file and
3536 update its windows to indicate that we have a live capture in
3538 fflush(global_ld.pdh);
3539 report_new_capture_file(capture_opts->save_file);
3542 /* initialize capture stop (and alike) conditions */
3543 init_capture_stop_conditions();
3544 /* create stop conditions */
3545 if (capture_opts->has_autostop_filesize)
3547 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
3548 if (capture_opts->has_autostop_duration)
3549 cnd_autostop_duration =
3550 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3552 if (capture_opts->multi_files_on) {
3553 if (capture_opts->has_file_duration)
3555 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3557 if (capture_opts->has_autostop_files)
3558 cnd_autostop_files =
3559 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
3562 /* init the time values */
3564 upd_time = GetTickCount();
3566 gettimeofday(&upd_time, NULL);
3568 start_time = create_timestamp();
3569 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
3571 /* WOW, everything is prepared! */
3572 /* please fasten your seat belts, we will enter now the actual capture loop */
3574 pcap_queue = g_async_queue_new();
3575 pcap_queue_bytes = 0;
3576 pcap_queue_packets = 0;
3577 for (i = 0; i < global_ld.pcaps->len; i++) {
3578 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3579 #if GLIB_CHECK_VERSION(2,31,0)
3580 /* XXX - Add an interface name here? */
3581 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3583 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3587 while (global_ld.go) {
3588 /* dispatch incoming packets */
3590 pcap_queue_element *queue_element;
3591 #if GLIB_CHECK_VERSION(2,31,18)
3593 g_async_queue_lock(pcap_queue);
3594 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3596 GTimeVal write_thread_time;
3598 g_get_current_time(&write_thread_time);
3599 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3600 g_async_queue_lock(pcap_queue);
3601 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3603 if (queue_element) {
3604 pcap_queue_bytes -= queue_element->phdr.caplen;
3605 pcap_queue_packets -= 1;
3607 g_async_queue_unlock(pcap_queue);
3608 if (queue_element) {
3609 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3610 "Dequeued a packet of length %d captured on interface %d.",
3611 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3613 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3614 &queue_element->phdr,
3616 g_free(queue_element->pd);
3617 g_free(queue_element);
3623 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3624 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3625 sizeof(errmsg), pcap_opts);
3628 /* Were we asked to print packet counts by the SIGINFO handler? */
3629 if (global_ld.report_packet_count) {
3630 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3631 plurality(global_ld.packet_count, "", "s"));
3632 global_ld.report_packet_count = FALSE;
3637 /* any news from our parent (signal pipe)? -> just stop the capture */
3638 if (!signal_pipe_check_running()) {
3639 global_ld.go = FALSE;
3644 global_ld.inpkts_to_sync_pipe += inpkts;
3646 /* check capture size condition */
3647 if (cnd_autostop_size != NULL &&
3648 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)) {
3649 /* Capture size limit reached, do we have another file? */
3650 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3651 cnd_autostop_size, cnd_file_duration))
3653 } /* cnd_autostop_size */
3654 if (capture_opts->output_to_pipe) {
3655 fflush(global_ld.pdh);
3659 /* Only update once every 500ms so as not to overload slow displays.
3660 * This also prevents too much context-switching between the dumpcap
3661 * and wireshark processes.
3663 #define DUMPCAP_UPD_TIME 500
3666 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3667 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3669 gettimeofday(&cur_time, NULL);
3670 if ((cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3671 (upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3674 upd_time = cur_time;
3677 if (pcap_stats(pch, stats) >= 0) {
3678 *stats_known = TRUE;
3681 /* Let the parent process know. */
3682 if (global_ld.inpkts_to_sync_pipe) {
3684 fflush(global_ld.pdh);
3686 /* Send our parent a message saying we've written out
3687 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3689 report_packet_count(global_ld.inpkts_to_sync_pipe);
3691 global_ld.inpkts_to_sync_pipe = 0;
3694 /* check capture duration condition */
3695 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3696 /* The maximum capture time has elapsed; stop the capture. */
3697 global_ld.go = FALSE;
3701 /* check capture file duration condition */
3702 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3703 /* duration limit reached, do we have another file? */
3704 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3705 cnd_autostop_size, cnd_file_duration))
3707 } /* cnd_file_duration */
3711 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3713 pcap_queue_element *queue_element;
3715 for (i = 0; i < global_ld.pcaps->len; i++) {
3716 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3717 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3718 pcap_opts->interface_id);
3719 g_thread_join(pcap_opts->tid);
3720 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3721 pcap_opts->interface_id);
3724 g_async_queue_lock(pcap_queue);
3725 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3726 if (queue_element) {
3727 pcap_queue_bytes -= queue_element->phdr.caplen;
3728 pcap_queue_packets -= 1;
3730 g_async_queue_unlock(pcap_queue);
3731 if (queue_element == NULL) {
3734 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3735 "Dequeued a packet of length %d captured on interface %d.",
3736 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3737 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3738 &queue_element->phdr,
3740 g_free(queue_element->pd);
3741 g_free(queue_element);
3742 global_ld.inpkts_to_sync_pipe += 1;
3743 if (capture_opts->output_to_pipe) {
3744 fflush(global_ld.pdh);
3750 /* delete stop conditions */
3751 if (cnd_file_duration != NULL)
3752 cnd_delete(cnd_file_duration);
3753 if (cnd_autostop_files != NULL)
3754 cnd_delete(cnd_autostop_files);
3755 if (cnd_autostop_size != NULL)
3756 cnd_delete(cnd_autostop_size);
3757 if (cnd_autostop_duration != NULL)
3758 cnd_delete(cnd_autostop_duration);
3760 /* did we have a pcap (input) error? */
3761 for (i = 0; i < capture_opts->ifaces->len; i++) {
3762 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3763 if (pcap_opts->pcap_err) {
3764 /* On Linux, if an interface goes down while you're capturing on it,
3765 you'll get a "recvfrom: Network is down" or
3766 "The interface went down" error (ENETDOWN).
3767 (At least you will if g_strerror() doesn't show a local translation
3770 On FreeBSD and OS X, if a network adapter disappears while
3771 you're capturing on it, you'll get a "read: Device not configured"
3772 error (ENXIO). (See previous parenthetical note.)
3774 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3776 These should *not* be reported to the Wireshark developers. */
3779 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3780 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3781 strcmp(cap_err_str, "The interface went down") == 0 ||
3782 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3783 strcmp(cap_err_str, "read: I/O error") == 0 ||
3784 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3785 report_capture_error("The network adapter on which the capture was being done "
3786 "is no longer running; the capture has stopped.",
3789 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3791 report_capture_error(errmsg, please_report);
3794 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3795 report_capture_error(errmsg, "");
3799 /* did we have an output error while capturing? */
3800 if (global_ld.err == 0) {
3803 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3804 global_ld.err, FALSE);
3805 report_capture_error(errmsg, please_report);
3809 if (capture_opts->saving_to_file) {
3810 /* close the output file */
3811 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3815 /* there might be packets not yet notified to the parent */
3816 /* (do this after closing the file, so all packets are already flushed) */
3817 if (global_ld.inpkts_to_sync_pipe) {
3819 report_packet_count(global_ld.inpkts_to_sync_pipe);
3820 global_ld.inpkts_to_sync_pipe = 0;
3823 /* If we've displayed a message about a write error, there's no point
3824 in displaying another message about an error on close. */
3825 if (!close_ok && write_ok) {
3826 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3828 report_capture_error(errmsg, "");
3832 * XXX We exhibit different behaviour between normal mode and sync mode
3833 * when the pipe is stdin and not already at EOF. If we're a child, the
3834 * parent's stdin isn't closed, so if the user starts another capture,
3835 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3836 * will say "Unrecognized libpcap format". On the other hand, in normal
3837 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3840 report_capture_count(TRUE);
3842 /* get packet drop statistics from pcap */
3843 for (i = 0; i < capture_opts->ifaces->len; i++) {
3845 guint32 pcap_dropped = 0;
3847 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3848 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3849 received = pcap_opts->received;
3850 if (pcap_opts->pcap_h != NULL) {
3851 g_assert(!pcap_opts->from_cap_pipe);
3852 /* Get the capture statistics, so we know how many packets were dropped. */
3853 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3854 *stats_known = TRUE;
3855 /* Let the parent process know. */
3856 pcap_dropped += stats->ps_drop;
3858 g_snprintf(errmsg, sizeof(errmsg),
3859 "Can't get packet-drop statistics: %s",
3860 pcap_geterr(pcap_opts->pcap_h));
3861 report_capture_error(errmsg, please_report);
3864 report_packet_drops(received, pcap_dropped, pcap_opts->dropped, pcap_opts->flushed, interface_opts.console_display_name);
3867 /* close the input file (pcap or capture pipe) */
3868 capture_loop_close_input(&global_ld);
3870 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
3872 /* ok, if the write and the close were successful. */
3873 return write_ok && close_ok;
3876 if (capture_opts->multi_files_on) {
3877 /* cleanup ringbuffer */
3878 ringbuf_error_cleanup();
3880 /* We can't use the save file, and we have no FILE * for the stream
3881 to close in order to close it, so close the FD directly. */
3882 if (global_ld.save_file_fd != -1) {
3883 ws_close(global_ld.save_file_fd);
3886 /* We couldn't even start the capture, so get rid of the capture
3888 if (capture_opts->save_file != NULL) {
3889 ws_unlink(capture_opts->save_file);
3890 g_free(capture_opts->save_file);
3893 capture_opts->save_file = NULL;
3895 report_cfilter_error(capture_opts, error_index, errmsg);
3897 report_capture_error(errmsg, secondary_errmsg);
3899 /* close the input file (pcap or cap_pipe) */
3900 capture_loop_close_input(&global_ld);
3902 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3909 capture_loop_stop(void)
3911 #ifdef HAVE_PCAP_BREAKLOOP
3913 pcap_options *pcap_opts;
3915 for (i = 0; i < global_ld.pcaps->len; i++) {
3916 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3917 if (pcap_opts->pcap_h != NULL)
3918 pcap_breakloop(pcap_opts->pcap_h);
3921 global_ld.go = FALSE;
3926 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3927 int err, gboolean is_close)
3932 g_snprintf(errmsg, errmsglen,
3933 "Not all the packets could be written to the file"
3934 " to which the capture was being saved\n"
3935 "(\"%s\") because there is no space left on the file system\n"
3936 "on which that file resides.",
3942 g_snprintf(errmsg, errmsglen,
3943 "Not all the packets could be written to the file"
3944 " to which the capture was being saved\n"
3945 "(\"%s\") because you are too close to, or over,"
3946 " your disk quota\n"
3947 "on the file system on which that file resides.",
3954 g_snprintf(errmsg, errmsglen,
3955 "The file to which the capture was being saved\n"
3956 "(\"%s\") could not be closed: %s.",
3957 fname, g_strerror(err));
3959 g_snprintf(errmsg, errmsglen,
3960 "An error occurred while writing to the file"
3961 " to which the capture was being saved\n"
3963 fname, g_strerror(err));
3970 /* one packet was captured, process it */
3972 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3975 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3977 guint ts_mul = pcap_opts->ts_nsec ? 1000000000 : 1000000;
3979 /* We may be called multiple times from pcap_dispatch(); if we've set
3980 the "stop capturing" flag, ignore this packet, as we're not
3981 supposed to be saving any more packets. */
3982 if (!global_ld.go) {
3983 pcap_opts->flushed++;
3987 if (global_ld.pdh) {
3988 gboolean successful;
3990 /* We're supposed to write the packet to a file; do so.
3991 If this fails, set "ld->go" to FALSE, to stop the capture, and set
3992 "ld->err" to the error. */
3993 if (global_capture_opts.use_pcapng) {
3994 successful = libpcap_write_enhanced_packet_block(libpcap_write_to_file, global_ld.pdh,
3996 phdr->ts.tv_sec, phdr->ts.tv_usec,
3997 phdr->caplen, phdr->len,
3998 pcap_opts->interface_id,
4001 &global_ld.bytes_written, &err);
4003 successful = libpcap_write_packet(libpcap_write_to_file, global_ld.pdh,
4004 phdr->ts.tv_sec, phdr->ts.tv_usec,
4005 phdr->caplen, phdr->len,
4007 &global_ld.bytes_written, &err);
4010 global_ld.go = FALSE;
4011 global_ld.err = err;
4012 pcap_opts->dropped++;
4014 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4015 "Wrote a packet of length %d captured on interface %u.",
4016 phdr->caplen, pcap_opts->interface_id);
4017 global_ld.packet_count++;
4018 pcap_opts->received++;
4019 /* if the user told us to stop after x packets, do we already have enough? */
4020 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
4021 global_ld.go = FALSE;
4027 /* one packet was captured, queue it */
4029 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4032 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4033 pcap_queue_element *queue_element;
4034 gboolean limit_reached;
4036 /* We may be called multiple times from pcap_dispatch(); if we've set
4037 the "stop capturing" flag, ignore this packet, as we're not
4038 supposed to be saving any more packets. */
4039 if (!global_ld.go) {
4040 pcap_opts->flushed++;
4044 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4045 if (queue_element == NULL) {
4046 pcap_opts->dropped++;
4049 queue_element->pcap_opts = pcap_opts;
4050 queue_element->phdr = *phdr;
4051 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4052 if (queue_element->pd == NULL) {
4053 pcap_opts->dropped++;
4054 g_free(queue_element);
4057 memcpy(queue_element->pd, pd, phdr->caplen);
4058 g_async_queue_lock(pcap_queue);
4059 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4060 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4061 limit_reached = FALSE;
4062 g_async_queue_push_unlocked(pcap_queue, queue_element);
4063 pcap_queue_bytes += phdr->caplen;
4064 pcap_queue_packets += 1;
4066 limit_reached = TRUE;
4068 g_async_queue_unlock(pcap_queue);
4069 if (limit_reached) {
4070 pcap_opts->dropped++;
4071 g_free(queue_element->pd);
4072 g_free(queue_element);
4073 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4074 "Dropped a packet of length %d captured on interface %u.",
4075 phdr->caplen, pcap_opts->interface_id);
4077 pcap_opts->received++;
4078 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4079 "Queued a packet of length %d captured on interface %u.",
4080 phdr->caplen, pcap_opts->interface_id);
4082 /* I don't want to hold the mutex over the debug output. So the
4083 output may be wrong */
4084 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4085 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4086 pcap_queue_bytes, pcap_queue_packets);
4090 set_80211_channel(const char *iface, const char *opt)
4092 int freq = 0, type, ret;
4093 gchar **options = NULL;
4095 options = g_strsplit_set(opt, ",", 2);
4098 freq = atoi(options[0]);
4101 type = ws80211_str_to_chan_type(options[1]);
4110 ret = ws80211_init();
4112 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4116 ret = ws80211_set_freq(iface, freq, type);
4119 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4125 pipe_write_block(2, SP_SUCCESS, NULL);
4129 g_strfreev(options);
4133 /* And now our feature presentation... [ fade to music ] */
4135 main(int argc, char *argv[])
4137 GString *comp_info_str;
4138 GString *runtime_info_str;
4140 gboolean arg_error = FALSE;
4145 struct sigaction action, oldaction;
4148 gboolean start_capture = TRUE;
4149 gboolean stats_known;
4150 struct pcap_stat stats;
4151 GLogLevelFlags log_flags;
4152 gboolean list_interfaces = FALSE;
4153 gboolean list_link_layer_types = FALSE;
4154 #ifdef HAVE_BPF_IMAGE
4155 gboolean print_bpf_code = FALSE;
4157 gboolean set_chan = FALSE;
4158 gchar *set_chan_arg = NULL;
4159 gboolean machine_readable = FALSE;
4160 gboolean print_statistics = FALSE;
4161 int status, run_once_args = 0;
4164 #if defined(__APPLE__) && defined(__LP64__)
4165 struct utsname osinfo;
4169 /* Assemble the compile-time version information string */
4170 comp_info_str = g_string_new("Compiled ");
4171 get_compiled_version_info(comp_info_str, NULL, NULL);
4173 /* Assemble the run-time version information string */
4174 runtime_info_str = g_string_new("Running ");
4175 get_runtime_version_info(runtime_info_str, NULL);
4177 /* Add it to the information to be reported on a crash. */
4178 ws_add_crash_info("Dumpcap " VERSION "%s\n"
4183 wireshark_svnversion, comp_info_str->str, runtime_info_str->str);
4186 arg_list_utf_16to8(argc, argv);
4187 create_app_running_mutex();
4190 * Initialize our DLL search path. MUST be called before LoadLibrary
4193 ws_init_dll_search_path();
4196 #ifdef HAVE_PCAP_REMOTE
4197 #define OPTSTRING_A "A:"
4198 #define OPTSTRING_r "r"
4199 #define OPTSTRING_u "u"
4201 #define OPTSTRING_A ""
4202 #define OPTSTRING_r ""
4203 #define OPTSTRING_u ""
4206 #ifdef HAVE_PCAP_SETSAMPLING
4207 #define OPTSTRING_m "m:"
4209 #define OPTSTRING_m ""
4212 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4213 #define OPTSTRING_B "B:"
4215 #define OPTSTRING_B ""
4216 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4218 #ifdef HAVE_PCAP_CREATE
4219 #define OPTSTRING_I "I"
4221 #define OPTSTRING_I ""
4224 #ifdef HAVE_BPF_IMAGE
4225 #define OPTSTRING_d "d"
4227 #define OPTSTRING_d ""
4230 #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:"
4232 #ifdef DEBUG_CHILD_DUMPCAP
4233 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4234 fprintf (stderr, "Unable to open debug log file !\n");
4239 #if defined(__APPLE__) && defined(__LP64__)
4241 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
4242 * a bug workaround - timeouts less than 1 second don't work with libpcap
4243 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
4244 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4245 * The problem is extremely unlikely to be reintroduced in a future
4248 if (uname(&osinfo) == 0) {
4250 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
4251 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4252 * number of 10.0.0, not 10.1.0 - go figure).
4254 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
4255 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
4256 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
4257 need_timeout_workaround = TRUE;
4262 * Determine if dumpcap is being requested to run in a special
4263 * capture_child mode by going thru the command line args to see if
4264 * a -Z is present. (-Z is a hidden option).
4266 * The primary result of running in capture_child mode is that
4267 * all messages sent out on stderr are in a special type/len/string
4268 * format to allow message processing by type. These messages include
4269 * error messages if dumpcap fails to start the operation it was
4270 * requested to do, as well as various "status" messages which are sent
4271 * when an actual capture is in progress, and a "success" message sent
4272 * if dumpcap was requested to perform an operation other than a
4275 * Capture_child mode would normally be requested by a parent process
4276 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4277 * to which dumpcap stderr has been redirected. It might also have
4278 * another pipe to obtain dumpcap stdout output; for operations other
4279 * than a capture, that information is formatted specially for easier
4280 * parsing by the parent process.
4282 * Capture_child mode needs to be determined immediately upon
4283 * startup so that any messages generated by dumpcap in this mode
4284 * (eg: during initialization) will be formatted properly.
4287 for (i=1; i<argc; i++) {
4288 if (strcmp("-Z", argv[i]) == 0) {
4289 capture_child = TRUE;
4290 machine_readable = TRUE; /* request machine-readable output */
4292 /* set output pipe to binary mode, to avoid ugly text conversions */
4293 _setmode(2, O_BINARY);
4298 /* The default_log_handler will use stdout, which makes trouble in */
4299 /* capture child mode, as it uses stdout for its sync_pipe. */
4300 /* So: the filtering is done in the console_log_handler and not here.*/
4301 /* We set the log handlers right up front to make sure that any log */
4302 /* messages when running as child will be sent back to the parent */
4303 /* with the correct format. */
4308 G_LOG_LEVEL_CRITICAL|
4309 G_LOG_LEVEL_WARNING|
4310 G_LOG_LEVEL_MESSAGE|
4314 G_LOG_FLAG_RECURSION);
4316 g_log_set_handler(NULL,
4318 console_log_handler, NULL /* user_data */);
4319 g_log_set_handler(LOG_DOMAIN_MAIN,
4321 console_log_handler, NULL /* user_data */);
4322 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4324 console_log_handler, NULL /* user_data */);
4325 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4327 console_log_handler, NULL /* user_data */);
4329 /* Initialize the pcaps list */
4330 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
4332 #if !GLIB_CHECK_VERSION(2,31,0)
4333 /* Initialize the thread system */
4334 g_thread_init(NULL);
4338 /* Load wpcap if possible. Do this before collecting the run-time version information */
4341 /* ... and also load the packet.dll from wpcap */
4342 /* XXX - currently not required, may change later. */
4343 /*wpcap_packet_load();*/
4345 /* Start windows sockets */
4346 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4348 /* Set handler for Ctrl+C key */
4349 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4351 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4352 and exit. Do the same with SIGPIPE, in case, for example,
4353 we're writing to our standard output and it's a pipe.
4354 Do the same with SIGHUP if it's not being ignored (if we're
4355 being run under nohup, it might be ignored, in which case we
4356 should leave it ignored).
4358 XXX - apparently, Coverity complained that part of action
4359 wasn't initialized. Perhaps it's running on Linux, where
4360 struct sigaction has an ignored "sa_restorer" element and
4361 where "sa_handler" and "sa_sigaction" might not be two
4362 members of a union. */
4363 memset(&action, 0, sizeof(action));
4364 action.sa_handler = capture_cleanup_handler;
4366 * Arrange that system calls not get restarted, because when
4367 * our signal handler returns we don't want to restart
4368 * a call that was waiting for packets to arrive.
4370 action.sa_flags = 0;
4371 sigemptyset(&action.sa_mask);
4372 sigaction(SIGTERM, &action, NULL);
4373 sigaction(SIGINT, &action, NULL);
4374 sigaction(SIGPIPE, &action, NULL);
4375 sigaction(SIGHUP, NULL, &oldaction);
4376 if (oldaction.sa_handler == SIG_DFL)
4377 sigaction(SIGHUP, &action, NULL);
4380 /* Catch SIGINFO and, if we get it and we're capturing in
4381 quiet mode, report the number of packets we've captured. */
4382 action.sa_handler = report_counts_siginfo;
4383 action.sa_flags = SA_RESTART;
4384 sigemptyset(&action.sa_mask);
4385 sigaction(SIGINFO, &action, NULL);
4386 #endif /* SIGINFO */
4389 /* ----------------------------------------------------------------- */
4390 /* Privilege and capability handling */
4392 /* 1. Running not as root or suid root; no special capabilities. */
4395 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4398 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4400 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4401 /* capabilities; Drop all other capabilities; */
4402 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4403 /* else: after pcap_open_live() in capture_loop_open_input() */
4404 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4405 /* (Note: this means that the process, although logged in */
4406 /* as root, does not have various permissions such as the */
4407 /* ability to bypass file access permissions). */
4408 /* XXX: Should we just leave capabilities alone in this case */
4409 /* so that user gets expected effect that root can do */
4412 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4414 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4415 /* else: after pcap_open_live() in capture_loop_open_input() */
4416 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4417 /* pcap_open_live). */
4419 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4421 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4422 /* capabilities; Drop all other capabilities; */
4423 /* Drop suid privileges (euid=ruid); */
4424 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4425 /* else: after pcap_open_live() in capture_loop_open_input() */
4426 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4428 /* XXX: For some Linux versions/distros with capabilities */
4429 /* a 'normal' process with any capabilities cannot be */
4430 /* 'killed' (signaled) from another (same uid) non-privileged */
4432 /* For example: If (non-suid) Wireshark forks a */
4433 /* child suid dumpcap which acts as described here (case 5), */
4434 /* Wireshark will be unable to kill (signal) the child */
4435 /* dumpcap process until the capabilities have been dropped */
4436 /* (after pcap_open_live()). */
4437 /* This behaviour will apparently be changed in the kernel */
4438 /* to allow the kill (signal) in this case. */
4439 /* See the following for details: */
4440 /* http://www.mail-archive.com/ [wrapped] */
4441 /* linux-security-module@vger.kernel.org/msg02913.html */
4443 /* It is therefore conceivable that if dumpcap somehow hangs */
4444 /* in pcap_open_live or before that wireshark will not */
4445 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4446 /* In this case, exiting wireshark will kill the child */
4447 /* dumpcap process. */
4449 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4450 /* capabilities; Using libcap. Note: capset cmd (which see) */
4451 /* used to assign capabilities to file. */
4453 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4454 /* else: after pcap_open_live() in capture_loop_open_input() */
4455 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4457 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4458 /* longer required (similar to capture). */
4460 /* ----------------------------------------------------------------- */
4462 init_process_policies();
4465 /* If 'started with special privileges' (and using libcap) */
4466 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4467 /* Set euid/egid = ruid/rgid to remove suid privileges */
4468 relinquish_privs_except_capture();
4471 /* Set the initial values in the capture options. This might be overwritten
4472 by the command line parameters. */
4473 capture_opts_init(&global_capture_opts, NULL);
4475 /* We always save to a file - if no file was specified, we save to a
4477 global_capture_opts.saving_to_file = TRUE;
4478 global_capture_opts.has_ring_num_files = TRUE;
4480 /* Now get our args */
4481 while ((opt = getopt(argc, argv, OPTSTRING)) != -1) {
4483 case 'h': /* Print help and exit */
4487 case 'v': /* Show version and exit */
4489 show_version(comp_info_str, runtime_info_str);
4490 g_string_free(comp_info_str, TRUE);
4491 g_string_free(runtime_info_str, TRUE);
4495 /*** capture option specific ***/
4496 case 'a': /* autostop criteria */
4497 case 'b': /* Ringbuffer option */
4498 case 'c': /* Capture x packets */
4499 case 'f': /* capture filter */
4500 case 'g': /* enable group read access on file(s) */
4501 case 'i': /* Use interface x */
4502 case 'n': /* Use pcapng format */
4503 case 'p': /* Don't capture in promiscuous mode */
4504 case 'P': /* Use pcap format */
4505 case 's': /* Set the snapshot (capture) length */
4506 case 'w': /* Write to capture file x */
4507 case 'y': /* Set the pcap data link type */
4508 #ifdef HAVE_PCAP_REMOTE
4509 case 'u': /* Use UDP for data transfer */
4510 case 'r': /* Capture own RPCAP traffic too */
4511 case 'A': /* Authentication */
4513 #ifdef HAVE_PCAP_SETSAMPLING
4514 case 'm': /* Sampling */
4516 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4517 case 'B': /* Buffer size */
4518 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4519 #ifdef HAVE_PCAP_CREATE
4520 case 'I': /* Monitor mode */
4522 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4527 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4529 capture_child = TRUE;
4531 /* set output pipe to binary mode, to avoid ugly text conversions */
4532 _setmode(2, O_BINARY);
4534 * optarg = the control ID, aka the PPID, currently used for the
4537 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4538 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4539 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4540 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4542 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4543 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4544 "Signal pipe: Unable to open %s. Dead parent?",
4552 case 'q': /* Quiet */
4558 /*** all non capture option specific ***/
4559 case 'D': /* Print a list of capture devices and exit */
4560 list_interfaces = TRUE;
4563 case 'L': /* Print list of link-layer types and exit */
4564 list_link_layer_types = TRUE;
4567 #ifdef HAVE_BPF_IMAGE
4568 case 'd': /* Print BPF code for capture filter and exit */
4569 print_bpf_code = TRUE;
4573 case 'S': /* Print interface statistics once a second */
4574 print_statistics = TRUE;
4577 case 'k': /* Set wireless channel */
4579 set_chan_arg = optarg;
4582 case 'M': /* For -D, -L, and -S, print machine-readable output */
4583 machine_readable = TRUE;
4586 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4589 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4592 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4594 case '?': /* Bad flag - print usage message */
4603 /* user specified file name as regular command-line argument */
4604 /* XXX - use it as the capture file name (or something else)? */
4610 * Extra command line arguments were specified; complain.
4611 * XXX - interpret as capture filter, as tcpdump and tshark do?
4613 cmdarg_err("Invalid argument: %s", argv[0]);
4618 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4621 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4622 /* Use some default if the user hasn't specified some */
4623 /* XXX: Are these defaults good enough? */
4624 pcap_queue_byte_limit = 1000 * 1000;
4625 pcap_queue_packet_limit = 1000;
4632 if (run_once_args > 1) {
4633 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
4635 } else if (run_once_args == 1) {
4636 /* We're supposed to print some information, rather than
4637 to capture traffic; did they specify a ring buffer option? */
4638 if (global_capture_opts.multi_files_on) {
4639 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4643 /* We're supposed to capture traffic; */
4644 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4645 if (global_capture_opts.ifaces->len > 1) {
4647 global_capture_opts.use_pcapng = TRUE;
4649 /* Was the ring buffer option specified and, if so, does it make sense? */
4650 if (global_capture_opts.multi_files_on) {
4651 /* Ring buffer works only under certain conditions:
4652 a) ring buffer does not work with temporary files;
4653 b) it makes no sense to enable the ring buffer if the maximum
4654 file size is set to "infinite". */
4655 if (global_capture_opts.save_file == NULL) {
4656 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4657 global_capture_opts.multi_files_on = FALSE;
4659 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4660 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4662 /* XXX - this must be redesigned as the conditions changed */
4663 global_capture_opts.multi_files_on = FALSE;
4670 * "-D" requires no interface to be selected; it's supposed to list
4673 if (list_interfaces) {
4674 /* Get the list of interfaces */
4679 if_list = capture_interface_list(&err, &err_str);
4680 if (if_list == NULL) {
4682 case CANT_GET_INTERFACE_LIST:
4683 case DONT_HAVE_PCAP:
4684 cmdarg_err("%s", err_str);
4689 case NO_INTERFACES_FOUND:
4691 * If we're being run by another program, just give them
4692 * an empty list of interfaces, don't report this as
4693 * an error; that lets them decide whether to report
4694 * this as an error or not.
4696 if (!machine_readable) {
4697 cmdarg_err("There are no interfaces on which a capture can be done");
4704 if (machine_readable) /* tab-separated values to stdout */
4705 print_machine_readable_interfaces(if_list);
4707 capture_opts_print_interfaces(if_list);
4708 free_interface_list(if_list);
4713 * "-S" requires no interface to be selected; it gives statistics
4714 * for all interfaces.
4716 if (print_statistics) {
4717 status = print_statistics_loop(machine_readable);
4722 interface_options interface_opts;
4724 if (global_capture_opts.ifaces->len != 1) {
4725 cmdarg_err("Need one interface");
4729 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4730 status = set_80211_channel(interface_opts.name, set_chan_arg);
4735 * "-L", "-d", and capturing act on a particular interface, so we have to
4736 * have an interface; if none was specified, pick a default.
4738 status = capture_opts_trim_iface(&global_capture_opts, NULL);
4740 /* cmdarg_err() already called .... */
4744 /* Let the user know what interfaces were chosen. */
4745 if (capture_child) {
4746 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4747 interface_options interface_opts;
4749 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4750 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4751 interface_opts.name);
4754 str = g_string_new("");
4756 if (global_capture_opts.ifaces->len < 2)
4758 if (global_capture_opts.ifaces->len < 4)
4761 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4762 interface_options interface_opts;
4764 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4766 if (global_capture_opts.ifaces->len > 2) {
4767 g_string_append_printf(str, ",");
4769 g_string_append_printf(str, " ");
4770 if (j == global_capture_opts.ifaces->len - 1) {
4771 g_string_append_printf(str, "and ");
4774 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
4777 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4779 fprintf(stderr, "Capturing on %s\n", str->str);
4780 g_string_free(str, TRUE);
4783 if (list_link_layer_types) {
4784 /* Get the list of link-layer types for the capture device. */
4785 if_capabilities_t *caps;
4789 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4790 interface_options interface_opts;
4792 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4793 caps = get_if_capabilities(interface_opts.name,
4794 interface_opts.monitor_mode, &err_str);
4796 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4797 "Please check to make sure you have sufficient permissions, and that\n"
4798 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4802 if (caps->data_link_types == NULL) {
4803 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4806 if (machine_readable) /* tab-separated values to stdout */
4807 /* XXX: We need to change the format and adopt consumers */
4808 print_machine_readable_if_capabilities(caps);
4810 /* XXX: We might want to print also the interface name */
4811 capture_opts_print_if_capabilities(caps, interface_opts.name,
4812 interface_opts.monitor_mode);
4813 free_if_capabilities(caps);
4818 /* We're supposed to do a capture, or print the BPF code for a filter.
4819 Process the snapshot length, as that affects the generated BPF code. */
4820 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4822 #ifdef HAVE_BPF_IMAGE
4823 if (print_bpf_code) {
4824 show_filter_code(&global_capture_opts);
4829 /* We're supposed to do a capture. Process the ring buffer arguments. */
4830 capture_opts_trim_ring_num_files(&global_capture_opts);
4832 /* flush stderr prior to starting the main capture loop */
4835 /* Now start the capture. */
4837 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4841 /* capture failed */
4844 return 0; /* never here, make compiler happy */
4849 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4850 const char *message, gpointer user_data _U_)
4857 /* ignore log message, if log_level isn't interesting */
4858 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4859 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4864 /* create a "timestamp" */
4866 today = localtime(&curr);
4868 switch(log_level & G_LOG_LEVEL_MASK) {
4869 case G_LOG_LEVEL_ERROR:
4872 case G_LOG_LEVEL_CRITICAL:
4875 case G_LOG_LEVEL_WARNING:
4878 case G_LOG_LEVEL_MESSAGE:
4881 case G_LOG_LEVEL_INFO:
4884 case G_LOG_LEVEL_DEBUG:
4888 fprintf(stderr, "unknown log_level %u\n", log_level);
4890 g_assert_not_reached();
4893 /* Generate the output message */
4894 if (log_level & G_LOG_LEVEL_MESSAGE) {
4895 /* normal user messages without additional infos */
4896 msg = g_strdup_printf("%s\n", message);
4898 /* info/debug messages with additional infos */
4899 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4900 today->tm_hour, today->tm_min, today->tm_sec,
4901 log_domain != NULL ? log_domain : "",
4905 /* DEBUG & INFO msgs (if we're debugging today) */
4906 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4907 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4908 #ifdef DEBUG_DUMPCAP
4909 fprintf(stderr, "%s", msg);
4912 #ifdef DEBUG_CHILD_DUMPCAP
4913 fprintf(debug_log, "%s", msg);
4921 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4922 /* to parent especially formatted if dumpcap running as child. */
4923 if (capture_child) {
4924 sync_pipe_errmsg_to_parent(2, msg, "");
4926 fprintf(stderr, "%s", msg);
4933 /****************************************************************************************************************/
4934 /* indication report routines */
4938 report_packet_count(unsigned int packet_count)
4940 char tmp[SP_DECISIZE+1+1];
4941 static unsigned int count = 0;
4943 if (capture_child) {
4944 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
4945 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
4946 pipe_write_block(2, SP_PACKET_COUNT, tmp);
4948 count += packet_count;
4949 fprintf(stderr, "\rPackets: %u ", count);
4950 /* stderr could be line buffered */
4956 report_new_capture_file(const char *filename)
4958 if (capture_child) {
4959 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
4960 pipe_write_block(2, SP_FILE, filename);
4964 * Prevent a SIGINFO handler from writing to the standard error
4965 * while we're doing so; instead, have it just set a flag telling
4966 * us to print that information when we're done.
4969 #endif /* SIGINFO */
4970 fprintf(stderr, "File: %s\n", filename);
4971 /* stderr could be line buffered */
4976 * Allow SIGINFO handlers to write.
4981 * If a SIGINFO handler asked us to write out capture counts, do so.
4984 report_counts_for_siginfo();
4985 #endif /* SIGINFO */
4990 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
4992 interface_options interface_opts;
4993 char tmp[MSG_MAX_LENGTH+1+6];
4995 if (i < capture_opts->ifaces->len) {
4996 if (capture_child) {
4997 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
4998 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
4999 pipe_write_block(2, SP_BAD_FILTER, tmp);
5002 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5003 * the error message below.
5005 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
5007 "Invalid capture filter \"%s\" for interface %s!\n"
5009 "That string isn't a valid capture filter (%s).\n"
5010 "See the User's Guide for a description of the capture filter syntax.",
5011 interface_opts.cfilter, interface_opts.name, errmsg);
5017 report_capture_error(const char *error_msg, const char *secondary_error_msg)
5019 if (capture_child) {
5020 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5021 "Primary Error: %s", error_msg);
5022 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5023 "Secondary Error: %s", secondary_error_msg);
5024 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5026 cmdarg_err("%s", error_msg);
5027 if (secondary_error_msg[0] != '\0')
5028 cmdarg_err_cont("%s", secondary_error_msg);
5033 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, gchar *name)
5035 char tmp[SP_DECISIZE+1+1];
5036 guint32 total_drops = pcap_drops + drops + flushed;
5038 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
5040 if (capture_child) {
5041 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5042 "Packets received/dropped on interface %s: %u/%u (pcap:%u/dumpcap:%u/flushed:%u)",
5043 name, received, total_drops, pcap_drops, drops, flushed);
5044 /* XXX: Need to provide interface id, changes to consumers required. */
5045 pipe_write_block(2, SP_DROPS, tmp);
5048 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u) (%.1f%%)\n",
5049 name, received, total_drops, pcap_drops, drops, flushed,
5050 received ? 100.0 * received / (received + total_drops) : 0.0);
5051 /* stderr could be line buffered */
5057 /************************************************************************************************/
5058 /* signal_pipe handling */
5063 signal_pipe_check_running(void)
5065 /* any news from our parent? -> just stop the capture */
5069 /* if we are running standalone, no check required */
5070 if (!capture_child) {
5074 if (!sig_pipe_name || !sig_pipe_handle) {
5075 /* This shouldn't happen */
5076 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5077 "Signal pipe: No name or handle");
5082 * XXX - We should have the process ID of the parent (from the "-Z" flag)
5083 * at this point. Should we check to see if the parent is still alive,
5084 * e.g. by using OpenProcess?
5087 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5089 if (!result || avail > 0) {
5090 /* peek failed or some bytes really available */
5091 /* (if not piping from stdin this would fail) */
5092 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5093 "Signal pipe: Stop capture: %s", sig_pipe_name);
5094 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5095 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
5096 sig_pipe_handle, result, avail);
5099 /* pipe ok and no bytes available */
5106 * Editor modelines - http://www.wireshark.org/tools/modelines.html
5111 * indent-tabs-mode: nil
5114 * vi: set shiftwidth=4 tabstop=8 expandtab:
5115 * :indentSize=4:tabSize=8:noTabs=true: