5 * Wireshark - Network traffic analyzer
6 * By Gerald Combs <gerald@wireshark.org>
7 * Copyright 1998 Gerald Combs
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 #include <stdlib.h> /* for exit() */
33 #ifdef HAVE_SYS_TYPES_H
34 # include <sys/types.h>
37 #ifdef HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
41 #ifdef HAVE_NETINET_IN_H
42 #include <netinet/in.h>
45 #ifdef HAVE_SYS_STAT_H
46 # include <sys/stat.h>
61 #ifdef HAVE_ARPA_INET_H
62 #include <arpa/inet.h>
65 #if defined(__APPLE__) && defined(__LP64__)
66 #include <sys/utsname.h>
72 #include <wsutil/crash_info.h>
75 #include "wsutil/wsgetopt.h"
83 # include <sys/prctl.h>
84 # include <sys/capability.h>
87 #include "ringbuffer.h"
88 #include "clopts_common.h"
89 #include "cmdarg_err.h"
90 #include "version_info.h"
92 #include "capture-pcap-util.h"
94 #include "capture-wpcap.h"
100 #include "capture-wpcap.h"
101 #include <wsutil/unicode-utils.h>
108 #ifdef NEED_INET_V6DEFS_H
109 # include "wsutil/inet_v6defs.h"
112 #include <wsutil/privileges.h>
114 #include "sync_pipe.h"
116 #include "capture_opts.h"
117 #include "capture_session.h"
118 #include "capture_ifinfo.h"
119 #include "capture_sync.h"
121 #include "conditions.h"
122 #include "capture_stop_conditions.h"
124 #include "wsutil/tempfile.h"
126 #include "wsutil/file_util.h"
128 #include "ws80211_utils.h"
131 * Get information about libpcap format from "wiretap/libpcap.h".
132 * XXX - can we just use pcap_open_offline() to read the pipe?
134 #include "wiretap/libpcap.h"
136 /**#define DEBUG_DUMPCAP**/
137 /**#define DEBUG_CHILD_DUMPCAP**/
141 #include <conio.h> /* _getch() */
145 #ifdef DEBUG_CHILD_DUMPCAP
146 FILE *debug_log; /* for logging debug messages to */
147 /* a file if DEBUG_CHILD_DUMPCAP */
151 static GAsyncQueue *pcap_queue;
152 static gint64 pcap_queue_bytes;
153 static gint64 pcap_queue_packets;
154 static gint64 pcap_queue_byte_limit = 0;
155 static gint64 pcap_queue_packet_limit = 0;
157 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
159 static gchar *sig_pipe_name = NULL;
160 static HANDLE sig_pipe_handle = NULL;
161 static gboolean signal_pipe_check_running(void);
165 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
166 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
169 /** Stop a low-level capture (stops the capture child). */
170 static void capture_loop_stop(void);
171 /** Close a pipe, or socket if \a from_socket is TRUE */
172 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
176 * Enable kernel BPF JIT compiler if available.
177 * If any calls fail, just drive on - the JIT compiler might not be
178 * enabled, but filtering will still work, and it's not clear what
179 * we could do if the calls fail; should we just report the error
180 * and not continue to capture, should we report it as a warning, or
184 enable_kernel_bpf_jit_compiler(void)
187 static const char file[] = "/proc/sys/net/core/bpf_jit_enable";
189 fd = open(file, O_WRONLY);
193 write(fd, "1", strlen("1"));
199 #if !defined (__linux__)
200 #ifndef HAVE_PCAP_BREAKLOOP
202 * We don't have pcap_breakloop(), which is the only way to ensure that
203 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
204 * won't, if the call to read the next packet or batch of packets is
205 * is interrupted by a signal on UN*X, just go back and try again to
208 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
209 * the signal handler, set a flag to stop capturing; however, without
210 * a guarantee of that sort, we can't guarantee that we'll stop capturing
211 * if the read will be retried and won't time out if no packets arrive.
213 * Therefore, on at least some platforms, we work around the lack of
214 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
215 * to wait for packets to arrive, so that we're probably going to be
216 * blocked in the select() when the signal arrives, and can just bail
217 * out of the loop at that point.
219 * However, we don't want to do that on BSD (because "select()" doesn't work
220 * correctly on BPF devices on at least some releases of some flavors of
221 * BSD), and we don't want to do it on Windows (because "select()" is
222 * something for sockets, not for arbitrary handles). (Note that "Windows"
223 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
224 * using WinPcap, not a UNIX libpcap.)
226 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
227 * on BSD times out even if no packets have arrived, so we'll eventually
228 * exit pcap_dispatch() with an indication that no packets have arrived,
229 * and will break out of the capture loop at that point.
231 * On Windows, we can't send a SIGINT to stop capturing, so none of this
232 * applies in any case.
234 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
235 * want to include it if it's not present on this platform, however.
237 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
238 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
240 # define MUST_DO_SELECT
241 # endif /* avoid select */
242 #endif /* HAVE_PCAP_BREAKLOOP */
244 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
245 * in pcap_dispatch(); on the other hand, select() works just fine there.
246 * Hence we use a select for that come what may.
248 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
249 * internally, and, with TPACKET_V3, once that's supported, it'll
250 * support timeouts, at least as I understand the way the code works.
252 #define MUST_DO_SELECT
255 /** init the capture filter */
258 INITFILTER_BAD_FILTER,
259 INITFILTER_OTHER_ERROR
260 } initfilter_status_t;
263 STATE_EXPECT_REC_HDR,
276 typedef struct _pcap_options {
281 #ifdef MUST_DO_SELECT
282 int pcap_fd; /**< pcap file descriptor */
289 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
290 /**< capture pipe (unix only "input file") */
291 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
292 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
293 struct pcap_hdr cap_pipe_hdr; /**< Pcap header when capturing from a pipe */
294 struct pcaprec_modified_hdr cap_pipe_rechdr; /**< Pcap record header when capturing from a pipe */
296 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
298 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
299 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
300 gboolean cap_pipe_byte_swapped; /**< TRUE if data in the pipe is byte swapped */
302 char * cap_pipe_buf; /**< Pointer to the data buffer we read into */
303 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
304 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
306 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
307 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
309 cap_pipe_state_t cap_pipe_state;
310 cap_pipe_err_t cap_pipe_err;
313 GMutex *cap_pipe_read_mtx;
314 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
318 typedef struct _loop_data {
320 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
321 int err; /**< if non-zero, error seen while capturing */
322 gint packet_count; /**< Number of packets we have already captured */
323 gint packet_max; /**< Number of packets we're supposed to capture - 0 means infinite */
324 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
326 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
332 guint64 bytes_written;
333 guint32 autostop_files;
336 typedef struct _pcap_queue_element {
337 pcap_options *pcap_opts;
338 struct pcap_pkthdr phdr;
340 } pcap_queue_element;
343 * Standard secondary message for unexpected errors.
345 static const char please_report[] =
346 "Please report this to the Wireshark developers.\n"
347 "http://bugs.wireshark.org/\n"
348 "(This is not a crash; please do not report it as such.)";
351 * This needs to be static, so that the SIGINT handler can clear the "go"
354 static loop_data global_ld;
358 * Timeout, in milliseconds, for reads from the stream of captured packets
359 * from a capture device.
361 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
362 * 64-bit applications, with sub-second timeouts not to work. The bug is
363 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
365 #if defined(__APPLE__) && defined(__LP64__)
366 static gboolean need_timeout_workaround;
368 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
370 #define CAP_READ_TIMEOUT 250
374 * Timeout, in microseconds, for reads from the stream of captured packets
375 * from a pipe. Pipes don't have the same problem that BPF devices do
376 * in OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
377 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
378 * of the offending versions of Snow Leopard.
380 * On Windows this value is converted to milliseconds and passed to
381 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
382 * will return immediately.
385 #define PIPE_READ_TIMEOUT 100000
387 #define PIPE_READ_TIMEOUT 250000
390 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
393 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
394 const char *message, gpointer user_data _U_);
396 /* capture related options */
397 static capture_options global_capture_opts;
398 static gboolean quiet = FALSE;
399 static gboolean use_threads = FALSE;
400 static guint64 start_time;
402 static void capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
404 static void capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
406 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
407 int err, gboolean is_close);
409 static void WS_MSVC_NORETURN exit_main(int err) G_GNUC_NORETURN;
411 static void report_new_capture_file(const char *filename);
412 static void report_packet_count(unsigned int packet_count);
413 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, gchar *name);
414 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
415 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
417 #define MSG_MAX_LENGTH 4096
419 /* Copied from pcapio.c libpcap_write_interface_statistics_block()*/
421 create_timestamp(void) {
431 * Current time, represented as 100-nanosecond intervals since
432 * January 1, 1601, 00:00:00 UTC.
434 * I think DWORD might be signed, so cast both parts of "now"
435 * to guint32 so that the sign bit doesn't get treated specially.
437 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
438 * might want to use instead.
440 GetSystemTimeAsFileTime(&now);
441 timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
442 (guint32)now.dwLowDateTime;
445 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
451 * Subtract difference, in microseconds, between January 1, 1601
452 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
454 timestamp -= G_GINT64_CONSTANT(11644473600000000U);
457 * Current time, represented as seconds and microseconds since
458 * January 1, 1970, 00:00:00 UTC.
460 gettimeofday(&now, NULL);
463 * Convert to delta in microseconds.
465 timestamp = (guint64)(now.tv_sec) * 1000000 +
466 (guint64)(now.tv_usec);
472 print_usage(gboolean print_ver)
479 "Dumpcap " VERSION "%s\n"
480 "Capture network packets and dump them into a pcapng file.\n"
481 "See http://www.wireshark.org for more information.\n",
482 wireshark_svnversion);
486 fprintf(output, "\nUsage: dumpcap [options] ...\n");
487 fprintf(output, "\n");
488 fprintf(output, "Capture interface:\n");
489 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
490 " or for remote capturing, use one of these formats:\n"
491 " rpcap://<host>/<interface>\n"
492 " TCP@<host>:<port>\n");
493 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
494 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
495 fprintf(output, " -p don't capture in promiscuous mode\n");
496 #ifdef HAVE_PCAP_CREATE
497 fprintf(output, " -I capture in monitor mode, if available\n");
499 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
500 fprintf(output, " -B <buffer size> size of kernel buffer in MB (def: %dMB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
502 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
503 fprintf(output, " -D print list of interfaces and exit\n");
504 fprintf(output, " -L print list of link-layer types of iface and exit\n");
505 #ifdef HAVE_BPF_IMAGE
506 fprintf(output, " -d print generated BPF code for capture filter\n");
508 fprintf(output, " -k set channel on wifi interface <freq>,[<type>]\n");
509 fprintf(output, " -S print statistics for each interface once per second\n");
510 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
511 fprintf(output, "\n");
512 #ifdef HAVE_PCAP_REMOTE
513 fprintf(output, "RPCAP options:\n");
514 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
515 fprintf(output, " -u use UDP for RPCAP data transfer\n");
516 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
517 #ifdef HAVE_PCAP_SETSAMPLING
518 fprintf(output, " -m <sampling type> use packet sampling\n");
519 fprintf(output, " count:NUM - capture one packet of every NUM\n");
520 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
523 fprintf(output, "Stop conditions:\n");
524 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
525 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
526 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
527 fprintf(output, " files:NUM - stop after NUM files\n");
528 /*fprintf(output, "\n");*/
529 fprintf(output, "Output (files):\n");
530 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
531 fprintf(output, " -g enable group read access on the output file(s)\n");
532 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
533 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
534 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
535 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
536 fprintf(output, " -P use libpcap format instead of pcapng\n");
537 fprintf(output, " --capture-comment <comment>\n");
538 fprintf(output, " add a capture comment to the output file\n");
539 fprintf(output, " (only for pcapng)\n");
540 fprintf(output, "\n");
541 fprintf(output, "Miscellaneous:\n");
542 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
543 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
544 fprintf(output, " within dumpcap\n");
545 fprintf(output, " -t use a separate thread per interface\n");
546 fprintf(output, " -q don't report packet capture counts\n");
547 fprintf(output, " -v print version information and exit\n");
548 fprintf(output, " -h display this help and exit\n");
549 fprintf(output, "\n");
550 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
551 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
552 fprintf(output, "\n");
553 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
557 show_version(GString *comp_info_str, GString *runtime_info_str)
560 "Dumpcap " VERSION "%s\n"
565 "See http://www.wireshark.org for more information.\n",
566 wireshark_svnversion, get_copyright_info(), comp_info_str->str, runtime_info_str->str);
570 * Report an error in command-line arguments.
573 cmdarg_err(const char *fmt, ...)
579 /* Generate a 'special format' message back to parent */
581 msg = g_strdup_vprintf(fmt, ap);
582 sync_pipe_errmsg_to_parent(2, msg, "");
587 fprintf(stderr, "dumpcap: ");
588 vfprintf(stderr, fmt, ap);
589 fprintf(stderr, "\n");
595 * Report additional information for an error in command-line arguments.
598 cmdarg_err_cont(const char *fmt, ...)
605 msg = g_strdup_vprintf(fmt, ap);
606 sync_pipe_errmsg_to_parent(2, msg, "");
611 vfprintf(stderr, fmt, ap);
612 fprintf(stderr, "\n");
619 #if 0 /* Set to enable capability debugging */
620 /* see 'man cap_to_text()' for explanation of output */
621 /* '=' means 'all= ' ie: no capabilities */
622 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
624 print_caps(const char *pfx) {
625 cap_t caps = cap_get_proc();
626 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
627 "%s: EUID: %d Capabilities: %s", pfx,
628 geteuid(), cap_to_text(caps, NULL));
631 print_caps(const char *pfx _U_) {
636 relinquish_all_capabilities(void)
638 /* Drop any and all capabilities this process may have. */
639 /* Allowed whether or not process has any privileges. */
640 cap_t caps = cap_init(); /* all capabilities initialized to off */
641 print_caps("Pre-clear");
642 if (cap_set_proc(caps)) {
643 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
645 print_caps("Post-clear");
651 open_capture_device(interface_options *interface_opts,
652 char (*open_err_str)[PCAP_ERRBUF_SIZE])
655 #ifdef HAVE_PCAP_CREATE
658 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
659 struct pcap_rmtauth auth;
662 /* Open the network interface to capture from it.
663 Some versions of libpcap may put warnings into the error buffer
664 if they succeed; to tell if that's happened, we have to clear
665 the error buffer, and check if it's still a null string. */
666 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Entering open_capture_device().");
667 (*open_err_str)[0] = '\0';
668 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
670 * If we're opening a remote device, use pcap_open(); that's currently
671 * the only open routine that supports remote devices.
673 if (strncmp (interface_opts->name, "rpcap://", 8) == 0) {
674 auth.type = interface_opts->auth_type == CAPTURE_AUTH_PWD ?
675 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
676 auth.username = interface_opts->auth_username;
677 auth.password = interface_opts->auth_password;
679 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
680 "Calling pcap_open() using name %s, snaplen %d, promisc_mode %d, datatx_udp %d, nocap_rpcap %d.",
681 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode,
682 interface_opts->datatx_udp, interface_opts->nocap_rpcap);
683 pcap_h = pcap_open(interface_opts->name, interface_opts->snaplen,
685 (interface_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
686 (interface_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
687 (interface_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
688 CAP_READ_TIMEOUT, &auth, *open_err_str);
689 if (pcap_h == NULL) {
690 /* Error - did pcap actually supply an error message? */
691 if ((*open_err_str)[0] == '\0') {
692 /* Work around known WinPcap bug wherein no error message is
693 filled in on a failure to open an rpcap: URL. */
694 g_strlcpy(*open_err_str,
695 "Unknown error (pcap bug; actual error cause not reported)",
696 sizeof *open_err_str);
699 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
700 "pcap_open() returned %p.", (void *)pcap_h);
705 * If we're not opening a remote device, use pcap_create() and
706 * pcap_activate() if we have them, so that we can set the buffer
707 * size, otherwise use pcap_open_live().
709 #ifdef HAVE_PCAP_CREATE
710 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
711 "Calling pcap_create() using %s.", interface_opts->name);
712 pcap_h = pcap_create(interface_opts->name, *open_err_str);
713 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
714 "pcap_create() returned %p.", (void *)pcap_h);
715 if (pcap_h != NULL) {
716 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
717 "Calling pcap_set_snaplen() with snaplen %d.", interface_opts->snaplen);
718 pcap_set_snaplen(pcap_h, interface_opts->snaplen);
719 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
720 "Calling pcap_set_promisc() with promisc_mode %d.", interface_opts->promisc_mode);
721 pcap_set_promisc(pcap_h, interface_opts->promisc_mode);
722 pcap_set_timeout(pcap_h, CAP_READ_TIMEOUT);
724 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
725 "buffersize %d.", interface_opts->buffer_size);
726 if (interface_opts->buffer_size != 0) {
727 pcap_set_buffer_size(pcap_h, interface_opts->buffer_size * 1024 * 1024);
729 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
730 "monitor_mode %d.", interface_opts->monitor_mode);
731 if (interface_opts->monitor_mode)
732 pcap_set_rfmon(pcap_h, 1);
733 err = pcap_activate(pcap_h);
734 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
735 "pcap_activate() returned %d.", err);
737 /* Failed to activate, set to NULL */
738 if (err == PCAP_ERROR)
739 g_strlcpy(*open_err_str, pcap_geterr(pcap_h), sizeof *open_err_str);
741 g_strlcpy(*open_err_str, pcap_statustostr(err), sizeof *open_err_str);
747 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
748 "pcap_open_live() calling using name %s, snaplen %d, promisc_mode %d.",
749 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode);
750 pcap_h = pcap_open_live(interface_opts->name, interface_opts->snaplen,
751 interface_opts->promisc_mode, CAP_READ_TIMEOUT,
753 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
754 "pcap_open_live() returned %p.", (void *)pcap_h);
757 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "open_capture_device %s : %s", pcap_h ? "SUCCESS" : "FAILURE", interface_opts->name);
762 get_capture_device_open_failure_messages(const char *open_err_str,
768 char *errmsg, size_t errmsg_len,
769 char *secondary_errmsg,
770 size_t secondary_errmsg_len)
773 const char *libpcap_warn;
774 static const char ppamsg[] = "can't find PPA for ";
777 g_snprintf(errmsg, (gulong) errmsg_len,
778 "The capture session could not be initiated (%s).", open_err_str);
781 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
783 "In order to capture packets, WinPcap must be installed; see\n"
785 " http://www.winpcap.org/\n"
789 " http://www.mirrors.wiretapped.net/security/packet-capture/winpcap/\n"
793 " http://winpcap.cs.pu.edu.tw/\n"
795 "for a downloadable version of WinPcap and for instructions on how to install\n"
798 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
800 "Please check that \"%s\" is the proper interface.\n"
803 "Help can be found at:\n"
805 " http://wiki.wireshark.org/WinPcap\n"
806 " http://wiki.wireshark.org/CaptureSetup\n",
810 /* If we got a "can't find PPA for X" message, warn the user (who
811 is running dumpcap on HP-UX) that they don't have a version of
812 libpcap that properly handles HP-UX (libpcap 0.6.x and later
813 versions, which properly handle HP-UX, say "can't find /dev/dlpi
814 PPA for X" rather than "can't find PPA for X"). */
815 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
818 "You are running (T)Wireshark with a version of the libpcap library\n"
819 "that doesn't handle HP-UX network devices well; this means that\n"
820 "(T)Wireshark may not be able to capture packets.\n"
822 "To fix this, you should install libpcap 0.6.2, or a later version\n"
823 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
824 "packaged binary form from the Software Porting And Archive Centre\n"
825 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
826 "at the URL lists a number of mirror sites.";
830 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
831 "Please check to make sure you have sufficient permissions, and that you have "
832 "the proper interface or pipe specified.%s", libpcap_warn);
836 /* Set the data link type on a pcap. */
838 set_pcap_linktype(pcap_t *pcap_h, int linktype,
839 #ifdef HAVE_PCAP_SET_DATALINK
844 char *errmsg, size_t errmsg_len,
845 char *secondary_errmsg, size_t secondary_errmsg_len)
847 char *set_linktype_err_str;
850 return TRUE; /* just use the default */
851 #ifdef HAVE_PCAP_SET_DATALINK
852 if (pcap_set_datalink(pcap_h, linktype) == 0)
853 return TRUE; /* no error */
854 set_linktype_err_str = pcap_geterr(pcap_h);
856 /* Let them set it to the type it is; reject any other request. */
857 if (get_pcap_linktype(pcap_h, name) == linktype)
858 return TRUE; /* no error */
859 set_linktype_err_str =
860 "That DLT isn't one of the DLTs supported by this device";
862 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
863 set_linktype_err_str);
865 * If the error isn't "XXX is not one of the DLTs supported by this device",
866 * tell the user to tell the Wireshark developers about it.
868 if (strstr(set_linktype_err_str, "is not one of the DLTs supported by this device") == NULL)
869 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
871 secondary_errmsg[0] = '\0';
876 compile_capture_filter(const char *iface, pcap_t *pcap_h,
877 struct bpf_program *fcode, const char *cfilter)
879 bpf_u_int32 netnum, netmask;
880 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
882 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
884 * Well, we can't get the netmask for this interface; it's used
885 * only for filters that check for broadcast IP addresses, so
886 * we just punt and use 0. It might be nice to warn the user,
887 * but that's a pain in a GUI application, as it'd involve popping
888 * up a message box, and it's not clear how often this would make
889 * a difference (only filters that check for IP broadcast addresses
893 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
898 * Sigh. Older versions of libpcap don't properly declare the
899 * third argument to pcap_compile() as a const pointer. Cast
902 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
907 #ifdef HAVE_BPF_IMAGE
909 show_filter_code(capture_options *capture_opts)
911 interface_options interface_opts;
913 gchar open_err_str[PCAP_ERRBUF_SIZE];
914 char errmsg[MSG_MAX_LENGTH+1];
915 char secondary_errmsg[MSG_MAX_LENGTH+1];
916 struct bpf_program fcode;
917 struct bpf_insn *insn;
921 for (j = 0; j < capture_opts->ifaces->len; j++) {
922 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
923 pcap_h = open_capture_device(&interface_opts, &open_err_str);
924 if (pcap_h == NULL) {
925 /* Open failed; get messages */
926 get_capture_device_open_failure_messages(open_err_str,
928 errmsg, sizeof errmsg,
930 sizeof secondary_errmsg);
931 /* And report them */
932 report_capture_error(errmsg, secondary_errmsg);
936 /* Set the link-layer type. */
937 if (!set_pcap_linktype(pcap_h, interface_opts.linktype, interface_opts.name,
938 errmsg, sizeof errmsg,
939 secondary_errmsg, sizeof secondary_errmsg)) {
941 report_capture_error(errmsg, secondary_errmsg);
945 /* OK, try to compile the capture filter. */
946 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
947 interface_opts.cfilter)) {
949 report_cfilter_error(capture_opts, j, errmsg);
954 /* Now print the filter code. */
955 insn = fcode.bf_insns;
957 for (i = 0; i < fcode.bf_len; insn++, i++)
958 printf("%s\n", bpf_image(insn, i));
960 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
961 /* to remove any suid privileges. */
962 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
963 /* (euid/egid have already previously been set to ruid/rgid. */
964 /* (See comment in main() for details) */
966 relinquish_special_privs_perm();
968 relinquish_all_capabilities();
971 /* Let our parent know we succeeded. */
972 pipe_write_block(2, SP_SUCCESS, NULL);
979 * capture_interface_list() is expected to do the right thing to get
980 * a list of interfaces.
982 * In most of the programs in the Wireshark suite, "the right thing"
983 * is to run dumpcap and ask it for the list, because dumpcap may
984 * be the only program in the suite with enough privileges to get
987 * In dumpcap itself, however, we obviously can't run dumpcap to
988 * ask for the list. Therefore, our capture_interface_list() should
989 * just call get_interface_list().
992 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
994 return get_interface_list(err, err_str);
998 * Get the data-link type for a libpcap device.
999 * This works around AIX 5.x's non-standard and incompatible-with-the-
1000 * rest-of-the-universe libpcap.
1003 get_pcap_linktype(pcap_t *pch, const char *devicename
1011 const char *ifacename;
1014 linktype = pcap_datalink(pch);
1018 * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
1019 * rather than DLT_ values for link-layer types; the ifType values
1020 * for LAN devices are:
1027 * and the ifType value for a loopback device is 24.
1029 * The AIX names for LAN devices begin with:
1036 * and the AIX names for loopback devices begin with "lo".
1038 * (The difference between "Ethernet" and "802.3" is presumably
1039 * whether packets have an Ethernet header, with a packet type,
1040 * or an 802.3 header, with a packet length, followed by an 802.2
1041 * header and possibly a SNAP header.)
1043 * If the device name matches "linktype" interpreted as an ifType
1044 * value, rather than as a DLT_ value, we will assume this is AIX's
1045 * non-standard, incompatible libpcap, rather than a standard libpcap,
1046 * and will map the link-layer type to the standard DLT_ value for
1047 * that link-layer type, as that's what the rest of Wireshark expects.
1049 * (This means the capture files won't be readable by a tcpdump
1050 * linked with AIX's non-standard libpcap, but so it goes. They
1051 * *will* be readable by standard versions of tcpdump, Wireshark,
1054 * XXX - if we conclude we're using AIX libpcap, should we also
1055 * set a flag to cause us to assume the time stamps are in
1056 * seconds-and-nanoseconds form, and to convert them to
1057 * seconds-and-microseconds form before processing them and
1062 * Find the last component of the device name, which is the
1065 ifacename = strchr(devicename, '/');
1066 if (ifacename == NULL)
1067 ifacename = devicename;
1069 /* See if it matches any of the LAN device names. */
1070 if (strncmp(ifacename, "en", 2) == 0) {
1071 if (linktype == 6) {
1073 * That's the RFC 1573 value for Ethernet; map it to DLT_EN10MB.
1077 } else if (strncmp(ifacename, "et", 2) == 0) {
1078 if (linktype == 7) {
1080 * That's the RFC 1573 value for 802.3; map it to DLT_EN10MB.
1081 * (libpcap, tcpdump, Wireshark, etc. don't care if it's Ethernet
1086 } else if (strncmp(ifacename, "tr", 2) == 0) {
1087 if (linktype == 9) {
1089 * That's the RFC 1573 value for 802.5 (Token Ring); map it to
1090 * DLT_IEEE802, which is what's used for Token Ring.
1094 } else if (strncmp(ifacename, "fi", 2) == 0) {
1095 if (linktype == 15) {
1097 * That's the RFC 1573 value for FDDI; map it to DLT_FDDI.
1101 } else if (strncmp(ifacename, "lo", 2) == 0) {
1102 if (linktype == 24) {
1104 * That's the RFC 1573 value for "software loopback" devices; map it
1105 * to DLT_NULL, which is what's used for loopback devices on BSD.
1115 static data_link_info_t *
1116 create_data_link_info(int dlt)
1118 data_link_info_t *data_link_info;
1121 data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
1122 data_link_info->dlt = dlt;
1123 text = pcap_datalink_val_to_name(dlt);
1125 data_link_info->name = g_strdup(text);
1127 data_link_info->name = g_strdup_printf("DLT %d", dlt);
1128 text = pcap_datalink_val_to_description(dlt);
1130 data_link_info->description = g_strdup(text);
1132 data_link_info->description = NULL;
1133 return data_link_info;
1137 * Get the capabilities of a network device.
1139 static if_capabilities_t *
1140 get_if_capabilities(const char *devicename, gboolean monitor_mode
1141 #ifndef HAVE_PCAP_CREATE
1146 if_capabilities_t *caps;
1147 char errbuf[PCAP_ERRBUF_SIZE];
1149 #ifdef HAVE_PCAP_CREATE
1153 #ifdef HAVE_PCAP_LIST_DATALINKS
1157 data_link_info_t *data_link_info;
1160 * Allocate the interface capabilities structure.
1162 caps = (if_capabilities_t *)g_malloc(sizeof *caps);
1165 * WinPcap 4.1.2, and possibly earlier versions, have a bug
1166 * wherein, when an open with an rpcap: URL fails, the error
1167 * message for the error is not copied to errbuf and whatever
1168 * on-the-stack junk is in errbuf is treated as the error
1171 * To work around that (and any other bugs of that sort, we
1172 * initialize errbuf to an empty string. If we get an error
1173 * and the string is empty, we report it as an unknown error.
1174 * (If we *don't* get an error, and the string is *non*-empty,
1175 * that could be a warning returned, such as "can't turn
1176 * promiscuous mode on"; we currently don't do so.)
1179 #ifdef HAVE_PCAP_OPEN
1180 pch = pcap_open(devicename, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1181 caps->can_set_rfmon = FALSE;
1183 if (err_str != NULL)
1184 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1188 #elif defined(HAVE_PCAP_CREATE)
1189 pch = pcap_create(devicename, errbuf);
1191 if (err_str != NULL)
1192 *err_str = g_strdup(errbuf);
1196 status = pcap_can_set_rfmon(pch);
1199 if (status == PCAP_ERROR)
1200 *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
1203 *err_str = g_strdup(pcap_statustostr(status));
1209 caps->can_set_rfmon = FALSE;
1210 else if (status == 1) {
1211 caps->can_set_rfmon = TRUE;
1213 pcap_set_rfmon(pch, 1);
1215 if (err_str != NULL) {
1216 *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
1224 status = pcap_activate(pch);
1226 /* Error. We ignore warnings (status > 0). */
1227 if (err_str != NULL) {
1228 if (status == PCAP_ERROR)
1229 *err_str = g_strdup_printf("pcap_activate() failed: %s",
1232 *err_str = g_strdup(pcap_statustostr(status));
1239 pch = pcap_open_live(devicename, MIN_PACKET_SIZE, 0, 0, errbuf);
1240 caps->can_set_rfmon = FALSE;
1242 if (err_str != NULL)
1243 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1248 deflt = get_pcap_linktype(pch, devicename);
1249 #ifdef HAVE_PCAP_LIST_DATALINKS
1250 nlt = pcap_list_datalinks(pch, &linktypes);
1251 if (nlt == 0 || linktypes == NULL) {
1253 if (err_str != NULL)
1254 *err_str = NULL; /* an empty list doesn't mean an error */
1258 caps->data_link_types = NULL;
1259 for (i = 0; i < nlt; i++) {
1260 data_link_info = create_data_link_info(linktypes[i]);
1263 * XXX - for 802.11, make the most detailed 802.11
1264 * version the default, rather than the one the
1265 * device has as the default?
1267 if (linktypes[i] == deflt)
1268 caps->data_link_types = g_list_prepend(caps->data_link_types,
1271 caps->data_link_types = g_list_append(caps->data_link_types,
1274 #ifdef HAVE_PCAP_FREE_DATALINKS
1275 pcap_free_datalinks(linktypes);
1278 * In Windows, there's no guarantee that if you have a library
1279 * built with one version of the MSVC++ run-time library, and
1280 * it returns a pointer to allocated data, you can free that
1281 * data from a program linked with another version of the
1282 * MSVC++ run-time library.
1284 * This is not an issue on UN*X.
1286 * See the mail threads starting at
1288 * http://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
1292 * http://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
1295 #define xx_free free /* hack so checkAPIs doesn't complain */
1298 #endif /* HAVE_PCAP_FREE_DATALINKS */
1299 #else /* HAVE_PCAP_LIST_DATALINKS */
1301 data_link_info = create_data_link_info(deflt);
1302 caps->data_link_types = g_list_append(caps->data_link_types,
1304 #endif /* HAVE_PCAP_LIST_DATALINKS */
1308 if (err_str != NULL)
1313 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
1315 * Output a machine readable list of the interfaces
1316 * This list is retrieved by the sync_interface_list_open() function
1317 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
1320 print_machine_readable_interfaces(GList *if_list)
1327 char addr_str[ADDRSTRLEN];
1329 if (capture_child) {
1330 /* Let our parent know we succeeded. */
1331 pipe_write_block(2, SP_SUCCESS, NULL);
1334 i = 1; /* Interface id number */
1335 for (if_entry = g_list_first(if_list); if_entry != NULL;
1336 if_entry = g_list_next(if_entry)) {
1337 if_info = (if_info_t *)if_entry->data;
1338 printf("%d. %s\t", i++, if_info->name);
1341 * Print the contents of the if_entry struct in a parseable format.
1342 * Each if_entry element is tab-separated. Addresses are comma-
1345 /* XXX - Make sure our description doesn't contain a tab */
1346 if (if_info->vendor_description != NULL)
1347 printf("%s\t", if_info->vendor_description);
1351 /* XXX - Make sure our friendly name doesn't contain a tab */
1352 if (if_info->friendly_name != NULL)
1353 printf("%s\t", if_info->friendly_name);
1357 printf("%u\t", if_info->type);
1359 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
1360 addr = g_slist_next(addr)) {
1361 if (addr != g_slist_nth(if_info->addrs, 0))
1364 if_addr = (if_addr_t *)addr->data;
1365 switch(if_addr->ifat_type) {
1367 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
1369 printf("%s", addr_str);
1371 printf("<unknown IPv4>");
1375 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
1376 addr_str, ADDRSTRLEN)) {
1377 printf("%s", addr_str);
1379 printf("<unknown IPv6>");
1383 printf("<type unknown %u>", if_addr->ifat_type);
1387 if (if_info->loopback)
1388 printf("\tloopback");
1390 printf("\tnetwork");
1397 * If you change the machine-readable output format of this function,
1398 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
1401 print_machine_readable_if_capabilities(if_capabilities_t *caps)
1404 data_link_info_t *data_link_info;
1405 const gchar *desc_str;
1407 if (capture_child) {
1408 /* Let our parent know we succeeded. */
1409 pipe_write_block(2, SP_SUCCESS, NULL);
1412 if (caps->can_set_rfmon)
1416 for (lt_entry = caps->data_link_types; lt_entry != NULL;
1417 lt_entry = g_list_next(lt_entry)) {
1418 data_link_info = (data_link_info_t *)lt_entry->data;
1419 if (data_link_info->description != NULL)
1420 desc_str = data_link_info->description;
1422 desc_str = "(not supported)";
1423 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
1433 /* Print the number of packets captured for each interface until we're killed. */
1435 print_statistics_loop(gboolean machine_readable)
1437 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1443 char errbuf[PCAP_ERRBUF_SIZE];
1444 struct pcap_stat ps;
1446 if_list = get_interface_list(&err, &err_str);
1447 if (if_list == NULL) {
1449 case CANT_GET_INTERFACE_LIST:
1450 case DONT_HAVE_PCAP:
1451 cmdarg_err("%s", err_str);
1455 case NO_INTERFACES_FOUND:
1456 cmdarg_err("There are no interfaces on which a capture can be done");
1462 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1463 if_info = (if_info_t *)if_entry->data;
1464 #ifdef HAVE_PCAP_OPEN
1465 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1467 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1471 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
1472 if_stat->name = g_strdup(if_info->name);
1474 stat_list = g_list_append(stat_list, if_stat);
1479 cmdarg_err("There are no interfaces on which a capture can be done");
1483 if (capture_child) {
1484 /* Let our parent know we succeeded. */
1485 pipe_write_block(2, SP_SUCCESS, NULL);
1488 if (!machine_readable) {
1489 printf("%-15s %10s %10s\n", "Interface", "Received",
1493 global_ld.go = TRUE;
1494 while (global_ld.go) {
1495 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1496 if_stat = (if_stat_t *)stat_entry->data;
1497 pcap_stats(if_stat->pch, &ps);
1499 if (!machine_readable) {
1500 printf("%-15s %10u %10u\n", if_stat->name,
1501 ps.ps_recv, ps.ps_drop);
1503 printf("%s\t%u\t%u\n", if_stat->name,
1504 ps.ps_recv, ps.ps_drop);
1515 /* XXX - Not reached. Should we look for 'q' in stdin? */
1516 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1517 if_stat = (if_stat_t *)stat_entry->data;
1518 pcap_close(if_stat->pch);
1519 g_free(if_stat->name);
1522 g_list_free(stat_list);
1523 free_interface_list(if_list);
1531 capture_cleanup_handler(DWORD dwCtrlType)
1533 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1534 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1535 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1536 like SIGTERM at least when the machine's shutting down.
1538 For now, if we're running as a command rather than a capture child,
1539 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1540 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1541 in that way on UN*X.
1543 If we're not running as a capture child, we might be running as
1544 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1545 user logs out. (XXX - can we explicitly check whether we're
1546 running as a service?) */
1548 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1549 "Console: Control signal");
1550 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1551 "Console: Control signal, CtrlType: %u", dwCtrlType);
1553 /* Keep capture running if we're a service and a user logs off */
1554 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1555 capture_loop_stop();
1563 capture_cleanup_handler(int signum _U_)
1565 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1566 SIGTERM. We assume that if the user wanted it to keep running
1567 after they logged out, they'd have nohupped it. */
1569 /* Note: don't call g_log() in the signal handler: if we happened to be in
1570 * g_log() in process context when the signal came in, g_log will detect
1571 * the "recursion" and abort.
1574 capture_loop_stop();
1580 report_capture_count(gboolean reportit)
1582 /* Don't print this if we're a capture child. */
1583 if (!capture_child && reportit) {
1584 fprintf(stderr, "\rPackets captured: %u\n", global_ld.packet_count);
1585 /* stderr could be line buffered */
1593 report_counts_for_siginfo(void)
1595 report_capture_count(quiet);
1596 infoprint = FALSE; /* we just reported it */
1600 report_counts_siginfo(int signum _U_)
1602 int sav_errno = errno;
1604 /* If we've been told to delay printing, just set a flag asking
1605 that we print counts (if we're supposed to), otherwise print
1606 the count of packets captured (if we're supposed to). */
1610 report_counts_for_siginfo();
1613 #endif /* SIGINFO */
1616 exit_main(int status)
1619 /* Shutdown windows sockets */
1622 /* can be helpful for debugging */
1623 #ifdef DEBUG_DUMPCAP
1624 printf("Press any key\n");
1635 * If we were linked with libcap (not related to libpcap), make sure we have
1636 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1637 * (See comment in main() for details)
1640 relinquish_privs_except_capture(void)
1642 /* If 'started_with_special_privs' (ie: suid) then enable for
1643 * ourself the NET_ADMIN and NET_RAW capabilities and then
1644 * drop our suid privileges.
1646 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1647 * stuff we don't need (and shouldn't have).
1648 * CAP_NET_RAW: Packet capture (raw sockets).
1651 if (started_with_special_privs()) {
1652 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1653 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1655 cap_t caps = cap_init(); /* all capabilities initialized to off */
1657 print_caps("Pre drop, pre set");
1659 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1660 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1663 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1664 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1666 if (cap_set_proc(caps)) {
1667 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1669 print_caps("Pre drop, post set");
1671 relinquish_special_privs_perm();
1673 print_caps("Post drop, pre set");
1674 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1675 if (cap_set_proc(caps)) {
1676 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1678 print_caps("Post drop, post set");
1684 #endif /* HAVE_LIBCAP */
1686 /* Take care of byte order in the libpcap headers read from pipes.
1687 * (function taken from wiretap/libpcap.c) */
1689 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1692 /* Byte-swap the record header fields. */
1693 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
1694 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
1695 rechdr->incl_len = BSWAP32(rechdr->incl_len);
1696 rechdr->orig_len = BSWAP32(rechdr->orig_len);
1699 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1700 swapped, in order to match the BPF header layout.
1702 Unfortunately, some files were, according to a comment in the "libpcap"
1703 source, written with version 2.3 in their headers but without the
1704 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1705 would make no sense - we assume that we need to swap them. */
1706 if (hdr->version_major == 2 &&
1707 (hdr->version_minor < 3 ||
1708 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1711 temp = rechdr->orig_len;
1712 rechdr->orig_len = rechdr->incl_len;
1713 rechdr->incl_len = temp;
1717 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1721 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1725 return recv(pipe_fd, buf, (int)sz, 0);
1730 return ws_read(pipe_fd, buf, sz);
1736 * Thread function that reads from a pipe and pushes the data
1737 * to the main application thread.
1740 * XXX Right now we use async queues for basic signaling. The main thread
1741 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1742 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1743 * Iff the read is successful cap_pipe_read pushes an item onto
1744 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1745 * the queues themselves (yet).
1747 * We might want to move some of the cap_pipe_dispatch logic here so that
1748 * we can let cap_thread_read run independently, queuing up multiple reads
1749 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1751 static void *cap_thread_read(void *arg)
1753 pcap_options *pcap_opts;
1756 DWORD b, last_err, bytes_read;
1762 pcap_opts = (pcap_options *)arg;
1763 while (pcap_opts->cap_pipe_err == PIPOK) {
1764 g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1765 g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1767 while (bytes_read < pcap_opts->cap_pipe_bytes_to_read) {
1768 if ((pcap_opts->from_cap_socket)
1774 b = cap_pipe_read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1775 pcap_opts->cap_pipe_bytes_to_read - bytes_read, pcap_opts->from_cap_socket);
1778 pcap_opts->cap_pipe_err = PIPEOF;
1782 pcap_opts->cap_pipe_err = PIPERR;
1793 /* If we try to use read() on a named pipe on Windows with partial
1794 * data it appears to return EOF.
1796 res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1797 pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1802 last_err = GetLastError();
1803 if (last_err == ERROR_MORE_DATA) {
1805 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1806 pcap_opts->cap_pipe_err = PIPEOF;
1810 pcap_opts->cap_pipe_err = PIPERR;
1813 } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1814 pcap_opts->cap_pipe_err = PIPEOF;
1821 pcap_opts->cap_pipe_bytes_read = bytes_read;
1822 if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1823 g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1825 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1831 /* Provide select() functionality for a single file descriptor
1832 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1834 * Returns the same values as select.
1837 cap_pipe_select(int pipe_fd)
1840 struct timeval timeout;
1843 FD_SET(pipe_fd, &rfds);
1845 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1846 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1848 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1851 #define DEF_TCP_PORT 19000
1854 cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errmsgl)
1856 char *sockname = pipename + 4;
1857 struct sockaddr_in sa;
1864 memset(&sa, 0, sizeof(sa));
1866 p = strchr(sockname, ':');
1868 len = strlen(sockname);
1869 port = DEF_TCP_PORT;
1873 port = strtoul(p + 1, &p, 10);
1874 if (*p || port > 65535) {
1883 strncpy(buf, sockname, len);
1885 if (inet_pton(AF_INET, buf, &sa.sin_addr) <= 0) {
1889 sa.sin_family = AF_INET;
1890 sa.sin_port = htons((u_short)port);
1892 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1893 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1895 LPTSTR errorText = NULL;
1898 lastError = WSAGetLastError();
1899 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1900 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1901 FORMAT_MESSAGE_IGNORE_INSERTS,
1902 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1903 (LPTSTR)&errorText, 0, NULL);
1905 g_snprintf(errmsg, errmsgl,
1906 "The capture session could not be initiated due to the socket error: \n"
1908 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
1910 LocalFree(errorText);
1912 " %d: %s", errno, strerror(errno));
1914 pcap_opts->cap_pipe_err = PIPERR;
1917 cap_pipe_close(fd, TRUE);
1921 pcap_opts->from_cap_socket = TRUE;
1925 g_snprintf(errmsg, errmsgl,
1926 "The capture session could not be initiated because\n"
1927 "\"%s\" is not a valid socket specification", pipename);
1928 pcap_opts->cap_pipe_err = PIPERR;
1932 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1936 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1940 closesocket(pipe_fd);
1947 /* Mimic pcap_open_live() for pipe captures
1949 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1950 * open it, and read the header.
1952 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1953 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1955 cap_pipe_open_live(char *pipename,
1956 pcap_options *pcap_opts,
1957 struct pcap_hdr *hdr,
1958 char *errmsg, int errmsgl)
1961 ws_statb64 pipe_stat;
1962 struct sockaddr_un sa;
1972 pcap_opts->cap_pipe_fd = -1;
1974 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
1976 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1979 * XXX - this blocks until a pcap per-file header has been written to
1980 * the pipe, so it could block indefinitely.
1982 if (strcmp(pipename, "-") == 0) {
1984 fd = 0; /* read from stdin */
1986 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1988 } else if (!strncmp(pipename, "TCP@", 4)) {
1989 if ((fd = cap_open_socket(pipename, pcap_opts, errmsg, errmsgl)) < 0) {
1994 if (ws_stat64(pipename, &pipe_stat) < 0) {
1995 if (errno == ENOENT || errno == ENOTDIR)
1996 pcap_opts->cap_pipe_err = PIPNEXIST;
1998 g_snprintf(errmsg, errmsgl,
1999 "The capture session could not be initiated "
2000 "due to error getting information on pipe/socket: %s", g_strerror(errno));
2001 pcap_opts->cap_pipe_err = PIPERR;
2005 if (S_ISFIFO(pipe_stat.st_mode)) {
2006 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
2008 g_snprintf(errmsg, errmsgl,
2009 "The capture session could not be initiated "
2010 "due to error on pipe open: %s", g_strerror(errno));
2011 pcap_opts->cap_pipe_err = PIPERR;
2014 } else if (S_ISSOCK(pipe_stat.st_mode)) {
2015 fd = socket(AF_UNIX, SOCK_STREAM, 0);
2017 g_snprintf(errmsg, errmsgl,
2018 "The capture session could not be initiated "
2019 "due to error on socket create: %s", g_strerror(errno));
2020 pcap_opts->cap_pipe_err = PIPERR;
2023 sa.sun_family = AF_UNIX;
2025 * The Single UNIX Specification says:
2027 * The size of sun_path has intentionally been left undefined.
2028 * This is because different implementations use different sizes.
2029 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
2030 * of 104. Since most implementations originate from BSD versions,
2031 * the size is typically in the range 92 to 108.
2033 * Applications should not assume a particular length for sun_path
2034 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
2038 * The <sys/un.h> header shall define the sockaddr_un structure,
2039 * which shall include at least the following members:
2041 * sa_family_t sun_family Address family.
2042 * char sun_path[] Socket pathname.
2044 * so we assume that it's an array, with a specified size,
2045 * and that the size reflects the maximum path length.
2047 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
2048 /* Path name too long */
2049 g_snprintf(errmsg, errmsgl,
2050 "The capture session coud not be initiated "
2051 "due to error on socket connect: Path name too long");
2052 pcap_opts->cap_pipe_err = PIPERR;
2056 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
2058 g_snprintf(errmsg, errmsgl,
2059 "The capture session coud not be initiated "
2060 "due to error on socket connect: %s", g_strerror(errno));
2061 pcap_opts->cap_pipe_err = PIPERR;
2066 if (S_ISCHR(pipe_stat.st_mode)) {
2068 * Assume the user specified an interface on a system where
2069 * interfaces are in /dev. Pretend we haven't seen it.
2071 pcap_opts->cap_pipe_err = PIPNEXIST;
2073 g_snprintf(errmsg, errmsgl,
2074 "The capture session could not be initiated because\n"
2075 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
2076 pcap_opts->cap_pipe_err = PIPERR;
2081 #define PIPE_STR "\\pipe\\"
2082 /* Under Windows, named pipes _must_ have the form
2083 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
2085 pncopy = g_strdup(pipename);
2086 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
2087 pos = strchr(pncopy + 3, '\\');
2088 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
2095 g_snprintf(errmsg, errmsgl,
2096 "The capture session could not be initiated because\n"
2097 "\"%s\" is neither an interface nor a pipe", pipename);
2098 pcap_opts->cap_pipe_err = PIPNEXIST;
2102 /* Wait for the pipe to appear */
2104 pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
2105 OPEN_EXISTING, 0, NULL);
2107 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
2110 if (GetLastError() != ERROR_PIPE_BUSY) {
2111 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2112 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2113 g_snprintf(errmsg, errmsgl,
2114 "The capture session on \"%s\" could not be started "
2115 "due to error on pipe open: %s (error %d)",
2116 pipename, utf_16to8(err_str), GetLastError());
2118 pcap_opts->cap_pipe_err = PIPERR;
2122 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
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\" timed out during "
2127 "pipe open: %s (error %d)",
2128 pipename, utf_16to8(err_str), GetLastError());
2130 pcap_opts->cap_pipe_err = PIPERR;
2137 pcap_opts->from_cap_pipe = TRUE;
2140 if (pcap_opts->from_cap_socket)
2143 /* read the pcap header */
2145 while (bytes_read < sizeof magic) {
2146 sel_ret = cap_pipe_select(fd);
2148 g_snprintf(errmsg, errmsgl,
2149 "Unexpected error from select: %s", g_strerror(errno));
2151 } else if (sel_ret > 0) {
2152 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
2153 sizeof magic-bytes_read,
2154 pcap_opts->from_cap_socket);
2157 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2159 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2169 #if GLIB_CHECK_VERSION(2,31,0)
2170 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_opts);
2172 g_thread_create(&cap_thread_read, pcap_opts, FALSE, NULL);
2175 pcap_opts->cap_pipe_buf = (char *) &magic;
2176 pcap_opts->cap_pipe_bytes_read = 0;
2177 pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
2178 /* We don't have to worry about cap_pipe_read_mtx here */
2179 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2180 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2181 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2182 if (pcap_opts->cap_pipe_bytes_read == 0)
2183 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2185 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2194 case PCAP_NSEC_MAGIC:
2195 /* Host that wrote it has our byte order, and was running
2196 a program using either standard or ss990417 libpcap. */
2197 pcap_opts->cap_pipe_byte_swapped = FALSE;
2198 pcap_opts->cap_pipe_modified = FALSE;
2199 pcap_opts->ts_nsec = magic == PCAP_NSEC_MAGIC;
2201 case PCAP_MODIFIED_MAGIC:
2202 /* Host that wrote it has our byte order, but was running
2203 a program using either ss990915 or ss991029 libpcap. */
2204 pcap_opts->cap_pipe_byte_swapped = FALSE;
2205 pcap_opts->cap_pipe_modified = TRUE;
2207 case PCAP_SWAPPED_MAGIC:
2208 case PCAP_SWAPPED_NSEC_MAGIC:
2209 /* Host that wrote it has a byte order opposite to ours,
2210 and was running a program using either standard or
2211 ss990417 libpcap. */
2212 pcap_opts->cap_pipe_byte_swapped = TRUE;
2213 pcap_opts->cap_pipe_modified = FALSE;
2214 pcap_opts->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
2216 case PCAP_SWAPPED_MODIFIED_MAGIC:
2217 /* Host that wrote it out has a byte order opposite to
2218 ours, and was running a program using either ss990915
2219 or ss991029 libpcap. */
2220 pcap_opts->cap_pipe_byte_swapped = TRUE;
2221 pcap_opts->cap_pipe_modified = TRUE;
2224 /* Not a "libpcap" type we know about. */
2225 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
2230 if (pcap_opts->from_cap_socket)
2233 /* Read the rest of the header */
2235 while (bytes_read < sizeof(struct pcap_hdr)) {
2236 sel_ret = cap_pipe_select(fd);
2238 g_snprintf(errmsg, errmsgl,
2239 "Unexpected error from select: %s", g_strerror(errno));
2241 } else if (sel_ret > 0) {
2242 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
2243 sizeof(struct pcap_hdr) - bytes_read,
2244 pcap_opts->from_cap_socket);
2247 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2249 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
2259 pcap_opts->cap_pipe_buf = (char *) hdr;
2260 pcap_opts->cap_pipe_bytes_read = 0;
2261 pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
2262 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2263 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2264 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2265 if (pcap_opts->cap_pipe_bytes_read == 0)
2266 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2268 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
2275 if (pcap_opts->cap_pipe_byte_swapped) {
2276 /* Byte-swap the header fields about which we care. */
2277 hdr->version_major = BSWAP16(hdr->version_major);
2278 hdr->version_minor = BSWAP16(hdr->version_minor);
2279 hdr->snaplen = BSWAP32(hdr->snaplen);
2280 hdr->network = BSWAP32(hdr->network);
2282 pcap_opts->linktype = hdr->network;
2284 if (hdr->version_major < 2) {
2285 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
2289 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2290 pcap_opts->cap_pipe_err = PIPOK;
2291 pcap_opts->cap_pipe_fd = fd;
2295 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
2296 pcap_opts->cap_pipe_err = PIPERR;
2297 cap_pipe_close(fd, pcap_opts->from_cap_socket);
2298 pcap_opts->cap_pipe_fd = -1;
2302 /* We read one record from the pipe, take care of byte order in the record
2303 * header, write the record to the capture file, and update capture statistics. */
2305 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
2307 struct pcap_pkthdr phdr;
2308 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2311 #if !GLIB_CHECK_VERSION(2,31,18)
2319 #ifdef LOG_CAPTURE_VERBOSE
2320 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
2323 switch (pcap_opts->cap_pipe_state) {
2325 case STATE_EXPECT_REC_HDR:
2327 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2330 pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
2331 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
2332 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2333 pcap_opts->cap_pipe_bytes_read = 0;
2336 pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
2337 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2338 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2343 case STATE_READ_REC_HDR:
2345 if (pcap_opts->from_cap_socket)
2348 b = cap_pipe_read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
2349 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
2352 result = PD_PIPE_EOF;
2354 result = PD_PIPE_ERR;
2357 pcap_opts->cap_pipe_bytes_read += b;
2361 #if GLIB_CHECK_VERSION(2,31,18)
2362 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2364 g_get_current_time(&wait_time);
2365 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2366 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2368 if (pcap_opts->cap_pipe_err == PIPEOF) {
2369 result = PD_PIPE_EOF;
2371 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2372 result = PD_PIPE_ERR;
2380 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2382 result = PD_REC_HDR_READ;
2385 case STATE_EXPECT_DATA:
2387 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2390 pcap_opts->cap_pipe_state = STATE_READ_DATA;
2391 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2392 pcap_opts->cap_pipe_bytes_read = 0;
2395 pcap_opts->cap_pipe_buf = (char *) data;
2396 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2397 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2402 case STATE_READ_DATA:
2404 if (pcap_opts->from_cap_socket)
2407 b = cap_pipe_read(pcap_opts->cap_pipe_fd,
2408 data+pcap_opts->cap_pipe_bytes_read,
2409 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read,
2410 pcap_opts->from_cap_socket);
2413 result = PD_PIPE_EOF;
2415 result = PD_PIPE_ERR;
2418 pcap_opts->cap_pipe_bytes_read += b;
2423 #if GLIB_CHECK_VERSION(2,31,18)
2424 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2426 g_get_current_time(&wait_time);
2427 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2428 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2429 #endif /* GLIB_CHECK_VERSION(2,31,18) */
2430 if (pcap_opts->cap_pipe_err == PIPEOF) {
2431 result = PD_PIPE_EOF;
2433 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2434 result = PD_PIPE_ERR;
2442 if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2444 result = PD_DATA_READ;
2448 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2451 } /* switch (pcap_opts->cap_pipe_state) */
2454 * We've now read as much data as we were expecting, so process it.
2458 case PD_REC_HDR_READ:
2459 /* We've read the header. Take care of byte order. */
2460 cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
2461 &pcap_opts->cap_pipe_rechdr.hdr);
2462 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2463 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2464 ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
2468 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2469 pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2472 /* no data to read? fall through */
2475 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2476 phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2477 phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2478 phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2479 phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2482 capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2484 capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2486 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2490 pcap_opts->cap_pipe_err = PIPEOF;
2495 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2496 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2497 g_snprintf(errmsg, errmsgl,
2498 "Error reading from pipe: %s (error %d)",
2499 utf_16to8(err_str), GetLastError());
2502 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2510 pcap_opts->cap_pipe_err = PIPERR;
2511 /* Return here rather than inside the switch to prevent GCC warning */
2516 /** Open the capture input file (pcap or capture pipe).
2517 * Returns TRUE if it succeeds, FALSE otherwise. */
2519 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2520 char *errmsg, size_t errmsg_len,
2521 char *secondary_errmsg, size_t secondary_errmsg_len)
2523 gchar open_err_str[PCAP_ERRBUF_SIZE];
2524 gchar *sync_msg_str;
2525 interface_options interface_opts;
2526 pcap_options *pcap_opts;
2530 gchar *sync_secondary_msg_str;
2531 WORD wVersionRequested;
2535 /* XXX - opening Winsock on tshark? */
2537 /* Initialize Windows Socket if we are in a WIN32 OS
2538 This needs to be done before querying the interface for network/netmask */
2540 /* XXX - do we really require 1.1 or earlier?
2541 Are there any versions that support only 2.0 or higher? */
2542 wVersionRequested = MAKEWORD(1, 1);
2543 err = WSAStartup(wVersionRequested, &wsaData);
2547 case WSASYSNOTREADY:
2548 g_snprintf(errmsg, (gulong) errmsg_len,
2549 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2552 case WSAVERNOTSUPPORTED:
2553 g_snprintf(errmsg, (gulong) errmsg_len,
2554 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2555 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2558 case WSAEINPROGRESS:
2559 g_snprintf(errmsg, (gulong) errmsg_len,
2560 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2564 g_snprintf(errmsg, (gulong) errmsg_len,
2565 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2569 g_snprintf(errmsg, (gulong) errmsg_len,
2570 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2574 g_snprintf(errmsg, (gulong) errmsg_len,
2575 "Couldn't initialize Windows Sockets: error %d", err);
2578 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2582 if ((use_threads == FALSE) &&
2583 (capture_opts->ifaces->len > 1)) {
2584 g_snprintf(errmsg, (gulong) errmsg_len,
2585 "Using threads is required for capturing on multiple interfaces!");
2589 for (i = 0; i < capture_opts->ifaces->len; i++) {
2590 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2591 pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2592 if (pcap_opts == NULL) {
2593 g_snprintf(errmsg, (gulong) errmsg_len,
2594 "Could not allocate memory.");
2597 pcap_opts->received = 0;
2598 pcap_opts->dropped = 0;
2599 pcap_opts->flushed = 0;
2600 pcap_opts->pcap_h = NULL;
2601 #ifdef MUST_DO_SELECT
2602 pcap_opts->pcap_fd = -1;
2604 pcap_opts->pcap_err = FALSE;
2605 pcap_opts->interface_id = i;
2606 pcap_opts->tid = NULL;
2607 pcap_opts->snaplen = 0;
2608 pcap_opts->linktype = -1;
2609 pcap_opts->ts_nsec = FALSE;
2610 pcap_opts->from_cap_pipe = FALSE;
2611 pcap_opts->from_cap_socket = FALSE;
2612 memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2613 memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2615 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2617 pcap_opts->cap_pipe_fd = -1;
2618 pcap_opts->cap_pipe_modified = FALSE;
2619 pcap_opts->cap_pipe_byte_swapped = FALSE;
2621 pcap_opts->cap_pipe_buf = NULL;
2623 pcap_opts->cap_pipe_bytes_to_read = 0;
2624 pcap_opts->cap_pipe_bytes_read = 0;
2625 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2626 pcap_opts->cap_pipe_err = PIPOK;
2628 #if GLIB_CHECK_VERSION(2,31,0)
2629 pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2630 g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2632 pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2634 pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2635 pcap_opts->cap_pipe_done_q = g_async_queue_new();
2637 g_array_append_val(ld->pcaps, pcap_opts);
2639 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2640 pcap_opts->pcap_h = open_capture_device(&interface_opts, &open_err_str);
2642 if (pcap_opts->pcap_h != NULL) {
2643 /* we've opened "iface" as a network device */
2645 /* try to set the capture buffer size */
2646 if (interface_opts.buffer_size > 1 &&
2647 pcap_setbuff(pcap_opts->pcap_h, interface_opts.buffer_size * 1024 * 1024) != 0) {
2648 sync_secondary_msg_str = g_strdup_printf(
2649 "The capture buffer size of %dMB seems to be too high for your machine,\n"
2650 "the default of 1MB will be used.\n"
2652 "Nonetheless, the capture is started.\n",
2653 interface_opts.buffer_size);
2654 report_capture_error("Couldn't set the capture buffer size!",
2655 sync_secondary_msg_str);
2656 g_free(sync_secondary_msg_str);
2660 #if defined(HAVE_PCAP_SETSAMPLING)
2661 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2662 struct pcap_samp *samp;
2664 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2665 switch (interface_opts.sampling_method) {
2666 case CAPTURE_SAMP_BY_COUNT:
2667 samp->method = PCAP_SAMP_1_EVERY_N;
2670 case CAPTURE_SAMP_BY_TIMER:
2671 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2675 sync_msg_str = g_strdup_printf(
2676 "Unknown sampling method %d specified,\n"
2677 "continue without packet sampling",
2678 interface_opts.sampling_method);
2679 report_capture_error("Couldn't set the capture "
2680 "sampling", sync_msg_str);
2681 g_free(sync_msg_str);
2683 samp->value = interface_opts.sampling_param;
2685 report_capture_error("Couldn't set the capture sampling",
2686 "Cannot get packet sampling data structure");
2691 /* setting the data link type only works on real interfaces */
2692 if (!set_pcap_linktype(pcap_opts->pcap_h, interface_opts.linktype, interface_opts.name,
2694 secondary_errmsg, secondary_errmsg_len)) {
2697 pcap_opts->linktype = get_pcap_linktype(pcap_opts->pcap_h, interface_opts.name);
2699 /* We couldn't open "iface" as a network device. */
2700 /* Try to open it as a pipe */
2701 cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2704 if (pcap_opts->cap_pipe_fd == -1) {
2706 if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2708 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2709 /* Pipe doesn't exist, so output message for interface */
2710 get_capture_device_open_failure_messages(open_err_str,
2711 interface_opts.name,
2715 secondary_errmsg_len);
2718 * Else pipe (or file) does exist and cap_pipe_open_live() has
2723 /* cap_pipe_open_live() succeeded; don't want
2724 error message from pcap_open_live() */
2725 open_err_str[0] = '\0';
2729 /* XXX - will this work for tshark? */
2730 #ifdef MUST_DO_SELECT
2731 if (!pcap_opts->from_cap_pipe) {
2732 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2733 pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2735 pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2740 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2741 returned a warning; print it, but keep capturing. */
2742 if (open_err_str[0] != '\0') {
2743 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2744 report_capture_error(sync_msg_str, "");
2745 g_free(sync_msg_str);
2747 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2748 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2751 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2752 /* to remove any suid privileges. */
2753 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2754 /* (euid/egid have already previously been set to ruid/rgid. */
2755 /* (See comment in main() for details) */
2757 relinquish_special_privs_perm();
2759 relinquish_all_capabilities();
2764 /* close the capture input file (pcap or capture pipe) */
2765 static void capture_loop_close_input(loop_data *ld)
2768 pcap_options *pcap_opts;
2770 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2772 for (i = 0; i < ld->pcaps->len; i++) {
2773 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2774 /* if open, close the capture pipe "input file" */
2775 if (pcap_opts->cap_pipe_fd >= 0) {
2776 g_assert(pcap_opts->from_cap_pipe);
2777 cap_pipe_close(pcap_opts->cap_pipe_fd, pcap_opts->from_cap_socket);
2778 pcap_opts->cap_pipe_fd = -1;
2781 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2782 CloseHandle(pcap_opts->cap_pipe_h);
2783 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2786 /* if open, close the pcap "input file" */
2787 if (pcap_opts->pcap_h != NULL) {
2788 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2789 pcap_close(pcap_opts->pcap_h);
2790 pcap_opts->pcap_h = NULL;
2797 /* Shut down windows sockets */
2803 /* init the capture filter */
2804 static initfilter_status_t
2805 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2806 const gchar * name, const gchar * cfilter)
2808 struct bpf_program fcode;
2810 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2812 /* capture filters only work on real interfaces */
2813 if (cfilter && !from_cap_pipe) {
2814 /* A capture filter was specified; set it up. */
2815 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2816 /* Treat this specially - our caller might try to compile this
2817 as a display filter and, if that succeeds, warn the user that
2818 the display and capture filter syntaxes are different. */
2819 return INITFILTER_BAD_FILTER;
2821 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2822 #ifdef HAVE_PCAP_FREECODE
2823 pcap_freecode(&fcode);
2825 return INITFILTER_OTHER_ERROR;
2827 #ifdef HAVE_PCAP_FREECODE
2828 pcap_freecode(&fcode);
2832 return INITFILTER_NO_ERROR;
2836 /* set up to write to the already-opened capture output file/files */
2838 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2842 pcap_options *pcap_opts;
2843 interface_options interface_opts;
2844 gboolean successful;
2846 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2848 if ((capture_opts->use_pcapng == FALSE) &&
2849 (capture_opts->ifaces->len > 1)) {
2850 g_snprintf(errmsg, errmsg_len,
2851 "Using PCAPNG is required for capturing on multiple interfaces! Use the -n option.");
2855 /* Set up to write to the capture file. */
2856 if (capture_opts->multi_files_on) {
2857 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2859 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2860 if (ld->pdh == NULL) {
2865 if (capture_opts->use_pcapng) {
2867 GString *os_info_str;
2869 os_info_str = g_string_new("");
2870 get_os_version_info(os_info_str);
2872 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2873 successful = libpcap_write_session_header_block(libpcap_write_to_file, ld->pdh,
2874 (const char *)capture_opts->capture_comment, /* Comment*/
2876 os_info_str->str, /* OS*/
2878 -1, /* section_length */
2882 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2883 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2884 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2885 if (pcap_opts->from_cap_pipe) {
2886 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2888 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2890 successful = libpcap_write_interface_description_block(libpcap_write_to_file, global_ld.pdh,
2891 NULL, /* OPT_COMMENT 1 */
2892 interface_opts.name, /* IDB_NAME 2 */
2893 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2894 interface_opts.cfilter, /* IDB_FILTER 11 */
2895 os_info_str->str, /* IDB_OS 12 */
2896 pcap_opts->linktype,
2898 &(global_ld.bytes_written),
2899 0, /* IDB_IF_SPEED 8 */
2900 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2904 g_string_free(os_info_str, TRUE);
2907 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
2908 if (pcap_opts->from_cap_pipe) {
2909 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2911 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2913 successful = libpcap_write_file_header(libpcap_write_to_file, ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
2914 pcap_opts->ts_nsec, &ld->bytes_written, &err);
2922 if (ld->pdh == NULL) {
2923 /* We couldn't set up to write to the capture file. */
2924 /* XXX - use cf_open_error_message from tshark instead? */
2929 g_snprintf(errmsg, errmsg_len,
2930 "The file to which the capture would be"
2931 " saved (\"%s\") could not be opened: Error %d.",
2932 capture_opts->save_file, err);
2934 g_snprintf(errmsg, errmsg_len,
2935 "The file to which the capture would be"
2936 " saved (\"%s\") could not be opened: %s.",
2937 capture_opts->save_file, g_strerror(err));
2949 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2953 pcap_options *pcap_opts;
2954 guint64 end_time = create_timestamp();
2956 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2958 if (capture_opts->multi_files_on) {
2959 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2961 if (capture_opts->use_pcapng) {
2962 for (i = 0; i < global_ld.pcaps->len; i++) {
2963 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2964 if (!pcap_opts->from_cap_pipe) {
2965 guint64 isb_ifrecv, isb_ifdrop;
2966 struct pcap_stat stats;
2968 if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
2969 isb_ifrecv = pcap_opts->received;
2970 isb_ifdrop = stats.ps_drop + pcap_opts->dropped + pcap_opts->flushed;
2972 isb_ifrecv = G_MAXUINT64;
2973 isb_ifdrop = G_MAXUINT64;
2975 libpcap_write_interface_statistics_block(libpcap_write_to_file, ld->pdh,
2978 "Counters provided by dumpcap",
2987 if (fclose(ld->pdh) == EOF) {
2988 if (err_close != NULL) {
2998 /* dispatch incoming packets (pcap or capture pipe)
3000 * Waits for incoming packets to be available, and calls pcap_dispatch()
3001 * to cause them to be processed.
3003 * Returns the number of packets which were processed.
3005 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3006 * packet-batching behaviour does not cause packets to get held back
3010 capture_loop_dispatch(loop_data *ld,
3011 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
3014 gint packet_count_before;
3015 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
3020 packet_count_before = ld->packet_count;
3021 if (pcap_opts->from_cap_pipe) {
3022 /* dispatch from capture pipe */
3023 #ifdef LOG_CAPTURE_VERBOSE
3024 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
3027 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
3029 if (sel_ret < 0 && errno != EINTR) {
3030 g_snprintf(errmsg, errmsg_len,
3031 "Unexpected error from select: %s", g_strerror(errno));
3032 report_capture_error(errmsg, please_report);
3037 * "select()" says we can read from the pipe without blocking
3040 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
3050 /* dispatch from pcap */
3051 #ifdef MUST_DO_SELECT
3053 * If we have "pcap_get_selectable_fd()", we use it to get the
3054 * descriptor on which to select; if that's -1, it means there
3055 * is no descriptor on which you can do a "select()" (perhaps
3056 * because you're capturing on a special device, and that device's
3057 * driver unfortunately doesn't support "select()", in which case
3058 * we don't do the select - which means it might not be possible
3059 * to stop a capture until a packet arrives. If that's unacceptable,
3060 * plead with whoever supplies the software for that device to add
3061 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3062 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3063 * later, so it can use pcap_breakloop().
3065 #ifdef LOG_CAPTURE_VERBOSE
3066 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3068 if (pcap_opts->pcap_fd != -1) {
3069 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
3072 * "select()" says we can read from it without blocking; go for
3075 * We don't have pcap_breakloop(), so we only process one packet
3076 * per pcap_dispatch() call, to allow a signal to stop the
3077 * processing immediately, rather than processing all packets
3078 * in a batch before quitting.
3081 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3083 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3087 /* Error, rather than pcap_breakloop(). */
3088 pcap_opts->pcap_err = TRUE;
3090 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3093 if (sel_ret < 0 && errno != EINTR) {
3094 g_snprintf(errmsg, errmsg_len,
3095 "Unexpected error from select: %s", g_strerror(errno));
3096 report_capture_error(errmsg, please_report);
3102 #endif /* MUST_DO_SELECT */
3104 /* dispatch from pcap without select */
3106 #ifdef LOG_CAPTURE_VERBOSE
3107 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3111 * On Windows, we don't support asynchronously telling a process to
3112 * stop capturing; instead, we check for an indication on a pipe
3113 * after processing packets. We therefore process only one packet
3114 * at a time, so that we can check the pipe after every packet.
3117 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3119 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3123 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3125 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3130 /* Error, rather than pcap_breakloop(). */
3131 pcap_opts->pcap_err = TRUE;
3133 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3135 #else /* pcap_next_ex */
3136 #ifdef LOG_CAPTURE_VERBOSE
3137 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3139 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3142 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3143 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
3144 * This should be fixed in the WinPcap 4.0 alpha release.
3146 * For reference, an example remote interface:
3147 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3150 /* emulate dispatch from pcap */
3153 struct pcap_pkthdr *pkt_header;
3158 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
3160 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3162 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3167 pcap_opts->pcap_err = TRUE;
3171 #endif /* pcap_next_ex */
3175 #ifdef LOG_CAPTURE_VERBOSE
3176 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3179 return ld->packet_count - packet_count_before;
3183 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3184 * want to grab only the characters between the '{' and '}' delimiters.
3186 * Returns a GString that must be freed with g_string_free(). */
3188 isolate_uuid(const char *iface)
3193 ptr = strchr(iface, '{');
3195 return g_string_new(iface);
3196 gstr = g_string_new(ptr + 1);
3198 ptr = strchr(gstr->str, '}');
3202 gstr = g_string_truncate(gstr, ptr - gstr->str);
3207 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3208 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3210 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3211 char *errmsg, int errmsg_len)
3214 gchar *capfile_name;
3216 gboolean is_tempfile;
3218 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3219 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3221 if (capture_opts->save_file != NULL) {
3222 /* We return to the caller while the capture is in progress.
3223 * Therefore we need to take a copy of save_file in
3224 * case the caller destroys it after we return.
3226 capfile_name = g_strdup(capture_opts->save_file);
3228 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3229 if (capture_opts->multi_files_on) {
3230 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3231 g_snprintf(errmsg, errmsg_len,
3232 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3233 g_free(capfile_name);
3236 if (strcmp(capfile_name, "-") == 0) {
3237 /* write to stdout */
3240 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3241 _setmode(1, O_BINARY);
3244 } /* if (...output_to_pipe ... */
3247 if (capture_opts->multi_files_on) {
3248 /* ringbuffer is enabled */
3249 *save_file_fd = ringbuf_init(capfile_name,
3250 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3251 capture_opts->group_read_access);
3253 /* we need the ringbuf name */
3254 if (*save_file_fd != -1) {
3255 g_free(capfile_name);
3256 capfile_name = g_strdup(ringbuf_current_filename());
3259 /* Try to open/create the specified file for use as a capture buffer. */
3260 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
3261 (capture_opts->group_read_access) ? 0640 : 0600);
3264 is_tempfile = FALSE;
3266 /* Choose a random name for the temporary capture buffer */
3267 if (global_capture_opts.ifaces->len > 1) {
3268 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3271 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
3273 /* use the generic portion of the interface guid to form the basis of the filename */
3274 if (strncmp("NPF_{", basename, 5)==0)
3276 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
3278 iface = isolate_uuid(basename);
3280 basename = g_strdup(iface->str);
3281 g_string_free(iface, TRUE);
3284 /* generate the temp file name prefix...
3285 * It would be nice if we could specify a pcapng/pcap filename suffix,
3286 * create_tempfile() however currently uses mkstemp() which doesn't allow this - one day perhaps*/
3287 if (capture_opts->use_pcapng) {
3288 prefix = g_strconcat("wireshark_pcapng_", basename, NULL);
3290 prefix = g_strconcat("wireshark_pcap_", basename, NULL);
3294 *save_file_fd = create_tempfile(&tmpname, prefix);
3296 capfile_name = g_strdup(tmpname);
3300 /* did we fail to open the output file? */
3301 if (*save_file_fd == -1) {
3303 g_snprintf(errmsg, errmsg_len,
3304 "The temporary file to which the capture would be saved (\"%s\") "
3305 "could not be opened: %s.", capfile_name, g_strerror(errno));
3307 if (capture_opts->multi_files_on) {
3308 ringbuf_error_cleanup();
3311 g_snprintf(errmsg, errmsg_len,
3312 "The file to which the capture would be saved (\"%s\") "
3313 "could not be opened: %s.", capfile_name,
3316 g_free(capfile_name);
3320 if (capture_opts->save_file != NULL) {
3321 g_free(capture_opts->save_file);
3323 capture_opts->save_file = capfile_name;
3324 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3325 "g_free(capfile_name)". */
3331 /* Do the work of handling either the file size or file duration capture
3332 conditions being reached, and switching files or stopping. */
3334 do_file_switch_or_stop(capture_options *capture_opts,
3335 condition *cnd_autostop_files,
3336 condition *cnd_autostop_size,
3337 condition *cnd_file_duration)
3340 pcap_options *pcap_opts;
3341 interface_options interface_opts;
3342 gboolean successful;
3344 if (capture_opts->multi_files_on) {
3345 if (cnd_autostop_files != NULL &&
3346 cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
3347 /* no files left: stop here */
3348 global_ld.go = FALSE;
3352 /* Switch to the next ringbuffer file */
3353 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3354 &global_ld.save_file_fd, &global_ld.err)) {
3356 /* File switch succeeded: reset the conditions */
3357 global_ld.bytes_written = 0;
3358 if (capture_opts->use_pcapng) {
3360 GString *os_info_str;
3362 os_info_str = g_string_new("");
3363 get_os_version_info(os_info_str);
3365 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
3366 successful = libpcap_write_session_header_block(libpcap_write_to_file, global_ld.pdh,
3369 os_info_str->str, /* OS */
3371 -1, /* section_length */
3372 &(global_ld.bytes_written),
3375 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3376 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3377 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3378 successful = libpcap_write_interface_description_block(libpcap_write_to_file, global_ld.pdh,
3379 NULL, /* OPT_COMMENT 1 */
3380 interface_opts.name, /* IDB_NAME 2 */
3381 interface_opts.descr, /* IDB_DESCRIPTION 3 */
3382 interface_opts.cfilter, /* IDB_FILTER 11 */
3383 os_info_str->str, /* IDB_OS 12 */
3384 pcap_opts->linktype,
3386 &(global_ld.bytes_written),
3387 0, /* IDB_IF_SPEED 8 */
3388 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3392 g_string_free(os_info_str, TRUE);
3395 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3396 successful = libpcap_write_file_header(libpcap_write_to_file, global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
3397 pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3400 fclose(global_ld.pdh);
3401 global_ld.pdh = NULL;
3402 global_ld.go = FALSE;
3405 if (cnd_autostop_size)
3406 cnd_reset(cnd_autostop_size);
3407 if (cnd_file_duration)
3408 cnd_reset(cnd_file_duration);
3409 fflush(global_ld.pdh);
3411 report_packet_count(global_ld.inpkts_to_sync_pipe);
3412 global_ld.inpkts_to_sync_pipe = 0;
3413 report_new_capture_file(capture_opts->save_file);
3415 /* File switch failed: stop here */
3416 global_ld.go = FALSE;
3420 /* single file, stop now */
3421 global_ld.go = FALSE;
3428 pcap_read_handler(void* arg)
3430 pcap_options *pcap_opts;
3431 char errmsg[MSG_MAX_LENGTH+1];
3433 pcap_opts = (pcap_options *)arg;
3435 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3436 pcap_opts->interface_id);
3438 while (global_ld.go) {
3439 /* dispatch incoming packets */
3440 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3442 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3443 pcap_opts->interface_id);
3444 g_thread_exit(NULL);
3448 /* Do the low-level work of a capture.
3449 Returns TRUE if it succeeds, FALSE otherwise. */
3451 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3454 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3456 struct timeval upd_time, cur_time;
3460 condition *cnd_file_duration = NULL;
3461 condition *cnd_autostop_files = NULL;
3462 condition *cnd_autostop_size = NULL;
3463 condition *cnd_autostop_duration = NULL;
3466 gboolean cfilter_error = FALSE;
3467 char errmsg[MSG_MAX_LENGTH+1];
3468 char secondary_errmsg[MSG_MAX_LENGTH+1];
3469 pcap_options *pcap_opts;
3470 interface_options interface_opts;
3471 guint i, error_index = 0;
3474 *secondary_errmsg = '\0';
3476 /* init the loop data */
3477 global_ld.go = TRUE;
3478 global_ld.packet_count = 0;
3480 global_ld.report_packet_count = FALSE;
3482 if (capture_opts->has_autostop_packets)
3483 global_ld.packet_max = capture_opts->autostop_packets;
3485 global_ld.packet_max = 0; /* no limit */
3486 global_ld.inpkts_to_sync_pipe = 0;
3487 global_ld.err = 0; /* no error seen yet */
3488 global_ld.pdh = NULL;
3489 global_ld.autostop_files = 0;
3490 global_ld.save_file_fd = -1;
3492 /* We haven't yet gotten the capture statistics. */
3493 *stats_known = FALSE;
3495 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3496 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3498 /* open the "input file" from network interface or capture pipe */
3499 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3500 secondary_errmsg, sizeof(secondary_errmsg))) {
3503 for (i = 0; i < capture_opts->ifaces->len; i++) {
3504 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3505 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3506 /* init the input filter from the network interface (capture pipe will do nothing) */
3508 * When remote capturing WinPCap crashes when the capture filter
3509 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3512 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3513 interface_opts.name,
3514 interface_opts.cfilter?interface_opts.cfilter:"")) {
3516 case INITFILTER_NO_ERROR:
3519 case INITFILTER_BAD_FILTER:
3520 cfilter_error = TRUE;
3522 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3525 case INITFILTER_OTHER_ERROR:
3526 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3527 pcap_geterr(pcap_opts->pcap_h));
3528 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3533 /* If we're supposed to write to a capture file, open it for output
3534 (temporary/specified name/ringbuffer) */
3535 if (capture_opts->saving_to_file) {
3536 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3537 errmsg, sizeof(errmsg))) {
3541 /* set up to write to the already-opened capture output file/files */
3542 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3547 /* XXX - capture SIGTERM and close the capture, in case we're on a
3548 Linux 2.0[.x] system and you have to explicitly close the capture
3549 stream in order to turn promiscuous mode off? We need to do that
3550 in other places as well - and I don't think that works all the
3551 time in any case, due to libpcap bugs. */
3553 /* Well, we should be able to start capturing.
3555 Sync out the capture file, so the header makes it to the file system,
3556 and send a "capture started successfully and capture file created"
3557 message to our parent so that they'll open the capture file and
3558 update its windows to indicate that we have a live capture in
3560 fflush(global_ld.pdh);
3561 report_new_capture_file(capture_opts->save_file);
3564 /* initialize capture stop (and alike) conditions */
3565 init_capture_stop_conditions();
3566 /* create stop conditions */
3567 if (capture_opts->has_autostop_filesize)
3569 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
3570 if (capture_opts->has_autostop_duration)
3571 cnd_autostop_duration =
3572 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3574 if (capture_opts->multi_files_on) {
3575 if (capture_opts->has_file_duration)
3577 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3579 if (capture_opts->has_autostop_files)
3580 cnd_autostop_files =
3581 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
3584 /* init the time values */
3586 upd_time = GetTickCount();
3588 gettimeofday(&upd_time, NULL);
3590 start_time = create_timestamp();
3591 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
3593 /* WOW, everything is prepared! */
3594 /* please fasten your seat belts, we will enter now the actual capture loop */
3596 pcap_queue = g_async_queue_new();
3597 pcap_queue_bytes = 0;
3598 pcap_queue_packets = 0;
3599 for (i = 0; i < global_ld.pcaps->len; i++) {
3600 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3601 #if GLIB_CHECK_VERSION(2,31,0)
3602 /* XXX - Add an interface name here? */
3603 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3605 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3609 while (global_ld.go) {
3610 /* dispatch incoming packets */
3612 pcap_queue_element *queue_element;
3613 #if GLIB_CHECK_VERSION(2,31,18)
3615 g_async_queue_lock(pcap_queue);
3616 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3618 GTimeVal write_thread_time;
3620 g_get_current_time(&write_thread_time);
3621 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3622 g_async_queue_lock(pcap_queue);
3623 queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3625 if (queue_element) {
3626 pcap_queue_bytes -= queue_element->phdr.caplen;
3627 pcap_queue_packets -= 1;
3629 g_async_queue_unlock(pcap_queue);
3630 if (queue_element) {
3631 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3632 "Dequeued a packet of length %d captured on interface %d.",
3633 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3635 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3636 &queue_element->phdr,
3638 g_free(queue_element->pd);
3639 g_free(queue_element);
3645 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3646 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3647 sizeof(errmsg), pcap_opts);
3650 /* Were we asked to print packet counts by the SIGINFO handler? */
3651 if (global_ld.report_packet_count) {
3652 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3653 plurality(global_ld.packet_count, "", "s"));
3654 global_ld.report_packet_count = FALSE;
3659 /* any news from our parent (signal pipe)? -> just stop the capture */
3660 if (!signal_pipe_check_running()) {
3661 global_ld.go = FALSE;
3666 global_ld.inpkts_to_sync_pipe += inpkts;
3668 /* check capture size condition */
3669 if (cnd_autostop_size != NULL &&
3670 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)) {
3671 /* Capture size limit reached, do we have another file? */
3672 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3673 cnd_autostop_size, cnd_file_duration))
3675 } /* cnd_autostop_size */
3676 if (capture_opts->output_to_pipe) {
3677 fflush(global_ld.pdh);
3681 /* Only update once every 500ms so as not to overload slow displays.
3682 * This also prevents too much context-switching between the dumpcap
3683 * and wireshark processes.
3685 #define DUMPCAP_UPD_TIME 500
3688 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3689 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3691 gettimeofday(&cur_time, NULL);
3692 if ((cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3693 (upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3696 upd_time = cur_time;
3699 if (pcap_stats(pch, stats) >= 0) {
3700 *stats_known = TRUE;
3703 /* Let the parent process know. */
3704 if (global_ld.inpkts_to_sync_pipe) {
3706 fflush(global_ld.pdh);
3708 /* Send our parent a message saying we've written out
3709 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3711 report_packet_count(global_ld.inpkts_to_sync_pipe);
3713 global_ld.inpkts_to_sync_pipe = 0;
3716 /* check capture duration condition */
3717 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3718 /* The maximum capture time has elapsed; stop the capture. */
3719 global_ld.go = FALSE;
3723 /* check capture file duration condition */
3724 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3725 /* duration limit reached, do we have another file? */
3726 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3727 cnd_autostop_size, cnd_file_duration))
3729 } /* cnd_file_duration */
3733 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3735 pcap_queue_element *queue_element;
3737 for (i = 0; i < global_ld.pcaps->len; i++) {
3738 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3739 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3740 pcap_opts->interface_id);
3741 g_thread_join(pcap_opts->tid);
3742 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3743 pcap_opts->interface_id);
3746 g_async_queue_lock(pcap_queue);
3747 queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3748 if (queue_element) {
3749 pcap_queue_bytes -= queue_element->phdr.caplen;
3750 pcap_queue_packets -= 1;
3752 g_async_queue_unlock(pcap_queue);
3753 if (queue_element == NULL) {
3756 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3757 "Dequeued a packet of length %d captured on interface %d.",
3758 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3759 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3760 &queue_element->phdr,
3762 g_free(queue_element->pd);
3763 g_free(queue_element);
3764 global_ld.inpkts_to_sync_pipe += 1;
3765 if (capture_opts->output_to_pipe) {
3766 fflush(global_ld.pdh);
3772 /* delete stop conditions */
3773 if (cnd_file_duration != NULL)
3774 cnd_delete(cnd_file_duration);
3775 if (cnd_autostop_files != NULL)
3776 cnd_delete(cnd_autostop_files);
3777 if (cnd_autostop_size != NULL)
3778 cnd_delete(cnd_autostop_size);
3779 if (cnd_autostop_duration != NULL)
3780 cnd_delete(cnd_autostop_duration);
3782 /* did we have a pcap (input) error? */
3783 for (i = 0; i < capture_opts->ifaces->len; i++) {
3784 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3785 if (pcap_opts->pcap_err) {
3786 /* On Linux, if an interface goes down while you're capturing on it,
3787 you'll get a "recvfrom: Network is down" or
3788 "The interface went down" error (ENETDOWN).
3789 (At least you will if g_strerror() doesn't show a local translation
3792 On FreeBSD and OS X, if a network adapter disappears while
3793 you're capturing on it, you'll get a "read: Device not configured"
3794 error (ENXIO). (See previous parenthetical note.)
3796 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3798 These should *not* be reported to the Wireshark developers. */
3801 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3802 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3803 strcmp(cap_err_str, "The interface went down") == 0 ||
3804 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3805 strcmp(cap_err_str, "read: I/O error") == 0 ||
3806 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3807 report_capture_error("The network adapter on which the capture was being done "
3808 "is no longer running; the capture has stopped.",
3811 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3813 report_capture_error(errmsg, please_report);
3816 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3817 report_capture_error(errmsg, "");
3821 /* did we have an output error while capturing? */
3822 if (global_ld.err == 0) {
3825 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3826 global_ld.err, FALSE);
3827 report_capture_error(errmsg, please_report);
3831 if (capture_opts->saving_to_file) {
3832 /* close the output file */
3833 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3837 /* there might be packets not yet notified to the parent */
3838 /* (do this after closing the file, so all packets are already flushed) */
3839 if (global_ld.inpkts_to_sync_pipe) {
3841 report_packet_count(global_ld.inpkts_to_sync_pipe);
3842 global_ld.inpkts_to_sync_pipe = 0;
3845 /* If we've displayed a message about a write error, there's no point
3846 in displaying another message about an error on close. */
3847 if (!close_ok && write_ok) {
3848 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3850 report_capture_error(errmsg, "");
3854 * XXX We exhibit different behaviour between normal mode and sync mode
3855 * when the pipe is stdin and not already at EOF. If we're a child, the
3856 * parent's stdin isn't closed, so if the user starts another capture,
3857 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3858 * will say "Unrecognized libpcap format". On the other hand, in normal
3859 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3862 report_capture_count(TRUE);
3864 /* get packet drop statistics from pcap */
3865 for (i = 0; i < capture_opts->ifaces->len; i++) {
3867 guint32 pcap_dropped = 0;
3869 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3870 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3871 received = pcap_opts->received;
3872 if (pcap_opts->pcap_h != NULL) {
3873 g_assert(!pcap_opts->from_cap_pipe);
3874 /* Get the capture statistics, so we know how many packets were dropped. */
3875 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3876 *stats_known = TRUE;
3877 /* Let the parent process know. */
3878 pcap_dropped += stats->ps_drop;
3880 g_snprintf(errmsg, sizeof(errmsg),
3881 "Can't get packet-drop statistics: %s",
3882 pcap_geterr(pcap_opts->pcap_h));
3883 report_capture_error(errmsg, please_report);
3886 report_packet_drops(received, pcap_dropped, pcap_opts->dropped, pcap_opts->flushed, interface_opts.console_display_name);
3889 /* close the input file (pcap or capture pipe) */
3890 capture_loop_close_input(&global_ld);
3892 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
3894 /* ok, if the write and the close were successful. */
3895 return write_ok && close_ok;
3898 if (capture_opts->multi_files_on) {
3899 /* cleanup ringbuffer */
3900 ringbuf_error_cleanup();
3902 /* We can't use the save file, and we have no FILE * for the stream
3903 to close in order to close it, so close the FD directly. */
3904 if (global_ld.save_file_fd != -1) {
3905 ws_close(global_ld.save_file_fd);
3908 /* We couldn't even start the capture, so get rid of the capture
3910 if (capture_opts->save_file != NULL) {
3911 ws_unlink(capture_opts->save_file);
3912 g_free(capture_opts->save_file);
3915 capture_opts->save_file = NULL;
3917 report_cfilter_error(capture_opts, error_index, errmsg);
3919 report_capture_error(errmsg, secondary_errmsg);
3921 /* close the input file (pcap or cap_pipe) */
3922 capture_loop_close_input(&global_ld);
3924 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3931 capture_loop_stop(void)
3933 #ifdef HAVE_PCAP_BREAKLOOP
3935 pcap_options *pcap_opts;
3937 for (i = 0; i < global_ld.pcaps->len; i++) {
3938 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3939 if (pcap_opts->pcap_h != NULL)
3940 pcap_breakloop(pcap_opts->pcap_h);
3943 global_ld.go = FALSE;
3948 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3949 int err, gboolean is_close)
3954 g_snprintf(errmsg, errmsglen,
3955 "Not all the packets could be written to the file"
3956 " to which the capture was being saved\n"
3957 "(\"%s\") because there is no space left on the file system\n"
3958 "on which that file resides.",
3964 g_snprintf(errmsg, errmsglen,
3965 "Not all the packets could be written to the file"
3966 " to which the capture was being saved\n"
3967 "(\"%s\") because you are too close to, or over,"
3968 " your disk quota\n"
3969 "on the file system on which that file resides.",
3976 g_snprintf(errmsg, errmsglen,
3977 "The file to which the capture was being saved\n"
3978 "(\"%s\") could not be closed: %s.",
3979 fname, g_strerror(err));
3981 g_snprintf(errmsg, errmsglen,
3982 "An error occurred while writing to the file"
3983 " to which the capture was being saved\n"
3985 fname, g_strerror(err));
3992 /* one packet was captured, process it */
3994 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3997 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3999 guint ts_mul = pcap_opts->ts_nsec ? 1000000000 : 1000000;
4001 /* We may be called multiple times from pcap_dispatch(); if we've set
4002 the "stop capturing" flag, ignore this packet, as we're not
4003 supposed to be saving any more packets. */
4004 if (!global_ld.go) {
4005 pcap_opts->flushed++;
4009 if (global_ld.pdh) {
4010 gboolean successful;
4012 /* We're supposed to write the packet to a file; do so.
4013 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4014 "ld->err" to the error. */
4015 if (global_capture_opts.use_pcapng) {
4016 successful = libpcap_write_enhanced_packet_block(libpcap_write_to_file, global_ld.pdh,
4018 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4019 phdr->caplen, phdr->len,
4020 pcap_opts->interface_id,
4023 &global_ld.bytes_written, &err);
4025 successful = libpcap_write_packet(libpcap_write_to_file, global_ld.pdh,
4026 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4027 phdr->caplen, phdr->len,
4029 &global_ld.bytes_written, &err);
4032 global_ld.go = FALSE;
4033 global_ld.err = err;
4034 pcap_opts->dropped++;
4036 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4037 "Wrote a packet of length %d captured on interface %u.",
4038 phdr->caplen, pcap_opts->interface_id);
4039 global_ld.packet_count++;
4040 pcap_opts->received++;
4041 /* if the user told us to stop after x packets, do we already have enough? */
4042 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
4043 global_ld.go = FALSE;
4049 /* one packet was captured, queue it */
4051 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4054 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4055 pcap_queue_element *queue_element;
4056 gboolean limit_reached;
4058 /* We may be called multiple times from pcap_dispatch(); if we've set
4059 the "stop capturing" flag, ignore this packet, as we're not
4060 supposed to be saving any more packets. */
4061 if (!global_ld.go) {
4062 pcap_opts->flushed++;
4066 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4067 if (queue_element == NULL) {
4068 pcap_opts->dropped++;
4071 queue_element->pcap_opts = pcap_opts;
4072 queue_element->phdr = *phdr;
4073 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4074 if (queue_element->pd == NULL) {
4075 pcap_opts->dropped++;
4076 g_free(queue_element);
4079 memcpy(queue_element->pd, pd, phdr->caplen);
4080 g_async_queue_lock(pcap_queue);
4081 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4082 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4083 limit_reached = FALSE;
4084 g_async_queue_push_unlocked(pcap_queue, queue_element);
4085 pcap_queue_bytes += phdr->caplen;
4086 pcap_queue_packets += 1;
4088 limit_reached = TRUE;
4090 g_async_queue_unlock(pcap_queue);
4091 if (limit_reached) {
4092 pcap_opts->dropped++;
4093 g_free(queue_element->pd);
4094 g_free(queue_element);
4095 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4096 "Dropped a packet of length %d captured on interface %u.",
4097 phdr->caplen, pcap_opts->interface_id);
4099 pcap_opts->received++;
4100 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4101 "Queued a packet of length %d captured on interface %u.",
4102 phdr->caplen, pcap_opts->interface_id);
4104 /* I don't want to hold the mutex over the debug output. So the
4105 output may be wrong */
4106 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4107 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4108 pcap_queue_bytes, pcap_queue_packets);
4112 set_80211_channel(const char *iface, const char *opt)
4114 int freq = 0, type, ret;
4115 gchar **options = NULL;
4117 options = g_strsplit_set(opt, ",", 2);
4120 freq = atoi(options[0]);
4123 type = ws80211_str_to_chan_type(options[1]);
4132 ret = ws80211_init();
4134 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4138 ret = ws80211_set_freq(iface, freq, type);
4141 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4147 pipe_write_block(2, SP_SUCCESS, NULL);
4151 g_strfreev(options);
4155 /* And now our feature presentation... [ fade to music ] */
4157 main(int argc, char *argv[])
4159 GString *comp_info_str;
4160 GString *runtime_info_str;
4162 struct option long_options[] = {
4163 {(char *)"capture-comment", required_argument, NULL, LONGOPT_NUM_CAP_COMMENT },
4167 gboolean arg_error = FALSE;
4172 struct sigaction action, oldaction;
4175 gboolean start_capture = TRUE;
4176 gboolean stats_known;
4177 struct pcap_stat stats;
4178 GLogLevelFlags log_flags;
4179 gboolean list_interfaces = FALSE;
4180 gboolean list_link_layer_types = FALSE;
4181 #ifdef HAVE_BPF_IMAGE
4182 gboolean print_bpf_code = FALSE;
4184 gboolean set_chan = FALSE;
4185 gchar *set_chan_arg = NULL;
4186 gboolean machine_readable = FALSE;
4187 gboolean print_statistics = FALSE;
4188 int status, run_once_args = 0;
4191 #if defined(__APPLE__) && defined(__LP64__)
4192 struct utsname osinfo;
4196 /* Assemble the compile-time version information string */
4197 comp_info_str = g_string_new("Compiled ");
4198 get_compiled_version_info(comp_info_str, NULL, NULL);
4200 /* Assemble the run-time version information string */
4201 runtime_info_str = g_string_new("Running ");
4202 get_runtime_version_info(runtime_info_str, NULL);
4204 /* Add it to the information to be reported on a crash. */
4205 ws_add_crash_info("Dumpcap " VERSION "%s\n"
4210 wireshark_svnversion, comp_info_str->str, runtime_info_str->str);
4213 arg_list_utf_16to8(argc, argv);
4214 create_app_running_mutex();
4217 * Initialize our DLL search path. MUST be called before LoadLibrary
4220 ws_init_dll_search_path();
4223 #ifdef HAVE_PCAP_REMOTE
4224 #define OPTSTRING_A "A:"
4225 #define OPTSTRING_r "r"
4226 #define OPTSTRING_u "u"
4228 #define OPTSTRING_A ""
4229 #define OPTSTRING_r ""
4230 #define OPTSTRING_u ""
4233 #ifdef HAVE_PCAP_SETSAMPLING
4234 #define OPTSTRING_m "m:"
4236 #define OPTSTRING_m ""
4239 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4240 #define OPTSTRING_B "B:"
4242 #define OPTSTRING_B ""
4243 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4245 #ifdef HAVE_PCAP_CREATE
4246 #define OPTSTRING_I "I"
4248 #define OPTSTRING_I ""
4251 #ifdef HAVE_BPF_IMAGE
4252 #define OPTSTRING_d "d"
4254 #define OPTSTRING_d ""
4257 #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:"
4259 #ifdef DEBUG_CHILD_DUMPCAP
4260 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4261 fprintf (stderr, "Unable to open debug log file !\n");
4266 #if defined(__APPLE__) && defined(__LP64__)
4268 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
4269 * a bug workaround - timeouts less than 1 second don't work with libpcap
4270 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
4271 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4272 * The problem is extremely unlikely to be reintroduced in a future
4275 if (uname(&osinfo) == 0) {
4277 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
4278 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4279 * number of 10.0.0, not 10.1.0 - go figure).
4281 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
4282 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
4283 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
4284 need_timeout_workaround = TRUE;
4289 * Determine if dumpcap is being requested to run in a special
4290 * capture_child mode by going thru the command line args to see if
4291 * a -Z is present. (-Z is a hidden option).
4293 * The primary result of running in capture_child mode is that
4294 * all messages sent out on stderr are in a special type/len/string
4295 * format to allow message processing by type. These messages include
4296 * error messages if dumpcap fails to start the operation it was
4297 * requested to do, as well as various "status" messages which are sent
4298 * when an actual capture is in progress, and a "success" message sent
4299 * if dumpcap was requested to perform an operation other than a
4302 * Capture_child mode would normally be requested by a parent process
4303 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4304 * to which dumpcap stderr has been redirected. It might also have
4305 * another pipe to obtain dumpcap stdout output; for operations other
4306 * than a capture, that information is formatted specially for easier
4307 * parsing by the parent process.
4309 * Capture_child mode needs to be determined immediately upon
4310 * startup so that any messages generated by dumpcap in this mode
4311 * (eg: during initialization) will be formatted properly.
4314 for (i=1; i<argc; i++) {
4315 if (strcmp("-Z", argv[i]) == 0) {
4316 capture_child = TRUE;
4317 machine_readable = TRUE; /* request machine-readable output */
4319 /* set output pipe to binary mode, to avoid ugly text conversions */
4320 _setmode(2, O_BINARY);
4325 /* The default_log_handler will use stdout, which makes trouble in */
4326 /* capture child mode, as it uses stdout for its sync_pipe. */
4327 /* So: the filtering is done in the console_log_handler and not here.*/
4328 /* We set the log handlers right up front to make sure that any log */
4329 /* messages when running as child will be sent back to the parent */
4330 /* with the correct format. */
4335 G_LOG_LEVEL_CRITICAL|
4336 G_LOG_LEVEL_WARNING|
4337 G_LOG_LEVEL_MESSAGE|
4341 G_LOG_FLAG_RECURSION);
4343 g_log_set_handler(NULL,
4345 console_log_handler, NULL /* user_data */);
4346 g_log_set_handler(LOG_DOMAIN_MAIN,
4348 console_log_handler, NULL /* user_data */);
4349 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4351 console_log_handler, NULL /* user_data */);
4352 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4354 console_log_handler, NULL /* user_data */);
4356 /* Initialize the pcaps list */
4357 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
4359 #if !GLIB_CHECK_VERSION(2,31,0)
4360 /* Initialize the thread system */
4361 g_thread_init(NULL);
4365 /* Load wpcap if possible. Do this before collecting the run-time version information */
4368 /* ... and also load the packet.dll from wpcap */
4369 /* XXX - currently not required, may change later. */
4370 /*wpcap_packet_load();*/
4372 /* Start windows sockets */
4373 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4375 /* Set handler for Ctrl+C key */
4376 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4378 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4379 and exit. Do the same with SIGPIPE, in case, for example,
4380 we're writing to our standard output and it's a pipe.
4381 Do the same with SIGHUP if it's not being ignored (if we're
4382 being run under nohup, it might be ignored, in which case we
4383 should leave it ignored).
4385 XXX - apparently, Coverity complained that part of action
4386 wasn't initialized. Perhaps it's running on Linux, where
4387 struct sigaction has an ignored "sa_restorer" element and
4388 where "sa_handler" and "sa_sigaction" might not be two
4389 members of a union. */
4390 memset(&action, 0, sizeof(action));
4391 action.sa_handler = capture_cleanup_handler;
4393 * Arrange that system calls not get restarted, because when
4394 * our signal handler returns we don't want to restart
4395 * a call that was waiting for packets to arrive.
4397 action.sa_flags = 0;
4398 sigemptyset(&action.sa_mask);
4399 sigaction(SIGTERM, &action, NULL);
4400 sigaction(SIGINT, &action, NULL);
4401 sigaction(SIGPIPE, &action, NULL);
4402 sigaction(SIGHUP, NULL, &oldaction);
4403 if (oldaction.sa_handler == SIG_DFL)
4404 sigaction(SIGHUP, &action, NULL);
4407 /* Catch SIGINFO and, if we get it and we're capturing in
4408 quiet mode, report the number of packets we've captured. */
4409 action.sa_handler = report_counts_siginfo;
4410 action.sa_flags = SA_RESTART;
4411 sigemptyset(&action.sa_mask);
4412 sigaction(SIGINFO, &action, NULL);
4413 #endif /* SIGINFO */
4417 enable_kernel_bpf_jit_compiler();
4420 /* ----------------------------------------------------------------- */
4421 /* Privilege and capability handling */
4423 /* 1. Running not as root or suid root; no special capabilities. */
4426 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4429 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4431 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4432 /* capabilities; Drop all other capabilities; */
4433 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4434 /* else: after pcap_open_live() in capture_loop_open_input() */
4435 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4436 /* (Note: this means that the process, although logged in */
4437 /* as root, does not have various permissions such as the */
4438 /* ability to bypass file access permissions). */
4439 /* XXX: Should we just leave capabilities alone in this case */
4440 /* so that user gets expected effect that root can do */
4443 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4445 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4446 /* else: after pcap_open_live() in capture_loop_open_input() */
4447 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4448 /* pcap_open_live). */
4450 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4452 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4453 /* capabilities; Drop all other capabilities; */
4454 /* Drop suid privileges (euid=ruid); */
4455 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4456 /* else: after pcap_open_live() in capture_loop_open_input() */
4457 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4459 /* XXX: For some Linux versions/distros with capabilities */
4460 /* a 'normal' process with any capabilities cannot be */
4461 /* 'killed' (signaled) from another (same uid) non-privileged */
4463 /* For example: If (non-suid) Wireshark forks a */
4464 /* child suid dumpcap which acts as described here (case 5), */
4465 /* Wireshark will be unable to kill (signal) the child */
4466 /* dumpcap process until the capabilities have been dropped */
4467 /* (after pcap_open_live()). */
4468 /* This behaviour will apparently be changed in the kernel */
4469 /* to allow the kill (signal) in this case. */
4470 /* See the following for details: */
4471 /* http://www.mail-archive.com/ [wrapped] */
4472 /* linux-security-module@vger.kernel.org/msg02913.html */
4474 /* It is therefore conceivable that if dumpcap somehow hangs */
4475 /* in pcap_open_live or before that wireshark will not */
4476 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4477 /* In this case, exiting wireshark will kill the child */
4478 /* dumpcap process. */
4480 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4481 /* capabilities; Using libcap. Note: capset cmd (which see) */
4482 /* used to assign capabilities to file. */
4484 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4485 /* else: after pcap_open_live() in capture_loop_open_input() */
4486 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4488 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4489 /* longer required (similar to capture). */
4491 /* ----------------------------------------------------------------- */
4493 init_process_policies();
4496 /* If 'started with special privileges' (and using libcap) */
4497 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4498 /* Set euid/egid = ruid/rgid to remove suid privileges */
4499 relinquish_privs_except_capture();
4502 /* Set the initial values in the capture options. This might be overwritten
4503 by the command line parameters. */
4504 capture_opts_init(&global_capture_opts);
4506 /* We always save to a file - if no file was specified, we save to a
4508 global_capture_opts.saving_to_file = TRUE;
4509 global_capture_opts.has_ring_num_files = TRUE;
4511 /* Pass on capture_child mode for capture_opts */
4512 global_capture_opts.capture_child = capture_child;
4514 /* Now get our args */
4515 while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4517 case 'h': /* Print help and exit */
4521 case 'v': /* Show version and exit */
4523 show_version(comp_info_str, runtime_info_str);
4524 g_string_free(comp_info_str, TRUE);
4525 g_string_free(runtime_info_str, TRUE);
4529 /*** capture option specific ***/
4530 case 'a': /* autostop criteria */
4531 case 'b': /* Ringbuffer option */
4532 case 'c': /* Capture x packets */
4533 case 'f': /* capture filter */
4534 case 'g': /* enable group read access on file(s) */
4535 case 'i': /* Use interface x */
4536 case 'n': /* Use pcapng format */
4537 case 'p': /* Don't capture in promiscuous mode */
4538 case 'P': /* Use pcap format */
4539 case 's': /* Set the snapshot (capture) length */
4540 case 'w': /* Write to capture file x */
4541 case 'y': /* Set the pcap data link type */
4542 case LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4543 #ifdef HAVE_PCAP_REMOTE
4544 case 'u': /* Use UDP for data transfer */
4545 case 'r': /* Capture own RPCAP traffic too */
4546 case 'A': /* Authentication */
4548 #ifdef HAVE_PCAP_SETSAMPLING
4549 case 'm': /* Sampling */
4551 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4552 case 'B': /* Buffer size */
4553 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4554 #ifdef HAVE_PCAP_CREATE
4555 case 'I': /* Monitor mode */
4557 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4562 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4564 capture_child = TRUE;
4566 /* set output pipe to binary mode, to avoid ugly text conversions */
4567 _setmode(2, O_BINARY);
4569 * optarg = the control ID, aka the PPID, currently used for the
4572 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4573 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4574 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4575 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4577 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4578 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4579 "Signal pipe: Unable to open %s. Dead parent?",
4587 case 'q': /* Quiet */
4593 /*** all non capture option specific ***/
4594 case 'D': /* Print a list of capture devices and exit */
4595 list_interfaces = TRUE;
4598 case 'L': /* Print list of link-layer types and exit */
4599 list_link_layer_types = TRUE;
4602 #ifdef HAVE_BPF_IMAGE
4603 case 'd': /* Print BPF code for capture filter and exit */
4604 print_bpf_code = TRUE;
4608 case 'S': /* Print interface statistics once a second */
4609 print_statistics = TRUE;
4612 case 'k': /* Set wireless channel */
4614 set_chan_arg = optarg;
4617 case 'M': /* For -D, -L, and -S, print machine-readable output */
4618 machine_readable = TRUE;
4621 pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4624 pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4627 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4629 case '?': /* Bad flag - print usage message */
4638 /* user specified file name as regular command-line argument */
4639 /* XXX - use it as the capture file name (or something else)? */
4645 * Extra command line arguments were specified; complain.
4646 * XXX - interpret as capture filter, as tcpdump and tshark do?
4648 cmdarg_err("Invalid argument: %s", argv[0]);
4653 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4656 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4657 /* Use some default if the user hasn't specified some */
4658 /* XXX: Are these defaults good enough? */
4659 pcap_queue_byte_limit = 1000 * 1000;
4660 pcap_queue_packet_limit = 1000;
4667 if (run_once_args > 1) {
4668 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
4670 } else if (run_once_args == 1) {
4671 /* We're supposed to print some information, rather than
4672 to capture traffic; did they specify a ring buffer option? */
4673 if (global_capture_opts.multi_files_on) {
4674 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4678 /* We're supposed to capture traffic; */
4680 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4681 if (global_capture_opts.ifaces->len > 1) {
4683 global_capture_opts.use_pcapng = TRUE;
4686 if (global_capture_opts.capture_comment &&
4687 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4688 /* XXX - for ringbuffer, should we apply the comment to each file? */
4689 cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4693 /* Was the ring buffer option specified and, if so, does it make sense? */
4694 if (global_capture_opts.multi_files_on) {
4695 /* Ring buffer works only under certain conditions:
4696 a) ring buffer does not work with temporary files;
4697 b) it makes no sense to enable the ring buffer if the maximum
4698 file size is set to "infinite". */
4699 if (global_capture_opts.save_file == NULL) {
4700 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4701 global_capture_opts.multi_files_on = FALSE;
4703 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4704 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4706 /* XXX - this must be redesigned as the conditions changed */
4707 global_capture_opts.multi_files_on = FALSE;
4714 * "-D" requires no interface to be selected; it's supposed to list
4717 if (list_interfaces) {
4718 /* Get the list of interfaces */
4723 if_list = capture_interface_list(&err, &err_str,NULL);
4724 if (if_list == NULL) {
4726 case CANT_GET_INTERFACE_LIST:
4727 case DONT_HAVE_PCAP:
4728 cmdarg_err("%s", err_str);
4733 case NO_INTERFACES_FOUND:
4735 * If we're being run by another program, just give them
4736 * an empty list of interfaces, don't report this as
4737 * an error; that lets them decide whether to report
4738 * this as an error or not.
4740 if (!machine_readable) {
4741 cmdarg_err("There are no interfaces on which a capture can be done");
4748 if (machine_readable) /* tab-separated values to stdout */
4749 print_machine_readable_interfaces(if_list);
4751 capture_opts_print_interfaces(if_list);
4752 free_interface_list(if_list);
4757 * "-S" requires no interface to be selected; it gives statistics
4758 * for all interfaces.
4760 if (print_statistics) {
4761 status = print_statistics_loop(machine_readable);
4766 interface_options interface_opts;
4768 if (global_capture_opts.ifaces->len != 1) {
4769 cmdarg_err("Need one interface");
4773 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4774 status = set_80211_channel(interface_opts.name, set_chan_arg);
4779 * "-L", "-d", and capturing act on a particular interface, so we have to
4780 * have an interface; if none was specified, pick a default.
4782 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4784 /* cmdarg_err() already called .... */
4788 /* Let the user know what interfaces were chosen. */
4789 if (capture_child) {
4790 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4791 interface_options interface_opts;
4793 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4794 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4795 interface_opts.name);
4798 str = g_string_new("");
4800 if (global_capture_opts.ifaces->len < 2)
4802 if (global_capture_opts.ifaces->len < 4)
4805 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4806 interface_options interface_opts;
4808 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4810 if (global_capture_opts.ifaces->len > 2) {
4811 g_string_append_printf(str, ",");
4813 g_string_append_printf(str, " ");
4814 if (j == global_capture_opts.ifaces->len - 1) {
4815 g_string_append_printf(str, "and ");
4818 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
4821 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4823 fprintf(stderr, "Capturing on %s\n", str->str);
4824 g_string_free(str, TRUE);
4827 if (list_link_layer_types) {
4828 /* Get the list of link-layer types for the capture device. */
4829 if_capabilities_t *caps;
4833 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4834 interface_options interface_opts;
4836 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4837 caps = get_if_capabilities(interface_opts.name,
4838 interface_opts.monitor_mode, &err_str);
4840 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4841 "Please check to make sure you have sufficient permissions, and that\n"
4842 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4846 if (caps->data_link_types == NULL) {
4847 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4850 if (machine_readable) /* tab-separated values to stdout */
4851 /* XXX: We need to change the format and adopt consumers */
4852 print_machine_readable_if_capabilities(caps);
4854 /* XXX: We might want to print also the interface name */
4855 capture_opts_print_if_capabilities(caps, interface_opts.name,
4856 interface_opts.monitor_mode);
4857 free_if_capabilities(caps);
4862 /* We're supposed to do a capture, or print the BPF code for a filter.
4863 Process the snapshot length, as that affects the generated BPF code. */
4864 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4866 #ifdef HAVE_BPF_IMAGE
4867 if (print_bpf_code) {
4868 show_filter_code(&global_capture_opts);
4873 /* We're supposed to do a capture. Process the ring buffer arguments. */
4874 capture_opts_trim_ring_num_files(&global_capture_opts);
4876 /* flush stderr prior to starting the main capture loop */
4879 /* Now start the capture. */
4881 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4885 /* capture failed */
4888 return 0; /* never here, make compiler happy */
4893 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4894 const char *message, gpointer user_data _U_)
4901 /* ignore log message, if log_level isn't interesting */
4902 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4903 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4908 /* create a "timestamp" */
4910 today = localtime(&curr);
4912 switch(log_level & G_LOG_LEVEL_MASK) {
4913 case G_LOG_LEVEL_ERROR:
4916 case G_LOG_LEVEL_CRITICAL:
4919 case G_LOG_LEVEL_WARNING:
4922 case G_LOG_LEVEL_MESSAGE:
4925 case G_LOG_LEVEL_INFO:
4928 case G_LOG_LEVEL_DEBUG:
4932 fprintf(stderr, "unknown log_level %u\n", log_level);
4934 g_assert_not_reached();
4937 /* Generate the output message */
4938 if (log_level & G_LOG_LEVEL_MESSAGE) {
4939 /* normal user messages without additional infos */
4940 msg = g_strdup_printf("%s\n", message);
4942 /* info/debug messages with additional infos */
4943 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4944 today->tm_hour, today->tm_min, today->tm_sec,
4945 log_domain != NULL ? log_domain : "",
4949 /* DEBUG & INFO msgs (if we're debugging today) */
4950 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4951 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4952 #ifdef DEBUG_DUMPCAP
4953 fprintf(stderr, "%s", msg);
4956 #ifdef DEBUG_CHILD_DUMPCAP
4957 fprintf(debug_log, "%s", msg);
4965 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4966 /* to parent especially formatted if dumpcap running as child. */
4967 if (capture_child) {
4968 sync_pipe_errmsg_to_parent(2, msg, "");
4970 fprintf(stderr, "%s", msg);
4977 /****************************************************************************************************************/
4978 /* indication report routines */
4982 report_packet_count(unsigned int packet_count)
4984 char tmp[SP_DECISIZE+1+1];
4985 static unsigned int count = 0;
4987 if (capture_child) {
4988 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
4989 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
4990 pipe_write_block(2, SP_PACKET_COUNT, tmp);
4992 count += packet_count;
4993 fprintf(stderr, "\rPackets: %u ", count);
4994 /* stderr could be line buffered */
5000 report_new_capture_file(const char *filename)
5002 if (capture_child) {
5003 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
5004 pipe_write_block(2, SP_FILE, filename);
5008 * Prevent a SIGINFO handler from writing to the standard error
5009 * while we're doing so; instead, have it just set a flag telling
5010 * us to print that information when we're done.
5013 #endif /* SIGINFO */
5014 fprintf(stderr, "File: %s\n", filename);
5015 /* stderr could be line buffered */
5020 * Allow SIGINFO handlers to write.
5025 * If a SIGINFO handler asked us to write out capture counts, do so.
5028 report_counts_for_siginfo();
5029 #endif /* SIGINFO */
5034 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
5036 interface_options interface_opts;
5037 char tmp[MSG_MAX_LENGTH+1+6];
5039 if (i < capture_opts->ifaces->len) {
5040 if (capture_child) {
5041 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
5042 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
5043 pipe_write_block(2, SP_BAD_FILTER, tmp);
5046 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5047 * the error message below.
5049 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
5051 "Invalid capture filter \"%s\" for interface %s!\n"
5053 "That string isn't a valid capture filter (%s).\n"
5054 "See the User's Guide for a description of the capture filter syntax.",
5055 interface_opts.cfilter, interface_opts.name, errmsg);
5061 report_capture_error(const char *error_msg, const char *secondary_error_msg)
5063 if (capture_child) {
5064 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5065 "Primary Error: %s", error_msg);
5066 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5067 "Secondary Error: %s", secondary_error_msg);
5068 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5070 cmdarg_err("%s", error_msg);
5071 if (secondary_error_msg[0] != '\0')
5072 cmdarg_err_cont("%s", secondary_error_msg);
5077 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, gchar *name)
5079 char tmp[SP_DECISIZE+1+1];
5080 guint32 total_drops = pcap_drops + drops + flushed;
5082 g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
5084 if (capture_child) {
5085 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5086 "Packets received/dropped on interface %s: %u/%u (pcap:%u/dumpcap:%u/flushed:%u)",
5087 name, received, total_drops, pcap_drops, drops, flushed);
5088 /* XXX: Need to provide interface id, changes to consumers required. */
5089 pipe_write_block(2, SP_DROPS, tmp);
5092 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u) (%.1f%%)\n",
5093 name, received, total_drops, pcap_drops, drops, flushed,
5094 received ? 100.0 * received / (received + total_drops) : 0.0);
5095 /* stderr could be line buffered */
5101 /************************************************************************************************/
5102 /* signal_pipe handling */
5107 signal_pipe_check_running(void)
5109 /* any news from our parent? -> just stop the capture */
5113 /* if we are running standalone, no check required */
5114 if (!capture_child) {
5118 if (!sig_pipe_name || !sig_pipe_handle) {
5119 /* This shouldn't happen */
5120 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5121 "Signal pipe: No name or handle");
5126 * XXX - We should have the process ID of the parent (from the "-Z" flag)
5127 * at this point. Should we check to see if the parent is still alive,
5128 * e.g. by using OpenProcess?
5131 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5133 if (!result || avail > 0) {
5134 /* peek failed or some bytes really available */
5135 /* (if not piping from stdin this would fail) */
5136 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5137 "Signal pipe: Stop capture: %s", sig_pipe_name);
5138 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5139 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
5140 sig_pipe_handle, result, avail);
5143 /* pipe ok and no bytes available */
5154 * Editor modelines - http://www.wireshark.org/tools/modelines.html
5159 * indent-tabs-mode: nil
5162 * vi: set shiftwidth=4 tabstop=8 expandtab:
5163 * :indentSize=4:tabSize=8:noTabs=true: