5 * Wireshark - Network traffic analyzer
6 * By Gerald Combs <gerald@wireshark.org>
7 * Copyright 1998 Gerald Combs
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 #include <stdlib.h> /* for exit() */
33 #ifdef HAVE_SYS_TYPES_H
34 # include <sys/types.h>
37 #ifdef HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
41 #ifdef HAVE_NETINET_IN_H
42 #include <netinet/in.h>
45 #ifdef HAVE_SYS_STAT_H
46 # include <sys/stat.h>
61 #ifdef HAVE_ARPA_INET_H
62 #include <arpa/inet.h>
65 #if defined(__APPLE__) && defined(__LP64__)
66 #include <sys/utsname.h>
72 #include <wsutil/crash_info.h>
75 #include "wsutil/wsgetopt.h"
83 # include <sys/prctl.h>
84 # include <sys/capability.h>
87 #include "ringbuffer.h"
88 #include "clopts_common.h"
89 #include "cmdarg_err.h"
90 #include "version_info.h"
92 #include "capture-pcap-util.h"
94 #include "capture-wpcap.h"
100 #include "capture-wpcap.h"
101 #include <wsutil/unicode-utils.h>
108 #ifdef NEED_INET_V6DEFS_H
109 # include "wsutil/inet_v6defs.h"
112 #include <wsutil/privileges.h>
114 #include "sync_pipe.h"
116 #include "capture_opts.h"
117 #include "capture_session.h"
118 #include "capture_ifinfo.h"
119 #include "capture_sync.h"
121 #include "conditions.h"
122 #include "capture_stop_conditions.h"
124 #include "wsutil/tempfile.h"
126 #include "wsutil/file_util.h"
128 #include "ws80211_utils.h"
131 * Get information about libpcap format from "wiretap/libpcap.h".
132 * XXX - can we just use pcap_open_offline() to read the pipe?
134 #include "wiretap/libpcap.h"
136 /**#define DEBUG_DUMPCAP**/
137 /**#define DEBUG_CHILD_DUMPCAP**/
141 #include <conio.h> /* _getch() */
145 #ifdef DEBUG_CHILD_DUMPCAP
146 FILE *debug_log; /* for logging debug messages to */
147 /* a file if DEBUG_CHILD_DUMPCAP */
151 static GAsyncQueue *pcap_queue;
152 static gint64 pcap_queue_bytes;
153 static gint64 pcap_queue_packets;
154 static gint64 pcap_queue_byte_limit = 0;
155 static gint64 pcap_queue_packet_limit = 0;
157 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
159 static gchar *sig_pipe_name = NULL;
160 static HANDLE sig_pipe_handle = NULL;
161 static gboolean signal_pipe_check_running(void);
165 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
166 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
169 /** Stop a low-level capture (stops the capture child). */
170 static void capture_loop_stop(void);
171 /** Close a pipe, or socket if \a from_socket is TRUE */
172 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
174 #if !defined (__linux__)
175 #ifndef HAVE_PCAP_BREAKLOOP
177 * We don't have pcap_breakloop(), which is the only way to ensure that
178 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
179 * won't, if the call to read the next packet or batch of packets is
180 * is interrupted by a signal on UN*X, just go back and try again to
183 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
184 * the signal handler, set a flag to stop capturing; however, without
185 * a guarantee of that sort, we can't guarantee that we'll stop capturing
186 * if the read will be retried and won't time out if no packets arrive.
188 * Therefore, on at least some platforms, we work around the lack of
189 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
190 * to wait for packets to arrive, so that we're probably going to be
191 * blocked in the select() when the signal arrives, and can just bail
192 * out of the loop at that point.
194 * However, we don't want to do that on BSD (because "select()" doesn't work
195 * correctly on BPF devices on at least some releases of some flavors of
196 * BSD), and we don't want to do it on Windows (because "select()" is
197 * something for sockets, not for arbitrary handles). (Note that "Windows"
198 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
199 * using WinPcap, not a UNIX libpcap.)
201 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
202 * on BSD times out even if no packets have arrived, so we'll eventually
203 * exit pcap_dispatch() with an indication that no packets have arrived,
204 * and will break out of the capture loop at that point.
206 * On Windows, we can't send a SIGINT to stop capturing, so none of this
207 * applies in any case.
209 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
210 * want to include it if it's not present on this platform, however.
212 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
213 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
215 # define MUST_DO_SELECT
216 # endif /* avoid select */
217 #endif /* HAVE_PCAP_BREAKLOOP */
219 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
220 * in pcap_dispatch(); on the other hand, select() works just fine there.
221 * Hence we use a select for that come what may.
223 #define MUST_DO_SELECT
226 /** init the capture filter */
229 INITFILTER_BAD_FILTER,
230 INITFILTER_OTHER_ERROR
231 } initfilter_status_t;
234 STATE_EXPECT_REC_HDR,
247 typedef struct _pcap_options {
252 #ifdef MUST_DO_SELECT
253 int pcap_fd; /**< pcap file descriptor */
260 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
261 /**< capture pipe (unix only "input file") */
262 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
263 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
264 struct pcap_hdr cap_pipe_hdr; /**< Pcap header when capturing from a pipe */
265 struct pcaprec_modified_hdr cap_pipe_rechdr; /**< Pcap record header when capturing from a pipe */
267 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
269 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
270 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
271 gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
273 char * cap_pipe_buf; /**< Pointer to the data buffer we read into */
274 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
275 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
277 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
278 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
280 cap_pipe_state_t cap_pipe_state;
281 cap_pipe_err_t cap_pipe_err;
284 GMutex *cap_pipe_read_mtx;
285 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
289 typedef struct _loop_data {
291 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
292 int err; /**< if non-zero, error seen while capturing */
293 gint packet_count; /**< Number of packets we have already captured */
294 gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
295 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
297 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
303 guint64 bytes_written;
304 guint32 autostop_files;
307 typedef struct _pcap_queue_element {
308 pcap_options *pcap_opts;
309 struct pcap_pkthdr phdr;
311 } pcap_queue_element;
314 * Standard secondary message for unexpected errors.
316 static const char please_report[] =
317 "Please report this to the Wireshark developers.\n"
318 "http://bugs.wireshark.org/\n"
319 "(This is not a crash; please do not report it as such.)";
322 * This needs to be static, so that the SIGINT handler can clear the "go"
325 static loop_data global_ld;
329 * Timeout, in milliseconds, for reads from the stream of captured packets
330 * from a capture device.
332 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
333 * 64-bit applications, with sub-second timeouts not to work. The bug is
334 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
336 #if defined(__APPLE__) && defined(__LP64__)
337 static gboolean need_timeout_workaround;
339 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
341 #define CAP_READ_TIMEOUT 250
345 * Timeout, in microseconds, for reads from the stream of captured packets
346 * from a pipe. Pipes don't have the same problem that BPF devices do
347 * in OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
348 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
349 * of the offending versions of Snow Leopard.
351 * On Windows this value is converted to milliseconds and passed to
352 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
353 * will return immediately.
356 #define PIPE_READ_TIMEOUT 100000
358 #define PIPE_READ_TIMEOUT 250000
361 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
364 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
365 const char *message, gpointer user_data _U_);
367 /* capture related options */
368 static capture_options global_capture_opts;
369 static gboolean quiet = FALSE;
370 static gboolean use_threads = FALSE;
371 static guint64 start_time;
373 static void capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
375 static void capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
377 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
378 int err, gboolean is_close);
380 static void WS_MSVC_NORETURN exit_main(int err) G_GNUC_NORETURN;
382 static void report_new_capture_file(const char *filename);
383 static void report_packet_count(unsigned int packet_count);
384 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, gchar *name);
385 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
386 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
388 #define MSG_MAX_LENGTH 4096
390 /* Copied from pcapio.c libpcap_write_interface_statistics_block()*/
392 create_timestamp(void) {
402 * Current time, represented as 100-nanosecond intervals since
403 * January 1, 1601, 00:00:00 UTC.
405 * I think DWORD might be signed, so cast both parts of "now"
406 * to guint32 so that the sign bit doesn't get treated specially.
408 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
409 * might want to use instead.
411 GetSystemTimeAsFileTime(&now);
412 timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
413 (guint32)now.dwLowDateTime;
416 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
422 * Subtract difference, in microseconds, between January 1, 1601
423 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
425 timestamp -= G_GINT64_CONSTANT(11644473600000000U);
428 * Current time, represented as seconds and microseconds since
429 * January 1, 1970, 00:00:00 UTC.
431 gettimeofday(&now, NULL);
434 * Convert to delta in microseconds.
436 timestamp = (guint64)(now.tv_sec) * 1000000 +
437 (guint64)(now.tv_usec);
443 print_usage(gboolean print_ver)
450 "Dumpcap " VERSION "%s\n"
451 "Capture network packets and dump them into a pcapng file.\n"
452 "See http://www.wireshark.org for more information.\n",
453 wireshark_svnversion);
457 fprintf(output, "\nUsage: dumpcap [options] ...\n");
458 fprintf(output, "\n");
459 fprintf(output, "Capture interface:\n");
460 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
461 " or for remote capturing, use one of these formats:\n"
462 " rpcap://<host>/<interface>\n"
463 " TCP@<host>:<port>\n");
464 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
465 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
466 fprintf(output, " -p don't capture in promiscuous mode\n");
467 #ifdef HAVE_PCAP_CREATE
468 fprintf(output, " -I capture in monitor mode, if available\n");
470 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
471 fprintf(output, " -B <buffer size> size of kernel buffer in MB (def: %dMB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
473 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
474 fprintf(output, " -D print list of interfaces and exit\n");
475 fprintf(output, " -L print list of link-layer types of iface and exit\n");
476 #ifdef HAVE_BPF_IMAGE
477 fprintf(output, " -d print generated BPF code for capture filter\n");
479 fprintf(output, " -k set channel on wifi interface <freq>,[<type>]\n");
480 fprintf(output, " -S print statistics for each interface once per second\n");
481 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
482 fprintf(output, "\n");
483 #ifdef HAVE_PCAP_REMOTE
484 fprintf(output, "RPCAP options:\n");
485 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
486 fprintf(output, " -u use UDP for RPCAP data transfer\n");
487 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
488 #ifdef HAVE_PCAP_SETSAMPLING
489 fprintf(output, " -m <sampling type> use packet sampling\n");
490 fprintf(output, " count:NUM - capture one packet of every NUM\n");
491 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
494 fprintf(output, "Stop conditions:\n");
495 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
496 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
497 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
498 fprintf(output, " files:NUM - stop after NUM files\n");
499 /*fprintf(output, "\n");*/
500 fprintf(output, "Output (files):\n");
501 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
502 fprintf(output, " -g enable group read access on the output file(s)\n");
503 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
504 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
505 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
506 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
507 fprintf(output, " -P use libpcap format instead of pcapng\n");
508 fprintf(output, " --capture-comment <comment>\n");
509 fprintf(output, " add a capture comment to the output file\n");
510 fprintf(output, " (only for pcapng)\n");
511 fprintf(output, "\n");
512 fprintf(output, "Miscellaneous:\n");
513 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
514 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
515 fprintf(output, " within dumpcap\n");
516 fprintf(output, " -t use a separate thread per interface\n");
517 fprintf(output, " -q don't report packet capture counts\n");
518 fprintf(output, " -v print version information and exit\n");
519 fprintf(output, " -h display this help and exit\n");
520 fprintf(output, "\n");
521 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
522 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
523 fprintf(output, "\n");
524 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
528 show_version(GString *comp_info_str, GString *runtime_info_str)
531 "Dumpcap " VERSION "%s\n"
536 "See http://www.wireshark.org for more information.\n",
537 wireshark_svnversion, get_copyright_info(), comp_info_str->str, runtime_info_str->str);
541 * Report an error in command-line arguments.
544 cmdarg_err(const char *fmt, ...)
550 /* Generate a 'special format' message back to parent */
552 msg = g_strdup_vprintf(fmt, ap);
553 sync_pipe_errmsg_to_parent(2, msg, "");
558 fprintf(stderr, "dumpcap: ");
559 vfprintf(stderr, fmt, ap);
560 fprintf(stderr, "\n");
566 * Report additional information for an error in command-line arguments.
569 cmdarg_err_cont(const char *fmt, ...)
576 msg = g_strdup_vprintf(fmt, ap);
577 sync_pipe_errmsg_to_parent(2, msg, "");
582 vfprintf(stderr, fmt, ap);
583 fprintf(stderr, "\n");
590 #if 0 /* Set to enable capability debugging */
591 /* see 'man cap_to_text()' for explanation of output */
592 /* '=' means 'all= ' ie: no capabilities */
593 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
595 print_caps(const char *pfx) {
596 cap_t caps = cap_get_proc();
597 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
598 "%s: EUID: %d Capabilities: %s", pfx,
599 geteuid(), cap_to_text(caps, NULL));
602 print_caps(const char *pfx _U_) {
607 relinquish_all_capabilities(void)
609 /* Drop any and all capabilities this process may have. */
610 /* Allowed whether or not process has any privileges. */
611 cap_t caps = cap_init(); /* all capabilities initialized to off */
612 print_caps("Pre-clear");
613 if (cap_set_proc(caps)) {
614 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
616 print_caps("Post-clear");
622 open_capture_device(interface_options *interface_opts,
623 char (*open_err_str)[PCAP_ERRBUF_SIZE])
626 #ifdef HAVE_PCAP_CREATE
629 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
630 struct pcap_rmtauth auth;
633 /* Open the network interface to capture from it.
634 Some versions of libpcap may put warnings into the error buffer
635 if they succeed; to tell if that's happened, we have to clear
636 the error buffer, and check if it's still a null string. */
637 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Entering open_capture_device().");
638 (*open_err_str)[0] = '\0';
639 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
641 * If we're opening a remote device, use pcap_open(); that's currently
642 * the only open routine that supports remote devices.
644 if (strncmp (interface_opts->name, "rpcap://", 8) == 0) {
645 auth.type = interface_opts->auth_type == CAPTURE_AUTH_PWD ?
646 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
647 auth.username = interface_opts->auth_username;
648 auth.password = interface_opts->auth_password;
650 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
651 "Calling pcap_open() using name %s, snaplen %d, promisc_mode %d, datatx_udp %d, nocap_rpcap %d.",
652 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode,
653 interface_opts->datatx_udp, interface_opts->nocap_rpcap);
654 pcap_h = pcap_open(interface_opts->name, interface_opts->snaplen,
656 (interface_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
657 (interface_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
658 (interface_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
659 CAP_READ_TIMEOUT, &auth, *open_err_str);
660 if (pcap_h == NULL) {
661 /* Error - did pcap actually supply an error message? */
662 if ((*open_err_str)[0] == '\0') {
663 /* Work around known WinPcap bug wherein no error message is
664 filled in on a failure to open an rpcap: URL. */
665 g_strlcpy(*open_err_str,
666 "Unknown error (pcap bug; actual error cause not reported)",
667 sizeof *open_err_str);
670 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
671 "pcap_open() returned %p.", (void *)pcap_h);
676 * If we're not opening a remote device, use pcap_create() and
677 * pcap_activate() if we have them, so that we can set the buffer
678 * size, otherwise use pcap_open_live().
680 #ifdef HAVE_PCAP_CREATE
681 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
682 "Calling pcap_create() using %s.", interface_opts->name);
683 pcap_h = pcap_create(interface_opts->name, *open_err_str);
684 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
685 "pcap_create() returned %p.", (void *)pcap_h);
686 if (pcap_h != NULL) {
687 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
688 "Calling pcap_set_snaplen() with snaplen %d.", interface_opts->snaplen);
689 pcap_set_snaplen(pcap_h, interface_opts->snaplen);
690 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
691 "Calling pcap_set_promisc() with promisc_mode %d.", interface_opts->promisc_mode);
692 pcap_set_promisc(pcap_h, interface_opts->promisc_mode);
693 pcap_set_timeout(pcap_h, CAP_READ_TIMEOUT);
695 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
696 "buffersize %d.", interface_opts->buffer_size);
697 if (interface_opts->buffer_size != 0) {
698 pcap_set_buffer_size(pcap_h, interface_opts->buffer_size * 1024 * 1024);
700 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
701 "monitor_mode %d.", interface_opts->monitor_mode);
702 if (interface_opts->monitor_mode)
703 pcap_set_rfmon(pcap_h, 1);
704 err = pcap_activate(pcap_h);
705 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
706 "pcap_activate() returned %d.", err);
708 /* Failed to activate, set to NULL */
709 if (err == PCAP_ERROR)
710 g_strlcpy(*open_err_str, pcap_geterr(pcap_h), sizeof *open_err_str);
712 g_strlcpy(*open_err_str, pcap_statustostr(err), sizeof *open_err_str);
718 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
719 "pcap_open_live() calling using name %s, snaplen %d, promisc_mode %d.",
720 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode);
721 pcap_h = pcap_open_live(interface_opts->name, interface_opts->snaplen,
722 interface_opts->promisc_mode, CAP_READ_TIMEOUT,
724 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
725 "pcap_open_live() returned %p.", (void *)pcap_h);
728 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "open_capture_device %s : %s", pcap_h ? "SUCCESS" : "FAILURE", interface_opts->name);
733 get_capture_device_open_failure_messages(const char *open_err_str,
739 char *errmsg, size_t errmsg_len,
740 char *secondary_errmsg,
741 size_t secondary_errmsg_len)
744 const char *libpcap_warn;
745 static const char ppamsg[] = "can't find PPA for ";
748 g_snprintf(errmsg, (gulong) errmsg_len,
749 "The capture session could not be initiated (%s).", open_err_str);
752 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
754 "In order to capture packets, WinPcap must be installed; see\n"
756 " http://www.winpcap.org/\n"
760 " http://www.mirrors.wiretapped.net/security/packet-capture/winpcap/\n"
764 " http://winpcap.cs.pu.edu.tw/\n"
766 "for a downloadable version of WinPcap and for instructions on how to install\n"
769 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
771 "Please check that \"%s\" is the proper interface.\n"
774 "Help can be found at:\n"
776 " http://wiki.wireshark.org/WinPcap\n"
777 " http://wiki.wireshark.org/CaptureSetup\n",
781 /* If we got a "can't find PPA for X" message, warn the user (who
782 is running dumpcap on HP-UX) that they don't have a version of
783 libpcap that properly handles HP-UX (libpcap 0.6.x and later
784 versions, which properly handle HP-UX, say "can't find /dev/dlpi
785 PPA for X" rather than "can't find PPA for X"). */
786 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
789 "You are running (T)Wireshark with a version of the libpcap library\n"
790 "that doesn't handle HP-UX network devices well; this means that\n"
791 "(T)Wireshark may not be able to capture packets.\n"
793 "To fix this, you should install libpcap 0.6.2, or a later version\n"
794 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
795 "packaged binary form from the Software Porting And Archive Centre\n"
796 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
797 "at the URL lists a number of mirror sites.";
801 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
802 "Please check to make sure you have sufficient permissions, and that you have "
803 "the proper interface or pipe specified.%s", libpcap_warn);
807 /* Set the data link type on a pcap. */
809 set_pcap_linktype(pcap_t *pcap_h, int linktype,
810 #ifdef HAVE_PCAP_SET_DATALINK
815 char *errmsg, size_t errmsg_len,
816 char *secondary_errmsg, size_t secondary_errmsg_len)
818 char *set_linktype_err_str;
821 return TRUE; /* just use the default */
822 #ifdef HAVE_PCAP_SET_DATALINK
823 if (pcap_set_datalink(pcap_h, linktype) == 0)
824 return TRUE; /* no error */
825 set_linktype_err_str = pcap_geterr(pcap_h);
827 /* Let them set it to the type it is; reject any other request. */
828 if (get_pcap_linktype(pcap_h, name) == linktype)
829 return TRUE; /* no error */
830 set_linktype_err_str =
831 "That DLT isn't one of the DLTs supported by this device";
833 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
834 set_linktype_err_str);
836 * If the error isn't "XXX is not one of the DLTs supported by this device",
837 * tell the user to tell the Wireshark developers about it.
839 if (strstr(set_linktype_err_str, "is not one of the DLTs supported by this device") == NULL)
840 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
842 secondary_errmsg[0] = '\0';
847 compile_capture_filter(const char *iface, pcap_t *pcap_h,
848 struct bpf_program *fcode, const char *cfilter)
850 bpf_u_int32 netnum, netmask;
851 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
853 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
855 * Well, we can't get the netmask for this interface; it's used
856 * only for filters that check for broadcast IP addresses, so
857 * we just punt and use 0. It might be nice to warn the user,
858 * but that's a pain in a GUI application, as it'd involve popping
859 * up a message box, and it's not clear how often this would make
860 * a difference (only filters that check for IP broadcast addresses
864 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
869 * Sigh. Older versions of libpcap don't properly declare the
870 * third argument to pcap_compile() as a const pointer. Cast
873 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
878 #ifdef HAVE_BPF_IMAGE
880 show_filter_code(capture_options *capture_opts)
882 interface_options interface_opts;
884 gchar open_err_str[PCAP_ERRBUF_SIZE];
885 char errmsg[MSG_MAX_LENGTH+1];
886 char secondary_errmsg[MSG_MAX_LENGTH+1];
887 struct bpf_program fcode;
888 struct bpf_insn *insn;
892 for (j = 0; j < capture_opts->ifaces->len; j++) {
893 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
894 pcap_h = open_capture_device(&interface_opts, &open_err_str);
895 if (pcap_h == NULL) {
896 /* Open failed; get messages */
897 get_capture_device_open_failure_messages(open_err_str,
899 errmsg, sizeof errmsg,
901 sizeof secondary_errmsg);
902 /* And report them */
903 report_capture_error(errmsg, secondary_errmsg);
907 /* Set the link-layer type. */
908 if (!set_pcap_linktype(pcap_h, interface_opts.linktype, interface_opts.name,
909 errmsg, sizeof errmsg,
910 secondary_errmsg, sizeof secondary_errmsg)) {
912 report_capture_error(errmsg, secondary_errmsg);
916 /* OK, try to compile the capture filter. */
917 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
918 interface_opts.cfilter)) {
920 report_cfilter_error(capture_opts, j, errmsg);
925 /* Now print the filter code. */
926 insn = fcode.bf_insns;
928 for (i = 0; i < fcode.bf_len; insn++, i++)
929 printf("%s\n", bpf_image(insn, i));
931 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
932 /* to remove any suid privileges. */
933 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
934 /* (euid/egid have already previously been set to ruid/rgid. */
935 /* (See comment in main() for details) */
937 relinquish_special_privs_perm();
939 relinquish_all_capabilities();
942 /* Let our parent know we succeeded. */
943 pipe_write_block(2, SP_SUCCESS, NULL);
950 * capture_interface_list() is expected to do the right thing to get
951 * a list of interfaces.
953 * In most of the programs in the Wireshark suite, "the right thing"
954 * is to run dumpcap and ask it for the list, because dumpcap may
955 * be the only program in the suite with enough privileges to get
958 * In dumpcap itself, however, we obviously can't run dumpcap to
959 * ask for the list. Therefore, our capture_interface_list() should
960 * just call get_interface_list().
963 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
965 return get_interface_list(err, err_str);
969 * Get the data-link type for a libpcap device.
970 * This works around AIX 5.x's non-standard and incompatible-with-the-
971 * rest-of-the-universe libpcap.
974 get_pcap_linktype(pcap_t *pch, const char *devicename
982 const char *ifacename;
985 linktype = pcap_datalink(pch);
989 * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
990 * rather than DLT_ values for link-layer types; the ifType values
991 * for LAN devices are:
998 * and the ifType value for a loopback device is 24.
1000 * The AIX names for LAN devices begin with:
1007 * and the AIX names for loopback devices begin with "lo".
1009 * (The difference between "Ethernet" and "802.3" is presumably
1010 * whether packets have an Ethernet header, with a packet type,
1011 * or an 802.3 header, with a packet length, followed by an 802.2
1012 * header and possibly a SNAP header.)
1014 * If the device name matches "linktype" interpreted as an ifType
1015 * value, rather than as a DLT_ value, we will assume this is AIX's
1016 * non-standard, incompatible libpcap, rather than a standard libpcap,
1017 * and will map the link-layer type to the standard DLT_ value for
1018 * that link-layer type, as that's what the rest of Wireshark expects.
1020 * (This means the capture files won't be readable by a tcpdump
1021 * linked with AIX's non-standard libpcap, but so it goes. They
1022 * *will* be readable by standard versions of tcpdump, Wireshark,
1025 * XXX - if we conclude we're using AIX libpcap, should we also
1026 * set a flag to cause us to assume the time stamps are in
1027 * seconds-and-nanoseconds form, and to convert them to
1028 * seconds-and-microseconds form before processing them and
1033 * Find the last component of the device name, which is the
1036 ifacename = strchr(devicename, '/');
1037 if (ifacename == NULL)
1038 ifacename = devicename;
1040 /* See if it matches any of the LAN device names. */
1041 if (strncmp(ifacename, "en", 2) == 0) {
1042 if (linktype == 6) {
1044 * That's the RFC 1573 value for Ethernet; map it to DLT_EN10MB.
1048 } else if (strncmp(ifacename, "et", 2) == 0) {
1049 if (linktype == 7) {
1051 * That's the RFC 1573 value for 802.3; map it to DLT_EN10MB.
1052 * (libpcap, tcpdump, Wireshark, etc. don't care if it's Ethernet
1057 } else if (strncmp(ifacename, "tr", 2) == 0) {
1058 if (linktype == 9) {
1060 * That's the RFC 1573 value for 802.5 (Token Ring); map it to
1061 * DLT_IEEE802, which is what's used for Token Ring.
1065 } else if (strncmp(ifacename, "fi", 2) == 0) {
1066 if (linktype == 15) {
1068 * That's the RFC 1573 value for FDDI; map it to DLT_FDDI.
1072 } else if (strncmp(ifacename, "lo", 2) == 0) {
1073 if (linktype == 24) {
1075 * That's the RFC 1573 value for "software loopback" devices; map it
1076 * to DLT_NULL, which is what's used for loopback devices on BSD.
1086 static data_link_info_t *
1087 create_data_link_info(int dlt)
1089 data_link_info_t *data_link_info;
1092 data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
1093 data_link_info->dlt = dlt;
1094 text = pcap_datalink_val_to_name(dlt);
1096 data_link_info->name = g_strdup(text);
1098 data_link_info->name = g_strdup_printf("DLT %d", dlt);
1099 text = pcap_datalink_val_to_description(dlt);
1101 data_link_info->description = g_strdup(text);
1103 data_link_info->description = NULL;
1104 return data_link_info;
1108 * Get the capabilities of a network device.
1110 static if_capabilities_t *
1111 get_if_capabilities(const char *devicename, gboolean monitor_mode
1112 #ifndef HAVE_PCAP_CREATE
1117 if_capabilities_t *caps;
1118 char errbuf[PCAP_ERRBUF_SIZE];
1120 #ifdef HAVE_PCAP_CREATE
1124 #ifdef HAVE_PCAP_LIST_DATALINKS
1128 data_link_info_t *data_link_info;
1131 * Allocate the interface capabilities structure.
1133 caps = (if_capabilities_t *)g_malloc(sizeof *caps);
1136 * WinPcap 4.1.2, and possibly earlier versions, have a bug
1137 * wherein, when an open with an rpcap: URL fails, the error
1138 * message for the error is not copied to errbuf and whatever
1139 * on-the-stack junk is in errbuf is treated as the error
1142 * To work around that (and any other bugs of that sort, we
1143 * initialize errbuf to an empty string. If we get an error
1144 * and the string is empty, we report it as an unknown error.
1145 * (If we *don't* get an error, and the string is *non*-empty,
1146 * that could be a warning returned, such as "can't turn
1147 * promiscuous mode on"; we currently don't do so.)
1150 #ifdef HAVE_PCAP_OPEN
1151 pch = pcap_open(devicename, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1152 caps->can_set_rfmon = FALSE;
1154 if (err_str != NULL)
1155 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1159 #elif defined(HAVE_PCAP_CREATE)
1160 pch = pcap_create(devicename, errbuf);
1162 if (err_str != NULL)
1163 *err_str = g_strdup(errbuf);
1167 status = pcap_can_set_rfmon(pch);
1170 if (status == PCAP_ERROR)
1171 *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
1174 *err_str = g_strdup(pcap_statustostr(status));
1180 caps->can_set_rfmon = FALSE;
1181 else if (status == 1) {
1182 caps->can_set_rfmon = TRUE;
1184 pcap_set_rfmon(pch, 1);
1186 if (err_str != NULL) {
1187 *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
1195 status = pcap_activate(pch);
1197 /* Error. We ignore warnings (status > 0). */
1198 if (err_str != NULL) {
1199 if (status == PCAP_ERROR)
1200 *err_str = g_strdup_printf("pcap_activate() failed: %s",
1203 *err_str = g_strdup(pcap_statustostr(status));
1210 pch = pcap_open_live(devicename, MIN_PACKET_SIZE, 0, 0, errbuf);
1211 caps->can_set_rfmon = FALSE;
1213 if (err_str != NULL)
1214 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1219 deflt = get_pcap_linktype(pch, devicename);
1220 #ifdef HAVE_PCAP_LIST_DATALINKS
1221 nlt = pcap_list_datalinks(pch, &linktypes);
1222 if (nlt == 0 || linktypes == NULL) {
1224 if (err_str != NULL)
1225 *err_str = NULL; /* an empty list doesn't mean an error */
1229 caps->data_link_types = NULL;
1230 for (i = 0; i < nlt; i++) {
1231 data_link_info = create_data_link_info(linktypes[i]);
1234 * XXX - for 802.11, make the most detailed 802.11
1235 * version the default, rather than the one the
1236 * device has as the default?
1238 if (linktypes[i] == deflt)
1239 caps->data_link_types = g_list_prepend(caps->data_link_types,
1242 caps->data_link_types = g_list_append(caps->data_link_types,
1245 #ifdef HAVE_PCAP_FREE_DATALINKS
1246 pcap_free_datalinks(linktypes);
1249 * In Windows, there's no guarantee that if you have a library
1250 * built with one version of the MSVC++ run-time library, and
1251 * it returns a pointer to allocated data, you can free that
1252 * data from a program linked with another version of the
1253 * MSVC++ run-time library.
1255 * This is not an issue on UN*X.
1257 * See the mail threads starting at
1259 * http://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
1263 * http://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
1266 #define xx_free free /* hack so checkAPIs doesn't complain */
1269 #endif /* HAVE_PCAP_FREE_DATALINKS */
1270 #else /* HAVE_PCAP_LIST_DATALINKS */
1272 data_link_info = create_data_link_info(deflt);
1273 caps->data_link_types = g_list_append(caps->data_link_types,
1275 #endif /* HAVE_PCAP_LIST_DATALINKS */
1279 if (err_str != NULL)
1284 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
1286 * Output a machine readable list of the interfaces
1287 * This list is retrieved by the sync_interface_list_open() function
1288 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
1291 print_machine_readable_interfaces(GList *if_list)
1298 char addr_str[ADDRSTRLEN];
1300 if (capture_child) {
1301 /* Let our parent know we succeeded. */
1302 pipe_write_block(2, SP_SUCCESS, NULL);
1305 i = 1; /* Interface id number */
1306 for (if_entry = g_list_first(if_list); if_entry != NULL;
1307 if_entry = g_list_next(if_entry)) {
1308 if_info = (if_info_t *)if_entry->data;
1309 printf("%d. %s\t", i++, if_info->name);
1312 * Print the contents of the if_entry struct in a parseable format.
1313 * Each if_entry element is tab-separated. Addresses are comma-
1316 /* XXX - Make sure our description doesn't contain a tab */
1317 if (if_info->vendor_description != NULL)
1318 printf("%s\t", if_info->vendor_description);
1322 /* XXX - Make sure our friendly name doesn't contain a tab */
1323 if (if_info->friendly_name != NULL)
1324 printf("%s\t", if_info->friendly_name);
1328 printf("%u\t", if_info->type);
1330 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
1331 addr = g_slist_next(addr)) {
1332 if (addr != g_slist_nth(if_info->addrs, 0))
1335 if_addr = (if_addr_t *)addr->data;
1336 switch(if_addr->ifat_type) {
1338 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
1340 printf("%s", addr_str);
1342 printf("<unknown IPv4>");
1346 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
1347 addr_str, ADDRSTRLEN)) {
1348 printf("%s", addr_str);
1350 printf("<unknown IPv6>");
1354 printf("<type unknown %u>", if_addr->ifat_type);
1358 if (if_info->loopback)
1359 printf("\tloopback");
1361 printf("\tnetwork");
1368 * If you change the machine-readable output format of this function,
1369 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
1372 print_machine_readable_if_capabilities(if_capabilities_t *caps)
1375 data_link_info_t *data_link_info;
1376 const gchar *desc_str;
1378 if (capture_child) {
1379 /* Let our parent know we succeeded. */
1380 pipe_write_block(2, SP_SUCCESS, NULL);
1383 if (caps->can_set_rfmon)
1387 for (lt_entry = caps->data_link_types; lt_entry != NULL;
1388 lt_entry = g_list_next(lt_entry)) {
1389 data_link_info = (data_link_info_t *)lt_entry->data;
1390 if (data_link_info->description != NULL)
1391 desc_str = data_link_info->description;
1393 desc_str = "(not supported)";
1394 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
1404 /* Print the number of packets captured for each interface until we're killed. */
1406 print_statistics_loop(gboolean machine_readable)
1408 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1414 char errbuf[PCAP_ERRBUF_SIZE];
1415 struct pcap_stat ps;
1417 if_list = get_interface_list(&err, &err_str);
1418 if (if_list == NULL) {
1420 case CANT_GET_INTERFACE_LIST:
1421 case DONT_HAVE_PCAP:
1422 cmdarg_err("%s", err_str);
1426 case NO_INTERFACES_FOUND:
1427 cmdarg_err("There are no interfaces on which a capture can be done");
1433 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1434 if_info = (if_info_t *)if_entry->data;
1435 #ifdef HAVE_PCAP_OPEN
1436 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1438 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1442 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
1443 if_stat->name = g_strdup(if_info->name);
1445 stat_list = g_list_append(stat_list, if_stat);
1450 cmdarg_err("There are no interfaces on which a capture can be done");
1454 if (capture_child) {
1455 /* Let our parent know we succeeded. */
1456 pipe_write_block(2, SP_SUCCESS, NULL);
1459 if (!machine_readable) {
1460 printf("%-15s %10s %10s\n", "Interface", "Received",
1464 global_ld.go = TRUE;
1465 while (global_ld.go) {
1466 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1467 if_stat = (if_stat_t *)stat_entry->data;
1468 pcap_stats(if_stat->pch, &ps);
1470 if (!machine_readable) {
1471 printf("%-15s %10u %10u\n", if_stat->name,
1472 ps.ps_recv, ps.ps_drop);
1474 printf("%s\t%u\t%u\n", if_stat->name,
1475 ps.ps_recv, ps.ps_drop);
1486 /* XXX - Not reached. Should we look for 'q' in stdin? */
1487 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1488 if_stat = (if_stat_t *)stat_entry->data;
1489 pcap_close(if_stat->pch);
1490 g_free(if_stat->name);
1493 g_list_free(stat_list);
1494 free_interface_list(if_list);
1502 capture_cleanup_handler(DWORD dwCtrlType)
1504 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1505 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1506 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1507 like SIGTERM at least when the machine's shutting down.
1509 For now, if we're running as a command rather than a capture child,
1510 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1511 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1512 in that way on UN*X.
1514 If we're not running as a capture child, we might be running as
1515 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1516 user logs out. (XXX - can we explicitly check whether we're
1517 running as a service?) */
1519 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1520 "Console: Control signal");
1521 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1522 "Console: Control signal, CtrlType: %u", dwCtrlType);
1524 /* Keep capture running if we're a service and a user logs off */
1525 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1526 capture_loop_stop();
1534 capture_cleanup_handler(int signum _U_)
1536 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1537 SIGTERM. We assume that if the user wanted it to keep running
1538 after they logged out, they'd have nohupped it. */
1540 /* Note: don't call g_log() in the signal handler: if we happened to be in
1541 * g_log() in process context when the signal came in, g_log will detect
1542 * the "recursion" and abort.
1545 capture_loop_stop();
1551 report_capture_count(gboolean reportit)
1553 /* Don't print this if we're a capture child. */
1554 if (!capture_child && reportit) {
1555 fprintf(stderr, "\rPackets captured: %u\n", global_ld.packet_count);
1556 /* stderr could be line buffered */
1564 report_counts_for_siginfo(void)
1566 report_capture_count(quiet);
1567 infoprint = FALSE; /* we just reported it */
1571 report_counts_siginfo(int signum _U_)
1573 int sav_errno = errno;
1575 /* If we've been told to delay printing, just set a flag asking
1576 that we print counts (if we're supposed to), otherwise print
1577 the count of packets captured (if we're supposed to). */
1581 report_counts_for_siginfo();
1584 #endif /* SIGINFO */
1587 exit_main(int status)
1590 /* Shutdown windows sockets */
1593 /* can be helpful for debugging */
1594 #ifdef DEBUG_DUMPCAP
1595 printf("Press any key\n");
1606 * If we were linked with libcap (not related to libpcap), make sure we have
1607 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1608 * (See comment in main() for details)
1611 relinquish_privs_except_capture(void)
1613 /* If 'started_with_special_privs' (ie: suid) then enable for
1614 * ourself the NET_ADMIN and NET_RAW capabilities and then
1615 * drop our suid privileges.
1617 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1618 * stuff we don't need (and shouldn't have).
1619 * CAP_NET_RAW: Packet capture (raw sockets).
1622 if (started_with_special_privs()) {
1623 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1624 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1626 cap_t caps = cap_init(); /* all capabilities initialized to off */
1628 print_caps("Pre drop, pre set");
1630 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1631 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1634 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1635 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1637 if (cap_set_proc(caps)) {
1638 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1640 print_caps("Pre drop, post set");
1642 relinquish_special_privs_perm();
1644 print_caps("Post drop, pre set");
1645 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1646 if (cap_set_proc(caps)) {
1647 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1649 print_caps("Post drop, post set");
1655 #endif /* HAVE_LIBCAP */
1657 /* Take care of byte order in the libpcap headers read from pipes.
1658 * (function taken from wiretap/libpcap.c) */
1660 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1663 /* Byte-swap the record header fields. */
1664 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
1665 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
1666 rechdr->incl_len = BSWAP32(rechdr->incl_len);
1667 rechdr->orig_len = BSWAP32(rechdr->orig_len);
1670 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1671 swapped, in order to match the BPF header layout.
1673 Unfortunately, some files were, according to a comment in the "libpcap"
1674 source, written with version 2.3 in their headers but without the
1675 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1676 would make no sense - we assume that we need to swap them. */
1677 if (hdr->version_major == 2 &&
1678 (hdr->version_minor < 3 ||
1679 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1682 temp = rechdr->orig_len;
1683 rechdr->orig_len = rechdr->incl_len;
1684 rechdr->incl_len = temp;
1688 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1692 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1696 return recv(pipe_fd, buf, (int)sz, 0);
1701 return ws_read(pipe_fd, buf, sz);
1707 * Thread function that reads from a pipe and pushes the data
1708 * to the main application thread.
1711 * XXX Right now we use async queues for basic signaling. The main thread
1712 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1713 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1714 * Iff the read is successful cap_pipe_read pushes an item onto
1715 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1716 * the queues themselves (yet).
1718 * We might want to move some of the cap_pipe_dispatch logic here so that
1719 * we can let cap_thread_read run independently, queuing up multiple reads
1720 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1722 static void *cap_thread_read(void *arg)
1724 pcap_options *pcap_opts;
1727 DWORD b, last_err, bytes_read;
1733 pcap_opts = (pcap_options *)arg;
1734 while (pcap_opts->cap_pipe_err == PIPOK) {
1735 g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1736 g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1738 while (bytes_read < pcap_opts->cap_pipe_bytes_to_read) {
1739 if ((pcap_opts->from_cap_socket)
1745 b = cap_pipe_read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1746 pcap_opts->cap_pipe_bytes_to_read - bytes_read, pcap_opts->from_cap_socket);
1749 pcap_opts->cap_pipe_err = PIPEOF;
1753 pcap_opts->cap_pipe_err = PIPERR;
1764 /* If we try to use read() on a named pipe on Windows with partial
1765 * data it appears to return EOF.
1767 res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1768 pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1773 last_err = GetLastError();
1774 if (last_err == ERROR_MORE_DATA) {
1776 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1777 pcap_opts->cap_pipe_err = PIPEOF;
1781 pcap_opts->cap_pipe_err = PIPERR;
1784 } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1785 pcap_opts->cap_pipe_err = PIPEOF;
1792 pcap_opts->cap_pipe_bytes_read = bytes_read;
1793 if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1794 g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1796 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1802 /* Provide select() functionality for a single file descriptor
1803 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1805 * Returns the same values as select.
1808 cap_pipe_select(int pipe_fd)
1811 struct timeval timeout;
1814 FD_SET(pipe_fd, &rfds);
1816 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1817 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1819 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1822 #define DEF_TCP_PORT 19000
1825 cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errmsgl)
1827 char *sockname = pipename + 4;
1828 struct sockaddr_in sa;
1835 memset(&sa, 0, sizeof(sa));
1837 p = strchr(sockname, ':');
1839 len = strlen(sockname);
1840 port = DEF_TCP_PORT;
1844 port = strtoul(p + 1, &p, 10);
1845 if (*p || port > 65535) {
1854 strncpy(buf, sockname, len);
1856 if (inet_pton(AF_INET, buf, &sa.sin_addr) <= 0) {
1860 sa.sin_family = AF_INET;
1861 sa.sin_port = htons((u_short)port);
1863 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1864 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1866 LPTSTR errorText = NULL;
1869 lastError = WSAGetLastError();
1870 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1871 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1872 FORMAT_MESSAGE_IGNORE_INSERTS,
1873 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1874 (LPTSTR)&errorText, 0, NULL);
1876 g_snprintf(errmsg, errmsgl,
1877 "The capture session could not be initiated due to the socket error: \n"
1879 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
1881 LocalFree(errorText);
1883 " %d: %s", errno, strerror(errno));
1885 pcap_opts->cap_pipe_err = PIPERR;
1888 cap_pipe_close(fd, TRUE);
1892 pcap_opts->from_cap_socket = TRUE;
1896 g_snprintf(errmsg, errmsgl,
1897 "The capture session could not be initiated because\n"
1898 "\"%s\" is not a valid socket specification", pipename);
1899 pcap_opts->cap_pipe_err = PIPERR;
1903 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1907 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1911 closesocket(pipe_fd);
1918 /* Mimic pcap_open_live() for pipe captures
1920 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1921 * open it, and read the header.
1923 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1924 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1926 cap_pipe_open_live(char *pipename,
1927 pcap_options *pcap_opts,
1928 struct pcap_hdr *hdr,
1929 char *errmsg, int errmsgl)
1932 ws_statb64 pipe_stat;
1933 struct sockaddr_un sa;
1943 pcap_opts->cap_pipe_fd = -1;
1945 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
1947 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1950 * XXX - this blocks until a pcap per-file header has been written to
1951 * the pipe, so it could block indefinitely.
1953 if (strcmp(pipename, "-") == 0) {
1955 fd = 0; /* read from stdin */
1957 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1959 } else if (!strncmp(pipename, "TCP@", 4)) {
1960 if ((fd = cap_open_socket(pipename, pcap_opts, errmsg, errmsgl)) < 0) {
1965 if (ws_stat64(pipename, &pipe_stat) < 0) {
1966 if (errno == ENOENT || errno == ENOTDIR)
1967 pcap_opts->cap_pipe_err = PIPNEXIST;
1969 g_snprintf(errmsg, errmsgl,
1970 "The capture session could not be initiated "
1971 "due to error getting information on pipe/socket: %s", g_strerror(errno));
1972 pcap_opts->cap_pipe_err = PIPERR;
1976 if (S_ISFIFO(pipe_stat.st_mode)) {
1977 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1979 g_snprintf(errmsg, errmsgl,
1980 "The capture session could not be initiated "
1981 "due to error on pipe open: %s", g_strerror(errno));
1982 pcap_opts->cap_pipe_err = PIPERR;
1985 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1986 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1988 g_snprintf(errmsg, errmsgl,
1989 "The capture session could not be initiated "
1990 "due to error on socket create: %s", g_strerror(errno));
1991 pcap_opts->cap_pipe_err = PIPERR;
1994 sa.sun_family = AF_UNIX;
1996 * The Single UNIX Specification says:
1998 * The size of sun_path has intentionally been left undefined.
1999 * This is because different implementations use different sizes.
2000 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
2001 * of 104. Since most implementations originate from BSD versions,
2002 * the size is typically in the range 92 to 108.
2004 * Applications should not assume a particular length for sun_path
2005 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
2009 * The <sys/un.h> header shall define the sockaddr_un structure,
2010 * which shall include at least the following members:
2012 * sa_family_t sun_family Address family.
2013 * char sun_path[] Socket pathname.
2015 * so we assume that it's an array, with a specified size,
2016 * and that the size reflects the maximum path length.
2018 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
2019 /* Path name too long */
2020 g_snprintf(errmsg, errmsgl,
2021 "The capture session coud not be initiated "
2022 "due to error on socket connect: Path name too long");
2023 pcap_opts->cap_pipe_err = PIPERR;
2027 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
2029 g_snprintf(errmsg, errmsgl,
2030 "The capture session coud not be initiated "
2031 "due to error on socket connect: %s", g_strerror(errno));
2032 pcap_opts->cap_pipe_err = PIPERR;
2037 if (S_ISCHR(pipe_stat.st_mode)) {
2039 * Assume the user specified an interface on a system where
2040 * interfaces are in /dev. Pretend we haven't seen it.
2042 pcap_opts->cap_pipe_err = PIPNEXIST;
2044 g_snprintf(errmsg, errmsgl,
2045 "The capture session could not be initiated because\n"
2046 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
2047 pcap_opts->cap_pipe_err = PIPERR;
2052 #define PIPE_STR "\\pipe\\"
2053 /* Under Windows, named pipes _must_ have the form
2054 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
2056 pncopy = g_strdup(pipename);
2057 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
2058 pos = strchr(pncopy + 3, '\\');
2059 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
2066 g_snprintf(errmsg, errmsgl,
2067 "The capture session could not be initiated because\n"
2068 "\"%s\" is neither an interface nor a pipe", pipename);
2069 pcap_opts->cap_pipe_err = PIPNEXIST;
2073 /* Wait for the pipe to appear */
2075 pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
2076 OPEN_EXISTING, 0, NULL);
2078 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
2081 if (GetLastError() != ERROR_PIPE_BUSY) {
2082 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2083 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2084 g_snprintf(errmsg, errmsgl,
2085 "The capture session on \"%s\" could not be started "
2086 "due to error on pipe open: %s (error %d)",
2087 pipename, utf_16to8(err_str), GetLastError());
2089 pcap_opts->cap_pipe_err = PIPERR;
2093 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
2094 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2095 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2096 g_snprintf(errmsg, errmsgl,
2097 "The capture session on \"%s\" timed out during "
2098 "pipe open: %s (error %d)",
2099 pipename, utf_16to8(err_str), GetLastError());
2101 pcap_opts->cap_pipe_err = PIPERR;
2108 pcap_opts->from_cap_pipe = TRUE;
2111 if (pcap_opts->from_cap_socket)
2114 /* read the pcap header */
2116 while (bytes_read < sizeof magic) {
2117 sel_ret = cap_pipe_select(fd);
2119 g_snprintf(errmsg, errmsgl,
2120 "Unexpected error from select: %s", g_strerror(errno));
2122 } else if (sel_ret > 0) {
2123 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
2124 sizeof magic-bytes_read,
2125 pcap_opts->from_cap_socket);
2128 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2130 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2140 #if GLIB_CHECK_VERSION(2,31,0)
2141 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_opts);
2143 g_thread_create(&cap_thread_read, pcap_opts, FALSE, NULL);
2146 pcap_opts->cap_pipe_buf = (char *) &magic;
2147 pcap_opts->cap_pipe_bytes_read = 0;
2148 pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
2149 /* We don't have to worry about cap_pipe_read_mtx here */
2150 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2151 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2152 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2153 if (pcap_opts->cap_pipe_bytes_read == 0)
2154 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2156 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2165 case PCAP_NSEC_MAGIC:
2166 /* Host that wrote it has our byte order, and was running
2167 a program using either standard or ss990417 libpcap. */
2168 pcap_opts->cap_pipe_byte_swapped = FALSE;
2169 pcap_opts->cap_pipe_modified = FALSE;
2170 pcap_opts->ts_nsec = magic == PCAP_NSEC_MAGIC;
2172 case PCAP_MODIFIED_MAGIC:
2173 /* Host that wrote it has our byte order, but was running
2174 a program using either ss990915 or ss991029 libpcap. */
2175 pcap_opts->cap_pipe_byte_swapped = FALSE;
2176 pcap_opts->cap_pipe_modified = TRUE;
2178 case PCAP_SWAPPED_MAGIC:
2179 case PCAP_SWAPPED_NSEC_MAGIC:
2180 /* Host that wrote it has a byte order opposite to ours,
2181 and was running a program using either standard or
2182 ss990417 libpcap. */
2183 pcap_opts->cap_pipe_byte_swapped = TRUE;
2184 pcap_opts->cap_pipe_modified = FALSE;
2185 pcap_opts->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
2187 case PCAP_SWAPPED_MODIFIED_MAGIC:
2188 /* Host that wrote it out has a byte order opposite to
2189 ours, and was running a program using either ss990915
2190 or ss991029 libpcap. */
2191 pcap_opts->cap_pipe_byte_swapped = TRUE;
2192 pcap_opts->cap_pipe_modified = TRUE;
2195 /* Not a "libpcap" type we know about. */
2196 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
2201 if (pcap_opts->from_cap_socket)
2204 /* Read the rest of the header */
2206 while (bytes_read < sizeof(struct pcap_hdr)) {
2207 sel_ret = cap_pipe_select(fd);
2209 g_snprintf(errmsg, errmsgl,
2210 "Unexpected error from select: %s", g_strerror(errno));
2212 } else if (sel_ret > 0) {
2213 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
2214 sizeof(struct pcap_hdr) - bytes_read,
2215 pcap_opts->from_cap_socket);
2218 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2220 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
2230 pcap_opts->cap_pipe_buf = (char *) hdr;
2231 pcap_opts->cap_pipe_bytes_read = 0;
2232 pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
2233 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2234 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2235 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2236 if (pcap_opts->cap_pipe_bytes_read == 0)
2237 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2239 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
2246 if (pcap_opts->cap_pipe_byte_swapped) {
2247 /* Byte-swap the header fields about which we care. */
2248 hdr->version_major = BSWAP16(hdr->version_major);
2249 hdr->version_minor = BSWAP16(hdr->version_minor);
2250 hdr->snaplen = BSWAP32(hdr->snaplen);
2251 hdr->network = BSWAP32(hdr->network);
2253 pcap_opts->linktype = hdr->network;
2255 if (hdr->version_major < 2) {
2256 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
2260 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2261 pcap_opts->cap_pipe_err = PIPOK;
2262 pcap_opts->cap_pipe_fd = fd;
2266 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
2267 pcap_opts->cap_pipe_err = PIPERR;
2268 cap_pipe_close(fd, pcap_opts->from_cap_socket);
2269 pcap_opts->cap_pipe_fd = -1;
2273 /* We read one record from the pipe, take care of byte order in the record
2274 * header, write the record to the capture file, and update capture statistics. */
2276 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
2278 struct pcap_pkthdr phdr;
2279 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2282 #if !GLIB_CHECK_VERSION(2,31,18)
2290 #ifdef LOG_CAPTURE_VERBOSE
2291 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
2294 switch (pcap_opts->cap_pipe_state) {
2296 case STATE_EXPECT_REC_HDR:
2298 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2301 pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
2302 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
2303 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2304 pcap_opts->cap_pipe_bytes_read = 0;
2307 pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
2308 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2309 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2314 case STATE_READ_REC_HDR:
2316 if (pcap_opts->from_cap_socket)
2319 b = cap_pipe_read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
2320 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
2323 result = PD_PIPE_EOF;
2325 result = PD_PIPE_ERR;
2328 pcap_opts->cap_pipe_bytes_read += b;
2332 #if GLIB_CHECK_VERSION(2,31,18)
2333 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2335 g_get_current_time(&wait_time);
2336 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2337 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2339 if (pcap_opts->cap_pipe_err == PIPEOF) {
2340 result = PD_PIPE_EOF;
2342 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2343 result = PD_PIPE_ERR;
2351 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2353 result = PD_REC_HDR_READ;
2356 case STATE_EXPECT_DATA:
2358 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2361 pcap_opts->cap_pipe_state = STATE_READ_DATA;
2362 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2363 pcap_opts->cap_pipe_bytes_read = 0;
2366 pcap_opts->cap_pipe_buf = (char *) data;
2367 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2368 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2373 case STATE_READ_DATA:
2375 if (pcap_opts->from_cap_socket)
2378 b = cap_pipe_read(pcap_opts->cap_pipe_fd,
2379 data+pcap_opts->cap_pipe_bytes_read,
2380 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read,
2381 pcap_opts->from_cap_socket);
2384 result = PD_PIPE_EOF;
2386 result = PD_PIPE_ERR;
2389 pcap_opts->cap_pipe_bytes_read += b;
2394 #if GLIB_CHECK_VERSION(2,31,18)
2395 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2397 g_get_current_time(&wait_time);
2398 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2399 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2400 #endif /* GLIB_CHECK_VERSION(2,31,18) */
2401 if (pcap_opts->cap_pipe_err == PIPEOF) {
2402 result = PD_PIPE_EOF;
2404 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2405 result = PD_PIPE_ERR;
2413 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2415 result = PD_DATA_READ;
2419 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2422 } /* switch (pcap_opts->cap_pipe_state) */
2425 * We've now read as much data as we were expecting, so process it.
2429 case PD_REC_HDR_READ:
2430 /* We've read the header. Take care of byte order. */
2431 cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
2432 &pcap_opts->cap_pipe_rechdr.hdr);
2433 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2434 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2435 ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
2439 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2440 pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2443 /* no data to read? fall through */
2446 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2447 phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2448 phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2449 phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2450 phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2453 capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2455 capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2457 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2461 pcap_opts->cap_pipe_err = PIPEOF;
2466 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2467 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2468 g_snprintf(errmsg, errmsgl,
2469 "Error reading from pipe: %s (error %d)",
2470 utf_16to8(err_str), GetLastError());
2473 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2481 pcap_opts->cap_pipe_err = PIPERR;
2482 /* Return here rather than inside the switch to prevent GCC warning */
2487 /** Open the capture input file (pcap or capture pipe).
2488 * Returns TRUE if it succeeds, FALSE otherwise. */
2490 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2491 char *errmsg, size_t errmsg_len,
2492 char *secondary_errmsg, size_t secondary_errmsg_len)
2494 gchar open_err_str[PCAP_ERRBUF_SIZE];
2495 gchar *sync_msg_str;
2496 interface_options interface_opts;
2497 pcap_options *pcap_opts;
2501 gchar *sync_secondary_msg_str;
2502 WORD wVersionRequested;
2506 /* XXX - opening Winsock on tshark? */
2508 /* Initialize Windows Socket if we are in a WIN32 OS
2509 This needs to be done before querying the interface for network/netmask */
2511 /* XXX - do we really require 1.1 or earlier?
2512 Are there any versions that support only 2.0 or higher? */
2513 wVersionRequested = MAKEWORD(1, 1);
2514 err = WSAStartup(wVersionRequested, &wsaData);
2518 case WSASYSNOTREADY:
2519 g_snprintf(errmsg, (gulong) errmsg_len,
2520 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2523 case WSAVERNOTSUPPORTED:
2524 g_snprintf(errmsg, (gulong) errmsg_len,
2525 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2526 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2529 case WSAEINPROGRESS:
2530 g_snprintf(errmsg, (gulong) errmsg_len,
2531 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2535 g_snprintf(errmsg, (gulong) errmsg_len,
2536 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2540 g_snprintf(errmsg, (gulong) errmsg_len,
2541 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2545 g_snprintf(errmsg, (gulong) errmsg_len,
2546 "Couldn't initialize Windows Sockets: error %d", err);
2549 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2553 if ((use_threads == FALSE) &&
2554 (capture_opts->ifaces->len > 1)) {
2555 g_snprintf(errmsg, (gulong) errmsg_len,
2556 "Using threads is required for capturing on multiple interfaces!");
2560 for (i = 0; i < capture_opts->ifaces->len; i++) {
2561 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2562 pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2563 if (pcap_opts == NULL) {
2564 g_snprintf(errmsg, (gulong) errmsg_len,
2565 "Could not allocate memory.");
2568 pcap_opts->received = 0;
2569 pcap_opts->dropped = 0;
2570 pcap_opts->flushed = 0;
2571 pcap_opts->pcap_h = NULL;
2572 #ifdef MUST_DO_SELECT
2573 pcap_opts->pcap_fd = -1;
2575 pcap_opts->pcap_err = FALSE;
2576 pcap_opts->interface_id = i;
2577 pcap_opts->tid = NULL;
2578 pcap_opts->snaplen = 0;
2579 pcap_opts->linktype = -1;
2580 pcap_opts->ts_nsec = FALSE;
2581 pcap_opts->from_cap_pipe = FALSE;
2582 pcap_opts->from_cap_socket = FALSE;
2583 memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2584 memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2586 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2588 pcap_opts->cap_pipe_fd = -1;
2589 pcap_opts->cap_pipe_modified = FALSE;
2590 pcap_opts->cap_pipe_byte_swapped = FALSE;
2592 pcap_opts->cap_pipe_buf = NULL;
2594 pcap_opts->cap_pipe_bytes_to_read = 0;
2595 pcap_opts->cap_pipe_bytes_read = 0;
2596 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2597 pcap_opts->cap_pipe_err = PIPOK;
2599 #if GLIB_CHECK_VERSION(2,31,0)
2600 pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2601 g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2603 pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2605 pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2606 pcap_opts->cap_pipe_done_q = g_async_queue_new();
2608 g_array_append_val(ld->pcaps, pcap_opts);
2610 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2611 pcap_opts->pcap_h = open_capture_device(&interface_opts, &open_err_str);
2613 if (pcap_opts->pcap_h != NULL) {
2614 /* we've opened "iface" as a network device */
2616 /* try to set the capture buffer size */
2617 if (interface_opts.buffer_size > 1 &&
2618 pcap_setbuff(pcap_opts->pcap_h, interface_opts.buffer_size * 1024 * 1024) != 0) {
2619 sync_secondary_msg_str = g_strdup_printf(
2620 "The capture buffer size of %dMB seems to be too high for your machine,\n"
2621 "the default of 1MB will be used.\n"
2623 "Nonetheless, the capture is started.\n",
2624 interface_opts.buffer_size);
2625 report_capture_error("Couldn't set the capture buffer size!",
2626 sync_secondary_msg_str);
2627 g_free(sync_secondary_msg_str);
2631 #if defined(HAVE_PCAP_SETSAMPLING)
2632 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2633 struct pcap_samp *samp;
2635 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2636 switch (interface_opts.sampling_method) {
2637 case CAPTURE_SAMP_BY_COUNT:
2638 samp->method = PCAP_SAMP_1_EVERY_N;
2641 case CAPTURE_SAMP_BY_TIMER:
2642 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2646 sync_msg_str = g_strdup_printf(
2647 "Unknown sampling method %d specified,\n"
2648 "continue without packet sampling",
2649 interface_opts.sampling_method);
2650 report_capture_error("Couldn't set the capture "
2651 "sampling", sync_msg_str);
2652 g_free(sync_msg_str);
2654 samp->value = interface_opts.sampling_param;
2656 report_capture_error("Couldn't set the capture sampling",
2657 "Cannot get packet sampling data structure");
2662 /* setting the data link type only works on real interfaces */
2663 if (!set_pcap_linktype(pcap_opts->pcap_h, interface_opts.linktype, interface_opts.name,
2665 secondary_errmsg, secondary_errmsg_len)) {
2668 pcap_opts->linktype = get_pcap_linktype(pcap_opts->pcap_h, interface_opts.name);
2670 /* We couldn't open "iface" as a network device. */
2671 /* Try to open it as a pipe */
2672 cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2675 if (pcap_opts->cap_pipe_fd == -1) {
2677 if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2679 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2680 /* Pipe doesn't exist, so output message for interface */
2681 get_capture_device_open_failure_messages(open_err_str,
2682 interface_opts.name,
2686 secondary_errmsg_len);
2689 * Else pipe (or file) does exist and cap_pipe_open_live() has
2694 /* cap_pipe_open_live() succeeded; don't want
2695 error message from pcap_open_live() */
2696 open_err_str[0] = '\0';
2700 /* XXX - will this work for tshark? */
2701 #ifdef MUST_DO_SELECT
2702 if (!pcap_opts->from_cap_pipe) {
2703 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2704 pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2706 pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2711 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2712 returned a warning; print it, but keep capturing. */
2713 if (open_err_str[0] != '\0') {
2714 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2715 report_capture_error(sync_msg_str, "");
2716 g_free(sync_msg_str);
2718 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2719 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2722 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2723 /* to remove any suid privileges. */
2724 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2725 /* (euid/egid have already previously been set to ruid/rgid. */
2726 /* (See comment in main() for details) */
2728 relinquish_special_privs_perm();
2730 relinquish_all_capabilities();
2735 /* close the capture input file (pcap or capture pipe) */
2736 static void capture_loop_close_input(loop_data *ld)
2739 pcap_options *pcap_opts;
2741 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2743 for (i = 0; i < ld->pcaps->len; i++) {
2744 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2745 /* if open, close the capture pipe "input file" */
2746 if (pcap_opts->cap_pipe_fd >= 0) {
2747 g_assert(pcap_opts->from_cap_pipe);
2748 cap_pipe_close(pcap_opts->cap_pipe_fd, pcap_opts->from_cap_socket);
2749 pcap_opts->cap_pipe_fd = -1;
2752 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2753 CloseHandle(pcap_opts->cap_pipe_h);
2754 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2757 /* if open, close the pcap "input file" */
2758 if (pcap_opts->pcap_h != NULL) {
2759 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2760 pcap_close(pcap_opts->pcap_h);
2761 pcap_opts->pcap_h = NULL;
2768 /* Shut down windows sockets */
2774 /* init the capture filter */
2775 static initfilter_status_t
2776 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2777 const gchar * name, const gchar * cfilter)
2779 struct bpf_program fcode;
2781 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2783 /* capture filters only work on real interfaces */
2784 if (cfilter && !from_cap_pipe) {
2785 /* A capture filter was specified; set it up. */
2786 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2787 /* Treat this specially - our caller might try to compile this
2788 as a display filter and, if that succeeds, warn the user that
2789 the display and capture filter syntaxes are different. */
2790 return INITFILTER_BAD_FILTER;
2792 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2793 #ifdef HAVE_PCAP_FREECODE
2794 pcap_freecode(&fcode);
2796 return INITFILTER_OTHER_ERROR;
2798 #ifdef HAVE_PCAP_FREECODE
2799 pcap_freecode(&fcode);
2803 return INITFILTER_NO_ERROR;
2807 /* set up to write to the already-opened capture output file/files */
2809 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2813 pcap_options *pcap_opts;
2814 interface_options interface_opts;
2815 gboolean successful;
2817 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2819 if ((capture_opts->use_pcapng == FALSE) &&
2820 (capture_opts->ifaces->len > 1)) {
2821 g_snprintf(errmsg, errmsg_len,
2822 "Using PCAPNG is required for capturing on multiple interfaces! Use the -n option.");
2826 /* Set up to write to the capture file. */
2827 if (capture_opts->multi_files_on) {
2828 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2830 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2831 if (ld->pdh == NULL) {
2836 if (capture_opts->use_pcapng) {
2838 GString *os_info_str;
2840 os_info_str = g_string_new("");
2841 get_os_version_info(os_info_str);
2843 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2844 successful = libpcap_write_session_header_block(libpcap_write_to_file, ld->pdh,
2845 (const char *)capture_opts->capture_comment, /* Comment*/
2847 os_info_str->str, /* OS*/
2849 -1, /* section_length */
2853 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2854 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2855 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2856 if (pcap_opts->from_cap_pipe) {
2857 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2859 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2861 successful = libpcap_write_interface_description_block(libpcap_write_to_file, global_ld.pdh,
2862 NULL, /* OPT_COMMENT 1 */
2863 interface_opts.name, /* IDB_NAME 2 */
2864 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2865 interface_opts.cfilter, /* IDB_FILTER 11 */
2866 os_info_str->str, /* IDB_OS 12 */
2867 pcap_opts->linktype,
2869 &(global_ld.bytes_written),
2870 0, /* IDB_IF_SPEED 8 */
2871 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2875 g_string_free(os_info_str, TRUE);
2878 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
2879 if (pcap_opts->from_cap_pipe) {
2880 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2882 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2884 successful = libpcap_write_file_header(libpcap_write_to_file, ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
2885 pcap_opts->ts_nsec, &ld->bytes_written, &err);
2893 if (ld->pdh == NULL) {
2894 /* We couldn't set up to write to the capture file. */
2895 /* XXX - use cf_open_error_message from tshark instead? */
2900 g_snprintf(errmsg, errmsg_len,
2901 "The file to which the capture would be"
2902 " saved (\"%s\") could not be opened: Error %d.",
2903 capture_opts->save_file, err);
2905 g_snprintf(errmsg, errmsg_len,
2906 "The file to which the capture would be"
2907 " saved (\"%s\") could not be opened: %s.",
2908 capture_opts->save_file, g_strerror(err));
2920 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2924 pcap_options *pcap_opts;
2925 guint64 end_time = create_timestamp();
2927 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2929 if (capture_opts->multi_files_on) {
2930 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2932 if (capture_opts->use_pcapng) {
2933 for (i = 0; i < global_ld.pcaps->len; i++) {
2934 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2935 if (!pcap_opts->from_cap_pipe) {
2936 guint64 isb_ifrecv, isb_ifdrop;
2937 struct pcap_stat stats;
2939 if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
2940 isb_ifrecv = pcap_opts->received;
2941 isb_ifdrop = stats.ps_drop + pcap_opts->dropped + pcap_opts->flushed;
2943 isb_ifrecv = G_MAXUINT64;
2944 isb_ifdrop = G_MAXUINT64;
2946 libpcap_write_interface_statistics_block(libpcap_write_to_file, ld->pdh,
2949 "Counters provided by dumpcap",
2958 if (fclose(ld->pdh) == EOF) {
2959 if (err_close != NULL) {
2969 /* dispatch incoming packets (pcap or capture pipe)
2971 * Waits for incoming packets to be available, and calls pcap_dispatch()
2972 * to cause them to be processed.
2974 * Returns the number of packets which were processed.
2976 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2977 * packet-batching behaviour does not cause packets to get held back
2981 capture_loop_dispatch(loop_data *ld,
2982 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
2985 gint packet_count_before;
2986 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
2991 packet_count_before = ld->packet_count;
2992 if (pcap_opts->from_cap_pipe) {
2993 /* dispatch from capture pipe */
2994 #ifdef LOG_CAPTURE_VERBOSE
2995 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2998 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
3000 if (sel_ret < 0 && errno != EINTR) {
3001 g_snprintf(errmsg, errmsg_len,
3002 "Unexpected error from select: %s", g_strerror(errno));
3003 report_capture_error(errmsg, please_report);
3008 * "select()" says we can read from the pipe without blocking
3011 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
3021 /* dispatch from pcap */
3022 #ifdef MUST_DO_SELECT
3024 * If we have "pcap_get_selectable_fd()", we use it to get the
3025 * descriptor on which to select; if that's -1, it means there
3026 * is no descriptor on which you can do a "select()" (perhaps
3027 * because you're capturing on a special device, and that device's
3028 * driver unfortunately doesn't support "select()", in which case
3029 * we don't do the select - which means it might not be possible
3030 * to stop a capture until a packet arrives. If that's unacceptable,
3031 * plead with whoever supplies the software for that device to add
3032 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3033 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3034 * later, so it can use pcap_breakloop().
3036 #ifdef LOG_CAPTURE_VERBOSE
3037 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3039 if (pcap_opts->pcap_fd != -1) {
3040 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
3043 * "select()" says we can read from it without blocking; go for
3046 * We don't have pcap_breakloop(), so we only process one packet
3047 * per pcap_dispatch() call, to allow a signal to stop the
3048 * processing immediately, rather than processing all packets
3049 * in a batch before quitting.
3052 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3054 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3058 /* Error, rather than pcap_breakloop(). */
3059 pcap_opts->pcap_err = TRUE;
3061 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3064 if (sel_ret < 0 && errno != EINTR) {
3065 g_snprintf(errmsg, errmsg_len,
3066 "Unexpected error from select: %s", g_strerror(errno));
3067 report_capture_error(errmsg, please_report);
3073 #endif /* MUST_DO_SELECT */
3075 /* dispatch from pcap without select */
3077 #ifdef LOG_CAPTURE_VERBOSE
3078 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3082 * On Windows, we don't support asynchronously telling a process to
3083 * stop capturing; instead, we check for an indication on a pipe
3084 * after processing packets. We therefore process only one packet
3085 * at a time, so that we can check the pipe after every packet.
3088 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3090 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3094 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3096 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3101 /* Error, rather than pcap_breakloop(). */
3102 pcap_opts->pcap_err = TRUE;
3104 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3106 #else /* pcap_next_ex */
3107 #ifdef LOG_CAPTURE_VERBOSE
3108 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3110 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3113 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3114 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
3115 * This should be fixed in the WinPcap 4.0 alpha release.
3117 * For reference, an example remote interface:
3118 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3121 /* emulate dispatch from pcap */
3124 struct pcap_pkthdr *pkt_header;
3129 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
3131 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3133 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3138 pcap_opts->pcap_err = TRUE;
3142 #endif /* pcap_next_ex */
3146 #ifdef LOG_CAPTURE_VERBOSE
3147 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3150 return ld->packet_count - packet_count_before;
3154 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3155 * want to grab only the characters between the '{' and '}' delimiters.
3157 * Returns a GString that must be freed with g_string_free(). */
3159 isolate_uuid(const char *iface)
3164 ptr = strchr(iface, '{');
3166 return g_string_new(iface);
3167 gstr = g_string_new(ptr + 1);
3169 ptr = strchr(gstr->str, '}');
3173 gstr = g_string_truncate(gstr, ptr - gstr->str);
3178 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3179 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3181 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3182 char *errmsg, int errmsg_len)
3185 gchar *capfile_name;
3187 gboolean is_tempfile;
3189 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3190 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3192 if (capture_opts->save_file != NULL) {
3193 /* We return to the caller while the capture is in progress.
3194 * Therefore we need to take a copy of save_file in
3195 * case the caller destroys it after we return.
3197 capfile_name = g_strdup(capture_opts->save_file);
3199 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3200 if (capture_opts->multi_files_on) {
3201 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3202 g_snprintf(errmsg, errmsg_len,
3203 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3204 g_free(capfile_name);
3207 if (strcmp(capfile_name, "-") == 0) {
3208 /* write to stdout */
3211 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3212 _setmode(1, O_BINARY);
3215 } /* if (...output_to_pipe ... */
3218 if (capture_opts->multi_files_on) {
3219 /* ringbuffer is enabled */
3220 *save_file_fd = ringbuf_init(capfile_name,
3221 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3222 capture_opts->group_read_access);
3224 /* we need the ringbuf name */
3225 if (*save_file_fd != -1) {
3226 g_free(capfile_name);
3227 capfile_name = g_strdup(ringbuf_current_filename());
3230 /* Try to open/create the specified file for use as a capture buffer. */
3231 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
3232 (capture_opts->group_read_access) ? 0640 : 0600);
3235 is_tempfile = FALSE;
3237 /* Choose a random name for the temporary capture buffer */
3238 if (global_capture_opts.ifaces->len > 1) {
3239 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3242 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
3244 /* use the generic portion of the interface guid to form the basis of the filename */
3245 if (strncmp("NPF_{", basename, 5)==0)
3247 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
3249 iface = isolate_uuid(basename);
3251 basename = g_strdup(iface->str);
3252 g_string_free(iface, TRUE);
3255 /* generate the temp file name prefix...
3256 * It would be nice if we could specify a pcapng/pcap filename suffix,
3257 * create_tempfile() however currently uses mkstemp() which doesn't allow this - one day perhaps*/
3258 if (capture_opts->use_pcapng) {
3259 prefix = g_strconcat("wireshark_pcapng_", basename, NULL);
3261 prefix = g_strconcat("wireshark_pcap_", basename, NULL);
3265 *save_file_fd = create_tempfile(&tmpname, prefix);
3267 capfile_name = g_strdup(tmpname);
3271 /* did we fail to open the output file? */
3272 if (*save_file_fd == -1) {
3274 g_snprintf(errmsg, errmsg_len,
3275 "The temporary file to which the capture would be saved (\"%s\") "
3276 "could not be opened: %s.", capfile_name, g_strerror(errno));
3278 if (capture_opts->multi_files_on) {
3279 ringbuf_error_cleanup();
3282 g_snprintf(errmsg, errmsg_len,
3283 "The file to which the capture would be saved (\"%s\") "
3284 "could not be opened: %s.", capfile_name,
3287 g_free(capfile_name);
3291 if (capture_opts->save_file != NULL) {
3292 g_free(capture_opts->save_file);
3294 capture_opts->save_file = capfile_name;
3295 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3296 "g_free(capfile_name)". */
3302 /* Do the work of handling either the file size or file duration capture
3303 conditions being reached, and switching files or stopping. */
3305 do_file_switch_or_stop(capture_options *capture_opts,
3306 condition *cnd_autostop_files,
3307 condition *cnd_autostop_size,
3308 condition *cnd_file_duration)
3311 pcap_options *pcap_opts;
3312 interface_options interface_opts;
3313 gboolean successful;
3315 if (capture_opts->multi_files_on) {
3316 if (cnd_autostop_files != NULL &&
3317 cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
3318 /* no files left: stop here */
3319 global_ld.go = FALSE;
3323 /* Switch to the next ringbuffer file */
3324 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3325 &global_ld.save_file_fd, &global_ld.err)) {
3327 /* File switch succeeded: reset the conditions */
3328 global_ld.bytes_written = 0;
3329 if (capture_opts->use_pcapng) {
3331 GString *os_info_str;
3333 os_info_str = g_string_new("");
3334 get_os_version_info(os_info_str);
3336 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
3337 successful = libpcap_write_session_header_block(libpcap_write_to_file, global_ld.pdh,
3340 os_info_str->str, /* OS */
3342 -1, /* section_length */
3343 &(global_ld.bytes_written),
3346 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3347 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3348 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3349 successful = libpcap_write_interface_description_block(libpcap_write_to_file, global_ld.pdh,
3350 NULL, /* OPT_COMMENT 1 */
3351 interface_opts.name, /* IDB_NAME 2 */
3352 interface_opts.descr, /* IDB_DESCRIPTION 3 */
3353 interface_opts.cfilter, /* IDB_FILTER 11 */
3354 os_info_str->str, /* IDB_OS 12 */
3355 pcap_opts->linktype,
3357 &(global_ld.bytes_written),
3358 0, /* IDB_IF_SPEED 8 */
3359 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3363 g_string_free(os_info_str, TRUE);
3366 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3367 successful = libpcap_write_file_header(libpcap_write_to_file, global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
3368 pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3371 fclose(global_ld.pdh);
3372 global_ld.pdh = NULL;
3373 global_ld.go = FALSE;
3376 if (cnd_autostop_size)
3377 cnd_reset(cnd_autostop_size);
3378 if (cnd_file_duration)
3379 cnd_reset(cnd_file_duration);
3380 fflush(global_ld.pdh);
3382 report_packet_count(global_ld.inpkts_to_sync_pipe);
3383 global_ld.inpkts_to_sync_pipe = 0;
3384 report_new_capture_file(capture_opts->save_file);
3386 /* File switch failed: stop here */
3387 global_ld.go = FALSE;
3391 /* single file, stop now */
3392 global_ld.go = FALSE;
3399 pcap_read_handler(void* arg)
3401 pcap_options *pcap_opts;
3402 char errmsg[MSG_MAX_LENGTH+1];
3404 pcap_opts = (pcap_options *)arg;
3406 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3407 pcap_opts->interface_id);
3409 while (global_ld.go) {
3410 /* dispatch incoming packets */
3411 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3413 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3414 pcap_opts->interface_id);
3415 g_thread_exit(NULL);
3419 /* Do the low-level work of a capture.
3420 Returns TRUE if it succeeds, FALSE otherwise. */
3422 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3425 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3427 struct timeval upd_time, cur_time;
3431 condition *cnd_file_duration = NULL;
3432 condition *cnd_autostop_files = NULL;
3433 condition *cnd_autostop_size = NULL;
3434 condition *cnd_autostop_duration = NULL;
3437 gboolean cfilter_error = FALSE;
3438 char errmsg[MSG_MAX_LENGTH+1];
3439 char secondary_errmsg[MSG_MAX_LENGTH+1];
3440 pcap_options *pcap_opts;
3441 interface_options interface_opts;
3442 guint i, error_index = 0;
3445 *secondary_errmsg = '\0';
3447 /* init the loop data */
3448 global_ld.go = TRUE;
3449 global_ld.packet_count = 0;
3451 global_ld.report_packet_count = FALSE;
3453 if (capture_opts->has_autostop_packets)
3454 global_ld.packet_max = capture_opts->autostop_packets;
3456 global_ld.packet_max = 0; /* no limit */
3457 global_ld.inpkts_to_sync_pipe = 0;
3458 global_ld.err = 0; /* no error seen yet */
3459 global_ld.pdh = NULL;
3460 global_ld.autostop_files = 0;
3461 global_ld.save_file_fd = -1;
3463 /* We haven't yet gotten the capture statistics. */
3464 *stats_known = FALSE;
3466 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3467 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3469 /* open the "input file" from network interface or capture pipe */
3470 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3471 secondary_errmsg, sizeof(secondary_errmsg))) {
3474 for (i = 0; i < capture_opts->ifaces->len; i++) {
3475 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3476 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3477 /* init the input filter from the network interface (capture pipe will do nothing) */
3479 * When remote capturing WinPCap crashes when the capture filter
3480 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3483 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3484 interface_opts.name,
3485 interface_opts.cfilter?interface_opts.cfilter:"")) {
3487 case INITFILTER_NO_ERROR:
3490 case INITFILTER_BAD_FILTER:
3491 cfilter_error = TRUE;
3493 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3496 case INITFILTER_OTHER_ERROR:
3497 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3498 pcap_geterr(pcap_opts->pcap_h));
3499 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3504 /* If we're supposed to write to a capture file, open it for output
3505 (temporary/specified name/ringbuffer) */
3506 if (capture_opts->saving_to_file) {
3507 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3508 errmsg, sizeof(errmsg))) {
3512 /* set up to write to the already-opened capture output file/files */
3513 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3518 /* XXX - capture SIGTERM and close the capture, in case we're on a
3519 Linux 2.0[.x] system and you have to explicitly close the capture
3520 stream in order to turn promiscuous mode off? We need to do that
3521 in other places as well - and I don't think that works all the
3522 time in any case, due to libpcap bugs. */
3524 /* Well, we should be able to start capturing.
3526 Sync out the capture file, so the header makes it to the file system,
3527 and send a "capture started successfully and capture file created"
3528 message to our parent so that they'll open the capture file and
3529 update its windows to indicate that we have a live capture in
3531 fflush(global_ld.pdh);
3532 report_new_capture_file(capture_opts->save_file);
3535 /* initialize capture stop (and alike) conditions */
3536 init_capture_stop_conditions();
3537 /* create stop conditions */
3538 if (capture_opts->has_autostop_filesize)
3540 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
3541 if (capture_opts->has_autostop_duration)
3542 cnd_autostop_duration =
3543 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3545 if (capture_opts->multi_files_on) {
3546 if (capture_opts->has_file_duration)
3548 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3550 if (capture_opts->has_autostop_files)
3551 cnd_autostop_files =
3552 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
3555 /* init the time values */
3557 upd_time = GetTickCount();
3559 gettimeofday(&upd_time, NULL);
3561 start_time = create_timestamp();
3562 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
3564 /* WOW, everything is prepared! */
3565 /* please fasten your seat belts, we will enter now the actual capture loop */
3567 pcap_queue = g_async_queue_new();
3568 pcap_queue_bytes = 0;
3569 pcap_queue_packets = 0;
3570 for (i = 0; i < global_ld.pcaps->len; i++) {
3571 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3572 #if GLIB_CHECK_VERSION(2,31,0)
3573 /* XXX - Add an interface name here? */
3574 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3576 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3580 while (global_ld.go) {
3581 /* dispatch incoming packets */
3583 pcap_queue_element *queue_element;
3584 #if GLIB_CHECK_VERSION(2,31,18)
3586 g_async_queue_lock(pcap_queue);
3587 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3589 GTimeVal write_thread_time;
3591 g_get_current_time(&write_thread_time);
3592 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3593 g_async_queue_lock(pcap_queue);
3594 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3596 if (queue_element) {
3597 pcap_queue_bytes -= queue_element->phdr.caplen;
3598 pcap_queue_packets -= 1;
3600 g_async_queue_unlock(pcap_queue);
3601 if (queue_element) {
3602 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3603 "Dequeued a packet of length %d captured on interface %d.",
3604 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3606 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3607 &queue_element->phdr,
3609 g_free(queue_element->pd);
3610 g_free(queue_element);
3616 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3617 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3618 sizeof(errmsg), pcap_opts);
3621 /* Were we asked to print packet counts by the SIGINFO handler? */
3622 if (global_ld.report_packet_count) {
3623 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3624 plurality(global_ld.packet_count, "", "s"));
3625 global_ld.report_packet_count = FALSE;
3630 /* any news from our parent (signal pipe)? -> just stop the capture */
3631 if (!signal_pipe_check_running()) {
3632 global_ld.go = FALSE;
3637 global_ld.inpkts_to_sync_pipe += inpkts;
3639 /* check capture size condition */
3640 if (cnd_autostop_size != NULL &&
3641 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)) {
3642 /* Capture size limit reached, do we have another file? */
3643 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3644 cnd_autostop_size, cnd_file_duration))
3646 } /* cnd_autostop_size */
3647 if (capture_opts->output_to_pipe) {
3648 fflush(global_ld.pdh);
3652 /* Only update once every 500ms so as not to overload slow displays.
3653 * This also prevents too much context-switching between the dumpcap
3654 * and wireshark processes.
3656 #define DUMPCAP_UPD_TIME 500
3659 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3660 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3662 gettimeofday(&cur_time, NULL);
3663 if ((cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3664 (upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3667 upd_time = cur_time;
3670 if (pcap_stats(pch, stats) >= 0) {
3671 *stats_known = TRUE;
3674 /* Let the parent process know. */
3675 if (global_ld.inpkts_to_sync_pipe) {
3677 fflush(global_ld.pdh);
3679 /* Send our parent a message saying we've written out
3680 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3682 report_packet_count(global_ld.inpkts_to_sync_pipe);
3684 global_ld.inpkts_to_sync_pipe = 0;
3687 /* check capture duration condition */
3688 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3689 /* The maximum capture time has elapsed; stop the capture. */
3690 global_ld.go = FALSE;
3694 /* check capture file duration condition */
3695 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3696 /* duration limit reached, do we have another file? */
3697 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3698 cnd_autostop_size, cnd_file_duration))
3700 } /* cnd_file_duration */
3704 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3706 pcap_queue_element *queue_element;
3708 for (i = 0; i < global_ld.pcaps->len; i++) {
3709 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3710 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3711 pcap_opts->interface_id);
3712 g_thread_join(pcap_opts->tid);
3713 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3714 pcap_opts->interface_id);
3717 g_async_queue_lock(pcap_queue);
3718 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3719 if (queue_element) {
3720 pcap_queue_bytes -= queue_element->phdr.caplen;
3721 pcap_queue_packets -= 1;
3723 g_async_queue_unlock(pcap_queue);
3724 if (queue_element == NULL) {
3727 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3728 "Dequeued a packet of length %d captured on interface %d.",
3729 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3730 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3731 &queue_element->phdr,
3733 g_free(queue_element->pd);
3734 g_free(queue_element);
3735 global_ld.inpkts_to_sync_pipe += 1;
3736 if (capture_opts->output_to_pipe) {
3737 fflush(global_ld.pdh);
3743 /* delete stop conditions */
3744 if (cnd_file_duration != NULL)
3745 cnd_delete(cnd_file_duration);
3746 if (cnd_autostop_files != NULL)
3747 cnd_delete(cnd_autostop_files);
3748 if (cnd_autostop_size != NULL)
3749 cnd_delete(cnd_autostop_size);
3750 if (cnd_autostop_duration != NULL)
3751 cnd_delete(cnd_autostop_duration);
3753 /* did we have a pcap (input) error? */
3754 for (i = 0; i < capture_opts->ifaces->len; i++) {
3755 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3756 if (pcap_opts->pcap_err) {
3757 /* On Linux, if an interface goes down while you're capturing on it,
3758 you'll get a "recvfrom: Network is down" or
3759 "The interface went down" error (ENETDOWN).
3760 (At least you will if g_strerror() doesn't show a local translation
3763 On FreeBSD and OS X, if a network adapter disappears while
3764 you're capturing on it, you'll get a "read: Device not configured"
3765 error (ENXIO). (See previous parenthetical note.)
3767 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3769 These should *not* be reported to the Wireshark developers. */
3772 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3773 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3774 strcmp(cap_err_str, "The interface went down") == 0 ||
3775 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3776 strcmp(cap_err_str, "read: I/O error") == 0 ||
3777 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3778 report_capture_error("The network adapter on which the capture was being done "
3779 "is no longer running; the capture has stopped.",
3782 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3784 report_capture_error(errmsg, please_report);
3787 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3788 report_capture_error(errmsg, "");
3792 /* did we have an output error while capturing? */
3793 if (global_ld.err == 0) {
3796 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3797 global_ld.err, FALSE);
3798 report_capture_error(errmsg, please_report);
3802 if (capture_opts->saving_to_file) {
3803 /* close the output file */
3804 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3808 /* there might be packets not yet notified to the parent */
3809 /* (do this after closing the file, so all packets are already flushed) */
3810 if (global_ld.inpkts_to_sync_pipe) {
3812 report_packet_count(global_ld.inpkts_to_sync_pipe);
3813 global_ld.inpkts_to_sync_pipe = 0;
3816 /* If we've displayed a message about a write error, there's no point
3817 in displaying another message about an error on close. */
3818 if (!close_ok && write_ok) {
3819 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3821 report_capture_error(errmsg, "");
3825 * XXX We exhibit different behaviour between normal mode and sync mode
3826 * when the pipe is stdin and not already at EOF. If we're a child, the
3827 * parent's stdin isn't closed, so if the user starts another capture,
3828 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3829 * will say "Unrecognized libpcap format". On the other hand, in normal
3830 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3833 report_capture_count(TRUE);
3835 /* get packet drop statistics from pcap */
3836 for (i = 0; i < capture_opts->ifaces->len; i++) {
3838 guint32 pcap_dropped = 0;
3840 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3841 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3842 received = pcap_opts->received;
3843 if (pcap_opts->pcap_h != NULL) {
3844 g_assert(!pcap_opts->from_cap_pipe);
3845 /* Get the capture statistics, so we know how many packets were dropped. */
3846 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3847 *stats_known = TRUE;
3848 /* Let the parent process know. */
3849 pcap_dropped += stats->ps_drop;
3851 g_snprintf(errmsg, sizeof(errmsg),
3852 "Can't get packet-drop statistics: %s",
3853 pcap_geterr(pcap_opts->pcap_h));
3854 report_capture_error(errmsg, please_report);
3857 report_packet_drops(received, pcap_dropped, pcap_opts->dropped, pcap_opts->flushed, interface_opts.console_display_name);
3860 /* close the input file (pcap or capture pipe) */
3861 capture_loop_close_input(&global_ld);
3863 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
3865 /* ok, if the write and the close were successful. */
3866 return write_ok && close_ok;
3869 if (capture_opts->multi_files_on) {
3870 /* cleanup ringbuffer */
3871 ringbuf_error_cleanup();
3873 /* We can't use the save file, and we have no FILE * for the stream
3874 to close in order to close it, so close the FD directly. */
3875 if (global_ld.save_file_fd != -1) {
3876 ws_close(global_ld.save_file_fd);
3879 /* We couldn't even start the capture, so get rid of the capture
3881 if (capture_opts->save_file != NULL) {
3882 ws_unlink(capture_opts->save_file);
3883 g_free(capture_opts->save_file);
3886 capture_opts->save_file = NULL;
3888 report_cfilter_error(capture_opts, error_index, errmsg);
3890 report_capture_error(errmsg, secondary_errmsg);
3892 /* close the input file (pcap or cap_pipe) */
3893 capture_loop_close_input(&global_ld);
3895 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3902 capture_loop_stop(void)
3904 #ifdef HAVE_PCAP_BREAKLOOP
3906 pcap_options *pcap_opts;
3908 for (i = 0; i < global_ld.pcaps->len; i++) {
3909 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3910 if (pcap_opts->pcap_h != NULL)
3911 pcap_breakloop(pcap_opts->pcap_h);
3914 global_ld.go = FALSE;
3919 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3920 int err, gboolean is_close)
3925 g_snprintf(errmsg, errmsglen,
3926 "Not all the packets could be written to the file"
3927 " to which the capture was being saved\n"
3928 "(\"%s\") because there is no space left on the file system\n"
3929 "on which that file resides.",
3935 g_snprintf(errmsg, errmsglen,
3936 "Not all the packets could be written to the file"
3937 " to which the capture was being saved\n"
3938 "(\"%s\") because you are too close to, or over,"
3939 " your disk quota\n"
3940 "on the file system on which that file resides.",
3947 g_snprintf(errmsg, errmsglen,
3948 "The file to which the capture was being saved\n"
3949 "(\"%s\") could not be closed: %s.",
3950 fname, g_strerror(err));
3952 g_snprintf(errmsg, errmsglen,
3953 "An error occurred while writing to the file"
3954 " to which the capture was being saved\n"
3956 fname, g_strerror(err));
3963 /* one packet was captured, process it */
3965 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3968 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3970 guint ts_mul = pcap_opts->ts_nsec ? 1000000000 : 1000000;
3972 /* We may be called multiple times from pcap_dispatch(); if we've set
3973 the "stop capturing" flag, ignore this packet, as we're not
3974 supposed to be saving any more packets. */
3975 if (!global_ld.go) {
3976 pcap_opts->flushed++;
3980 if (global_ld.pdh) {
3981 gboolean successful;
3983 /* We're supposed to write the packet to a file; do so.
3984 If this fails, set "ld->go" to FALSE, to stop the capture, and set
3985 "ld->err" to the error. */
3986 if (global_capture_opts.use_pcapng) {
3987 successful = libpcap_write_enhanced_packet_block(libpcap_write_to_file, global_ld.pdh,
3989 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
3990 phdr->caplen, phdr->len,
3991 pcap_opts->interface_id,
3994 &global_ld.bytes_written, &err);
3996 successful = libpcap_write_packet(libpcap_write_to_file, global_ld.pdh,
3997 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
3998 phdr->caplen, phdr->len,
4000 &global_ld.bytes_written, &err);
4003 global_ld.go = FALSE;
4004 global_ld.err = err;
4005 pcap_opts->dropped++;
4007 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4008 "Wrote a packet of length %d captured on interface %u.",
4009 phdr->caplen, pcap_opts->interface_id);
4010 global_ld.packet_count++;
4011 pcap_opts->received++;
4012 /* if the user told us to stop after x packets, do we already have enough? */
4013 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
4014 global_ld.go = FALSE;
4020 /* one packet was captured, queue it */
4022 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4025 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4026 pcap_queue_element *queue_element;
4027 gboolean limit_reached;
4029 /* We may be called multiple times from pcap_dispatch(); if we've set
4030 the "stop capturing" flag, ignore this packet, as we're not
4031 supposed to be saving any more packets. */
4032 if (!global_ld.go) {
4033 pcap_opts->flushed++;
4037 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4038 if (queue_element == NULL) {
4039 pcap_opts->dropped++;
4042 queue_element->pcap_opts = pcap_opts;
4043 queue_element->phdr = *phdr;
4044 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4045 if (queue_element->pd == NULL) {
4046 pcap_opts->dropped++;
4047 g_free(queue_element);
4050 memcpy(queue_element->pd, pd, phdr->caplen);
4051 g_async_queue_lock(pcap_queue);
4052 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4053 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4054 limit_reached = FALSE;
4055 g_async_queue_push_unlocked(pcap_queue, queue_element);
4056 pcap_queue_bytes += phdr->caplen;
4057 pcap_queue_packets += 1;
4059 limit_reached = TRUE;
4061 g_async_queue_unlock(pcap_queue);
4062 if (limit_reached) {
4063 pcap_opts->dropped++;
4064 g_free(queue_element->pd);
4065 g_free(queue_element);
4066 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4067 "Dropped a packet of length %d captured on interface %u.",
4068 phdr->caplen, pcap_opts->interface_id);
4070 pcap_opts->received++;
4071 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4072 "Queued a packet of length %d captured on interface %u.",
4073 phdr->caplen, pcap_opts->interface_id);
4075 /* I don't want to hold the mutex over the debug output. So the
4076 output may be wrong */
4077 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4078 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4079 pcap_queue_bytes, pcap_queue_packets);
4083 set_80211_channel(const char *iface, const char *opt)
4085 int freq = 0, type, ret;
4086 gchar **options = NULL;
4088 options = g_strsplit_set(opt, ",", 2);
4091 freq = atoi(options[0]);
4094 type = ws80211_str_to_chan_type(options[1]);
4103 ret = ws80211_init();
4105 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4109 ret = ws80211_set_freq(iface, freq, type);
4112 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4118 pipe_write_block(2, SP_SUCCESS, NULL);
4122 g_strfreev(options);
4126 /* And now our feature presentation... [ fade to music ] */
4128 main(int argc, char *argv[])
4130 GString *comp_info_str;
4131 GString *runtime_info_str;
4133 struct option long_options[] = {
4134 {(char *)"capture-comment", required_argument, NULL, LONGOPT_NUM_CAP_COMMENT },
4138 gboolean arg_error = FALSE;
4143 struct sigaction action, oldaction;
4146 gboolean start_capture = TRUE;
4147 gboolean stats_known;
4148 struct pcap_stat stats;
4149 GLogLevelFlags log_flags;
4150 gboolean list_interfaces = FALSE;
4151 gboolean list_link_layer_types = FALSE;
4152 #ifdef HAVE_BPF_IMAGE
4153 gboolean print_bpf_code = FALSE;
4155 gboolean set_chan = FALSE;
4156 gchar *set_chan_arg = NULL;
4157 gboolean machine_readable = FALSE;
4158 gboolean print_statistics = FALSE;
4159 int status, run_once_args = 0;
4162 #if defined(__APPLE__) && defined(__LP64__)
4163 struct utsname osinfo;
4167 /* Assemble the compile-time version information string */
4168 comp_info_str = g_string_new("Compiled ");
4169 get_compiled_version_info(comp_info_str, NULL, NULL);
4171 /* Assemble the run-time version information string */
4172 runtime_info_str = g_string_new("Running ");
4173 get_runtime_version_info(runtime_info_str, NULL);
4175 /* Add it to the information to be reported on a crash. */
4176 ws_add_crash_info("Dumpcap " VERSION "%s\n"
4181 wireshark_svnversion, comp_info_str->str, runtime_info_str->str);
4184 arg_list_utf_16to8(argc, argv);
4185 create_app_running_mutex();
4188 * Initialize our DLL search path. MUST be called before LoadLibrary
4191 ws_init_dll_search_path();
4194 #ifdef HAVE_PCAP_REMOTE
4195 #define OPTSTRING_A "A:"
4196 #define OPTSTRING_r "r"
4197 #define OPTSTRING_u "u"
4199 #define OPTSTRING_A ""
4200 #define OPTSTRING_r ""
4201 #define OPTSTRING_u ""
4204 #ifdef HAVE_PCAP_SETSAMPLING
4205 #define OPTSTRING_m "m:"
4207 #define OPTSTRING_m ""
4210 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4211 #define OPTSTRING_B "B:"
4213 #define OPTSTRING_B ""
4214 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4216 #ifdef HAVE_PCAP_CREATE
4217 #define OPTSTRING_I "I"
4219 #define OPTSTRING_I ""
4222 #ifdef HAVE_BPF_IMAGE
4223 #define OPTSTRING_d "d"
4225 #define OPTSTRING_d ""
4228 #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:"
4230 #ifdef DEBUG_CHILD_DUMPCAP
4231 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4232 fprintf (stderr, "Unable to open debug log file !\n");
4237 #if defined(__APPLE__) && defined(__LP64__)
4239 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
4240 * a bug workaround - timeouts less than 1 second don't work with libpcap
4241 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
4242 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4243 * The problem is extremely unlikely to be reintroduced in a future
4246 if (uname(&osinfo) == 0) {
4248 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
4249 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4250 * number of 10.0.0, not 10.1.0 - go figure).
4252 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
4253 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
4254 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
4255 need_timeout_workaround = TRUE;
4260 * Determine if dumpcap is being requested to run in a special
4261 * capture_child mode by going thru the command line args to see if
4262 * a -Z is present. (-Z is a hidden option).
4264 * The primary result of running in capture_child mode is that
4265 * all messages sent out on stderr are in a special type/len/string
4266 * format to allow message processing by type. These messages include
4267 * error messages if dumpcap fails to start the operation it was
4268 * requested to do, as well as various "status" messages which are sent
4269 * when an actual capture is in progress, and a "success" message sent
4270 * if dumpcap was requested to perform an operation other than a
4273 * Capture_child mode would normally be requested by a parent process
4274 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4275 * to which dumpcap stderr has been redirected. It might also have
4276 * another pipe to obtain dumpcap stdout output; for operations other
4277 * than a capture, that information is formatted specially for easier
4278 * parsing by the parent process.
4280 * Capture_child mode needs to be determined immediately upon
4281 * startup so that any messages generated by dumpcap in this mode
4282 * (eg: during initialization) will be formatted properly.
4285 for (i=1; i<argc; i++) {
4286 if (strcmp("-Z", argv[i]) == 0) {
4287 capture_child = TRUE;
4288 machine_readable = TRUE; /* request machine-readable output */
4290 /* set output pipe to binary mode, to avoid ugly text conversions */
4291 _setmode(2, O_BINARY);
4296 /* The default_log_handler will use stdout, which makes trouble in */
4297 /* capture child mode, as it uses stdout for its sync_pipe. */
4298 /* So: the filtering is done in the console_log_handler and not here.*/
4299 /* We set the log handlers right up front to make sure that any log */
4300 /* messages when running as child will be sent back to the parent */
4301 /* with the correct format. */
4306 G_LOG_LEVEL_CRITICAL|
4307 G_LOG_LEVEL_WARNING|
4308 G_LOG_LEVEL_MESSAGE|
4312 G_LOG_FLAG_RECURSION);
4314 g_log_set_handler(NULL,
4316 console_log_handler, NULL /* user_data */);
4317 g_log_set_handler(LOG_DOMAIN_MAIN,
4319 console_log_handler, NULL /* user_data */);
4320 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4322 console_log_handler, NULL /* user_data */);
4323 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4325 console_log_handler, NULL /* user_data */);
4327 /* Initialize the pcaps list */
4328 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
4330 #if !GLIB_CHECK_VERSION(2,31,0)
4331 /* Initialize the thread system */
4332 g_thread_init(NULL);
4336 /* Load wpcap if possible. Do this before collecting the run-time version information */
4339 /* ... and also load the packet.dll from wpcap */
4340 /* XXX - currently not required, may change later. */
4341 /*wpcap_packet_load();*/
4343 /* Start windows sockets */
4344 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4346 /* Set handler for Ctrl+C key */
4347 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4349 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4350 and exit. Do the same with SIGPIPE, in case, for example,
4351 we're writing to our standard output and it's a pipe.
4352 Do the same with SIGHUP if it's not being ignored (if we're
4353 being run under nohup, it might be ignored, in which case we
4354 should leave it ignored).
4356 XXX - apparently, Coverity complained that part of action
4357 wasn't initialized. Perhaps it's running on Linux, where
4358 struct sigaction has an ignored "sa_restorer" element and
4359 where "sa_handler" and "sa_sigaction" might not be two
4360 members of a union. */
4361 memset(&action, 0, sizeof(action));
4362 action.sa_handler = capture_cleanup_handler;
4364 * Arrange that system calls not get restarted, because when
4365 * our signal handler returns we don't want to restart
4366 * a call that was waiting for packets to arrive.
4368 action.sa_flags = 0;
4369 sigemptyset(&action.sa_mask);
4370 sigaction(SIGTERM, &action, NULL);
4371 sigaction(SIGINT, &action, NULL);
4372 sigaction(SIGPIPE, &action, NULL);
4373 sigaction(SIGHUP, NULL, &oldaction);
4374 if (oldaction.sa_handler == SIG_DFL)
4375 sigaction(SIGHUP, &action, NULL);
4378 /* Catch SIGINFO and, if we get it and we're capturing in
4379 quiet mode, report the number of packets we've captured. */
4380 action.sa_handler = report_counts_siginfo;
4381 action.sa_flags = SA_RESTART;
4382 sigemptyset(&action.sa_mask);
4383 sigaction(SIGINFO, &action, NULL);
4384 #endif /* SIGINFO */
4387 /* ----------------------------------------------------------------- */
4388 /* Privilege and capability handling */
4390 /* 1. Running not as root or suid root; no special capabilities. */
4393 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4396 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4398 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4399 /* capabilities; Drop all other capabilities; */
4400 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4401 /* else: after pcap_open_live() in capture_loop_open_input() */
4402 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4403 /* (Note: this means that the process, although logged in */
4404 /* as root, does not have various permissions such as the */
4405 /* ability to bypass file access permissions). */
4406 /* XXX: Should we just leave capabilities alone in this case */
4407 /* so that user gets expected effect that root can do */
4410 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4412 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4413 /* else: after pcap_open_live() in capture_loop_open_input() */
4414 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4415 /* pcap_open_live). */
4417 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4419 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4420 /* capabilities; Drop all other capabilities; */
4421 /* Drop suid privileges (euid=ruid); */
4422 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4423 /* else: after pcap_open_live() in capture_loop_open_input() */
4424 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4426 /* XXX: For some Linux versions/distros with capabilities */
4427 /* a 'normal' process with any capabilities cannot be */
4428 /* 'killed' (signaled) from another (same uid) non-privileged */
4430 /* For example: If (non-suid) Wireshark forks a */
4431 /* child suid dumpcap which acts as described here (case 5), */
4432 /* Wireshark will be unable to kill (signal) the child */
4433 /* dumpcap process until the capabilities have been dropped */
4434 /* (after pcap_open_live()). */
4435 /* This behaviour will apparently be changed in the kernel */
4436 /* to allow the kill (signal) in this case. */
4437 /* See the following for details: */
4438 /* http://www.mail-archive.com/ [wrapped] */
4439 /* linux-security-module@vger.kernel.org/msg02913.html */
4441 /* It is therefore conceivable that if dumpcap somehow hangs */
4442 /* in pcap_open_live or before that wireshark will not */
4443 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4444 /* In this case, exiting wireshark will kill the child */
4445 /* dumpcap process. */
4447 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4448 /* capabilities; Using libcap. Note: capset cmd (which see) */
4449 /* used to assign capabilities to file. */
4451 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4452 /* else: after pcap_open_live() in capture_loop_open_input() */
4453 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4455 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4456 /* longer required (similar to capture). */
4458 /* ----------------------------------------------------------------- */
4460 init_process_policies();
4463 /* If 'started with special privileges' (and using libcap) */
4464 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4465 /* Set euid/egid = ruid/rgid to remove suid privileges */
4466 relinquish_privs_except_capture();
4469 /* Set the initial values in the capture options. This might be overwritten
4470 by the command line parameters. */
4471 capture_opts_init(&global_capture_opts);
4473 /* We always save to a file - if no file was specified, we save to a
4475 global_capture_opts.saving_to_file = TRUE;
4476 global_capture_opts.has_ring_num_files = TRUE;
4478 /* Pass on capture_child mode for capture_opts */
4479 global_capture_opts.capture_child = capture_child;
4481 /* Now get our args */
4482 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4484 case 'h': /* Print help and exit */
4488 case 'v': /* Show version and exit */
4490 show_version(comp_info_str, runtime_info_str);
4491 g_string_free(comp_info_str, TRUE);
4492 g_string_free(runtime_info_str, TRUE);
4496 /*** capture option specific ***/
4497 case 'a': /* autostop criteria */
4498 case 'b': /* Ringbuffer option */
4499 case 'c': /* Capture x packets */
4500 case 'f': /* capture filter */
4501 case 'g': /* enable group read access on file(s) */
4502 case 'i': /* Use interface x */
4503 case 'n': /* Use pcapng format */
4504 case 'p': /* Don't capture in promiscuous mode */
4505 case 'P': /* Use pcap format */
4506 case 's': /* Set the snapshot (capture) length */
4507 case 'w': /* Write to capture file x */
4508 case 'y': /* Set the pcap data link type */
4509 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4510 #ifdef HAVE_PCAP_REMOTE
4511 case 'u': /* Use UDP for data transfer */
4512 case 'r': /* Capture own RPCAP traffic too */
4513 case 'A': /* Authentication */
4515 #ifdef HAVE_PCAP_SETSAMPLING
4516 case 'm': /* Sampling */
4518 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4519 case 'B': /* Buffer size */
4520 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4521 #ifdef HAVE_PCAP_CREATE
4522 case 'I': /* Monitor mode */
4524 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4529 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4531 capture_child = TRUE;
4533 /* set output pipe to binary mode, to avoid ugly text conversions */
4534 _setmode(2, O_BINARY);
4536 * optarg = the control ID, aka the PPID, currently used for the
4539 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4540 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4541 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4542 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4544 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4545 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4546 "Signal pipe: Unable to open %s. Dead parent?",
4554 case 'q': /* Quiet */
4560 /*** all non capture option specific ***/
4561 case 'D': /* Print a list of capture devices and exit */
4562 list_interfaces = TRUE;
4565 case 'L': /* Print list of link-layer types and exit */
4566 list_link_layer_types = TRUE;
4569 #ifdef HAVE_BPF_IMAGE
4570 case 'd': /* Print BPF code for capture filter and exit */
4571 print_bpf_code = TRUE;
4575 case 'S': /* Print interface statistics once a second */
4576 print_statistics = TRUE;
4579 case 'k': /* Set wireless channel */
4581 set_chan_arg = optarg;
4584 case 'M': /* For -D, -L, and -S, print machine-readable output */
4585 machine_readable = TRUE;
4588 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4591 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4594 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4596 case '?': /* Bad flag - print usage message */
4605 /* user specified file name as regular command-line argument */
4606 /* XXX - use it as the capture file name (or something else)? */
4612 * Extra command line arguments were specified; complain.
4613 * XXX - interpret as capture filter, as tcpdump and tshark do?
4615 cmdarg_err("Invalid argument: %s", argv[0]);
4620 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4623 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4624 /* Use some default if the user hasn't specified some */
4625 /* XXX: Are these defaults good enough? */
4626 pcap_queue_byte_limit = 1000 * 1000;
4627 pcap_queue_packet_limit = 1000;
4634 if (run_once_args > 1) {
4635 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
4637 } else if (run_once_args == 1) {
4638 /* We're supposed to print some information, rather than
4639 to capture traffic; did they specify a ring buffer option? */
4640 if (global_capture_opts.multi_files_on) {
4641 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4645 /* We're supposed to capture traffic; */
4647 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4648 if (global_capture_opts.ifaces->len > 1) {
4650 global_capture_opts.use_pcapng = TRUE;
4653 if (global_capture_opts.capture_comment &&
4654 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4655 /* XXX - for ringbuffer, should we apply the comment to each file? */
4656 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4660 /* Was the ring buffer option specified and, if so, does it make sense? */
4661 if (global_capture_opts.multi_files_on) {
4662 /* Ring buffer works only under certain conditions:
4663 a) ring buffer does not work with temporary files;
4664 b) it makes no sense to enable the ring buffer if the maximum
4665 file size is set to "infinite". */
4666 if (global_capture_opts.save_file == NULL) {
4667 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4668 global_capture_opts.multi_files_on = FALSE;
4670 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4671 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4673 /* XXX - this must be redesigned as the conditions changed */
4674 global_capture_opts.multi_files_on = FALSE;
4681 * "-D" requires no interface to be selected; it's supposed to list
4684 if (list_interfaces) {
4685 /* Get the list of interfaces */
4690 if_list = capture_interface_list(&err, &err_str,NULL);
4691 if (if_list == NULL) {
4693 case CANT_GET_INTERFACE_LIST:
4694 case DONT_HAVE_PCAP:
4695 cmdarg_err("%s", err_str);
4700 case NO_INTERFACES_FOUND:
4702 * If we're being run by another program, just give them
4703 * an empty list of interfaces, don't report this as
4704 * an error; that lets them decide whether to report
4705 * this as an error or not.
4707 if (!machine_readable) {
4708 cmdarg_err("There are no interfaces on which a capture can be done");
4715 if (machine_readable) /* tab-separated values to stdout */
4716 print_machine_readable_interfaces(if_list);
4718 capture_opts_print_interfaces(if_list);
4719 free_interface_list(if_list);
4724 * "-S" requires no interface to be selected; it gives statistics
4725 * for all interfaces.
4727 if (print_statistics) {
4728 status = print_statistics_loop(machine_readable);
4733 interface_options interface_opts;
4735 if (global_capture_opts.ifaces->len != 1) {
4736 cmdarg_err("Need one interface");
4740 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4741 status = set_80211_channel(interface_opts.name, set_chan_arg);
4746 * "-L", "-d", and capturing act on a particular interface, so we have to
4747 * have an interface; if none was specified, pick a default.
4749 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4751 /* cmdarg_err() already called .... */
4755 /* Let the user know what interfaces were chosen. */
4756 if (capture_child) {
4757 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4758 interface_options interface_opts;
4760 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4761 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4762 interface_opts.name);
4765 str = g_string_new("");
4767 if (global_capture_opts.ifaces->len < 2)
4769 if (global_capture_opts.ifaces->len < 4)
4772 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4773 interface_options interface_opts;
4775 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4777 if (global_capture_opts.ifaces->len > 2) {
4778 g_string_append_printf(str, ",");
4780 g_string_append_printf(str, " ");
4781 if (j == global_capture_opts.ifaces->len - 1) {
4782 g_string_append_printf(str, "and ");
4785 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
4788 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4790 fprintf(stderr, "Capturing on %s\n", str->str);
4791 g_string_free(str, TRUE);
4794 if (list_link_layer_types) {
4795 /* Get the list of link-layer types for the capture device. */
4796 if_capabilities_t *caps;
4800 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4801 interface_options interface_opts;
4803 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4804 caps = get_if_capabilities(interface_opts.name,
4805 interface_opts.monitor_mode, &err_str);
4807 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4808 "Please check to make sure you have sufficient permissions, and that\n"
4809 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4813 if (caps->data_link_types == NULL) {
4814 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4817 if (machine_readable) /* tab-separated values to stdout */
4818 /* XXX: We need to change the format and adopt consumers */
4819 print_machine_readable_if_capabilities(caps);
4821 /* XXX: We might want to print also the interface name */
4822 capture_opts_print_if_capabilities(caps, interface_opts.name,
4823 interface_opts.monitor_mode);
4824 free_if_capabilities(caps);
4829 /* We're supposed to do a capture, or print the BPF code for a filter.
4830 Process the snapshot length, as that affects the generated BPF code. */
4831 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4833 #ifdef HAVE_BPF_IMAGE
4834 if (print_bpf_code) {
4835 show_filter_code(&global_capture_opts);
4840 /* We're supposed to do a capture. Process the ring buffer arguments. */
4841 capture_opts_trim_ring_num_files(&global_capture_opts);
4843 /* flush stderr prior to starting the main capture loop */
4846 /* Now start the capture. */
4848 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4852 /* capture failed */
4855 return 0; /* never here, make compiler happy */
4860 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4861 const char *message, gpointer user_data _U_)
4868 /* ignore log message, if log_level isn't interesting */
4869 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4870 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4875 /* create a "timestamp" */
4877 today = localtime(&curr);
4879 switch(log_level & G_LOG_LEVEL_MASK) {
4880 case G_LOG_LEVEL_ERROR:
4883 case G_LOG_LEVEL_CRITICAL:
4886 case G_LOG_LEVEL_WARNING:
4889 case G_LOG_LEVEL_MESSAGE:
4892 case G_LOG_LEVEL_INFO:
4895 case G_LOG_LEVEL_DEBUG:
4899 fprintf(stderr, "unknown log_level %u\n", log_level);
4901 g_assert_not_reached();
4904 /* Generate the output message */
4905 if (log_level & G_LOG_LEVEL_MESSAGE) {
4906 /* normal user messages without additional infos */
4907 msg = g_strdup_printf("%s\n", message);
4909 /* info/debug messages with additional infos */
4910 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4911 today->tm_hour, today->tm_min, today->tm_sec,
4912 log_domain != NULL ? log_domain : "",
4916 /* DEBUG & INFO msgs (if we're debugging today) */
4917 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4918 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4919 #ifdef DEBUG_DUMPCAP
4920 fprintf(stderr, "%s", msg);
4923 #ifdef DEBUG_CHILD_DUMPCAP
4924 fprintf(debug_log, "%s", msg);
4932 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4933 /* to parent especially formatted if dumpcap running as child. */
4934 if (capture_child) {
4935 sync_pipe_errmsg_to_parent(2, msg, "");
4937 fprintf(stderr, "%s", msg);
4944 /****************************************************************************************************************/
4945 /* indication report routines */
4949 report_packet_count(unsigned int packet_count)
4951 char tmp[SP_DECISIZE+1+1];
4952 static unsigned int count = 0;
4954 if (capture_child) {
4955 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
4956 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
4957 pipe_write_block(2, SP_PACKET_COUNT, tmp);
4959 count += packet_count;
4960 fprintf(stderr, "\rPackets: %u ", count);
4961 /* stderr could be line buffered */
4967 report_new_capture_file(const char *filename)
4969 if (capture_child) {
4970 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
4971 pipe_write_block(2, SP_FILE, filename);
4975 * Prevent a SIGINFO handler from writing to the standard error
4976 * while we're doing so; instead, have it just set a flag telling
4977 * us to print that information when we're done.
4980 #endif /* SIGINFO */
4981 fprintf(stderr, "File: %s\n", filename);
4982 /* stderr could be line buffered */
4987 * Allow SIGINFO handlers to write.
4992 * If a SIGINFO handler asked us to write out capture counts, do so.
4995 report_counts_for_siginfo();
4996 #endif /* SIGINFO */
5001 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
5003 interface_options interface_opts;
5004 char tmp[MSG_MAX_LENGTH+1+6];
5006 if (i < capture_opts->ifaces->len) {
5007 if (capture_child) {
5008 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
5009 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
5010 pipe_write_block(2, SP_BAD_FILTER, tmp);
5013 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5014 * the error message below.
5016 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
5018 "Invalid capture filter \"%s\" for interface %s!\n"
5020 "That string isn't a valid capture filter (%s).\n"
5021 "See the User's Guide for a description of the capture filter syntax.",
5022 interface_opts.cfilter, interface_opts.name, errmsg);
5028 report_capture_error(const char *error_msg, const char *secondary_error_msg)
5030 if (capture_child) {
5031 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5032 "Primary Error: %s", error_msg);
5033 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5034 "Secondary Error: %s", secondary_error_msg);
5035 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5037 cmdarg_err("%s", error_msg);
5038 if (secondary_error_msg[0] != '\0')
5039 cmdarg_err_cont("%s", secondary_error_msg);
5044 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, gchar *name)
5046 char tmp[SP_DECISIZE+1+1];
5047 guint32 total_drops = pcap_drops + drops + flushed;
5049 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
5051 if (capture_child) {
5052 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5053 "Packets received/dropped on interface %s: %u/%u (pcap:%u/dumpcap:%u/flushed:%u)",
5054 name, received, total_drops, pcap_drops, drops, flushed);
5055 /* XXX: Need to provide interface id, changes to consumers required. */
5056 pipe_write_block(2, SP_DROPS, tmp);
5059 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u) (%.1f%%)\n",
5060 name, received, total_drops, pcap_drops, drops, flushed,
5061 received ? 100.0 * received / (received + total_drops) : 0.0);
5062 /* stderr could be line buffered */
5068 /************************************************************************************************/
5069 /* signal_pipe handling */
5074 signal_pipe_check_running(void)
5076 /* any news from our parent? -> just stop the capture */
5080 /* if we are running standalone, no check required */
5081 if (!capture_child) {
5085 if (!sig_pipe_name || !sig_pipe_handle) {
5086 /* This shouldn't happen */
5087 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5088 "Signal pipe: No name or handle");
5093 * XXX - We should have the process ID of the parent (from the "-Z" flag)
5094 * at this point. Should we check to see if the parent is still alive,
5095 * e.g. by using OpenProcess?
5098 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5100 if (!result || avail > 0) {
5101 /* peek failed or some bytes really available */
5102 /* (if not piping from stdin this would fail) */
5103 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5104 "Signal pipe: Stop capture: %s", sig_pipe_name);
5105 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5106 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
5107 sig_pipe_handle, result, avail);
5110 /* pipe ok and no bytes available */
5121 * Editor modelines - http://www.wireshark.org/tools/modelines.html
5126 * indent-tabs-mode: nil
5129 * vi: set shiftwidth=4 tabstop=8 expandtab:
5130 * :indentSize=4:tabSize=8:noTabs=true: