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>
73 #include <wsutil/pint.h>
76 #include "wsutil/wsgetopt.h"
84 # include <sys/prctl.h>
85 # include <sys/capability.h>
88 #include "ringbuffer.h"
89 #include "clopts_common.h"
90 #include "cmdarg_err.h"
91 #include "version_info.h"
93 #include "capture-pcap-util.h"
95 #include "capture-wpcap.h"
101 #include "capture-wpcap.h"
102 #include <wsutil/unicode-utils.h>
109 #ifdef NEED_INET_V6DEFS_H
110 # include "wsutil/inet_v6defs.h"
113 #include <wsutil/privileges.h>
115 #include "sync_pipe.h"
117 #include "capture_opts.h"
118 #include "capture_session.h"
119 #include "capture_ifinfo.h"
120 #include "capture_sync.h"
122 #include "conditions.h"
123 #include "capture_stop_conditions.h"
125 #include "wsutil/tempfile.h"
127 #include "wsutil/file_util.h"
129 #include "ws80211_utils.h"
132 * Get information about libpcap format from "wiretap/libpcap.h".
133 * XXX - can we just use pcap_open_offline() to read the pipe?
135 #include "wiretap/libpcap.h"
137 /**#define DEBUG_DUMPCAP**/
138 /**#define DEBUG_CHILD_DUMPCAP**/
142 #include <conio.h> /* _getch() */
146 #ifdef DEBUG_CHILD_DUMPCAP
147 FILE *debug_log
; /* for logging debug messages to */
148 /* a file if DEBUG_CHILD_DUMPCAP */
152 static GAsyncQueue
*pcap_queue
;
153 static gint64 pcap_queue_bytes
;
154 static gint64 pcap_queue_packets
;
155 static gint64 pcap_queue_byte_limit
= 0;
156 static gint64 pcap_queue_packet_limit
= 0;
158 static gboolean capture_child
= FALSE
; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
160 static gchar
*sig_pipe_name
= NULL
;
161 static HANDLE sig_pipe_handle
= NULL
;
162 static gboolean
signal_pipe_check_running(void);
166 static gboolean infodelay
; /* if TRUE, don't print capture info in SIGINFO handler */
167 static gboolean infoprint
; /* if TRUE, print capture info after clearing infodelay */
170 /** Stop a low-level capture (stops the capture child). */
171 static void capture_loop_stop(void);
172 /** Close a pipe, or socket if \a from_socket is TRUE */
173 static void cap_pipe_close(int pipe_fd
, gboolean from_socket _U_
);
177 * Enable kernel BPF JIT compiler if available.
178 * If any calls fail, just drive on - the JIT compiler might not be
179 * enabled, but filtering will still work, and it's not clear what
180 * we could do if the calls fail; should we just report the error
181 * and not continue to capture, should we report it as a warning, or
185 enable_kernel_bpf_jit_compiler(void)
189 static const char file
[] = "/proc/sys/net/core/bpf_jit_enable";
191 fd
= open(file
, O_WRONLY
);
195 written
= write(fd
, "1", strlen("1"));
201 #if !defined (__linux__)
202 #ifndef HAVE_PCAP_BREAKLOOP
204 * We don't have pcap_breakloop(), which is the only way to ensure that
205 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
206 * won't, if the call to read the next packet or batch of packets is
207 * is interrupted by a signal on UN*X, just go back and try again to
210 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
211 * the signal handler, set a flag to stop capturing; however, without
212 * a guarantee of that sort, we can't guarantee that we'll stop capturing
213 * if the read will be retried and won't time out if no packets arrive.
215 * Therefore, on at least some platforms, we work around the lack of
216 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
217 * to wait for packets to arrive, so that we're probably going to be
218 * blocked in the select() when the signal arrives, and can just bail
219 * out of the loop at that point.
221 * However, we don't want to do that on BSD (because "select()" doesn't work
222 * correctly on BPF devices on at least some releases of some flavors of
223 * BSD), and we don't want to do it on Windows (because "select()" is
224 * something for sockets, not for arbitrary handles). (Note that "Windows"
225 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
226 * using WinPcap, not a UNIX libpcap.)
228 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
229 * on BSD times out even if no packets have arrived, so we'll eventually
230 * exit pcap_dispatch() with an indication that no packets have arrived,
231 * and will break out of the capture loop at that point.
233 * On Windows, we can't send a SIGINT to stop capturing, so none of this
234 * applies in any case.
236 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
237 * want to include it if it's not present on this platform, however.
239 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
240 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
242 # define MUST_DO_SELECT
243 # endif /* avoid select */
244 #endif /* HAVE_PCAP_BREAKLOOP */
246 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
247 * in pcap_dispatch(); on the other hand, select() works just fine there.
248 * Hence we use a select for that come what may.
250 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
251 * internally, and, with TPACKET_V3, once that's supported, it'll
252 * support timeouts, at least as I understand the way the code works.
254 #define MUST_DO_SELECT
257 /** init the capture filter */
260 INITFILTER_BAD_FILTER
,
261 INITFILTER_OTHER_ERROR
262 } initfilter_status_t
;
265 STATE_EXPECT_REC_HDR
,
278 typedef struct _pcap_options
{
283 #ifdef MUST_DO_SELECT
284 int pcap_fd
; /**< pcap file descriptor */
291 gboolean ts_nsec
; /**< TRUE if we're using nanosecond precision. */
292 /**< capture pipe (unix only "input file") */
293 gboolean from_cap_pipe
; /**< TRUE if we are capturing data from a capture pipe */
294 gboolean from_cap_socket
; /**< TRUE if we're capturing from socket */
295 struct pcap_hdr cap_pipe_hdr
; /**< Pcap header when capturing from a pipe */
296 struct pcaprec_modified_hdr cap_pipe_rechdr
; /**< Pcap record header when capturing from a pipe */
298 HANDLE cap_pipe_h
; /**< The handle of the capture pipe */
300 int cap_pipe_fd
; /**< the file descriptor of the capture pipe */
301 gboolean cap_pipe_modified
; /**< TRUE if data in the pipe uses modified pcap headers */
302 gboolean cap_pipe_byte_swapped
; /**< TRUE if data in the pipe is byte swapped */
304 char * cap_pipe_buf
; /**< Pointer to the data buffer we read into */
305 DWORD cap_pipe_bytes_to_read
; /**< Used by cap_pipe_dispatch */
306 DWORD cap_pipe_bytes_read
; /**< Used by cap_pipe_dispatch */
308 size_t cap_pipe_bytes_to_read
; /**< Used by cap_pipe_dispatch */
309 size_t cap_pipe_bytes_read
; /**< Used by cap_pipe_dispatch */
311 cap_pipe_state_t cap_pipe_state
;
312 cap_pipe_err_t cap_pipe_err
;
315 GMutex
*cap_pipe_read_mtx
;
316 GAsyncQueue
*cap_pipe_pending_q
, *cap_pipe_done_q
;
320 typedef struct _loop_data
{
322 gboolean go
; /**< TRUE as long as we're supposed to keep capturing */
323 int err
; /**< if non-zero, error seen while capturing */
324 gint packet_count
; /**< Number of packets we have already captured */
325 gint packet_max
; /**< Number of packets we're supposed to capture - 0 means infinite */
326 guint inpkts_to_sync_pipe
; /**< Packets not already send out to the sync_pipe */
328 gboolean report_packet_count
; /**< Set by SIGINFO handler; print packet count */
334 guint64 bytes_written
;
335 guint32 autostop_files
;
338 typedef struct _pcap_queue_element
{
339 pcap_options
*pcap_opts
;
340 struct pcap_pkthdr phdr
;
342 } pcap_queue_element
;
345 * Standard secondary message for unexpected errors.
347 static const char please_report
[] =
348 "Please report this to the Wireshark developers.\n"
349 "http://bugs.wireshark.org/\n"
350 "(This is not a crash; please do not report it as such.)";
353 * This needs to be static, so that the SIGINT handler can clear the "go"
356 static loop_data global_ld
;
360 * Timeout, in milliseconds, for reads from the stream of captured packets
361 * from a capture device.
363 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
364 * 64-bit applications, with sub-second timeouts not to work. The bug is
365 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
367 #if defined(__APPLE__) && defined(__LP64__)
368 static gboolean need_timeout_workaround
;
370 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
372 #define CAP_READ_TIMEOUT 250
376 * Timeout, in microseconds, for reads from the stream of captured packets
377 * from a pipe. Pipes don't have the same problem that BPF devices do
378 * in OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
379 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
380 * of the offending versions of Snow Leopard.
382 * On Windows this value is converted to milliseconds and passed to
383 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
384 * will return immediately.
387 #define PIPE_READ_TIMEOUT 100000
389 #define PIPE_READ_TIMEOUT 250000
392 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
395 console_log_handler(const char *log_domain
, GLogLevelFlags log_level
,
396 const char *message
, gpointer user_data _U_
);
398 /* capture related options */
399 static capture_options global_capture_opts
;
400 static gboolean quiet
= FALSE
;
401 static gboolean use_threads
= FALSE
;
402 static guint64 start_time
;
404 static void capture_loop_write_packet_cb(u_char
*pcap_opts_p
, const struct pcap_pkthdr
*phdr
,
406 static void capture_loop_queue_packet_cb(u_char
*pcap_opts_p
, const struct pcap_pkthdr
*phdr
,
408 static void capture_loop_get_errmsg(char *errmsg
, int errmsglen
, const char *fname
,
409 int err
, gboolean is_close
);
411 static void WS_MSVC_NORETURN
exit_main(int err
) G_GNUC_NORETURN
;
413 static void report_new_capture_file(const char *filename
);
414 static void report_packet_count(unsigned int packet_count
);
415 static void report_packet_drops(guint32 received
, guint32 pcap_drops
, guint32 drops
, guint32 flushed
, guint32 ps_ifdrop
, gchar
*name
);
416 static void report_capture_error(const char *error_msg
, const char *secondary_error_msg
);
417 static void report_cfilter_error(capture_options
*capture_opts
, guint i
, const char *errmsg
);
419 #define MSG_MAX_LENGTH 4096
421 /* Copied from pcapio.c pcapng_write_interface_statistics_block()*/
423 create_timestamp(void) {
433 * Current time, represented as 100-nanosecond intervals since
434 * January 1, 1601, 00:00:00 UTC.
436 * I think DWORD might be signed, so cast both parts of "now"
437 * to guint32 so that the sign bit doesn't get treated specially.
439 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
440 * might want to use instead.
442 GetSystemTimeAsFileTime(&now
);
443 timestamp
= (((guint64
)(guint32
)now
.dwHighDateTime
) << 32) +
444 (guint32
)now
.dwLowDateTime
;
447 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
453 * Subtract difference, in microseconds, between January 1, 1601
454 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
456 timestamp
-= G_GINT64_CONSTANT(11644473600000000U);
459 * Current time, represented as seconds and microseconds since
460 * January 1, 1970, 00:00:00 UTC.
462 gettimeofday(&now
, NULL
);
465 * Convert to delta in microseconds.
467 timestamp
= (guint64
)(now
.tv_sec
) * 1000000 +
468 (guint64
)(now
.tv_usec
);
474 print_usage(gboolean print_ver
)
481 "Dumpcap " VERSION
"%s\n"
482 "Capture network packets and dump them into a pcapng file.\n"
483 "See http://www.wireshark.org for more information.\n",
484 wireshark_svnversion
);
488 fprintf(output
, "\nUsage: dumpcap [options] ...\n");
489 fprintf(output
, "\n");
490 fprintf(output
, "Capture interface:\n");
491 fprintf(output
, " -i <interface> name or idx of interface (def: first non-loopback),\n"
492 " or for remote capturing, use one of these formats:\n"
493 " rpcap://<host>/<interface>\n"
494 " TCP@<host>:<port>\n");
495 fprintf(output
, " -f <capture filter> packet filter in libpcap filter syntax\n");
496 fprintf(output
, " -s <snaplen> packet snapshot length (def: 65535)\n");
497 fprintf(output
, " -p don't capture in promiscuous mode\n");
498 #ifdef HAVE_PCAP_CREATE
499 fprintf(output
, " -I capture in monitor mode, if available\n");
501 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
502 fprintf(output
, " -B <buffer size> size of kernel buffer in MB (def: %dMB)\n", DEFAULT_CAPTURE_BUFFER_SIZE
);
504 fprintf(output
, " -y <link type> link layer type (def: first appropriate)\n");
505 fprintf(output
, " -D print list of interfaces and exit\n");
506 fprintf(output
, " -L print list of link-layer types of iface and exit\n");
507 #ifdef HAVE_BPF_IMAGE
508 fprintf(output
, " -d print generated BPF code for capture filter\n");
510 fprintf(output
, " -k set channel on wifi interface <freq>,[<type>]\n");
511 fprintf(output
, " -S print statistics for each interface once per second\n");
512 fprintf(output
, " -M for -D, -L, and -S, produce machine-readable output\n");
513 fprintf(output
, "\n");
514 #ifdef HAVE_PCAP_REMOTE
515 fprintf(output
, "RPCAP options:\n");
516 fprintf(output
, " -r don't ignore own RPCAP traffic in capture\n");
517 fprintf(output
, " -u use UDP for RPCAP data transfer\n");
518 fprintf(output
, " -A <user>:<password> use RPCAP password authentication\n");
519 #ifdef HAVE_PCAP_SETSAMPLING
520 fprintf(output
, " -m <sampling type> use packet sampling\n");
521 fprintf(output
, " count:NUM - capture one packet of every NUM\n");
522 fprintf(output
, " timer:NUM - capture no more than 1 packet in NUM ms\n");
525 fprintf(output
, "Stop conditions:\n");
526 fprintf(output
, " -c <packet count> stop after n packets (def: infinite)\n");
527 fprintf(output
, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
528 fprintf(output
, " filesize:NUM - stop this file after NUM KB\n");
529 fprintf(output
, " files:NUM - stop after NUM files\n");
530 /*fprintf(output, "\n");*/
531 fprintf(output
, "Output (files):\n");
532 fprintf(output
, " -w <filename> name of file to save (def: tempfile)\n");
533 fprintf(output
, " -g enable group read access on the output file(s)\n");
534 fprintf(output
, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
535 fprintf(output
, " filesize:NUM - switch to next file after NUM KB\n");
536 fprintf(output
, " files:NUM - ringbuffer: replace after NUM files\n");
537 fprintf(output
, " -n use pcapng format instead of pcap (default)\n");
538 fprintf(output
, " -P use libpcap format instead of pcapng\n");
539 fprintf(output
, " --capture-comment <comment>\n");
540 fprintf(output
, " add a capture comment to the output file\n");
541 fprintf(output
, " (only for pcapng)\n");
542 fprintf(output
, "\n");
543 fprintf(output
, "Miscellaneous:\n");
544 fprintf(output
, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
545 fprintf(output
, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
546 fprintf(output
, " within dumpcap\n");
547 fprintf(output
, " -t use a separate thread per interface\n");
548 fprintf(output
, " -q don't report packet capture counts\n");
549 fprintf(output
, " -v print version information and exit\n");
550 fprintf(output
, " -h display this help and exit\n");
551 fprintf(output
, "\n");
553 fprintf(output
, "WARNING: dumpcap will enable kernel BPF JIT compiler if available.\n");
554 fprintf(output
, "You might want to reset it\n");
555 fprintf(output
, "By doing \"echo 0 > /proc/sys/net/core/bpf_jit_enable\"\n");
556 fprintf(output
, "\n");
558 fprintf(output
, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
559 fprintf(output
, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
560 fprintf(output
, "\n");
561 fprintf(output
, "Use Ctrl-C to stop capturing at any time.\n");
565 show_version(GString
*comp_info_str
, GString
*runtime_info_str
)
568 "Dumpcap " VERSION
"%s\n"
573 "See http://www.wireshark.org for more information.\n",
574 wireshark_svnversion
, get_copyright_info(), comp_info_str
->str
, runtime_info_str
->str
);
578 * Report an error in command-line arguments.
581 cmdarg_err(const char *fmt
, ...)
587 /* Generate a 'special format' message back to parent */
589 msg
= g_strdup_vprintf(fmt
, ap
);
590 sync_pipe_errmsg_to_parent(2, msg
, "");
595 fprintf(stderr
, "dumpcap: ");
596 vfprintf(stderr
, fmt
, ap
);
597 fprintf(stderr
, "\n");
603 * Report additional information for an error in command-line arguments.
606 cmdarg_err_cont(const char *fmt
, ...)
613 msg
= g_strdup_vprintf(fmt
, ap
);
614 sync_pipe_errmsg_to_parent(2, msg
, "");
619 vfprintf(stderr
, fmt
, ap
);
620 fprintf(stderr
, "\n");
627 #if 0 /* Set to enable capability debugging */
628 /* see 'man cap_to_text()' for explanation of output */
629 /* '=' means 'all= ' ie: no capabilities */
630 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
632 print_caps(const char *pfx
) {
633 cap_t caps
= cap_get_proc();
634 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
,
635 "%s: EUID: %d Capabilities: %s", pfx
,
636 geteuid(), cap_to_text(caps
, NULL
));
639 print_caps(const char *pfx _U_
) {
644 relinquish_all_capabilities(void)
646 /* Drop any and all capabilities this process may have. */
647 /* Allowed whether or not process has any privileges. */
648 cap_t caps
= cap_init(); /* all capabilities initialized to off */
649 print_caps("Pre-clear");
650 if (cap_set_proc(caps
)) {
651 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno
));
653 print_caps("Post-clear");
659 open_capture_device(interface_options
*interface_opts
,
660 char (*open_err_str
)[PCAP_ERRBUF_SIZE
])
663 #ifdef HAVE_PCAP_CREATE
666 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
667 struct pcap_rmtauth auth
;
670 /* Open the network interface to capture from it.
671 Some versions of libpcap may put warnings into the error buffer
672 if they succeed; to tell if that's happened, we have to clear
673 the error buffer, and check if it's still a null string. */
674 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "Entering open_capture_device().");
675 (*open_err_str
)[0] = '\0';
676 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
678 * If we're opening a remote device, use pcap_open(); that's currently
679 * the only open routine that supports remote devices.
681 if (strncmp (interface_opts
->name
, "rpcap://", 8) == 0) {
682 auth
.type
= interface_opts
->auth_type
== CAPTURE_AUTH_PWD
?
683 RPCAP_RMTAUTH_PWD
: RPCAP_RMTAUTH_NULL
;
684 auth
.username
= interface_opts
->auth_username
;
685 auth
.password
= interface_opts
->auth_password
;
687 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
,
688 "Calling pcap_open() using name %s, snaplen %d, promisc_mode %d, datatx_udp %d, nocap_rpcap %d.",
689 interface_opts
->name
, interface_opts
->snaplen
, interface_opts
->promisc_mode
,
690 interface_opts
->datatx_udp
, interface_opts
->nocap_rpcap
);
691 pcap_h
= pcap_open(interface_opts
->name
, interface_opts
->snaplen
,
693 (interface_opts
->promisc_mode
? PCAP_OPENFLAG_PROMISCUOUS
: 0) |
694 (interface_opts
->datatx_udp
? PCAP_OPENFLAG_DATATX_UDP
: 0) |
695 (interface_opts
->nocap_rpcap
? PCAP_OPENFLAG_NOCAPTURE_RPCAP
: 0),
696 CAP_READ_TIMEOUT
, &auth
, *open_err_str
);
697 if (pcap_h
== NULL
) {
698 /* Error - did pcap actually supply an error message? */
699 if ((*open_err_str
)[0] == '\0') {
700 /* Work around known WinPcap bug wherein no error message is
701 filled in on a failure to open an rpcap: URL. */
702 g_strlcpy(*open_err_str
,
703 "Unknown error (pcap bug; actual error cause not reported)",
704 sizeof *open_err_str
);
707 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
,
708 "pcap_open() returned %p.", (void *)pcap_h
);
713 * If we're not opening a remote device, use pcap_create() and
714 * pcap_activate() if we have them, so that we can set the buffer
715 * size, otherwise use pcap_open_live().
717 #ifdef HAVE_PCAP_CREATE
718 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
,
719 "Calling pcap_create() using %s.", interface_opts
->name
);
720 pcap_h
= pcap_create(interface_opts
->name
, *open_err_str
);
721 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
,
722 "pcap_create() returned %p.", (void *)pcap_h
);
723 if (pcap_h
!= NULL
) {
724 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
,
725 "Calling pcap_set_snaplen() with snaplen %d.", interface_opts
->snaplen
);
726 pcap_set_snaplen(pcap_h
, interface_opts
->snaplen
);
727 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
,
728 "Calling pcap_set_promisc() with promisc_mode %d.", interface_opts
->promisc_mode
);
729 pcap_set_promisc(pcap_h
, interface_opts
->promisc_mode
);
730 pcap_set_timeout(pcap_h
, CAP_READ_TIMEOUT
);
732 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
,
733 "buffersize %d.", interface_opts
->buffer_size
);
734 if (interface_opts
->buffer_size
!= 0) {
735 pcap_set_buffer_size(pcap_h
, interface_opts
->buffer_size
* 1024 * 1024);
737 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
,
738 "monitor_mode %d.", interface_opts
->monitor_mode
);
739 if (interface_opts
->monitor_mode
)
740 pcap_set_rfmon(pcap_h
, 1);
741 err
= pcap_activate(pcap_h
);
742 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
,
743 "pcap_activate() returned %d.", err
);
745 /* Failed to activate, set to NULL */
746 if (err
== PCAP_ERROR
)
747 g_strlcpy(*open_err_str
, pcap_geterr(pcap_h
), sizeof *open_err_str
);
749 g_strlcpy(*open_err_str
, pcap_statustostr(err
), sizeof *open_err_str
);
755 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
,
756 "pcap_open_live() calling using name %s, snaplen %d, promisc_mode %d.",
757 interface_opts
->name
, interface_opts
->snaplen
, interface_opts
->promisc_mode
);
758 pcap_h
= pcap_open_live(interface_opts
->name
, interface_opts
->snaplen
,
759 interface_opts
->promisc_mode
, CAP_READ_TIMEOUT
,
761 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
,
762 "pcap_open_live() returned %p.", (void *)pcap_h
);
765 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "open_capture_device %s : %s", pcap_h
? "SUCCESS" : "FAILURE", interface_opts
->name
);
770 get_capture_device_open_failure_messages(const char *open_err_str
,
776 char *errmsg
, size_t errmsg_len
,
777 char *secondary_errmsg
,
778 size_t secondary_errmsg_len
)
781 const char *libpcap_warn
;
782 static const char ppamsg
[] = "can't find PPA for ";
785 g_snprintf(errmsg
, (gulong
) errmsg_len
,
786 "The capture session could not be initiated (%s).", open_err_str
);
789 g_snprintf(secondary_errmsg
, (gulong
) secondary_errmsg_len
,
791 "In order to capture packets, WinPcap must be installed; see\n"
793 " http://www.winpcap.org/\n"
797 " http://www.mirrors.wiretapped.net/security/packet-capture/winpcap/\n"
801 " http://winpcap.cs.pu.edu.tw/\n"
803 "for a downloadable version of WinPcap and for instructions on how to install\n"
806 g_snprintf(secondary_errmsg
, (gulong
) secondary_errmsg_len
,
808 "Please check that \"%s\" is the proper interface.\n"
811 "Help can be found at:\n"
813 " http://wiki.wireshark.org/WinPcap\n"
814 " http://wiki.wireshark.org/CaptureSetup\n",
818 /* If we got a "can't find PPA for X" message, warn the user (who
819 is running dumpcap on HP-UX) that they don't have a version of
820 libpcap that properly handles HP-UX (libpcap 0.6.x and later
821 versions, which properly handle HP-UX, say "can't find /dev/dlpi
822 PPA for X" rather than "can't find PPA for X"). */
823 if (strncmp(open_err_str
, ppamsg
, sizeof ppamsg
- 1) == 0)
826 "You are running (T)Wireshark with a version of the libpcap library\n"
827 "that doesn't handle HP-UX network devices well; this means that\n"
828 "(T)Wireshark may not be able to capture packets.\n"
830 "To fix this, you should install libpcap 0.6.2, or a later version\n"
831 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
832 "packaged binary form from the Software Porting And Archive Centre\n"
833 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
834 "at the URL lists a number of mirror sites.";
838 g_snprintf(secondary_errmsg
, (gulong
) secondary_errmsg_len
,
839 "Please check to make sure you have sufficient permissions, and that you have "
840 "the proper interface or pipe specified.%s", libpcap_warn
);
844 /* Set the data link type on a pcap. */
846 set_pcap_linktype(pcap_t
*pcap_h
, int linktype
,
847 #ifdef HAVE_PCAP_SET_DATALINK
852 char *errmsg
, size_t errmsg_len
,
853 char *secondary_errmsg
, size_t secondary_errmsg_len
)
855 char *set_linktype_err_str
;
858 return TRUE
; /* just use the default */
859 #ifdef HAVE_PCAP_SET_DATALINK
860 if (pcap_set_datalink(pcap_h
, linktype
) == 0)
861 return TRUE
; /* no error */
862 set_linktype_err_str
= pcap_geterr(pcap_h
);
864 /* Let them set it to the type it is; reject any other request. */
865 if (get_pcap_linktype(pcap_h
, name
) == linktype
)
866 return TRUE
; /* no error */
867 set_linktype_err_str
=
868 "That DLT isn't one of the DLTs supported by this device";
870 g_snprintf(errmsg
, (gulong
) errmsg_len
, "Unable to set data link type (%s).",
871 set_linktype_err_str
);
873 * If the error isn't "XXX is not one of the DLTs supported by this device",
874 * tell the user to tell the Wireshark developers about it.
876 if (strstr(set_linktype_err_str
, "is not one of the DLTs supported by this device") == NULL
)
877 g_snprintf(secondary_errmsg
, (gulong
) secondary_errmsg_len
, please_report
);
879 secondary_errmsg
[0] = '\0';
884 compile_capture_filter(const char *iface
, pcap_t
*pcap_h
,
885 struct bpf_program
*fcode
, const char *cfilter
)
887 bpf_u_int32 netnum
, netmask
;
888 gchar lookup_net_err_str
[PCAP_ERRBUF_SIZE
];
890 if (pcap_lookupnet(iface
, &netnum
, &netmask
, lookup_net_err_str
) < 0) {
892 * Well, we can't get the netmask for this interface; it's used
893 * only for filters that check for broadcast IP addresses, so
894 * we just punt and use 0. It might be nice to warn the user,
895 * but that's a pain in a GUI application, as it'd involve popping
896 * up a message box, and it's not clear how often this would make
897 * a difference (only filters that check for IP broadcast addresses
901 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
906 * Sigh. Older versions of libpcap don't properly declare the
907 * third argument to pcap_compile() as a const pointer. Cast
910 if (pcap_compile(pcap_h
, fcode
, (char *)cfilter
, 1, netmask
) < 0)
915 #ifdef HAVE_BPF_IMAGE
917 show_filter_code(capture_options
*capture_opts
)
919 interface_options interface_opts
;
921 gchar open_err_str
[PCAP_ERRBUF_SIZE
];
922 char errmsg
[MSG_MAX_LENGTH
+1];
923 char secondary_errmsg
[MSG_MAX_LENGTH
+1];
924 struct bpf_program fcode
;
925 struct bpf_insn
*insn
;
929 for (j
= 0; j
< capture_opts
->ifaces
->len
; j
++) {
930 interface_opts
= g_array_index(capture_opts
->ifaces
, interface_options
, j
);
931 pcap_h
= open_capture_device(&interface_opts
, &open_err_str
);
932 if (pcap_h
== NULL
) {
933 /* Open failed; get messages */
934 get_capture_device_open_failure_messages(open_err_str
,
936 errmsg
, sizeof errmsg
,
938 sizeof secondary_errmsg
);
939 /* And report them */
940 report_capture_error(errmsg
, secondary_errmsg
);
944 /* Set the link-layer type. */
945 if (!set_pcap_linktype(pcap_h
, interface_opts
.linktype
, interface_opts
.name
,
946 errmsg
, sizeof errmsg
,
947 secondary_errmsg
, sizeof secondary_errmsg
)) {
949 report_capture_error(errmsg
, secondary_errmsg
);
953 /* OK, try to compile the capture filter. */
954 if (!compile_capture_filter(interface_opts
.name
, pcap_h
, &fcode
,
955 interface_opts
.cfilter
)) {
957 report_cfilter_error(capture_opts
, j
, errmsg
);
962 /* Now print the filter code. */
963 insn
= fcode
.bf_insns
;
965 for (i
= 0; i
< fcode
.bf_len
; insn
++, i
++)
966 printf("%s\n", bpf_image(insn
, i
));
968 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
969 /* to remove any suid privileges. */
970 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
971 /* (euid/egid have already previously been set to ruid/rgid. */
972 /* (See comment in main() for details) */
974 relinquish_special_privs_perm();
976 relinquish_all_capabilities();
979 /* Let our parent know we succeeded. */
980 pipe_write_block(2, SP_SUCCESS
, NULL
);
987 * capture_interface_list() is expected to do the right thing to get
988 * a list of interfaces.
990 * In most of the programs in the Wireshark suite, "the right thing"
991 * is to run dumpcap and ask it for the list, because dumpcap may
992 * be the only program in the suite with enough privileges to get
995 * In dumpcap itself, however, we obviously can't run dumpcap to
996 * ask for the list. Therefore, our capture_interface_list() should
997 * just call get_interface_list().
1000 capture_interface_list(int *err
, char **err_str
, void(*update_cb
)(void) _U_
)
1002 return get_interface_list(err
, err_str
);
1006 * Get the data-link type for a libpcap device.
1007 * This works around AIX 5.x's non-standard and incompatible-with-the-
1008 * rest-of-the-universe libpcap.
1011 get_pcap_linktype(pcap_t
*pch
, const char *devicename
1019 const char *ifacename
;
1022 linktype
= pcap_datalink(pch
);
1026 * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
1027 * rather than DLT_ values for link-layer types; the ifType values
1028 * for LAN devices are:
1035 * and the ifType value for a loopback device is 24.
1037 * The AIX names for LAN devices begin with:
1044 * and the AIX names for loopback devices begin with "lo".
1046 * (The difference between "Ethernet" and "802.3" is presumably
1047 * whether packets have an Ethernet header, with a packet type,
1048 * or an 802.3 header, with a packet length, followed by an 802.2
1049 * header and possibly a SNAP header.)
1051 * If the device name matches "linktype" interpreted as an ifType
1052 * value, rather than as a DLT_ value, we will assume this is AIX's
1053 * non-standard, incompatible libpcap, rather than a standard libpcap,
1054 * and will map the link-layer type to the standard DLT_ value for
1055 * that link-layer type, as that's what the rest of Wireshark expects.
1057 * (This means the capture files won't be readable by a tcpdump
1058 * linked with AIX's non-standard libpcap, but so it goes. They
1059 * *will* be readable by standard versions of tcpdump, Wireshark,
1062 * XXX - if we conclude we're using AIX libpcap, should we also
1063 * set a flag to cause us to assume the time stamps are in
1064 * seconds-and-nanoseconds form, and to convert them to
1065 * seconds-and-microseconds form before processing them and
1070 * Find the last component of the device name, which is the
1073 ifacename
= strchr(devicename
, '/');
1074 if (ifacename
== NULL
)
1075 ifacename
= devicename
;
1077 /* See if it matches any of the LAN device names. */
1078 if (strncmp(ifacename
, "en", 2) == 0) {
1079 if (linktype
== 6) {
1081 * That's the RFC 1573 value for Ethernet; map it to DLT_EN10MB.
1085 } else if (strncmp(ifacename
, "et", 2) == 0) {
1086 if (linktype
== 7) {
1088 * That's the RFC 1573 value for 802.3; map it to DLT_EN10MB.
1089 * (libpcap, tcpdump, Wireshark, etc. don't care if it's Ethernet
1094 } else if (strncmp(ifacename
, "tr", 2) == 0) {
1095 if (linktype
== 9) {
1097 * That's the RFC 1573 value for 802.5 (Token Ring); map it to
1098 * DLT_IEEE802, which is what's used for Token Ring.
1102 } else if (strncmp(ifacename
, "fi", 2) == 0) {
1103 if (linktype
== 15) {
1105 * That's the RFC 1573 value for FDDI; map it to DLT_FDDI.
1109 } else if (strncmp(ifacename
, "lo", 2) == 0) {
1110 if (linktype
== 24) {
1112 * That's the RFC 1573 value for "software loopback" devices; map it
1113 * to DLT_NULL, which is what's used for loopback devices on BSD.
1123 static data_link_info_t
*
1124 create_data_link_info(int dlt
)
1126 data_link_info_t
*data_link_info
;
1129 data_link_info
= (data_link_info_t
*)g_malloc(sizeof (data_link_info_t
));
1130 data_link_info
->dlt
= dlt
;
1131 text
= pcap_datalink_val_to_name(dlt
);
1133 data_link_info
->name
= g_strdup(text
);
1135 data_link_info
->name
= g_strdup_printf("DLT %d", dlt
);
1136 text
= pcap_datalink_val_to_description(dlt
);
1138 data_link_info
->description
= g_strdup(text
);
1140 data_link_info
->description
= NULL
;
1141 return data_link_info
;
1145 * Get the capabilities of a network device.
1147 static if_capabilities_t
*
1148 get_if_capabilities(const char *devicename
, gboolean monitor_mode
1149 #ifndef HAVE_PCAP_CREATE
1154 if_capabilities_t
*caps
;
1155 char errbuf
[PCAP_ERRBUF_SIZE
];
1157 #ifdef HAVE_PCAP_CREATE
1161 #ifdef HAVE_PCAP_LIST_DATALINKS
1165 data_link_info_t
*data_link_info
;
1168 * Allocate the interface capabilities structure.
1170 caps
= (if_capabilities_t
*)g_malloc(sizeof *caps
);
1173 * WinPcap 4.1.2, and possibly earlier versions, have a bug
1174 * wherein, when an open with an rpcap: URL fails, the error
1175 * message for the error is not copied to errbuf and whatever
1176 * on-the-stack junk is in errbuf is treated as the error
1179 * To work around that (and any other bugs of that sort, we
1180 * initialize errbuf to an empty string. If we get an error
1181 * and the string is empty, we report it as an unknown error.
1182 * (If we *don't* get an error, and the string is *non*-empty,
1183 * that could be a warning returned, such as "can't turn
1184 * promiscuous mode on"; we currently don't do so.)
1187 #ifdef HAVE_PCAP_OPEN
1188 pch
= pcap_open(devicename
, MIN_PACKET_SIZE
, 0, 0, NULL
, errbuf
);
1189 caps
->can_set_rfmon
= FALSE
;
1191 if (err_str
!= NULL
)
1192 *err_str
= g_strdup(errbuf
[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf
);
1196 #elif defined(HAVE_PCAP_CREATE)
1197 pch
= pcap_create(devicename
, errbuf
);
1199 if (err_str
!= NULL
)
1200 *err_str
= g_strdup(errbuf
);
1204 status
= pcap_can_set_rfmon(pch
);
1207 if (status
== PCAP_ERROR
)
1208 *err_str
= g_strdup_printf("pcap_can_set_rfmon() failed: %s",
1211 *err_str
= g_strdup(pcap_statustostr(status
));
1217 caps
->can_set_rfmon
= FALSE
;
1218 else if (status
== 1) {
1219 caps
->can_set_rfmon
= TRUE
;
1221 pcap_set_rfmon(pch
, 1);
1223 if (err_str
!= NULL
) {
1224 *err_str
= g_strdup_printf("pcap_can_set_rfmon() returned %d",
1232 status
= pcap_activate(pch
);
1234 /* Error. We ignore warnings (status > 0). */
1235 if (err_str
!= NULL
) {
1236 if (status
== PCAP_ERROR
)
1237 *err_str
= g_strdup_printf("pcap_activate() failed: %s",
1240 *err_str
= g_strdup(pcap_statustostr(status
));
1247 pch
= pcap_open_live(devicename
, MIN_PACKET_SIZE
, 0, 0, errbuf
);
1248 caps
->can_set_rfmon
= FALSE
;
1250 if (err_str
!= NULL
)
1251 *err_str
= g_strdup(errbuf
[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf
);
1256 deflt
= get_pcap_linktype(pch
, devicename
);
1257 #ifdef HAVE_PCAP_LIST_DATALINKS
1258 nlt
= pcap_list_datalinks(pch
, &linktypes
);
1259 if (nlt
== 0 || linktypes
== NULL
) {
1261 if (err_str
!= NULL
)
1262 *err_str
= NULL
; /* an empty list doesn't mean an error */
1266 caps
->data_link_types
= NULL
;
1267 for (i
= 0; i
< nlt
; i
++) {
1268 data_link_info
= create_data_link_info(linktypes
[i
]);
1271 * XXX - for 802.11, make the most detailed 802.11
1272 * version the default, rather than the one the
1273 * device has as the default?
1275 if (linktypes
[i
] == deflt
)
1276 caps
->data_link_types
= g_list_prepend(caps
->data_link_types
,
1279 caps
->data_link_types
= g_list_append(caps
->data_link_types
,
1282 #ifdef HAVE_PCAP_FREE_DATALINKS
1283 pcap_free_datalinks(linktypes
);
1286 * In Windows, there's no guarantee that if you have a library
1287 * built with one version of the MSVC++ run-time library, and
1288 * it returns a pointer to allocated data, you can free that
1289 * data from a program linked with another version of the
1290 * MSVC++ run-time library.
1292 * This is not an issue on UN*X.
1294 * See the mail threads starting at
1296 * http://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
1300 * http://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
1303 #define xx_free free /* hack so checkAPIs doesn't complain */
1306 #endif /* HAVE_PCAP_FREE_DATALINKS */
1307 #else /* HAVE_PCAP_LIST_DATALINKS */
1309 data_link_info
= create_data_link_info(deflt
);
1310 caps
->data_link_types
= g_list_append(caps
->data_link_types
,
1312 #endif /* HAVE_PCAP_LIST_DATALINKS */
1316 if (err_str
!= NULL
)
1321 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
1323 * Output a machine readable list of the interfaces
1324 * This list is retrieved by the sync_interface_list_open() function
1325 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
1328 print_machine_readable_interfaces(GList
*if_list
)
1335 char addr_str
[ADDRSTRLEN
];
1337 if (capture_child
) {
1338 /* Let our parent know we succeeded. */
1339 pipe_write_block(2, SP_SUCCESS
, NULL
);
1342 i
= 1; /* Interface id number */
1343 for (if_entry
= g_list_first(if_list
); if_entry
!= NULL
;
1344 if_entry
= g_list_next(if_entry
)) {
1345 if_info
= (if_info_t
*)if_entry
->data
;
1346 printf("%d. %s\t", i
++, if_info
->name
);
1349 * Print the contents of the if_entry struct in a parseable format.
1350 * Each if_entry element is tab-separated. Addresses are comma-
1353 /* XXX - Make sure our description doesn't contain a tab */
1354 if (if_info
->vendor_description
!= NULL
)
1355 printf("%s\t", if_info
->vendor_description
);
1359 /* XXX - Make sure our friendly name doesn't contain a tab */
1360 if (if_info
->friendly_name
!= NULL
)
1361 printf("%s\t", if_info
->friendly_name
);
1365 printf("%u\t", if_info
->type
);
1367 for (addr
= g_slist_nth(if_info
->addrs
, 0); addr
!= NULL
;
1368 addr
= g_slist_next(addr
)) {
1369 if (addr
!= g_slist_nth(if_info
->addrs
, 0))
1372 if_addr
= (if_addr_t
*)addr
->data
;
1373 switch(if_addr
->ifat_type
) {
1375 if (inet_ntop(AF_INET
, &if_addr
->addr
.ip4_addr
, addr_str
,
1377 printf("%s", addr_str
);
1379 printf("<unknown IPv4>");
1383 if (inet_ntop(AF_INET6
, &if_addr
->addr
.ip6_addr
,
1384 addr_str
, ADDRSTRLEN
)) {
1385 printf("%s", addr_str
);
1387 printf("<unknown IPv6>");
1391 printf("<type unknown %u>", if_addr
->ifat_type
);
1395 if (if_info
->loopback
)
1396 printf("\tloopback");
1398 printf("\tnetwork");
1405 * If you change the machine-readable output format of this function,
1406 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
1409 print_machine_readable_if_capabilities(if_capabilities_t
*caps
)
1412 data_link_info_t
*data_link_info
;
1413 const gchar
*desc_str
;
1415 if (capture_child
) {
1416 /* Let our parent know we succeeded. */
1417 pipe_write_block(2, SP_SUCCESS
, NULL
);
1420 if (caps
->can_set_rfmon
)
1424 for (lt_entry
= caps
->data_link_types
; lt_entry
!= NULL
;
1425 lt_entry
= g_list_next(lt_entry
)) {
1426 data_link_info
= (data_link_info_t
*)lt_entry
->data
;
1427 if (data_link_info
->description
!= NULL
)
1428 desc_str
= data_link_info
->description
;
1430 desc_str
= "(not supported)";
1431 printf("%d\t%s\t%s\n", data_link_info
->dlt
, data_link_info
->name
,
1441 /* Print the number of packets captured for each interface until we're killed. */
1443 print_statistics_loop(gboolean machine_readable
)
1445 GList
*if_list
, *if_entry
, *stat_list
= NULL
, *stat_entry
;
1451 char errbuf
[PCAP_ERRBUF_SIZE
];
1452 struct pcap_stat ps
;
1454 if_list
= get_interface_list(&err
, &err_str
);
1455 if (if_list
== NULL
) {
1457 case CANT_GET_INTERFACE_LIST
:
1458 case DONT_HAVE_PCAP
:
1459 cmdarg_err("%s", err_str
);
1463 case NO_INTERFACES_FOUND
:
1464 cmdarg_err("There are no interfaces on which a capture can be done");
1470 for (if_entry
= g_list_first(if_list
); if_entry
!= NULL
; if_entry
= g_list_next(if_entry
)) {
1471 if_info
= (if_info_t
*)if_entry
->data
;
1472 #ifdef HAVE_PCAP_OPEN
1473 pch
= pcap_open(if_info
->name
, MIN_PACKET_SIZE
, 0, 0, NULL
, errbuf
);
1475 pch
= pcap_open_live(if_info
->name
, MIN_PACKET_SIZE
, 0, 0, errbuf
);
1479 if_stat
= (if_stat_t
*)g_malloc(sizeof(if_stat_t
));
1480 if_stat
->name
= g_strdup(if_info
->name
);
1482 stat_list
= g_list_append(stat_list
, if_stat
);
1487 cmdarg_err("There are no interfaces on which a capture can be done");
1491 if (capture_child
) {
1492 /* Let our parent know we succeeded. */
1493 pipe_write_block(2, SP_SUCCESS
, NULL
);
1496 if (!machine_readable
) {
1497 printf("%-15s %10s %10s\n", "Interface", "Received",
1501 global_ld
.go
= TRUE
;
1502 while (global_ld
.go
) {
1503 for (stat_entry
= g_list_first(stat_list
); stat_entry
!= NULL
; stat_entry
= g_list_next(stat_entry
)) {
1504 if_stat
= (if_stat_t
*)stat_entry
->data
;
1505 pcap_stats(if_stat
->pch
, &ps
);
1507 if (!machine_readable
) {
1508 printf("%-15s %10u %10u\n", if_stat
->name
,
1509 ps
.ps_recv
, ps
.ps_drop
);
1511 printf("%s\t%u\t%u\n", if_stat
->name
,
1512 ps
.ps_recv
, ps
.ps_drop
);
1517 /* If we have a dummy signal pipe check it */
1518 if (!signal_pipe_check_running()) {
1519 global_ld
.go
= FALSE
;
1527 /* XXX - Not reached. Should we look for 'q' in stdin? */
1528 for (stat_entry
= g_list_first(stat_list
); stat_entry
!= NULL
; stat_entry
= g_list_next(stat_entry
)) {
1529 if_stat
= (if_stat_t
*)stat_entry
->data
;
1530 pcap_close(if_stat
->pch
);
1531 g_free(if_stat
->name
);
1534 g_list_free(stat_list
);
1535 free_interface_list(if_list
);
1543 capture_cleanup_handler(DWORD dwCtrlType
)
1545 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1546 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1547 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1548 like SIGTERM at least when the machine's shutting down.
1550 For now, if we're running as a command rather than a capture child,
1551 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1552 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1553 in that way on UN*X.
1555 If we're not running as a capture child, we might be running as
1556 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1557 user logs out. (XXX - can we explicitly check whether we're
1558 running as a service?) */
1560 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_INFO
,
1561 "Console: Control signal");
1562 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
,
1563 "Console: Control signal, CtrlType: %u", dwCtrlType
);
1565 /* Keep capture running if we're a service and a user logs off */
1566 if (capture_child
|| (dwCtrlType
!= CTRL_LOGOFF_EVENT
)) {
1567 capture_loop_stop();
1575 capture_cleanup_handler(int signum _U_
)
1577 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1578 SIGTERM. We assume that if the user wanted it to keep running
1579 after they logged out, they'd have nohupped it. */
1581 /* Note: don't call g_log() in the signal handler: if we happened to be in
1582 * g_log() in process context when the signal came in, g_log will detect
1583 * the "recursion" and abort.
1586 capture_loop_stop();
1592 report_capture_count(gboolean reportit
)
1594 /* Don't print this if we're a capture child. */
1595 if (!capture_child
&& reportit
) {
1596 fprintf(stderr
, "\rPackets captured: %u\n", global_ld
.packet_count
);
1597 /* stderr could be line buffered */
1605 report_counts_for_siginfo(void)
1607 report_capture_count(quiet
);
1608 infoprint
= FALSE
; /* we just reported it */
1612 report_counts_siginfo(int signum _U_
)
1614 int sav_errno
= errno
;
1616 /* If we've been told to delay printing, just set a flag asking
1617 that we print counts (if we're supposed to), otherwise print
1618 the count of packets captured (if we're supposed to). */
1622 report_counts_for_siginfo();
1625 #endif /* SIGINFO */
1628 exit_main(int status
)
1631 /* Shutdown windows sockets */
1634 /* can be helpful for debugging */
1635 #ifdef DEBUG_DUMPCAP
1636 printf("Press any key\n");
1647 * If we were linked with libcap (not related to libpcap), make sure we have
1648 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1649 * (See comment in main() for details)
1652 relinquish_privs_except_capture(void)
1654 /* If 'started_with_special_privs' (ie: suid) then enable for
1655 * ourself the NET_ADMIN and NET_RAW capabilities and then
1656 * drop our suid privileges.
1658 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1659 * stuff we don't need (and shouldn't have).
1660 * CAP_NET_RAW: Packet capture (raw sockets).
1663 if (started_with_special_privs()) {
1664 cap_value_t cap_list
[2] = { CAP_NET_ADMIN
, CAP_NET_RAW
};
1665 int cl_len
= sizeof(cap_list
) / sizeof(cap_value_t
);
1667 cap_t caps
= cap_init(); /* all capabilities initialized to off */
1669 print_caps("Pre drop, pre set");
1671 if (prctl(PR_SET_KEEPCAPS
, 1, 0, 0, 0) == -1) {
1672 cmdarg_err("prctl() fail return: %s", g_strerror(errno
));
1675 cap_set_flag(caps
, CAP_PERMITTED
, cl_len
, cap_list
, CAP_SET
);
1676 cap_set_flag(caps
, CAP_INHERITABLE
, cl_len
, cap_list
, CAP_SET
);
1678 if (cap_set_proc(caps
)) {
1679 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno
));
1681 print_caps("Pre drop, post set");
1683 relinquish_special_privs_perm();
1685 print_caps("Post drop, pre set");
1686 cap_set_flag(caps
, CAP_EFFECTIVE
, cl_len
, cap_list
, CAP_SET
);
1687 if (cap_set_proc(caps
)) {
1688 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno
));
1690 print_caps("Post drop, post set");
1696 #endif /* HAVE_LIBCAP */
1698 /* Take care of byte order in the libpcap headers read from pipes.
1699 * (function taken from wiretap/libpcap.c) */
1701 cap_pipe_adjust_header(gboolean byte_swapped
, struct pcap_hdr
*hdr
, struct pcaprec_hdr
*rechdr
)
1704 /* Byte-swap the record header fields. */
1705 rechdr
->ts_sec
= BSWAP32(rechdr
->ts_sec
);
1706 rechdr
->ts_usec
= BSWAP32(rechdr
->ts_usec
);
1707 rechdr
->incl_len
= BSWAP32(rechdr
->incl_len
);
1708 rechdr
->orig_len
= BSWAP32(rechdr
->orig_len
);
1711 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1712 swapped, in order to match the BPF header layout.
1714 Unfortunately, some files were, according to a comment in the "libpcap"
1715 source, written with version 2.3 in their headers but without the
1716 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1717 would make no sense - we assume that we need to swap them. */
1718 if (hdr
->version_major
== 2 &&
1719 (hdr
->version_minor
< 3 ||
1720 (hdr
->version_minor
== 3 && rechdr
->incl_len
> rechdr
->orig_len
))) {
1723 temp
= rechdr
->orig_len
;
1724 rechdr
->orig_len
= rechdr
->incl_len
;
1725 rechdr
->incl_len
= temp
;
1729 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1733 cap_pipe_read(int pipe_fd
, char *buf
, size_t sz
, gboolean from_socket _U_
)
1737 return recv(pipe_fd
, buf
, (int)sz
, 0);
1742 return ws_read(pipe_fd
, buf
, sz
);
1748 * Thread function that reads from a pipe and pushes the data
1749 * to the main application thread.
1752 * XXX Right now we use async queues for basic signaling. The main thread
1753 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1754 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1755 * Iff the read is successful cap_pipe_read pushes an item onto
1756 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1757 * the queues themselves (yet).
1759 * We might want to move some of the cap_pipe_dispatch logic here so that
1760 * we can let cap_thread_read run independently, queuing up multiple reads
1761 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1763 static void *cap_thread_read(void *arg
)
1765 pcap_options
*pcap_opts
;
1768 DWORD b
, last_err
, bytes_read
;
1774 pcap_opts
= (pcap_options
*)arg
;
1775 while (pcap_opts
->cap_pipe_err
== PIPOK
) {
1776 g_async_queue_pop(pcap_opts
->cap_pipe_pending_q
); /* Wait for our cue (ahem) from the main thread */
1777 g_mutex_lock(pcap_opts
->cap_pipe_read_mtx
);
1779 while (bytes_read
< pcap_opts
->cap_pipe_bytes_to_read
) {
1780 if ((pcap_opts
->from_cap_socket
)
1786 b
= cap_pipe_read(pcap_opts
->cap_pipe_fd
, pcap_opts
->cap_pipe_buf
+bytes_read
,
1787 pcap_opts
->cap_pipe_bytes_to_read
- bytes_read
, pcap_opts
->from_cap_socket
);
1790 pcap_opts
->cap_pipe_err
= PIPEOF
;
1794 pcap_opts
->cap_pipe_err
= PIPERR
;
1805 /* If we try to use read() on a named pipe on Windows with partial
1806 * data it appears to return EOF.
1808 res
= ReadFile(pcap_opts
->cap_pipe_h
, pcap_opts
->cap_pipe_buf
+bytes_read
,
1809 pcap_opts
->cap_pipe_bytes_to_read
- bytes_read
,
1814 last_err
= GetLastError();
1815 if (last_err
== ERROR_MORE_DATA
) {
1817 } else if (last_err
== ERROR_HANDLE_EOF
|| last_err
== ERROR_BROKEN_PIPE
|| last_err
== ERROR_PIPE_NOT_CONNECTED
) {
1818 pcap_opts
->cap_pipe_err
= PIPEOF
;
1822 pcap_opts
->cap_pipe_err
= PIPERR
;
1825 } else if (b
== 0 && pcap_opts
->cap_pipe_bytes_to_read
> 0) {
1826 pcap_opts
->cap_pipe_err
= PIPEOF
;
1833 pcap_opts
->cap_pipe_bytes_read
= bytes_read
;
1834 if (pcap_opts
->cap_pipe_bytes_read
>= pcap_opts
->cap_pipe_bytes_to_read
) {
1835 g_async_queue_push(pcap_opts
->cap_pipe_done_q
, pcap_opts
->cap_pipe_buf
); /* Any non-NULL value will do */
1837 g_mutex_unlock(pcap_opts
->cap_pipe_read_mtx
);
1843 /* Provide select() functionality for a single file descriptor
1844 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1846 * Returns the same values as select.
1849 cap_pipe_select(int pipe_fd
)
1852 struct timeval timeout
;
1855 FD_SET(pipe_fd
, &rfds
);
1857 timeout
.tv_sec
= PIPE_READ_TIMEOUT
/ 1000000;
1858 timeout
.tv_usec
= PIPE_READ_TIMEOUT
% 1000000;
1860 return select(pipe_fd
+1, &rfds
, NULL
, NULL
, &timeout
);
1863 #define DEF_TCP_PORT 19000
1866 cap_open_socket(char *pipename
, pcap_options
*pcap_opts
, char *errmsg
, int errmsgl
)
1868 char *sockname
= pipename
+ 4;
1869 struct sockaddr_in sa
;
1876 memset(&sa
, 0, sizeof(sa
));
1878 p
= strchr(sockname
, ':');
1880 len
= strlen(sockname
);
1881 port
= DEF_TCP_PORT
;
1885 port
= strtoul(p
+ 1, &p
, 10);
1886 if (*p
|| port
> 65535) {
1895 strncpy(buf
, sockname
, len
);
1897 if (inet_pton(AF_INET
, buf
, &sa
.sin_addr
) <= 0) {
1901 sa
.sin_family
= AF_INET
;
1902 sa
.sin_port
= htons((u_short
)port
);
1904 if (((fd
= (int)socket(AF_INET
, SOCK_STREAM
, 0)) < 0) ||
1905 (connect(fd
, (struct sockaddr
*)&sa
, sizeof(sa
)) < 0)) {
1907 LPTSTR errorText
= NULL
;
1910 lastError
= WSAGetLastError();
1911 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
|
1912 FORMAT_MESSAGE_ALLOCATE_BUFFER
|
1913 FORMAT_MESSAGE_IGNORE_INSERTS
,
1914 NULL
, lastError
, MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
1915 (LPTSTR
)&errorText
, 0, NULL
);
1917 g_snprintf(errmsg
, errmsgl
,
1918 "The capture session could not be initiated due to the socket error: \n"
1920 " %d: %S", lastError
, errorText
? (char *)errorText
: "Unknown");
1922 LocalFree(errorText
);
1924 " %d: %s", errno
, strerror(errno
));
1926 pcap_opts
->cap_pipe_err
= PIPERR
;
1929 cap_pipe_close(fd
, TRUE
);
1933 pcap_opts
->from_cap_socket
= TRUE
;
1937 g_snprintf(errmsg
, errmsgl
,
1938 "The capture session could not be initiated because\n"
1939 "\"%s\" is not a valid socket specification", pipename
);
1940 pcap_opts
->cap_pipe_err
= PIPERR
;
1944 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1948 cap_pipe_close(int pipe_fd
, gboolean from_socket _U_
)
1952 closesocket(pipe_fd
);
1959 /* Mimic pcap_open_live() for pipe captures
1961 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1962 * open it, and read the header.
1964 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1965 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1967 cap_pipe_open_live(char *pipename
,
1968 pcap_options
*pcap_opts
,
1969 struct pcap_hdr
*hdr
,
1970 char *errmsg
, int errmsgl
)
1973 ws_statb64 pipe_stat
;
1974 struct sockaddr_un sa
;
1984 pcap_opts
->cap_pipe_fd
= -1;
1986 pcap_opts
->cap_pipe_h
= INVALID_HANDLE_VALUE
;
1988 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "cap_pipe_open_live: %s", pipename
);
1991 * XXX - this blocks until a pcap per-file header has been written to
1992 * the pipe, so it could block indefinitely.
1994 if (strcmp(pipename
, "-") == 0) {
1996 fd
= 0; /* read from stdin */
1998 pcap_opts
->cap_pipe_h
= GetStdHandle(STD_INPUT_HANDLE
);
2000 } else if (!strncmp(pipename
, "TCP@", 4)) {
2001 if ((fd
= cap_open_socket(pipename
, pcap_opts
, errmsg
, errmsgl
)) < 0) {
2006 if (ws_stat64(pipename
, &pipe_stat
) < 0) {
2007 if (errno
== ENOENT
|| errno
== ENOTDIR
)
2008 pcap_opts
->cap_pipe_err
= PIPNEXIST
;
2010 g_snprintf(errmsg
, errmsgl
,
2011 "The capture session could not be initiated "
2012 "due to error getting information on pipe/socket: %s", g_strerror(errno
));
2013 pcap_opts
->cap_pipe_err
= PIPERR
;
2017 if (S_ISFIFO(pipe_stat
.st_mode
)) {
2018 fd
= ws_open(pipename
, O_RDONLY
| O_NONBLOCK
, 0000 /* no creation so don't matter */);
2020 g_snprintf(errmsg
, errmsgl
,
2021 "The capture session could not be initiated "
2022 "due to error on pipe open: %s", g_strerror(errno
));
2023 pcap_opts
->cap_pipe_err
= PIPERR
;
2026 } else if (S_ISSOCK(pipe_stat
.st_mode
)) {
2027 fd
= socket(AF_UNIX
, SOCK_STREAM
, 0);
2029 g_snprintf(errmsg
, errmsgl
,
2030 "The capture session could not be initiated "
2031 "due to error on socket create: %s", g_strerror(errno
));
2032 pcap_opts
->cap_pipe_err
= PIPERR
;
2035 sa
.sun_family
= AF_UNIX
;
2037 * The Single UNIX Specification says:
2039 * The size of sun_path has intentionally been left undefined.
2040 * This is because different implementations use different sizes.
2041 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
2042 * of 104. Since most implementations originate from BSD versions,
2043 * the size is typically in the range 92 to 108.
2045 * Applications should not assume a particular length for sun_path
2046 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
2050 * The <sys/un.h> header shall define the sockaddr_un structure,
2051 * which shall include at least the following members:
2053 * sa_family_t sun_family Address family.
2054 * char sun_path[] Socket pathname.
2056 * so we assume that it's an array, with a specified size,
2057 * and that the size reflects the maximum path length.
2059 if (g_strlcpy(sa
.sun_path
, pipename
, sizeof sa
.sun_path
) > sizeof sa
.sun_path
) {
2060 /* Path name too long */
2061 g_snprintf(errmsg
, errmsgl
,
2062 "The capture session coud not be initiated "
2063 "due to error on socket connect: Path name too long");
2064 pcap_opts
->cap_pipe_err
= PIPERR
;
2068 b
= connect(fd
, (struct sockaddr
*)&sa
, sizeof sa
);
2070 g_snprintf(errmsg
, errmsgl
,
2071 "The capture session coud not be initiated "
2072 "due to error on socket connect: %s", g_strerror(errno
));
2073 pcap_opts
->cap_pipe_err
= PIPERR
;
2078 if (S_ISCHR(pipe_stat
.st_mode
)) {
2080 * Assume the user specified an interface on a system where
2081 * interfaces are in /dev. Pretend we haven't seen it.
2083 pcap_opts
->cap_pipe_err
= PIPNEXIST
;
2085 g_snprintf(errmsg
, errmsgl
,
2086 "The capture session could not be initiated because\n"
2087 "\"%s\" is neither an interface nor a socket nor a pipe", pipename
);
2088 pcap_opts
->cap_pipe_err
= PIPERR
;
2093 #define PIPE_STR "\\pipe\\"
2094 /* Under Windows, named pipes _must_ have the form
2095 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
2097 pncopy
= g_strdup(pipename
);
2098 if ( (pos
=strstr(pncopy
, "\\\\")) == pncopy
) {
2099 pos
= strchr(pncopy
+ 3, '\\');
2100 if (pos
&& g_ascii_strncasecmp(pos
, PIPE_STR
, strlen(PIPE_STR
)) != 0)
2107 g_snprintf(errmsg
, errmsgl
,
2108 "The capture session could not be initiated because\n"
2109 "\"%s\" is neither an interface nor a pipe", pipename
);
2110 pcap_opts
->cap_pipe_err
= PIPNEXIST
;
2114 /* Wait for the pipe to appear */
2116 pcap_opts
->cap_pipe_h
= CreateFile(utf_8to16(pipename
), GENERIC_READ
, 0, NULL
,
2117 OPEN_EXISTING
, 0, NULL
);
2119 if (pcap_opts
->cap_pipe_h
!= INVALID_HANDLE_VALUE
)
2122 if (GetLastError() != ERROR_PIPE_BUSY
) {
2123 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_IGNORE_INSERTS
,
2124 NULL
, GetLastError(), 0, (LPTSTR
) &err_str
, 0, NULL
);
2125 g_snprintf(errmsg
, errmsgl
,
2126 "The capture session on \"%s\" could not be started "
2127 "due to error on pipe open: %s (error %d)",
2128 pipename
, utf_16to8(err_str
), GetLastError());
2130 pcap_opts
->cap_pipe_err
= PIPERR
;
2134 if (!WaitNamedPipe(utf_8to16(pipename
), 30 * 1000)) {
2135 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_IGNORE_INSERTS
,
2136 NULL
, GetLastError(), 0, (LPTSTR
) &err_str
, 0, NULL
);
2137 g_snprintf(errmsg
, errmsgl
,
2138 "The capture session on \"%s\" timed out during "
2139 "pipe open: %s (error %d)",
2140 pipename
, utf_16to8(err_str
), GetLastError());
2142 pcap_opts
->cap_pipe_err
= PIPERR
;
2149 pcap_opts
->from_cap_pipe
= TRUE
;
2152 if (pcap_opts
->from_cap_socket
)
2155 /* read the pcap header */
2157 while (bytes_read
< sizeof magic
) {
2158 sel_ret
= cap_pipe_select(fd
);
2160 g_snprintf(errmsg
, errmsgl
,
2161 "Unexpected error from select: %s", g_strerror(errno
));
2163 } else if (sel_ret
> 0) {
2164 b
= cap_pipe_read(fd
, ((char *)&magic
)+bytes_read
,
2165 sizeof magic
-bytes_read
,
2166 pcap_opts
->from_cap_socket
);
2169 g_snprintf(errmsg
, errmsgl
, "End of file on pipe magic during open");
2171 g_snprintf(errmsg
, errmsgl
, "Error on pipe magic during open: %s",
2181 #if GLIB_CHECK_VERSION(2,31,0)
2182 g_thread_new("cap_pipe_open_live", &cap_thread_read
, pcap_opts
);
2184 g_thread_create(&cap_thread_read
, pcap_opts
, FALSE
, NULL
);
2187 pcap_opts
->cap_pipe_buf
= (char *) &magic
;
2188 pcap_opts
->cap_pipe_bytes_read
= 0;
2189 pcap_opts
->cap_pipe_bytes_to_read
= sizeof(magic
);
2190 /* We don't have to worry about cap_pipe_read_mtx here */
2191 g_async_queue_push(pcap_opts
->cap_pipe_pending_q
, pcap_opts
->cap_pipe_buf
);
2192 g_async_queue_pop(pcap_opts
->cap_pipe_done_q
);
2193 if (pcap_opts
->cap_pipe_bytes_read
<= 0) {
2194 if (pcap_opts
->cap_pipe_bytes_read
== 0)
2195 g_snprintf(errmsg
, errmsgl
, "End of file on pipe magic during open");
2197 g_snprintf(errmsg
, errmsgl
, "Error on pipe magic during open: %s",
2206 case PCAP_NSEC_MAGIC
:
2207 /* Host that wrote it has our byte order, and was running
2208 a program using either standard or ss990417 libpcap. */
2209 pcap_opts
->cap_pipe_byte_swapped
= FALSE
;
2210 pcap_opts
->cap_pipe_modified
= FALSE
;
2211 pcap_opts
->ts_nsec
= magic
== PCAP_NSEC_MAGIC
;
2213 case PCAP_MODIFIED_MAGIC
:
2214 /* Host that wrote it has our byte order, but was running
2215 a program using either ss990915 or ss991029 libpcap. */
2216 pcap_opts
->cap_pipe_byte_swapped
= FALSE
;
2217 pcap_opts
->cap_pipe_modified
= TRUE
;
2219 case PCAP_SWAPPED_MAGIC
:
2220 case PCAP_SWAPPED_NSEC_MAGIC
:
2221 /* Host that wrote it has a byte order opposite to ours,
2222 and was running a program using either standard or
2223 ss990417 libpcap. */
2224 pcap_opts
->cap_pipe_byte_swapped
= TRUE
;
2225 pcap_opts
->cap_pipe_modified
= FALSE
;
2226 pcap_opts
->ts_nsec
= magic
== PCAP_SWAPPED_NSEC_MAGIC
;
2228 case PCAP_SWAPPED_MODIFIED_MAGIC
:
2229 /* Host that wrote it out has a byte order opposite to
2230 ours, and was running a program using either ss990915
2231 or ss991029 libpcap. */
2232 pcap_opts
->cap_pipe_byte_swapped
= TRUE
;
2233 pcap_opts
->cap_pipe_modified
= TRUE
;
2236 /* Not a "libpcap" type we know about. */
2237 g_snprintf(errmsg
, errmsgl
, "Unrecognized libpcap format");
2242 if (pcap_opts
->from_cap_socket
)
2245 /* Read the rest of the header */
2247 while (bytes_read
< sizeof(struct pcap_hdr
)) {
2248 sel_ret
= cap_pipe_select(fd
);
2250 g_snprintf(errmsg
, errmsgl
,
2251 "Unexpected error from select: %s", g_strerror(errno
));
2253 } else if (sel_ret
> 0) {
2254 b
= cap_pipe_read(fd
, ((char *)hdr
)+bytes_read
,
2255 sizeof(struct pcap_hdr
) - bytes_read
,
2256 pcap_opts
->from_cap_socket
);
2259 g_snprintf(errmsg
, errmsgl
, "End of file on pipe header during open");
2261 g_snprintf(errmsg
, errmsgl
, "Error on pipe header during open: %s",
2271 pcap_opts
->cap_pipe_buf
= (char *) hdr
;
2272 pcap_opts
->cap_pipe_bytes_read
= 0;
2273 pcap_opts
->cap_pipe_bytes_to_read
= sizeof(struct pcap_hdr
);
2274 g_async_queue_push(pcap_opts
->cap_pipe_pending_q
, pcap_opts
->cap_pipe_buf
);
2275 g_async_queue_pop(pcap_opts
->cap_pipe_done_q
);
2276 if (pcap_opts
->cap_pipe_bytes_read
<= 0) {
2277 if (pcap_opts
->cap_pipe_bytes_read
== 0)
2278 g_snprintf(errmsg
, errmsgl
, "End of file on pipe header during open");
2280 g_snprintf(errmsg
, errmsgl
, "Error on pipe header header during open: %s",
2287 if (pcap_opts
->cap_pipe_byte_swapped
) {
2288 /* Byte-swap the header fields about which we care. */
2289 hdr
->version_major
= BSWAP16(hdr
->version_major
);
2290 hdr
->version_minor
= BSWAP16(hdr
->version_minor
);
2291 hdr
->snaplen
= BSWAP32(hdr
->snaplen
);
2292 hdr
->network
= BSWAP32(hdr
->network
);
2294 pcap_opts
->linktype
= hdr
->network
;
2296 if (hdr
->version_major
< 2) {
2297 g_snprintf(errmsg
, errmsgl
, "Unable to read old libpcap format");
2301 pcap_opts
->cap_pipe_state
= STATE_EXPECT_REC_HDR
;
2302 pcap_opts
->cap_pipe_err
= PIPOK
;
2303 pcap_opts
->cap_pipe_fd
= fd
;
2307 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "cap_pipe_open_live: error %s", errmsg
);
2308 pcap_opts
->cap_pipe_err
= PIPERR
;
2309 cap_pipe_close(fd
, pcap_opts
->from_cap_socket
);
2310 pcap_opts
->cap_pipe_fd
= -1;
2314 /* We read one record from the pipe, take care of byte order in the record
2315 * header, write the record to the capture file, and update capture statistics. */
2317 cap_pipe_dispatch(loop_data
*ld
, pcap_options
*pcap_opts
, guchar
*data
, char *errmsg
, int errmsgl
)
2319 struct pcap_pkthdr phdr
;
2320 enum { PD_REC_HDR_READ
, PD_DATA_READ
, PD_PIPE_EOF
, PD_PIPE_ERR
,
2323 #if !GLIB_CHECK_VERSION(2,31,18)
2331 #ifdef LOG_CAPTURE_VERBOSE
2332 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "cap_pipe_dispatch");
2335 switch (pcap_opts
->cap_pipe_state
) {
2337 case STATE_EXPECT_REC_HDR
:
2339 if (g_mutex_trylock(pcap_opts
->cap_pipe_read_mtx
)) {
2342 pcap_opts
->cap_pipe_state
= STATE_READ_REC_HDR
;
2343 pcap_opts
->cap_pipe_bytes_to_read
= pcap_opts
->cap_pipe_modified
?
2344 sizeof(struct pcaprec_modified_hdr
) : sizeof(struct pcaprec_hdr
);
2345 pcap_opts
->cap_pipe_bytes_read
= 0;
2348 pcap_opts
->cap_pipe_buf
= (char *) &pcap_opts
->cap_pipe_rechdr
;
2349 g_async_queue_push(pcap_opts
->cap_pipe_pending_q
, pcap_opts
->cap_pipe_buf
);
2350 g_mutex_unlock(pcap_opts
->cap_pipe_read_mtx
);
2355 case STATE_READ_REC_HDR
:
2357 if (pcap_opts
->from_cap_socket
)
2360 b
= cap_pipe_read(pcap_opts
->cap_pipe_fd
, ((char *)&pcap_opts
->cap_pipe_rechdr
)+pcap_opts
->cap_pipe_bytes_read
,
2361 pcap_opts
->cap_pipe_bytes_to_read
- pcap_opts
->cap_pipe_bytes_read
, pcap_opts
->from_cap_socket
);
2364 result
= PD_PIPE_EOF
;
2366 result
= PD_PIPE_ERR
;
2369 pcap_opts
->cap_pipe_bytes_read
+= b
;
2373 #if GLIB_CHECK_VERSION(2,31,18)
2374 q_status
= g_async_queue_timeout_pop(pcap_opts
->cap_pipe_done_q
, PIPE_READ_TIMEOUT
);
2376 g_get_current_time(&wait_time
);
2377 g_time_val_add(&wait_time
, PIPE_READ_TIMEOUT
);
2378 q_status
= g_async_queue_timed_pop(pcap_opts
->cap_pipe_done_q
, &wait_time
);
2380 if (pcap_opts
->cap_pipe_err
== PIPEOF
) {
2381 result
= PD_PIPE_EOF
;
2383 } else if (pcap_opts
->cap_pipe_err
== PIPERR
) {
2384 result
= PD_PIPE_ERR
;
2392 if (pcap_opts
->cap_pipe_bytes_read
< pcap_opts
->cap_pipe_bytes_to_read
)
2394 result
= PD_REC_HDR_READ
;
2397 case STATE_EXPECT_DATA
:
2399 if (g_mutex_trylock(pcap_opts
->cap_pipe_read_mtx
)) {
2402 pcap_opts
->cap_pipe_state
= STATE_READ_DATA
;
2403 pcap_opts
->cap_pipe_bytes_to_read
= pcap_opts
->cap_pipe_rechdr
.hdr
.incl_len
;
2404 pcap_opts
->cap_pipe_bytes_read
= 0;
2407 pcap_opts
->cap_pipe_buf
= (char *) data
;
2408 g_async_queue_push(pcap_opts
->cap_pipe_pending_q
, pcap_opts
->cap_pipe_buf
);
2409 g_mutex_unlock(pcap_opts
->cap_pipe_read_mtx
);
2414 case STATE_READ_DATA
:
2416 if (pcap_opts
->from_cap_socket
)
2419 b
= cap_pipe_read(pcap_opts
->cap_pipe_fd
,
2420 data
+pcap_opts
->cap_pipe_bytes_read
,
2421 pcap_opts
->cap_pipe_bytes_to_read
- pcap_opts
->cap_pipe_bytes_read
,
2422 pcap_opts
->from_cap_socket
);
2425 result
= PD_PIPE_EOF
;
2427 result
= PD_PIPE_ERR
;
2430 pcap_opts
->cap_pipe_bytes_read
+= b
;
2435 #if GLIB_CHECK_VERSION(2,31,18)
2436 q_status
= g_async_queue_timeout_pop(pcap_opts
->cap_pipe_done_q
, PIPE_READ_TIMEOUT
);
2438 g_get_current_time(&wait_time
);
2439 g_time_val_add(&wait_time
, PIPE_READ_TIMEOUT
);
2440 q_status
= g_async_queue_timed_pop(pcap_opts
->cap_pipe_done_q
, &wait_time
);
2441 #endif /* GLIB_CHECK_VERSION(2,31,18) */
2442 if (pcap_opts
->cap_pipe_err
== PIPEOF
) {
2443 result
= PD_PIPE_EOF
;
2445 } else if (pcap_opts
->cap_pipe_err
== PIPERR
) {
2446 result
= PD_PIPE_ERR
;
2454 if (pcap_opts
->cap_pipe_bytes_read
< pcap_opts
->cap_pipe_bytes_to_read
)
2456 result
= PD_DATA_READ
;
2460 g_snprintf(errmsg
, errmsgl
, "cap_pipe_dispatch: invalid state");
2463 } /* switch (pcap_opts->cap_pipe_state) */
2466 * We've now read as much data as we were expecting, so process it.
2470 case PD_REC_HDR_READ
:
2471 /* We've read the header. Take care of byte order. */
2472 cap_pipe_adjust_header(pcap_opts
->cap_pipe_byte_swapped
, &pcap_opts
->cap_pipe_hdr
,
2473 &pcap_opts
->cap_pipe_rechdr
.hdr
);
2474 if (pcap_opts
->cap_pipe_rechdr
.hdr
.incl_len
> WTAP_MAX_PACKET_SIZE
) {
2475 g_snprintf(errmsg
, errmsgl
, "Frame %u too long (%d bytes)",
2476 ld
->packet_count
+1, pcap_opts
->cap_pipe_rechdr
.hdr
.incl_len
);
2480 if (pcap_opts
->cap_pipe_rechdr
.hdr
.incl_len
) {
2481 pcap_opts
->cap_pipe_state
= STATE_EXPECT_DATA
;
2484 /* no data to read? fall through */
2487 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2488 phdr
.ts
.tv_sec
= pcap_opts
->cap_pipe_rechdr
.hdr
.ts_sec
;
2489 phdr
.ts
.tv_usec
= pcap_opts
->cap_pipe_rechdr
.hdr
.ts_usec
;
2490 phdr
.caplen
= pcap_opts
->cap_pipe_rechdr
.hdr
.incl_len
;
2491 phdr
.len
= pcap_opts
->cap_pipe_rechdr
.hdr
.orig_len
;
2494 capture_loop_queue_packet_cb((u_char
*)pcap_opts
, &phdr
, data
);
2496 capture_loop_write_packet_cb((u_char
*)pcap_opts
, &phdr
, data
);
2498 pcap_opts
->cap_pipe_state
= STATE_EXPECT_REC_HDR
;
2502 pcap_opts
->cap_pipe_err
= PIPEOF
;
2507 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_IGNORE_INSERTS
,
2508 NULL
, GetLastError(), 0, (LPTSTR
) &err_str
, 0, NULL
);
2509 g_snprintf(errmsg
, errmsgl
,
2510 "Error reading from pipe: %s (error %d)",
2511 utf_16to8(err_str
), GetLastError());
2514 g_snprintf(errmsg
, errmsgl
, "Error reading from pipe: %s",
2522 pcap_opts
->cap_pipe_err
= PIPERR
;
2523 /* Return here rather than inside the switch to prevent GCC warning */
2528 /** Open the capture input file (pcap or capture pipe).
2529 * Returns TRUE if it succeeds, FALSE otherwise. */
2531 capture_loop_open_input(capture_options
*capture_opts
, loop_data
*ld
,
2532 char *errmsg
, size_t errmsg_len
,
2533 char *secondary_errmsg
, size_t secondary_errmsg_len
)
2535 gchar open_err_str
[PCAP_ERRBUF_SIZE
];
2536 gchar
*sync_msg_str
;
2537 interface_options interface_opts
;
2538 pcap_options
*pcap_opts
;
2542 gchar
*sync_secondary_msg_str
;
2543 WORD wVersionRequested
;
2547 /* XXX - opening Winsock on tshark? */
2549 /* Initialize Windows Socket if we are in a WIN32 OS
2550 This needs to be done before querying the interface for network/netmask */
2552 /* XXX - do we really require 1.1 or earlier?
2553 Are there any versions that support only 2.0 or higher? */
2554 wVersionRequested
= MAKEWORD(1, 1);
2555 err
= WSAStartup(wVersionRequested
, &wsaData
);
2559 case WSASYSNOTREADY
:
2560 g_snprintf(errmsg
, (gulong
) errmsg_len
,
2561 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2564 case WSAVERNOTSUPPORTED
:
2565 g_snprintf(errmsg
, (gulong
) errmsg_len
,
2566 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2567 LOBYTE(wVersionRequested
), HIBYTE(wVersionRequested
));
2570 case WSAEINPROGRESS
:
2571 g_snprintf(errmsg
, (gulong
) errmsg_len
,
2572 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2576 g_snprintf(errmsg
, (gulong
) errmsg_len
,
2577 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2581 g_snprintf(errmsg
, (gulong
) errmsg_len
,
2582 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2586 g_snprintf(errmsg
, (gulong
) errmsg_len
,
2587 "Couldn't initialize Windows Sockets: error %d", err
);
2590 g_snprintf(secondary_errmsg
, (gulong
) secondary_errmsg_len
, please_report
);
2594 if ((use_threads
== FALSE
) &&
2595 (capture_opts
->ifaces
->len
> 1)) {
2596 g_snprintf(errmsg
, (gulong
) errmsg_len
,
2597 "Using threads is required for capturing on multiple interfaces!");
2601 for (i
= 0; i
< capture_opts
->ifaces
->len
; i
++) {
2602 interface_opts
= g_array_index(capture_opts
->ifaces
, interface_options
, i
);
2603 pcap_opts
= (pcap_options
*)g_malloc(sizeof (pcap_options
));
2604 if (pcap_opts
== NULL
) {
2605 g_snprintf(errmsg
, (gulong
) errmsg_len
,
2606 "Could not allocate memory.");
2609 pcap_opts
->received
= 0;
2610 pcap_opts
->dropped
= 0;
2611 pcap_opts
->flushed
= 0;
2612 pcap_opts
->pcap_h
= NULL
;
2613 #ifdef MUST_DO_SELECT
2614 pcap_opts
->pcap_fd
= -1;
2616 pcap_opts
->pcap_err
= FALSE
;
2617 pcap_opts
->interface_id
= i
;
2618 pcap_opts
->tid
= NULL
;
2619 pcap_opts
->snaplen
= 0;
2620 pcap_opts
->linktype
= -1;
2621 pcap_opts
->ts_nsec
= FALSE
;
2622 pcap_opts
->from_cap_pipe
= FALSE
;
2623 pcap_opts
->from_cap_socket
= FALSE
;
2624 memset(&pcap_opts
->cap_pipe_hdr
, 0, sizeof(struct pcap_hdr
));
2625 memset(&pcap_opts
->cap_pipe_rechdr
, 0, sizeof(struct pcaprec_modified_hdr
));
2627 pcap_opts
->cap_pipe_h
= INVALID_HANDLE_VALUE
;
2629 pcap_opts
->cap_pipe_fd
= -1;
2630 pcap_opts
->cap_pipe_modified
= FALSE
;
2631 pcap_opts
->cap_pipe_byte_swapped
= FALSE
;
2633 pcap_opts
->cap_pipe_buf
= NULL
;
2635 pcap_opts
->cap_pipe_bytes_to_read
= 0;
2636 pcap_opts
->cap_pipe_bytes_read
= 0;
2637 pcap_opts
->cap_pipe_state
= STATE_EXPECT_REC_HDR
;
2638 pcap_opts
->cap_pipe_err
= PIPOK
;
2640 #if GLIB_CHECK_VERSION(2,31,0)
2641 pcap_opts
->cap_pipe_read_mtx
= g_malloc(sizeof(GMutex
));
2642 g_mutex_init(pcap_opts
->cap_pipe_read_mtx
);
2644 pcap_opts
->cap_pipe_read_mtx
= g_mutex_new();
2646 pcap_opts
->cap_pipe_pending_q
= g_async_queue_new();
2647 pcap_opts
->cap_pipe_done_q
= g_async_queue_new();
2649 g_array_append_val(ld
->pcaps
, pcap_opts
);
2651 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "capture_loop_open_input : %s", interface_opts
.name
);
2652 pcap_opts
->pcap_h
= open_capture_device(&interface_opts
, &open_err_str
);
2654 if (pcap_opts
->pcap_h
!= NULL
) {
2655 /* we've opened "iface" as a network device */
2657 /* try to set the capture buffer size */
2658 if (interface_opts
.buffer_size
> 1 &&
2659 pcap_setbuff(pcap_opts
->pcap_h
, interface_opts
.buffer_size
* 1024 * 1024) != 0) {
2660 sync_secondary_msg_str
= g_strdup_printf(
2661 "The capture buffer size of %dMB seems to be too high for your machine,\n"
2662 "the default of 1MB will be used.\n"
2664 "Nonetheless, the capture is started.\n",
2665 interface_opts
.buffer_size
);
2666 report_capture_error("Couldn't set the capture buffer size!",
2667 sync_secondary_msg_str
);
2668 g_free(sync_secondary_msg_str
);
2672 #if defined(HAVE_PCAP_SETSAMPLING)
2673 if (interface_opts
.sampling_method
!= CAPTURE_SAMP_NONE
) {
2674 struct pcap_samp
*samp
;
2676 if ((samp
= pcap_setsampling(pcap_opts
->pcap_h
)) != NULL
) {
2677 switch (interface_opts
.sampling_method
) {
2678 case CAPTURE_SAMP_BY_COUNT
:
2679 samp
->method
= PCAP_SAMP_1_EVERY_N
;
2682 case CAPTURE_SAMP_BY_TIMER
:
2683 samp
->method
= PCAP_SAMP_FIRST_AFTER_N_MS
;
2687 sync_msg_str
= g_strdup_printf(
2688 "Unknown sampling method %d specified,\n"
2689 "continue without packet sampling",
2690 interface_opts
.sampling_method
);
2691 report_capture_error("Couldn't set the capture "
2692 "sampling", sync_msg_str
);
2693 g_free(sync_msg_str
);
2695 samp
->value
= interface_opts
.sampling_param
;
2697 report_capture_error("Couldn't set the capture sampling",
2698 "Cannot get packet sampling data structure");
2703 /* setting the data link type only works on real interfaces */
2704 if (!set_pcap_linktype(pcap_opts
->pcap_h
, interface_opts
.linktype
, interface_opts
.name
,
2706 secondary_errmsg
, secondary_errmsg_len
)) {
2709 pcap_opts
->linktype
= get_pcap_linktype(pcap_opts
->pcap_h
, interface_opts
.name
);
2711 /* We couldn't open "iface" as a network device. */
2712 /* Try to open it as a pipe */
2713 cap_pipe_open_live(interface_opts
.name
, pcap_opts
, &pcap_opts
->cap_pipe_hdr
, errmsg
, (int) errmsg_len
);
2716 if (pcap_opts
->cap_pipe_fd
== -1) {
2718 if (pcap_opts
->cap_pipe_h
== INVALID_HANDLE_VALUE
) {
2720 if (pcap_opts
->cap_pipe_err
== PIPNEXIST
) {
2721 /* Pipe doesn't exist, so output message for interface */
2722 get_capture_device_open_failure_messages(open_err_str
,
2723 interface_opts
.name
,
2727 secondary_errmsg_len
);
2730 * Else pipe (or file) does exist and cap_pipe_open_live() has
2735 /* cap_pipe_open_live() succeeded; don't want
2736 error message from pcap_open_live() */
2737 open_err_str
[0] = '\0';
2741 /* XXX - will this work for tshark? */
2742 #ifdef MUST_DO_SELECT
2743 if (!pcap_opts
->from_cap_pipe
) {
2744 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2745 pcap_opts
->pcap_fd
= pcap_get_selectable_fd(pcap_opts
->pcap_h
);
2747 pcap_opts
->pcap_fd
= pcap_fileno(pcap_opts
->pcap_h
);
2752 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2753 returned a warning; print it, but keep capturing. */
2754 if (open_err_str
[0] != '\0') {
2755 sync_msg_str
= g_strdup_printf("%s.", open_err_str
);
2756 report_capture_error(sync_msg_str
, "");
2757 g_free(sync_msg_str
);
2759 capture_opts
->ifaces
= g_array_remove_index(capture_opts
->ifaces
, i
);
2760 g_array_insert_val(capture_opts
->ifaces
, i
, interface_opts
);
2763 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2764 /* to remove any suid privileges. */
2765 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2766 /* (euid/egid have already previously been set to ruid/rgid. */
2767 /* (See comment in main() for details) */
2769 relinquish_special_privs_perm();
2771 relinquish_all_capabilities();
2776 /* close the capture input file (pcap or capture pipe) */
2777 static void capture_loop_close_input(loop_data
*ld
)
2780 pcap_options
*pcap_opts
;
2782 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "capture_loop_close_input");
2784 for (i
= 0; i
< ld
->pcaps
->len
; i
++) {
2785 pcap_opts
= g_array_index(ld
->pcaps
, pcap_options
*, i
);
2786 /* if open, close the capture pipe "input file" */
2787 if (pcap_opts
->cap_pipe_fd
>= 0) {
2788 g_assert(pcap_opts
->from_cap_pipe
);
2789 cap_pipe_close(pcap_opts
->cap_pipe_fd
, pcap_opts
->from_cap_socket
);
2790 pcap_opts
->cap_pipe_fd
= -1;
2793 if (pcap_opts
->cap_pipe_h
!= INVALID_HANDLE_VALUE
) {
2794 CloseHandle(pcap_opts
->cap_pipe_h
);
2795 pcap_opts
->cap_pipe_h
= INVALID_HANDLE_VALUE
;
2798 /* if open, close the pcap "input file" */
2799 if (pcap_opts
->pcap_h
!= NULL
) {
2800 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "capture_loop_close_input: closing %p", (void *)pcap_opts
->pcap_h
);
2801 pcap_close(pcap_opts
->pcap_h
);
2802 pcap_opts
->pcap_h
= NULL
;
2809 /* Shut down windows sockets */
2815 /* init the capture filter */
2816 static initfilter_status_t
2817 capture_loop_init_filter(pcap_t
*pcap_h
, gboolean from_cap_pipe
,
2818 const gchar
* name
, const gchar
* cfilter
)
2820 struct bpf_program fcode
;
2822 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "capture_loop_init_filter: %s", cfilter
);
2824 /* capture filters only work on real interfaces */
2825 if (cfilter
&& !from_cap_pipe
) {
2826 /* A capture filter was specified; set it up. */
2827 if (!compile_capture_filter(name
, pcap_h
, &fcode
, cfilter
)) {
2828 /* Treat this specially - our caller might try to compile this
2829 as a display filter and, if that succeeds, warn the user that
2830 the display and capture filter syntaxes are different. */
2831 return INITFILTER_BAD_FILTER
;
2833 if (pcap_setfilter(pcap_h
, &fcode
) < 0) {
2834 #ifdef HAVE_PCAP_FREECODE
2835 pcap_freecode(&fcode
);
2837 return INITFILTER_OTHER_ERROR
;
2839 #ifdef HAVE_PCAP_FREECODE
2840 pcap_freecode(&fcode
);
2844 return INITFILTER_NO_ERROR
;
2848 /* set up to write to the already-opened capture output file/files */
2850 capture_loop_init_output(capture_options
*capture_opts
, loop_data
*ld
, char *errmsg
, int errmsg_len
)
2854 pcap_options
*pcap_opts
;
2855 interface_options interface_opts
;
2856 gboolean successful
;
2858 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "capture_loop_init_output");
2860 if ((capture_opts
->use_pcapng
== FALSE
) &&
2861 (capture_opts
->ifaces
->len
> 1)) {
2862 g_snprintf(errmsg
, errmsg_len
,
2863 "Using PCAPNG is required for capturing on multiple interfaces! Use the -n option.");
2867 /* Set up to write to the capture file. */
2868 if (capture_opts
->multi_files_on
) {
2869 ld
->pdh
= ringbuf_init_libpcap_fdopen(&err
);
2871 ld
->pdh
= ws_fdopen(ld
->save_file_fd
, "wb");
2872 if (ld
->pdh
== NULL
) {
2877 if (capture_opts
->use_pcapng
) {
2879 GString
*os_info_str
;
2881 os_info_str
= g_string_new("");
2882 get_os_version_info(os_info_str
);
2884 g_snprintf(appname
, sizeof(appname
), "Dumpcap " VERSION
"%s", wireshark_svnversion
);
2885 successful
= pcapng_write_session_header_block(ld
->pdh
,
2886 (const char *)capture_opts
->capture_comment
, /* Comment*/
2888 os_info_str
->str
, /* OS*/
2890 -1, /* section_length */
2894 for (i
= 0; successful
&& (i
< capture_opts
->ifaces
->len
); i
++) {
2895 interface_opts
= g_array_index(capture_opts
->ifaces
, interface_options
, i
);
2896 pcap_opts
= g_array_index(ld
->pcaps
, pcap_options
*, i
);
2897 if (pcap_opts
->from_cap_pipe
) {
2898 pcap_opts
->snaplen
= pcap_opts
->cap_pipe_hdr
.snaplen
;
2900 pcap_opts
->snaplen
= pcap_snapshot(pcap_opts
->pcap_h
);
2902 successful
= pcapng_write_interface_description_block(global_ld
.pdh
,
2903 NULL
, /* OPT_COMMENT 1 */
2904 interface_opts
.name
, /* IDB_NAME 2 */
2905 interface_opts
.descr
, /* IDB_DESCRIPTION 3 */
2906 interface_opts
.cfilter
, /* IDB_FILTER 11 */
2907 os_info_str
->str
, /* IDB_OS 12 */
2908 pcap_opts
->linktype
,
2910 &(global_ld
.bytes_written
),
2911 0, /* IDB_IF_SPEED 8 */
2912 pcap_opts
->ts_nsec
? 9 : 6, /* IDB_TSRESOL 9 */
2916 g_string_free(os_info_str
, TRUE
);
2919 pcap_opts
= g_array_index(ld
->pcaps
, pcap_options
*, 0);
2920 if (pcap_opts
->from_cap_pipe
) {
2921 pcap_opts
->snaplen
= pcap_opts
->cap_pipe_hdr
.snaplen
;
2923 pcap_opts
->snaplen
= pcap_snapshot(pcap_opts
->pcap_h
);
2925 successful
= libpcap_write_file_header(ld
->pdh
, pcap_opts
->linktype
, pcap_opts
->snaplen
,
2926 pcap_opts
->ts_nsec
, &ld
->bytes_written
, &err
);
2934 if (ld
->pdh
== NULL
) {
2935 /* We couldn't set up to write to the capture file. */
2936 /* XXX - use cf_open_error_message from tshark instead? */
2941 g_snprintf(errmsg
, errmsg_len
,
2942 "The file to which the capture would be"
2943 " saved (\"%s\") could not be opened: Error %d.",
2944 capture_opts
->save_file
, err
);
2946 g_snprintf(errmsg
, errmsg_len
,
2947 "The file to which the capture would be"
2948 " saved (\"%s\") could not be opened: %s.",
2949 capture_opts
->save_file
, g_strerror(err
));
2961 capture_loop_close_output(capture_options
*capture_opts
, loop_data
*ld
, int *err_close
)
2965 pcap_options
*pcap_opts
;
2966 guint64 end_time
= create_timestamp();
2968 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "capture_loop_close_output");
2970 if (capture_opts
->multi_files_on
) {
2971 return ringbuf_libpcap_dump_close(&capture_opts
->save_file
, err_close
);
2973 if (capture_opts
->use_pcapng
) {
2974 for (i
= 0; i
< global_ld
.pcaps
->len
; i
++) {
2975 pcap_opts
= g_array_index(global_ld
.pcaps
, pcap_options
*, i
);
2976 if (!pcap_opts
->from_cap_pipe
) {
2977 guint64 isb_ifrecv
, isb_ifdrop
;
2978 struct pcap_stat stats
;
2980 if (pcap_stats(pcap_opts
->pcap_h
, &stats
) >= 0) {
2981 isb_ifrecv
= pcap_opts
->received
;
2982 isb_ifdrop
= stats
.ps_drop
+ pcap_opts
->dropped
+ pcap_opts
->flushed
;
2984 isb_ifrecv
= G_MAXUINT64
;
2985 isb_ifdrop
= G_MAXUINT64
;
2987 pcapng_write_interface_statistics_block(ld
->pdh
,
2990 "Counters provided by dumpcap",
2999 if (fclose(ld
->pdh
) == EOF
) {
3000 if (err_close
!= NULL
) {
3010 /* dispatch incoming packets (pcap or capture pipe)
3012 * Waits for incoming packets to be available, and calls pcap_dispatch()
3013 * to cause them to be processed.
3015 * Returns the number of packets which were processed.
3017 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3018 * packet-batching behaviour does not cause packets to get held back
3022 capture_loop_dispatch(loop_data
*ld
,
3023 char *errmsg
, int errmsg_len
, pcap_options
*pcap_opts
)
3026 gint packet_count_before
;
3027 guchar pcap_data
[WTAP_MAX_PACKET_SIZE
];
3032 packet_count_before
= ld
->packet_count
;
3033 if (pcap_opts
->from_cap_pipe
) {
3034 /* dispatch from capture pipe */
3035 #ifdef LOG_CAPTURE_VERBOSE
3036 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "capture_loop_dispatch: from capture pipe");
3039 sel_ret
= cap_pipe_select(pcap_opts
->cap_pipe_fd
);
3041 if (sel_ret
< 0 && errno
!= EINTR
) {
3042 g_snprintf(errmsg
, errmsg_len
,
3043 "Unexpected error from select: %s", g_strerror(errno
));
3044 report_capture_error(errmsg
, please_report
);
3049 * "select()" says we can read from the pipe without blocking
3052 inpkts
= cap_pipe_dispatch(ld
, pcap_opts
, pcap_data
, errmsg
, errmsg_len
);
3062 /* dispatch from pcap */
3063 #ifdef MUST_DO_SELECT
3065 * If we have "pcap_get_selectable_fd()", we use it to get the
3066 * descriptor on which to select; if that's -1, it means there
3067 * is no descriptor on which you can do a "select()" (perhaps
3068 * because you're capturing on a special device, and that device's
3069 * driver unfortunately doesn't support "select()", in which case
3070 * we don't do the select - which means it might not be possible
3071 * to stop a capture until a packet arrives. If that's unacceptable,
3072 * plead with whoever supplies the software for that device to add
3073 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3074 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3075 * later, so it can use pcap_breakloop().
3077 #ifdef LOG_CAPTURE_VERBOSE
3078 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "capture_loop_dispatch: from pcap_dispatch with select");
3080 if (pcap_opts
->pcap_fd
!= -1) {
3081 sel_ret
= cap_pipe_select(pcap_opts
->pcap_fd
);
3084 * "select()" says we can read from it without blocking; go for
3087 * We don't have pcap_breakloop(), so we only process one packet
3088 * per pcap_dispatch() call, to allow a signal to stop the
3089 * processing immediately, rather than processing all packets
3090 * in a batch before quitting.
3093 inpkts
= pcap_dispatch(pcap_opts
->pcap_h
, 1, capture_loop_queue_packet_cb
, (u_char
*)pcap_opts
);
3095 inpkts
= pcap_dispatch(pcap_opts
->pcap_h
, 1, capture_loop_write_packet_cb
, (u_char
*)pcap_opts
);
3099 /* Error, rather than pcap_breakloop(). */
3100 pcap_opts
->pcap_err
= TRUE
;
3102 ld
->go
= FALSE
; /* error or pcap_breakloop() - stop capturing */
3105 if (sel_ret
< 0 && errno
!= EINTR
) {
3106 g_snprintf(errmsg
, errmsg_len
,
3107 "Unexpected error from select: %s", g_strerror(errno
));
3108 report_capture_error(errmsg
, please_report
);
3114 #endif /* MUST_DO_SELECT */
3116 /* dispatch from pcap without select */
3118 #ifdef LOG_CAPTURE_VERBOSE
3119 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "capture_loop_dispatch: from pcap_dispatch");
3123 * On Windows, we don't support asynchronously telling a process to
3124 * stop capturing; instead, we check for an indication on a pipe
3125 * after processing packets. We therefore process only one packet
3126 * at a time, so that we can check the pipe after every packet.
3129 inpkts
= pcap_dispatch(pcap_opts
->pcap_h
, 1, capture_loop_queue_packet_cb
, (u_char
*)pcap_opts
);
3131 inpkts
= pcap_dispatch(pcap_opts
->pcap_h
, 1, capture_loop_write_packet_cb
, (u_char
*)pcap_opts
);
3135 inpkts
= pcap_dispatch(pcap_opts
->pcap_h
, -1, capture_loop_queue_packet_cb
, (u_char
*)pcap_opts
);
3137 inpkts
= pcap_dispatch(pcap_opts
->pcap_h
, -1, capture_loop_write_packet_cb
, (u_char
*)pcap_opts
);
3142 /* Error, rather than pcap_breakloop(). */
3143 pcap_opts
->pcap_err
= TRUE
;
3145 ld
->go
= FALSE
; /* error or pcap_breakloop() - stop capturing */
3147 #else /* pcap_next_ex */
3148 #ifdef LOG_CAPTURE_VERBOSE
3149 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "capture_loop_dispatch: from pcap_next_ex");
3151 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3154 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3155 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
3156 * This should be fixed in the WinPcap 4.0 alpha release.
3158 * For reference, an example remote interface:
3159 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3162 /* emulate dispatch from pcap */
3165 struct pcap_pkthdr
*pkt_header
;
3170 (in
= pcap_next_ex(pcap_opts
->pcap_h
, &pkt_header
, &pkt_data
)) == 1) {
3172 capture_loop_queue_packet_cb((u_char
*)pcap_opts
, pkt_header
, pkt_data
);
3174 capture_loop_write_packet_cb((u_char
*)pcap_opts
, pkt_header
, pkt_data
);
3179 pcap_opts
->pcap_err
= TRUE
;
3183 #endif /* pcap_next_ex */
3187 #ifdef LOG_CAPTURE_VERBOSE
3188 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "capture_loop_dispatch: %d new packet%s", inpkts
, plurality(inpkts
, "", "s"));
3191 return ld
->packet_count
- packet_count_before
;
3195 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3196 * want to grab only the characters between the '{' and '}' delimiters.
3198 * Returns a GString that must be freed with g_string_free(). */
3200 isolate_uuid(const char *iface
)
3205 ptr
= strchr(iface
, '{');
3207 return g_string_new(iface
);
3208 gstr
= g_string_new(ptr
+ 1);
3210 ptr
= strchr(gstr
->str
, '}');
3214 gstr
= g_string_truncate(gstr
, ptr
- gstr
->str
);
3219 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3220 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3222 capture_loop_open_output(capture_options
*capture_opts
, int *save_file_fd
,
3223 char *errmsg
, int errmsg_len
)
3226 gchar
*capfile_name
;
3228 gboolean is_tempfile
;
3230 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "capture_loop_open_output: %s",
3231 (capture_opts
->save_file
) ? capture_opts
->save_file
: "(not specified)");
3233 if (capture_opts
->save_file
!= NULL
) {
3234 /* We return to the caller while the capture is in progress.
3235 * Therefore we need to take a copy of save_file in
3236 * case the caller destroys it after we return.
3238 capfile_name
= g_strdup(capture_opts
->save_file
);
3240 if (capture_opts
->output_to_pipe
== TRUE
) { /* either "-" or named pipe */
3241 if (capture_opts
->multi_files_on
) {
3242 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3243 g_snprintf(errmsg
, errmsg_len
,
3244 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3245 g_free(capfile_name
);
3248 if (strcmp(capfile_name
, "-") == 0) {
3249 /* write to stdout */
3252 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3253 _setmode(1, O_BINARY
);
3256 } /* if (...output_to_pipe ... */
3259 if (capture_opts
->multi_files_on
) {
3260 /* ringbuffer is enabled */
3261 *save_file_fd
= ringbuf_init(capfile_name
,
3262 (capture_opts
->has_ring_num_files
) ? capture_opts
->ring_num_files
: 0,
3263 capture_opts
->group_read_access
);
3265 /* we need the ringbuf name */
3266 if (*save_file_fd
!= -1) {
3267 g_free(capfile_name
);
3268 capfile_name
= g_strdup(ringbuf_current_filename());
3271 /* Try to open/create the specified file for use as a capture buffer. */
3272 *save_file_fd
= ws_open(capfile_name
, O_RDWR
|O_BINARY
|O_TRUNC
|O_CREAT
,
3273 (capture_opts
->group_read_access
) ? 0640 : 0600);
3276 is_tempfile
= FALSE
;
3278 /* Choose a random name for the temporary capture buffer */
3279 if (global_capture_opts
.ifaces
->len
> 1) {
3280 prefix
= g_strdup_printf("wireshark_%d_interfaces", global_capture_opts
.ifaces
->len
);
3283 basename
= g_path_get_basename(g_array_index(global_capture_opts
.ifaces
, interface_options
, 0).console_display_name
);
3285 /* use the generic portion of the interface guid to form the basis of the filename */
3286 if (strncmp("NPF_{", basename
, 5)==0)
3288 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
3290 iface
= isolate_uuid(basename
);
3292 basename
= g_strdup(iface
->str
);
3293 g_string_free(iface
, TRUE
);
3296 /* generate the temp file name prefix...
3297 * It would be nice if we could specify a pcapng/pcap filename suffix,
3298 * create_tempfile() however currently uses mkstemp() which doesn't allow this - one day perhaps*/
3299 if (capture_opts
->use_pcapng
) {
3300 prefix
= g_strconcat("wireshark_pcapng_", basename
, NULL
);
3302 prefix
= g_strconcat("wireshark_pcap_", basename
, NULL
);
3306 *save_file_fd
= create_tempfile(&tmpname
, prefix
);
3308 capfile_name
= g_strdup(tmpname
);
3312 /* did we fail to open the output file? */
3313 if (*save_file_fd
== -1) {
3315 g_snprintf(errmsg
, errmsg_len
,
3316 "The temporary file to which the capture would be saved (\"%s\") "
3317 "could not be opened: %s.", capfile_name
, g_strerror(errno
));
3319 if (capture_opts
->multi_files_on
) {
3320 ringbuf_error_cleanup();
3323 g_snprintf(errmsg
, errmsg_len
,
3324 "The file to which the capture would be saved (\"%s\") "
3325 "could not be opened: %s.", capfile_name
,
3328 g_free(capfile_name
);
3332 if (capture_opts
->save_file
!= NULL
) {
3333 g_free(capture_opts
->save_file
);
3335 capture_opts
->save_file
= capfile_name
;
3336 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3337 "g_free(capfile_name)". */
3343 /* Do the work of handling either the file size or file duration capture
3344 conditions being reached, and switching files or stopping. */
3346 do_file_switch_or_stop(capture_options
*capture_opts
,
3347 condition
*cnd_autostop_files
,
3348 condition
*cnd_autostop_size
,
3349 condition
*cnd_file_duration
)
3352 pcap_options
*pcap_opts
;
3353 interface_options interface_opts
;
3354 gboolean successful
;
3356 if (capture_opts
->multi_files_on
) {
3357 if (cnd_autostop_files
!= NULL
&&
3358 cnd_eval(cnd_autostop_files
, ++global_ld
.autostop_files
)) {
3359 /* no files left: stop here */
3360 global_ld
.go
= FALSE
;
3364 /* Switch to the next ringbuffer file */
3365 if (ringbuf_switch_file(&global_ld
.pdh
, &capture_opts
->save_file
,
3366 &global_ld
.save_file_fd
, &global_ld
.err
)) {
3368 /* File switch succeeded: reset the conditions */
3369 global_ld
.bytes_written
= 0;
3370 if (capture_opts
->use_pcapng
) {
3372 GString
*os_info_str
;
3374 os_info_str
= g_string_new("");
3375 get_os_version_info(os_info_str
);
3377 g_snprintf(appname
, sizeof(appname
), "Dumpcap " VERSION
"%s", wireshark_svnversion
);
3378 successful
= pcapng_write_session_header_block(global_ld
.pdh
,
3381 os_info_str
->str
, /* OS */
3383 -1, /* section_length */
3384 &(global_ld
.bytes_written
),
3387 for (i
= 0; successful
&& (i
< capture_opts
->ifaces
->len
); i
++) {
3388 interface_opts
= g_array_index(capture_opts
->ifaces
, interface_options
, i
);
3389 pcap_opts
= g_array_index(global_ld
.pcaps
, pcap_options
*, i
);
3390 successful
= pcapng_write_interface_description_block(global_ld
.pdh
,
3391 NULL
, /* OPT_COMMENT 1 */
3392 interface_opts
.name
, /* IDB_NAME 2 */
3393 interface_opts
.descr
, /* IDB_DESCRIPTION 3 */
3394 interface_opts
.cfilter
, /* IDB_FILTER 11 */
3395 os_info_str
->str
, /* IDB_OS 12 */
3396 pcap_opts
->linktype
,
3398 &(global_ld
.bytes_written
),
3399 0, /* IDB_IF_SPEED 8 */
3400 pcap_opts
->ts_nsec
? 9 : 6, /* IDB_TSRESOL 9 */
3404 g_string_free(os_info_str
, TRUE
);
3407 pcap_opts
= g_array_index(global_ld
.pcaps
, pcap_options
*, 0);
3408 successful
= libpcap_write_file_header(global_ld
.pdh
, pcap_opts
->linktype
, pcap_opts
->snaplen
,
3409 pcap_opts
->ts_nsec
, &global_ld
.bytes_written
, &global_ld
.err
);
3412 fclose(global_ld
.pdh
);
3413 global_ld
.pdh
= NULL
;
3414 global_ld
.go
= FALSE
;
3417 if (cnd_autostop_size
)
3418 cnd_reset(cnd_autostop_size
);
3419 if (cnd_file_duration
)
3420 cnd_reset(cnd_file_duration
);
3421 fflush(global_ld
.pdh
);
3423 report_packet_count(global_ld
.inpkts_to_sync_pipe
);
3424 global_ld
.inpkts_to_sync_pipe
= 0;
3425 report_new_capture_file(capture_opts
->save_file
);
3427 /* File switch failed: stop here */
3428 global_ld
.go
= FALSE
;
3432 /* single file, stop now */
3433 global_ld
.go
= FALSE
;
3440 pcap_read_handler(void* arg
)
3442 pcap_options
*pcap_opts
;
3443 char errmsg
[MSG_MAX_LENGTH
+1];
3445 pcap_opts
= (pcap_options
*)arg
;
3447 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_INFO
, "Started thread for interface %d.",
3448 pcap_opts
->interface_id
);
3450 while (global_ld
.go
) {
3451 /* dispatch incoming packets */
3452 capture_loop_dispatch(&global_ld
, errmsg
, sizeof(errmsg
), pcap_opts
);
3454 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_INFO
, "Stopped thread for interface %d.",
3455 pcap_opts
->interface_id
);
3456 g_thread_exit(NULL
);
3460 /* Do the low-level work of a capture.
3461 Returns TRUE if it succeeds, FALSE otherwise. */
3463 capture_loop_start(capture_options
*capture_opts
, gboolean
*stats_known
, struct pcap_stat
*stats
)
3466 DWORD upd_time
, cur_time
; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3468 struct timeval upd_time
, cur_time
;
3472 condition
*cnd_file_duration
= NULL
;
3473 condition
*cnd_autostop_files
= NULL
;
3474 condition
*cnd_autostop_size
= NULL
;
3475 condition
*cnd_autostop_duration
= NULL
;
3478 gboolean cfilter_error
= FALSE
;
3479 char errmsg
[MSG_MAX_LENGTH
+1];
3480 char secondary_errmsg
[MSG_MAX_LENGTH
+1];
3481 pcap_options
*pcap_opts
;
3482 interface_options interface_opts
;
3483 guint i
, error_index
= 0;
3486 *secondary_errmsg
= '\0';
3488 /* init the loop data */
3489 global_ld
.go
= TRUE
;
3490 global_ld
.packet_count
= 0;
3492 global_ld
.report_packet_count
= FALSE
;
3494 if (capture_opts
->has_autostop_packets
)
3495 global_ld
.packet_max
= capture_opts
->autostop_packets
;
3497 global_ld
.packet_max
= 0; /* no limit */
3498 global_ld
.inpkts_to_sync_pipe
= 0;
3499 global_ld
.err
= 0; /* no error seen yet */
3500 global_ld
.pdh
= NULL
;
3501 global_ld
.autostop_files
= 0;
3502 global_ld
.save_file_fd
= -1;
3504 /* We haven't yet gotten the capture statistics. */
3505 *stats_known
= FALSE
;
3507 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_INFO
, "Capture loop starting ...");
3508 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, capture_opts
);
3510 /* open the "input file" from network interface or capture pipe */
3511 if (!capture_loop_open_input(capture_opts
, &global_ld
, errmsg
, sizeof(errmsg
),
3512 secondary_errmsg
, sizeof(secondary_errmsg
))) {
3515 for (i
= 0; i
< capture_opts
->ifaces
->len
; i
++) {
3516 pcap_opts
= g_array_index(global_ld
.pcaps
, pcap_options
*, i
);
3517 interface_opts
= g_array_index(capture_opts
->ifaces
, interface_options
, i
);
3518 /* init the input filter from the network interface (capture pipe will do nothing) */
3520 * When remote capturing WinPCap crashes when the capture filter
3521 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3524 switch (capture_loop_init_filter(pcap_opts
->pcap_h
, pcap_opts
->from_cap_pipe
,
3525 interface_opts
.name
,
3526 interface_opts
.cfilter
?interface_opts
.cfilter
:"")) {
3528 case INITFILTER_NO_ERROR
:
3531 case INITFILTER_BAD_FILTER
:
3532 cfilter_error
= TRUE
;
3534 g_snprintf(errmsg
, sizeof(errmsg
), "%s", pcap_geterr(pcap_opts
->pcap_h
));
3537 case INITFILTER_OTHER_ERROR
:
3538 g_snprintf(errmsg
, sizeof(errmsg
), "Can't install filter (%s).",
3539 pcap_geterr(pcap_opts
->pcap_h
));
3540 g_snprintf(secondary_errmsg
, sizeof(secondary_errmsg
), "%s", please_report
);
3545 /* If we're supposed to write to a capture file, open it for output
3546 (temporary/specified name/ringbuffer) */
3547 if (capture_opts
->saving_to_file
) {
3548 if (!capture_loop_open_output(capture_opts
, &global_ld
.save_file_fd
,
3549 errmsg
, sizeof(errmsg
))) {
3553 /* set up to write to the already-opened capture output file/files */
3554 if (!capture_loop_init_output(capture_opts
, &global_ld
, errmsg
,
3559 /* XXX - capture SIGTERM and close the capture, in case we're on a
3560 Linux 2.0[.x] system and you have to explicitly close the capture
3561 stream in order to turn promiscuous mode off? We need to do that
3562 in other places as well - and I don't think that works all the
3563 time in any case, due to libpcap bugs. */
3565 /* Well, we should be able to start capturing.
3567 Sync out the capture file, so the header makes it to the file system,
3568 and send a "capture started successfully and capture file created"
3569 message to our parent so that they'll open the capture file and
3570 update its windows to indicate that we have a live capture in
3572 fflush(global_ld
.pdh
);
3573 report_new_capture_file(capture_opts
->save_file
);
3576 /* initialize capture stop (and alike) conditions */
3577 init_capture_stop_conditions();
3578 /* create stop conditions */
3579 if (capture_opts
->has_autostop_filesize
) {
3580 if (capture_opts
->autostop_filesize
> (((guint32
)INT_MAX
+ 1) / 1024)) {
3581 capture_opts
->autostop_filesize
= ((guint32
)INT_MAX
+ 1) / 1024;
3584 cnd_new(CND_CLASS_CAPTURESIZE
, (guint64
)capture_opts
->autostop_filesize
* 1024);
3586 if (capture_opts
->has_autostop_duration
)
3587 cnd_autostop_duration
=
3588 cnd_new(CND_CLASS_TIMEOUT
,(gint32
)capture_opts
->autostop_duration
);
3590 if (capture_opts
->multi_files_on
) {
3591 if (capture_opts
->has_file_duration
)
3593 cnd_new(CND_CLASS_TIMEOUT
, capture_opts
->file_duration
);
3595 if (capture_opts
->has_autostop_files
)
3596 cnd_autostop_files
=
3597 cnd_new(CND_CLASS_CAPTURESIZE
, capture_opts
->autostop_files
);
3600 /* init the time values */
3602 upd_time
= GetTickCount();
3604 gettimeofday(&upd_time
, NULL
);
3606 start_time
= create_timestamp();
3607 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_INFO
, "Capture loop running!");
3609 /* WOW, everything is prepared! */
3610 /* please fasten your seat belts, we will enter now the actual capture loop */
3612 pcap_queue
= g_async_queue_new();
3613 pcap_queue_bytes
= 0;
3614 pcap_queue_packets
= 0;
3615 for (i
= 0; i
< global_ld
.pcaps
->len
; i
++) {
3616 pcap_opts
= g_array_index(global_ld
.pcaps
, pcap_options
*, i
);
3617 #if GLIB_CHECK_VERSION(2,31,0)
3618 /* XXX - Add an interface name here? */
3619 pcap_opts
->tid
= g_thread_new("Capture read", pcap_read_handler
, pcap_opts
);
3621 pcap_opts
->tid
= g_thread_create(pcap_read_handler
, pcap_opts
, TRUE
, NULL
);
3625 while (global_ld
.go
) {
3626 /* dispatch incoming packets */
3628 pcap_queue_element
*queue_element
;
3629 #if GLIB_CHECK_VERSION(2,31,18)
3631 g_async_queue_lock(pcap_queue
);
3632 queue_element
= (pcap_queue_element
*)g_async_queue_timeout_pop_unlocked(pcap_queue
, WRITER_THREAD_TIMEOUT
);
3634 GTimeVal write_thread_time
;
3636 g_get_current_time(&write_thread_time
);
3637 g_time_val_add(&write_thread_time
, WRITER_THREAD_TIMEOUT
);
3638 g_async_queue_lock(pcap_queue
);
3639 queue_element
= (pcap_queue_element
*)g_async_queue_timed_pop_unlocked(pcap_queue
, &write_thread_time
);
3641 if (queue_element
) {
3642 pcap_queue_bytes
-= queue_element
->phdr
.caplen
;
3643 pcap_queue_packets
-= 1;
3645 g_async_queue_unlock(pcap_queue
);
3646 if (queue_element
) {
3647 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_INFO
,
3648 "Dequeued a packet of length %d captured on interface %d.",
3649 queue_element
->phdr
.caplen
, queue_element
->pcap_opts
->interface_id
);
3651 capture_loop_write_packet_cb((u_char
*) queue_element
->pcap_opts
,
3652 &queue_element
->phdr
,
3654 g_free(queue_element
->pd
);
3655 g_free(queue_element
);
3661 pcap_opts
= g_array_index(global_ld
.pcaps
, pcap_options
*, 0);
3662 inpkts
= capture_loop_dispatch(&global_ld
, errmsg
,
3663 sizeof(errmsg
), pcap_opts
);
3666 /* Were we asked to print packet counts by the SIGINFO handler? */
3667 if (global_ld
.report_packet_count
) {
3668 fprintf(stderr
, "%u packet%s captured\n", global_ld
.packet_count
,
3669 plurality(global_ld
.packet_count
, "", "s"));
3670 global_ld
.report_packet_count
= FALSE
;
3675 /* any news from our parent (signal pipe)? -> just stop the capture */
3676 if (!signal_pipe_check_running()) {
3677 global_ld
.go
= FALSE
;
3682 global_ld
.inpkts_to_sync_pipe
+= inpkts
;
3684 /* check capture size condition */
3685 if (cnd_autostop_size
!= NULL
&&
3686 cnd_eval(cnd_autostop_size
, global_ld
.bytes_written
)) {
3687 /* Capture size limit reached, do we have another file? */
3688 if (!do_file_switch_or_stop(capture_opts
, cnd_autostop_files
,
3689 cnd_autostop_size
, cnd_file_duration
))
3691 } /* cnd_autostop_size */
3692 if (capture_opts
->output_to_pipe
) {
3693 fflush(global_ld
.pdh
);
3697 /* Only update once every 500ms so as not to overload slow displays.
3698 * This also prevents too much context-switching between the dumpcap
3699 * and wireshark processes.
3701 #define DUMPCAP_UPD_TIME 500
3704 cur_time
= GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3705 if ((cur_time
- upd_time
) > DUMPCAP_UPD_TIME
) { /* wrap just causes an extra update */
3707 gettimeofday(&cur_time
, NULL
);
3708 if ((cur_time
.tv_sec
* 1000000 + cur_time
.tv_usec
) >
3709 (upd_time
.tv_sec
* 1000000 + upd_time
.tv_usec
+ DUMPCAP_UPD_TIME
*1000)) {
3712 upd_time
= cur_time
;
3715 if (pcap_stats(pch
, stats
) >= 0) {
3716 *stats_known
= TRUE
;
3719 /* Let the parent process know. */
3720 if (global_ld
.inpkts_to_sync_pipe
) {
3722 fflush(global_ld
.pdh
);
3724 /* Send our parent a message saying we've written out
3725 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3727 report_packet_count(global_ld
.inpkts_to_sync_pipe
);
3729 global_ld
.inpkts_to_sync_pipe
= 0;
3732 /* check capture duration condition */
3733 if (cnd_autostop_duration
!= NULL
&& cnd_eval(cnd_autostop_duration
)) {
3734 /* The maximum capture time has elapsed; stop the capture. */
3735 global_ld
.go
= FALSE
;
3739 /* check capture file duration condition */
3740 if (cnd_file_duration
!= NULL
&& cnd_eval(cnd_file_duration
)) {
3741 /* duration limit reached, do we have another file? */
3742 if (!do_file_switch_or_stop(capture_opts
, cnd_autostop_files
,
3743 cnd_autostop_size
, cnd_file_duration
))
3745 } /* cnd_file_duration */
3749 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_INFO
, "Capture loop stopping ...");
3751 pcap_queue_element
*queue_element
;
3753 for (i
= 0; i
< global_ld
.pcaps
->len
; i
++) {
3754 pcap_opts
= g_array_index(global_ld
.pcaps
, pcap_options
*, i
);
3755 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_INFO
, "Waiting for thread of interface %u...",
3756 pcap_opts
->interface_id
);
3757 g_thread_join(pcap_opts
->tid
);
3758 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_INFO
, "Thread of interface %u terminated.",
3759 pcap_opts
->interface_id
);
3762 g_async_queue_lock(pcap_queue
);
3763 queue_element
= (pcap_queue_element
*)g_async_queue_try_pop_unlocked(pcap_queue
);
3764 if (queue_element
) {
3765 pcap_queue_bytes
-= queue_element
->phdr
.caplen
;
3766 pcap_queue_packets
-= 1;
3768 g_async_queue_unlock(pcap_queue
);
3769 if (queue_element
== NULL
) {
3772 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_INFO
,
3773 "Dequeued a packet of length %d captured on interface %d.",
3774 queue_element
->phdr
.caplen
, queue_element
->pcap_opts
->interface_id
);
3775 capture_loop_write_packet_cb((u_char
*)queue_element
->pcap_opts
,
3776 &queue_element
->phdr
,
3778 g_free(queue_element
->pd
);
3779 g_free(queue_element
);
3780 global_ld
.inpkts_to_sync_pipe
+= 1;
3781 if (capture_opts
->output_to_pipe
) {
3782 fflush(global_ld
.pdh
);
3788 /* delete stop conditions */
3789 if (cnd_file_duration
!= NULL
)
3790 cnd_delete(cnd_file_duration
);
3791 if (cnd_autostop_files
!= NULL
)
3792 cnd_delete(cnd_autostop_files
);
3793 if (cnd_autostop_size
!= NULL
)
3794 cnd_delete(cnd_autostop_size
);
3795 if (cnd_autostop_duration
!= NULL
)
3796 cnd_delete(cnd_autostop_duration
);
3798 /* did we have a pcap (input) error? */
3799 for (i
= 0; i
< capture_opts
->ifaces
->len
; i
++) {
3800 pcap_opts
= g_array_index(global_ld
.pcaps
, pcap_options
*, i
);
3801 if (pcap_opts
->pcap_err
) {
3802 /* On Linux, if an interface goes down while you're capturing on it,
3803 you'll get a "recvfrom: Network is down" or
3804 "The interface went down" error (ENETDOWN).
3805 (At least you will if g_strerror() doesn't show a local translation
3808 On FreeBSD and OS X, if a network adapter disappears while
3809 you're capturing on it, you'll get a "read: Device not configured"
3810 error (ENXIO). (See previous parenthetical note.)
3812 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3814 These should *not* be reported to the Wireshark developers. */
3817 cap_err_str
= pcap_geterr(pcap_opts
->pcap_h
);
3818 if (strcmp(cap_err_str
, "recvfrom: Network is down") == 0 ||
3819 strcmp(cap_err_str
, "The interface went down") == 0 ||
3820 strcmp(cap_err_str
, "read: Device not configured") == 0 ||
3821 strcmp(cap_err_str
, "read: I/O error") == 0 ||
3822 strcmp(cap_err_str
, "read error: PacketReceivePacket failed") == 0) {
3823 report_capture_error("The network adapter on which the capture was being done "
3824 "is no longer running; the capture has stopped.",
3827 g_snprintf(errmsg
, sizeof(errmsg
), "Error while capturing packets: %s",
3829 report_capture_error(errmsg
, please_report
);
3832 } else if (pcap_opts
->from_cap_pipe
&& pcap_opts
->cap_pipe_err
== PIPERR
) {
3833 report_capture_error(errmsg
, "");
3837 /* did we have an output error while capturing? */
3838 if (global_ld
.err
== 0) {
3841 capture_loop_get_errmsg(errmsg
, sizeof(errmsg
), capture_opts
->save_file
,
3842 global_ld
.err
, FALSE
);
3843 report_capture_error(errmsg
, please_report
);
3847 if (capture_opts
->saving_to_file
) {
3848 /* close the output file */
3849 close_ok
= capture_loop_close_output(capture_opts
, &global_ld
, &err_close
);
3853 /* there might be packets not yet notified to the parent */
3854 /* (do this after closing the file, so all packets are already flushed) */
3855 if (global_ld
.inpkts_to_sync_pipe
) {
3857 report_packet_count(global_ld
.inpkts_to_sync_pipe
);
3858 global_ld
.inpkts_to_sync_pipe
= 0;
3861 /* If we've displayed a message about a write error, there's no point
3862 in displaying another message about an error on close. */
3863 if (!close_ok
&& write_ok
) {
3864 capture_loop_get_errmsg(errmsg
, sizeof(errmsg
), capture_opts
->save_file
, err_close
,
3866 report_capture_error(errmsg
, "");
3870 * XXX We exhibit different behaviour between normal mode and sync mode
3871 * when the pipe is stdin and not already at EOF. If we're a child, the
3872 * parent's stdin isn't closed, so if the user starts another capture,
3873 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3874 * will say "Unrecognized libpcap format". On the other hand, in normal
3875 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3878 report_capture_count(TRUE
);
3880 /* get packet drop statistics from pcap */
3881 for (i
= 0; i
< capture_opts
->ifaces
->len
; i
++) {
3883 guint32 pcap_dropped
= 0;
3885 pcap_opts
= g_array_index(global_ld
.pcaps
, pcap_options
*, i
);
3886 interface_opts
= g_array_index(capture_opts
->ifaces
, interface_options
, i
);
3887 received
= pcap_opts
->received
;
3888 if (pcap_opts
->pcap_h
!= NULL
) {
3889 g_assert(!pcap_opts
->from_cap_pipe
);
3890 /* Get the capture statistics, so we know how many packets were dropped. */
3892 * Older versions of libpcap didn't set ps_ifdrop on some
3893 * platforms; initialize it to 0 to handle that.
3895 stats
->ps_ifdrop
= 0;
3896 if (pcap_stats(pcap_opts
->pcap_h
, stats
) >= 0) {
3897 *stats_known
= TRUE
;
3898 /* Let the parent process know. */
3899 pcap_dropped
+= stats
->ps_drop
;
3901 g_snprintf(errmsg
, sizeof(errmsg
),
3902 "Can't get packet-drop statistics: %s",
3903 pcap_geterr(pcap_opts
->pcap_h
));
3904 report_capture_error(errmsg
, please_report
);
3907 report_packet_drops(received
, pcap_dropped
, pcap_opts
->dropped
, pcap_opts
->flushed
, stats
->ps_ifdrop
, interface_opts
.console_display_name
);
3910 /* close the input file (pcap or capture pipe) */
3911 capture_loop_close_input(&global_ld
);
3913 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_INFO
, "Capture loop stopped!");
3915 /* ok, if the write and the close were successful. */
3916 return write_ok
&& close_ok
;
3919 if (capture_opts
->multi_files_on
) {
3920 /* cleanup ringbuffer */
3921 ringbuf_error_cleanup();
3923 /* We can't use the save file, and we have no FILE * for the stream
3924 to close in order to close it, so close the FD directly. */
3925 if (global_ld
.save_file_fd
!= -1) {
3926 ws_close(global_ld
.save_file_fd
);
3929 /* We couldn't even start the capture, so get rid of the capture
3931 if (capture_opts
->save_file
!= NULL
) {
3932 ws_unlink(capture_opts
->save_file
);
3933 g_free(capture_opts
->save_file
);
3936 capture_opts
->save_file
= NULL
;
3938 report_cfilter_error(capture_opts
, error_index
, errmsg
);
3940 report_capture_error(errmsg
, secondary_errmsg
);
3942 /* close the input file (pcap or cap_pipe) */
3943 capture_loop_close_input(&global_ld
);
3945 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_INFO
, "Capture loop stopped with error");
3952 capture_loop_stop(void)
3954 #ifdef HAVE_PCAP_BREAKLOOP
3956 pcap_options
*pcap_opts
;
3958 for (i
= 0; i
< global_ld
.pcaps
->len
; i
++) {
3959 pcap_opts
= g_array_index(global_ld
.pcaps
, pcap_options
*, i
);
3960 if (pcap_opts
->pcap_h
!= NULL
)
3961 pcap_breakloop(pcap_opts
->pcap_h
);
3964 global_ld
.go
= FALSE
;
3969 capture_loop_get_errmsg(char *errmsg
, int errmsglen
, const char *fname
,
3970 int err
, gboolean is_close
)
3975 g_snprintf(errmsg
, errmsglen
,
3976 "Not all the packets could be written to the file"
3977 " to which the capture was being saved\n"
3978 "(\"%s\") because there is no space left on the file system\n"
3979 "on which that file resides.",
3985 g_snprintf(errmsg
, errmsglen
,
3986 "Not all the packets could be written to the file"
3987 " to which the capture was being saved\n"
3988 "(\"%s\") because you are too close to, or over,"
3989 " your disk quota\n"
3990 "on the file system on which that file resides.",
3997 g_snprintf(errmsg
, errmsglen
,
3998 "The file to which the capture was being saved\n"
3999 "(\"%s\") could not be closed: %s.",
4000 fname
, g_strerror(err
));
4002 g_snprintf(errmsg
, errmsglen
,
4003 "An error occurred while writing to the file"
4004 " to which the capture was being saved\n"
4006 fname
, g_strerror(err
));
4013 /* one packet was captured, process it */
4015 capture_loop_write_packet_cb(u_char
*pcap_opts_p
, const struct pcap_pkthdr
*phdr
,
4018 pcap_options
*pcap_opts
= (pcap_options
*) (void *) pcap_opts_p
;
4020 guint ts_mul
= pcap_opts
->ts_nsec
? 1000000000 : 1000000;
4022 /* We may be called multiple times from pcap_dispatch(); if we've set
4023 the "stop capturing" flag, ignore this packet, as we're not
4024 supposed to be saving any more packets. */
4025 if (!global_ld
.go
) {
4026 pcap_opts
->flushed
++;
4030 if (global_ld
.pdh
) {
4031 gboolean successful
;
4033 /* We're supposed to write the packet to a file; do so.
4034 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4035 "ld->err" to the error. */
4036 if (global_capture_opts
.use_pcapng
) {
4037 successful
= pcapng_write_enhanced_packet_block(global_ld
.pdh
,
4039 phdr
->ts
.tv_sec
, (gint32
)phdr
->ts
.tv_usec
,
4040 phdr
->caplen
, phdr
->len
,
4041 pcap_opts
->interface_id
,
4044 &global_ld
.bytes_written
, &err
);
4046 successful
= libpcap_write_packet(global_ld
.pdh
,
4047 phdr
->ts
.tv_sec
, (gint32
)phdr
->ts
.tv_usec
,
4048 phdr
->caplen
, phdr
->len
,
4050 &global_ld
.bytes_written
, &err
);
4053 global_ld
.go
= FALSE
;
4054 global_ld
.err
= err
;
4055 pcap_opts
->dropped
++;
4057 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_INFO
,
4058 "Wrote a packet of length %d captured on interface %u.",
4059 phdr
->caplen
, pcap_opts
->interface_id
);
4060 global_ld
.packet_count
++;
4061 pcap_opts
->received
++;
4062 /* if the user told us to stop after x packets, do we already have enough? */
4063 if ((global_ld
.packet_max
> 0) && (global_ld
.packet_count
>= global_ld
.packet_max
)) {
4064 global_ld
.go
= FALSE
;
4070 /* one packet was captured, queue it */
4072 capture_loop_queue_packet_cb(u_char
*pcap_opts_p
, const struct pcap_pkthdr
*phdr
,
4075 pcap_options
*pcap_opts
= (pcap_options
*) (void *) pcap_opts_p
;
4076 pcap_queue_element
*queue_element
;
4077 gboolean limit_reached
;
4079 /* We may be called multiple times from pcap_dispatch(); if we've set
4080 the "stop capturing" flag, ignore this packet, as we're not
4081 supposed to be saving any more packets. */
4082 if (!global_ld
.go
) {
4083 pcap_opts
->flushed
++;
4087 queue_element
= (pcap_queue_element
*)g_malloc(sizeof(pcap_queue_element
));
4088 if (queue_element
== NULL
) {
4089 pcap_opts
->dropped
++;
4092 queue_element
->pcap_opts
= pcap_opts
;
4093 queue_element
->phdr
= *phdr
;
4094 queue_element
->pd
= (u_char
*)g_malloc(phdr
->caplen
);
4095 if (queue_element
->pd
== NULL
) {
4096 pcap_opts
->dropped
++;
4097 g_free(queue_element
);
4100 memcpy(queue_element
->pd
, pd
, phdr
->caplen
);
4101 g_async_queue_lock(pcap_queue
);
4102 if (((pcap_queue_byte_limit
== 0) || (pcap_queue_bytes
< pcap_queue_byte_limit
)) &&
4103 ((pcap_queue_packet_limit
== 0) || (pcap_queue_packets
< pcap_queue_packet_limit
))) {
4104 limit_reached
= FALSE
;
4105 g_async_queue_push_unlocked(pcap_queue
, queue_element
);
4106 pcap_queue_bytes
+= phdr
->caplen
;
4107 pcap_queue_packets
+= 1;
4109 limit_reached
= TRUE
;
4111 g_async_queue_unlock(pcap_queue
);
4112 if (limit_reached
) {
4113 pcap_opts
->dropped
++;
4114 g_free(queue_element
->pd
);
4115 g_free(queue_element
);
4116 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_INFO
,
4117 "Dropped a packet of length %d captured on interface %u.",
4118 phdr
->caplen
, pcap_opts
->interface_id
);
4120 pcap_opts
->received
++;
4121 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_INFO
,
4122 "Queued a packet of length %d captured on interface %u.",
4123 phdr
->caplen
, pcap_opts
->interface_id
);
4125 /* I don't want to hold the mutex over the debug output. So the
4126 output may be wrong */
4127 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_INFO
,
4128 "Queue size is now %" G_GINT64_MODIFIER
"d bytes (%" G_GINT64_MODIFIER
"d packets)",
4129 pcap_queue_bytes
, pcap_queue_packets
);
4133 set_80211_channel(const char *iface
, const char *opt
)
4135 int freq
= 0, type
, ret
;
4136 gchar
**options
= NULL
;
4138 options
= g_strsplit_set(opt
, ",", 2);
4141 freq
= atoi(options
[0]);
4144 type
= ws80211_str_to_chan_type(options
[1]);
4153 ret
= ws80211_init();
4155 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret
), g_strerror(abs(ret
)));
4159 ret
= ws80211_set_freq(iface
, freq
, type
);
4162 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret
), g_strerror(abs(ret
)));
4168 pipe_write_block(2, SP_SUCCESS
, NULL
);
4172 g_strfreev(options
);
4176 /* And now our feature presentation... [ fade to music ] */
4178 main(int argc
, char *argv
[])
4180 GString
*comp_info_str
;
4181 GString
*runtime_info_str
;
4183 struct option long_options
[] = {
4184 {(char *)"capture-comment", required_argument
, NULL
, LONGOPT_NUM_CAP_COMMENT
},
4188 gboolean arg_error
= FALSE
;
4193 struct sigaction action
, oldaction
;
4196 gboolean start_capture
= TRUE
;
4197 gboolean stats_known
;
4198 struct pcap_stat stats
;
4199 GLogLevelFlags log_flags
;
4200 gboolean list_interfaces
= FALSE
;
4201 gboolean list_link_layer_types
= FALSE
;
4202 #ifdef HAVE_BPF_IMAGE
4203 gboolean print_bpf_code
= FALSE
;
4205 gboolean set_chan
= FALSE
;
4206 gchar
*set_chan_arg
= NULL
;
4207 gboolean machine_readable
= FALSE
;
4208 gboolean print_statistics
= FALSE
;
4209 int status
, run_once_args
= 0;
4212 #if defined(__APPLE__) && defined(__LP64__)
4213 struct utsname osinfo
;
4217 /* Assemble the compile-time version information string */
4218 comp_info_str
= g_string_new("Compiled ");
4219 get_compiled_version_info(comp_info_str
, NULL
, NULL
);
4221 /* Assemble the run-time version information string */
4222 runtime_info_str
= g_string_new("Running ");
4223 get_runtime_version_info(runtime_info_str
, NULL
);
4225 /* Add it to the information to be reported on a crash. */
4226 ws_add_crash_info("Dumpcap " VERSION
"%s\n"
4231 wireshark_svnversion
, comp_info_str
->str
, runtime_info_str
->str
);
4234 arg_list_utf_16to8(argc
, argv
);
4235 create_app_running_mutex();
4238 * Initialize our DLL search path. MUST be called before LoadLibrary
4241 ws_init_dll_search_path();
4244 #ifdef HAVE_PCAP_REMOTE
4245 #define OPTSTRING_A "A:"
4246 #define OPTSTRING_r "r"
4247 #define OPTSTRING_u "u"
4249 #define OPTSTRING_A ""
4250 #define OPTSTRING_r ""
4251 #define OPTSTRING_u ""
4254 #ifdef HAVE_PCAP_SETSAMPLING
4255 #define OPTSTRING_m "m:"
4257 #define OPTSTRING_m ""
4260 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4261 #define OPTSTRING_B "B:"
4263 #define OPTSTRING_B ""
4264 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4266 #ifdef HAVE_PCAP_CREATE
4267 #define OPTSTRING_I "I"
4269 #define OPTSTRING_I ""
4272 #ifdef HAVE_BPF_IMAGE
4273 #define OPTSTRING_d "d"
4275 #define OPTSTRING_d ""
4278 #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:"
4280 #ifdef DEBUG_CHILD_DUMPCAP
4281 if ((debug_log
= ws_fopen("dumpcap_debug_log.tmp","w")) == NULL
) {
4282 fprintf (stderr
, "Unable to open debug log file !\n");
4287 #if defined(__APPLE__) && defined(__LP64__)
4289 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
4290 * a bug workaround - timeouts less than 1 second don't work with libpcap
4291 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
4292 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4293 * The problem is extremely unlikely to be reintroduced in a future
4296 if (uname(&osinfo
) == 0) {
4298 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
4299 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4300 * number of 10.0.0, not 10.1.0 - go figure).
4302 if (strcmp(osinfo
.release
, "10.0.0") == 0 || /* 10.6, 10.6.1 */
4303 strcmp(osinfo
.release
, "10.3.0") == 0 || /* 10.6.3 */
4304 strcmp(osinfo
.release
, "10.4.0") == 0) /* 10.6.4 */
4305 need_timeout_workaround
= TRUE
;
4310 * Determine if dumpcap is being requested to run in a special
4311 * capture_child mode by going thru the command line args to see if
4312 * a -Z is present. (-Z is a hidden option).
4314 * The primary result of running in capture_child mode is that
4315 * all messages sent out on stderr are in a special type/len/string
4316 * format to allow message processing by type. These messages include
4317 * error messages if dumpcap fails to start the operation it was
4318 * requested to do, as well as various "status" messages which are sent
4319 * when an actual capture is in progress, and a "success" message sent
4320 * if dumpcap was requested to perform an operation other than a
4323 * Capture_child mode would normally be requested by a parent process
4324 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4325 * to which dumpcap stderr has been redirected. It might also have
4326 * another pipe to obtain dumpcap stdout output; for operations other
4327 * than a capture, that information is formatted specially for easier
4328 * parsing by the parent process.
4330 * Capture_child mode needs to be determined immediately upon
4331 * startup so that any messages generated by dumpcap in this mode
4332 * (eg: during initialization) will be formatted properly.
4335 for (i
=1; i
<argc
; i
++) {
4336 if (strcmp("-Z", argv
[i
]) == 0) {
4337 capture_child
= TRUE
;
4338 machine_readable
= TRUE
; /* request machine-readable output */
4340 /* set output pipe to binary mode, to avoid ugly text conversions */
4341 _setmode(2, O_BINARY
);
4346 /* The default_log_handler will use stdout, which makes trouble in */
4347 /* capture child mode, as it uses stdout for its sync_pipe. */
4348 /* So: the filtering is done in the console_log_handler and not here.*/
4349 /* We set the log handlers right up front to make sure that any log */
4350 /* messages when running as child will be sent back to the parent */
4351 /* with the correct format. */
4356 G_LOG_LEVEL_CRITICAL
|
4357 G_LOG_LEVEL_WARNING
|
4358 G_LOG_LEVEL_MESSAGE
|
4362 G_LOG_FLAG_RECURSION
);
4364 g_log_set_handler(NULL
,
4366 console_log_handler
, NULL
/* user_data */);
4367 g_log_set_handler(LOG_DOMAIN_MAIN
,
4369 console_log_handler
, NULL
/* user_data */);
4370 g_log_set_handler(LOG_DOMAIN_CAPTURE
,
4372 console_log_handler
, NULL
/* user_data */);
4373 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD
,
4375 console_log_handler
, NULL
/* user_data */);
4377 /* Initialize the pcaps list */
4378 global_ld
.pcaps
= g_array_new(FALSE
, FALSE
, sizeof(pcap_options
*));
4380 #if !GLIB_CHECK_VERSION(2,31,0)
4381 /* Initialize the thread system */
4382 g_thread_init(NULL
);
4386 /* Load wpcap if possible. Do this before collecting the run-time version information */
4389 /* ... and also load the packet.dll from wpcap */
4390 /* XXX - currently not required, may change later. */
4391 /*wpcap_packet_load();*/
4393 /* Start windows sockets */
4394 WSAStartup( MAKEWORD( 1, 1 ), &wsaData
);
4396 /* Set handler for Ctrl+C key */
4397 SetConsoleCtrlHandler(capture_cleanup_handler
, TRUE
);
4399 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4400 and exit. Do the same with SIGPIPE, in case, for example,
4401 we're writing to our standard output and it's a pipe.
4402 Do the same with SIGHUP if it's not being ignored (if we're
4403 being run under nohup, it might be ignored, in which case we
4404 should leave it ignored).
4406 XXX - apparently, Coverity complained that part of action
4407 wasn't initialized. Perhaps it's running on Linux, where
4408 struct sigaction has an ignored "sa_restorer" element and
4409 where "sa_handler" and "sa_sigaction" might not be two
4410 members of a union. */
4411 memset(&action
, 0, sizeof(action
));
4412 action
.sa_handler
= capture_cleanup_handler
;
4414 * Arrange that system calls not get restarted, because when
4415 * our signal handler returns we don't want to restart
4416 * a call that was waiting for packets to arrive.
4418 action
.sa_flags
= 0;
4419 sigemptyset(&action
.sa_mask
);
4420 sigaction(SIGTERM
, &action
, NULL
);
4421 sigaction(SIGINT
, &action
, NULL
);
4422 sigaction(SIGPIPE
, &action
, NULL
);
4423 sigaction(SIGHUP
, NULL
, &oldaction
);
4424 if (oldaction
.sa_handler
== SIG_DFL
)
4425 sigaction(SIGHUP
, &action
, NULL
);
4428 /* Catch SIGINFO and, if we get it and we're capturing in
4429 quiet mode, report the number of packets we've captured. */
4430 action
.sa_handler
= report_counts_siginfo
;
4431 action
.sa_flags
= SA_RESTART
;
4432 sigemptyset(&action
.sa_mask
);
4433 sigaction(SIGINFO
, &action
, NULL
);
4434 #endif /* SIGINFO */
4438 enable_kernel_bpf_jit_compiler();
4441 /* ----------------------------------------------------------------- */
4442 /* Privilege and capability handling */
4444 /* 1. Running not as root or suid root; no special capabilities. */
4447 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4450 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4452 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4453 /* capabilities; Drop all other capabilities; */
4454 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4455 /* else: after pcap_open_live() in capture_loop_open_input() */
4456 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4457 /* (Note: this means that the process, although logged in */
4458 /* as root, does not have various permissions such as the */
4459 /* ability to bypass file access permissions). */
4460 /* XXX: Should we just leave capabilities alone in this case */
4461 /* so that user gets expected effect that root can do */
4464 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4466 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4467 /* else: after pcap_open_live() in capture_loop_open_input() */
4468 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4469 /* pcap_open_live). */
4471 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4473 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4474 /* capabilities; Drop all other capabilities; */
4475 /* Drop suid privileges (euid=ruid); */
4476 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4477 /* else: after pcap_open_live() in capture_loop_open_input() */
4478 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4480 /* XXX: For some Linux versions/distros with capabilities */
4481 /* a 'normal' process with any capabilities cannot be */
4482 /* 'killed' (signaled) from another (same uid) non-privileged */
4484 /* For example: If (non-suid) Wireshark forks a */
4485 /* child suid dumpcap which acts as described here (case 5), */
4486 /* Wireshark will be unable to kill (signal) the child */
4487 /* dumpcap process until the capabilities have been dropped */
4488 /* (after pcap_open_live()). */
4489 /* This behaviour will apparently be changed in the kernel */
4490 /* to allow the kill (signal) in this case. */
4491 /* See the following for details: */
4492 /* http://www.mail-archive.com/ [wrapped] */
4493 /* linux-security-module@vger.kernel.org/msg02913.html */
4495 /* It is therefore conceivable that if dumpcap somehow hangs */
4496 /* in pcap_open_live or before that wireshark will not */
4497 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4498 /* In this case, exiting wireshark will kill the child */
4499 /* dumpcap process. */
4501 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4502 /* capabilities; Using libcap. Note: capset cmd (which see) */
4503 /* used to assign capabilities to file. */
4505 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4506 /* else: after pcap_open_live() in capture_loop_open_input() */
4507 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4509 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4510 /* longer required (similar to capture). */
4512 /* ----------------------------------------------------------------- */
4514 init_process_policies();
4517 /* If 'started with special privileges' (and using libcap) */
4518 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4519 /* Set euid/egid = ruid/rgid to remove suid privileges */
4520 relinquish_privs_except_capture();
4523 /* Set the initial values in the capture options. This might be overwritten
4524 by the command line parameters. */
4525 capture_opts_init(&global_capture_opts
);
4527 /* We always save to a file - if no file was specified, we save to a
4529 global_capture_opts
.saving_to_file
= TRUE
;
4530 global_capture_opts
.has_ring_num_files
= TRUE
;
4532 /* Pass on capture_child mode for capture_opts */
4533 global_capture_opts
.capture_child
= capture_child
;
4535 /* Now get our args */
4536 while ((opt
= getopt_long(argc
, argv
, OPTSTRING
, long_options
, NULL
)) != -1) {
4538 case 'h': /* Print help and exit */
4542 case 'v': /* Show version and exit */
4544 show_version(comp_info_str
, runtime_info_str
);
4545 g_string_free(comp_info_str
, TRUE
);
4546 g_string_free(runtime_info_str
, TRUE
);
4550 /*** capture option specific ***/
4551 case 'a': /* autostop criteria */
4552 case 'b': /* Ringbuffer option */
4553 case 'c': /* Capture x packets */
4554 case 'f': /* capture filter */
4555 case 'g': /* enable group read access on file(s) */
4556 case 'i': /* Use interface x */
4557 case 'n': /* Use pcapng format */
4558 case 'p': /* Don't capture in promiscuous mode */
4559 case 'P': /* Use pcap format */
4560 case 's': /* Set the snapshot (capture) length */
4561 case 'w': /* Write to capture file x */
4562 case 'y': /* Set the pcap data link type */
4563 case LONGOPT_NUM_CAP_COMMENT
: /* add a capture comment */
4564 #ifdef HAVE_PCAP_REMOTE
4565 case 'u': /* Use UDP for data transfer */
4566 case 'r': /* Capture own RPCAP traffic too */
4567 case 'A': /* Authentication */
4569 #ifdef HAVE_PCAP_SETSAMPLING
4570 case 'm': /* Sampling */
4572 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4573 case 'B': /* Buffer size */
4574 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4575 #ifdef HAVE_PCAP_CREATE
4576 case 'I': /* Monitor mode */
4578 status
= capture_opts_add_opt(&global_capture_opts
, opt
, optarg
, &start_capture
);
4583 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4585 capture_child
= TRUE
;
4587 /* set output pipe to binary mode, to avoid ugly text conversions */
4588 _setmode(2, O_BINARY
);
4590 * optarg = the control ID, aka the PPID, currently used for the
4593 if (strcmp(optarg
, SIGNAL_PIPE_CTRL_ID_NONE
) != 0) {
4594 sig_pipe_name
= g_strdup_printf(SIGNAL_PIPE_FORMAT
, optarg
);
4595 sig_pipe_handle
= CreateFile(utf_8to16(sig_pipe_name
),
4596 GENERIC_READ
, 0, NULL
, OPEN_EXISTING
, 0, NULL
);
4598 if (sig_pipe_handle
== INVALID_HANDLE_VALUE
) {
4599 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_INFO
,
4600 "Signal pipe: Unable to open %s. Dead parent?",
4608 case 'q': /* Quiet */
4614 /*** all non capture option specific ***/
4615 case 'D': /* Print a list of capture devices and exit */
4616 list_interfaces
= TRUE
;
4619 case 'L': /* Print list of link-layer types and exit */
4620 list_link_layer_types
= TRUE
;
4623 #ifdef HAVE_BPF_IMAGE
4624 case 'd': /* Print BPF code for capture filter and exit */
4625 print_bpf_code
= TRUE
;
4629 case 'S': /* Print interface statistics once a second */
4630 print_statistics
= TRUE
;
4633 case 'k': /* Set wireless channel */
4635 set_chan_arg
= optarg
;
4638 case 'M': /* For -D, -L, and -S, print machine-readable output */
4639 machine_readable
= TRUE
;
4642 pcap_queue_byte_limit
= get_positive_int(optarg
, "byte_limit");
4645 pcap_queue_packet_limit
= get_positive_int(optarg
, "packet_limit");
4648 cmdarg_err("Invalid Option: %s", argv
[optind
-1]);
4650 case '?': /* Bad flag - print usage message */
4659 /* user specified file name as regular command-line argument */
4660 /* XXX - use it as the capture file name (or something else)? */
4666 * Extra command line arguments were specified; complain.
4667 * XXX - interpret as capture filter, as tcpdump and tshark do?
4669 cmdarg_err("Invalid argument: %s", argv
[0]);
4674 if ((pcap_queue_byte_limit
> 0) || (pcap_queue_packet_limit
> 0)) {
4677 if ((pcap_queue_byte_limit
== 0) && (pcap_queue_packet_limit
== 0)) {
4678 /* Use some default if the user hasn't specified some */
4679 /* XXX: Are these defaults good enough? */
4680 pcap_queue_byte_limit
= 1000 * 1000;
4681 pcap_queue_packet_limit
= 1000;
4688 if (run_once_args
> 1) {
4689 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
4691 } else if (run_once_args
== 1) {
4692 /* We're supposed to print some information, rather than
4693 to capture traffic; did they specify a ring buffer option? */
4694 if (global_capture_opts
.multi_files_on
) {
4695 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4699 /* We're supposed to capture traffic; */
4701 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4702 if (global_capture_opts
.ifaces
->len
> 1) {
4704 global_capture_opts
.use_pcapng
= TRUE
;
4707 if (global_capture_opts
.capture_comment
&&
4708 (!global_capture_opts
.use_pcapng
|| global_capture_opts
.multi_files_on
)) {
4709 /* XXX - for ringbuffer, should we apply the comment to each file? */
4710 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4714 /* Was the ring buffer option specified and, if so, does it make sense? */
4715 if (global_capture_opts
.multi_files_on
) {
4716 /* Ring buffer works only under certain conditions:
4717 a) ring buffer does not work with temporary files;
4718 b) it makes no sense to enable the ring buffer if the maximum
4719 file size is set to "infinite". */
4720 if (global_capture_opts
.save_file
== NULL
) {
4721 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4722 global_capture_opts
.multi_files_on
= FALSE
;
4724 if (!global_capture_opts
.has_autostop_filesize
&& !global_capture_opts
.has_file_duration
) {
4725 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4727 /* XXX - this must be redesigned as the conditions changed */
4728 global_capture_opts
.multi_files_on
= FALSE
;
4735 * "-D" requires no interface to be selected; it's supposed to list
4738 if (list_interfaces
) {
4739 /* Get the list of interfaces */
4744 if_list
= capture_interface_list(&err
, &err_str
,NULL
);
4745 if (if_list
== NULL
) {
4747 case CANT_GET_INTERFACE_LIST
:
4748 case DONT_HAVE_PCAP
:
4749 cmdarg_err("%s", err_str
);
4754 case NO_INTERFACES_FOUND
:
4756 * If we're being run by another program, just give them
4757 * an empty list of interfaces, don't report this as
4758 * an error; that lets them decide whether to report
4759 * this as an error or not.
4761 if (!machine_readable
) {
4762 cmdarg_err("There are no interfaces on which a capture can be done");
4769 if (machine_readable
) /* tab-separated values to stdout */
4770 print_machine_readable_interfaces(if_list
);
4772 capture_opts_print_interfaces(if_list
);
4773 free_interface_list(if_list
);
4778 * "-S" requires no interface to be selected; it gives statistics
4779 * for all interfaces.
4781 if (print_statistics
) {
4782 status
= print_statistics_loop(machine_readable
);
4787 interface_options interface_opts
;
4789 if (global_capture_opts
.ifaces
->len
!= 1) {
4790 cmdarg_err("Need one interface");
4794 interface_opts
= g_array_index(global_capture_opts
.ifaces
, interface_options
, 0);
4795 status
= set_80211_channel(interface_opts
.name
, set_chan_arg
);
4800 * "-L", "-d", and capturing act on a particular interface, so we have to
4801 * have an interface; if none was specified, pick a default.
4803 status
= capture_opts_default_iface_if_necessary(&global_capture_opts
, NULL
);
4805 /* cmdarg_err() already called .... */
4809 /* Let the user know what interfaces were chosen. */
4810 if (capture_child
) {
4811 for (j
= 0; j
< global_capture_opts
.ifaces
->len
; j
++) {
4812 interface_options interface_opts
;
4814 interface_opts
= g_array_index(global_capture_opts
.ifaces
, interface_options
, j
);
4815 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "Interface: %s\n",
4816 interface_opts
.name
);
4819 str
= g_string_new("");
4821 if (global_capture_opts
.ifaces
->len
< 2)
4823 if (global_capture_opts
.ifaces
->len
< 4)
4826 for (j
= 0; j
< global_capture_opts
.ifaces
->len
; j
++) {
4827 interface_options interface_opts
;
4829 interface_opts
= g_array_index(global_capture_opts
.ifaces
, interface_options
, j
);
4831 if (global_capture_opts
.ifaces
->len
> 2) {
4832 g_string_append_printf(str
, ",");
4834 g_string_append_printf(str
, " ");
4835 if (j
== global_capture_opts
.ifaces
->len
- 1) {
4836 g_string_append_printf(str
, "and ");
4839 g_string_append_printf(str
, "'%s'", interface_opts
.console_display_name
);
4842 g_string_append_printf(str
, "%u interfaces", global_capture_opts
.ifaces
->len
);
4844 fprintf(stderr
, "Capturing on %s\n", str
->str
);
4845 g_string_free(str
, TRUE
);
4848 if (list_link_layer_types
) {
4849 /* Get the list of link-layer types for the capture device. */
4850 if_capabilities_t
*caps
;
4854 for (ii
= 0; ii
< global_capture_opts
.ifaces
->len
; ii
++) {
4855 interface_options interface_opts
;
4857 interface_opts
= g_array_index(global_capture_opts
.ifaces
, interface_options
, ii
);
4858 caps
= get_if_capabilities(interface_opts
.name
,
4859 interface_opts
.monitor_mode
, &err_str
);
4861 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4862 "Please check to make sure you have sufficient permissions, and that\n"
4863 "you have the proper interface or pipe specified.", interface_opts
.name
, err_str
);
4867 if (caps
->data_link_types
== NULL
) {
4868 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts
.name
);
4871 if (machine_readable
) /* tab-separated values to stdout */
4872 /* XXX: We need to change the format and adopt consumers */
4873 print_machine_readable_if_capabilities(caps
);
4875 /* XXX: We might want to print also the interface name */
4876 capture_opts_print_if_capabilities(caps
, interface_opts
.name
,
4877 interface_opts
.monitor_mode
);
4878 free_if_capabilities(caps
);
4883 /* We're supposed to do a capture, or print the BPF code for a filter.
4884 Process the snapshot length, as that affects the generated BPF code. */
4885 capture_opts_trim_snaplen(&global_capture_opts
, MIN_PACKET_SIZE
);
4887 #ifdef HAVE_BPF_IMAGE
4888 if (print_bpf_code
) {
4889 show_filter_code(&global_capture_opts
);
4894 /* We're supposed to do a capture. Process the ring buffer arguments. */
4895 capture_opts_trim_ring_num_files(&global_capture_opts
);
4897 /* flush stderr prior to starting the main capture loop */
4900 /* Now start the capture. */
4902 if (capture_loop_start(&global_capture_opts
, &stats_known
, &stats
) == TRUE
) {
4906 /* capture failed */
4909 return 0; /* never here, make compiler happy */
4914 console_log_handler(const char *log_domain
, GLogLevelFlags log_level
,
4915 const char *message
, gpointer user_data _U_
)
4922 /* ignore log message, if log_level isn't interesting */
4923 if ( !(log_level
& G_LOG_LEVEL_MASK
& ~(G_LOG_LEVEL_DEBUG
|G_LOG_LEVEL_INFO
))) {
4924 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4929 /* create a "timestamp" */
4931 today
= localtime(&curr
);
4933 switch(log_level
& G_LOG_LEVEL_MASK
) {
4934 case G_LOG_LEVEL_ERROR
:
4937 case G_LOG_LEVEL_CRITICAL
:
4940 case G_LOG_LEVEL_WARNING
:
4943 case G_LOG_LEVEL_MESSAGE
:
4946 case G_LOG_LEVEL_INFO
:
4949 case G_LOG_LEVEL_DEBUG
:
4953 fprintf(stderr
, "unknown log_level %u\n", log_level
);
4955 g_assert_not_reached();
4958 /* Generate the output message */
4959 if (log_level
& G_LOG_LEVEL_MESSAGE
) {
4960 /* normal user messages without additional infos */
4961 msg
= g_strdup_printf("%s\n", message
);
4963 /* info/debug messages with additional infos */
4964 msg
= g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4965 today
->tm_hour
, today
->tm_min
, today
->tm_sec
,
4966 log_domain
!= NULL
? log_domain
: "",
4970 /* DEBUG & INFO msgs (if we're debugging today) */
4971 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4972 if ( !(log_level
& G_LOG_LEVEL_MASK
& ~(G_LOG_LEVEL_DEBUG
|G_LOG_LEVEL_INFO
))) {
4973 #ifdef DEBUG_DUMPCAP
4974 fprintf(stderr
, "%s", msg
);
4977 #ifdef DEBUG_CHILD_DUMPCAP
4978 fprintf(debug_log
, "%s", msg
);
4986 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4987 /* to parent especially formatted if dumpcap running as child. */
4988 if (capture_child
) {
4989 sync_pipe_errmsg_to_parent(2, msg
, "");
4991 fprintf(stderr
, "%s", msg
);
4998 /****************************************************************************************************************/
4999 /* indication report routines */
5003 report_packet_count(unsigned int packet_count
)
5005 char tmp
[SP_DECISIZE
+1+1];
5006 static unsigned int count
= 0;
5008 if (capture_child
) {
5009 g_snprintf(tmp
, sizeof(tmp
), "%u", packet_count
);
5010 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "Packets: %s", tmp
);
5011 pipe_write_block(2, SP_PACKET_COUNT
, tmp
);
5013 count
+= packet_count
;
5014 fprintf(stderr
, "\rPackets: %u ", count
);
5015 /* stderr could be line buffered */
5021 report_new_capture_file(const char *filename
)
5023 if (capture_child
) {
5024 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "File: %s", filename
);
5025 pipe_write_block(2, SP_FILE
, filename
);
5029 * Prevent a SIGINFO handler from writing to the standard error
5030 * while we're doing so; instead, have it just set a flag telling
5031 * us to print that information when we're done.
5034 #endif /* SIGINFO */
5035 fprintf(stderr
, "File: %s\n", filename
);
5036 /* stderr could be line buffered */
5041 * Allow SIGINFO handlers to write.
5046 * If a SIGINFO handler asked us to write out capture counts, do so.
5049 report_counts_for_siginfo();
5050 #endif /* SIGINFO */
5055 report_cfilter_error(capture_options
*capture_opts
, guint i
, const char *errmsg
)
5057 interface_options interface_opts
;
5058 char tmp
[MSG_MAX_LENGTH
+1+6];
5060 if (i
< capture_opts
->ifaces
->len
) {
5061 if (capture_child
) {
5062 g_snprintf(tmp
, sizeof(tmp
), "%u:%s", i
, errmsg
);
5063 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
, "Capture filter error: %s", errmsg
);
5064 pipe_write_block(2, SP_BAD_FILTER
, tmp
);
5067 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5068 * the error message below.
5070 interface_opts
= g_array_index(capture_opts
->ifaces
, interface_options
, i
);
5072 "Invalid capture filter \"%s\" for interface %s!\n"
5074 "That string isn't a valid capture filter (%s).\n"
5075 "See the User's Guide for a description of the capture filter syntax.",
5076 interface_opts
.cfilter
, interface_opts
.name
, errmsg
);
5082 report_capture_error(const char *error_msg
, const char *secondary_error_msg
)
5084 if (capture_child
) {
5085 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
,
5086 "Primary Error: %s", error_msg
);
5087 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
,
5088 "Secondary Error: %s", secondary_error_msg
);
5089 sync_pipe_errmsg_to_parent(2, error_msg
, secondary_error_msg
);
5091 cmdarg_err("%s", error_msg
);
5092 if (secondary_error_msg
[0] != '\0')
5093 cmdarg_err_cont("%s", secondary_error_msg
);
5098 report_packet_drops(guint32 received
, guint32 pcap_drops
, guint32 drops
, guint32 flushed
, guint32 ps_ifdrop
, gchar
*name
)
5100 char tmp
[SP_DECISIZE
+1+1];
5101 guint32 total_drops
= pcap_drops
+ drops
+ flushed
;
5103 g_snprintf(tmp
, sizeof(tmp
), "%u", total_drops
);
5105 if (capture_child
) {
5106 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
,
5107 "Packets received/dropped on interface %s: %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
5108 name
, received
, total_drops
, pcap_drops
, drops
, flushed
, ps_ifdrop
);
5109 /* XXX: Need to provide interface id, changes to consumers required. */
5110 pipe_write_block(2, SP_DROPS
, tmp
);
5113 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
5114 name
, received
, total_drops
, pcap_drops
, drops
, flushed
, ps_ifdrop
,
5115 received
? 100.0 * received
/ (received
+ total_drops
) : 0.0);
5116 /* stderr could be line buffered */
5122 /************************************************************************************************/
5123 /* signal_pipe handling */
5128 signal_pipe_check_running(void)
5130 /* any news from our parent? -> just stop the capture */
5134 /* if we are running standalone, no check required */
5135 if (!capture_child
) {
5139 if (!sig_pipe_name
|| !sig_pipe_handle
) {
5140 /* This shouldn't happen */
5141 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_INFO
,
5142 "Signal pipe: No name or handle");
5147 * XXX - We should have the process ID of the parent (from the "-Z" flag)
5148 * at this point. Should we check to see if the parent is still alive,
5149 * e.g. by using OpenProcess?
5152 result
= PeekNamedPipe(sig_pipe_handle
, NULL
, 0, NULL
, &avail
, NULL
);
5154 if (!result
|| avail
> 0) {
5155 /* peek failed or some bytes really available */
5156 /* (if not piping from stdin this would fail) */
5157 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_INFO
,
5158 "Signal pipe: Stop capture: %s", sig_pipe_name
);
5159 g_log(LOG_DOMAIN_CAPTURE_CHILD
, G_LOG_LEVEL_DEBUG
,
5160 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name
,
5161 sig_pipe_handle
, result
, avail
);
5164 /* pipe ok and no bytes available */
5175 * Editor modelines - http://www.wireshark.org/tools/modelines.html
5180 * indent-tabs-mode: nil
5183 * vi: set shiftwidth=4 tabstop=8 expandtab:
5184 * :indentSize=4:tabSize=8:noTabs=true: