5 * Wireshark - Network traffic analyzer
6 * By Gerald Combs <gerald@wireshark.org>
7 * Copyright 1998 Gerald Combs
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 #include <stdlib.h> /* for exit() */
33 #ifdef HAVE_SYS_TYPES_H
34 # include <sys/types.h>
37 #ifdef HAVE_SYS_SOCKET_H
38 #include <sys/socket.h>
41 #ifdef HAVE_NETINET_IN_H
42 #include <netinet/in.h>
45 #ifdef HAVE_SYS_STAT_H
46 # include <sys/stat.h>
57 #ifdef HAVE_ARPA_INET_H
58 #include <arpa/inet.h>
61 #if defined(__APPLE__) && defined(__LP64__)
62 #include <sys/utsname.h>
69 #include "wsutil/wsgetopt.h"
77 # include <sys/prctl.h>
78 # include <sys/capability.h>
81 #include "ringbuffer.h"
82 #include "clopts_common.h"
83 #include "console_io.h"
84 #include "cmdarg_err.h"
85 #include "version_info.h"
87 #include "capture-pcap-util.h"
89 #include "capture-wpcap.h"
95 #include "capture-wpcap.h"
96 #include <wsutil/unicode-utils.h>
103 #ifdef NEED_INET_V6DEFS_H
104 # include "wsutil/inet_v6defs.h"
107 #include <wsutil/privileges.h>
109 #include "sync_pipe.h"
111 #include "capture_opts.h"
112 #include "capture_ifinfo.h"
113 #include "capture_sync.h"
115 #include "conditions.h"
116 #include "capture_stop_conditions.h"
118 #include "tempfile.h"
120 #include "wsutil/file_util.h"
122 #include "ws80211_utils.h"
125 * Get information about libpcap format from "wiretap/libpcap.h".
126 * XXX - can we just use pcap_open_offline() to read the pipe?
128 #include "wiretap/libpcap.h"
130 /**#define DEBUG_DUMPCAP**/
131 /**#define DEBUG_CHILD_DUMPCAP**/
135 #include <conio.h> /* _getch() */
139 #ifdef DEBUG_CHILD_DUMPCAP
140 FILE *debug_log; /* for logging debug messages to */
141 /* a file if DEBUG_CHILD_DUMPCAP */
145 static GAsyncQueue *pcap_queue;
146 static gint64 pcap_queue_bytes;
147 static gint64 pcap_queue_packets;
148 static gint64 pcap_queue_byte_limit = 1024 * 1024;
149 static gint64 pcap_queue_packet_limit = 1000;
151 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
153 static gchar *sig_pipe_name = NULL;
154 static HANDLE sig_pipe_handle = NULL;
155 static gboolean signal_pipe_check_running(void);
159 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
160 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
163 /** Stop a low-level capture (stops the capture child). */
164 static void capture_loop_stop(void);
165 /** Close a pipe, or socket if \a from_socket is TRUE */
166 static void cap_pipe_close(int pipe_fd, gboolean from_socket _U_);
168 #if !defined (__linux__)
169 #ifndef HAVE_PCAP_BREAKLOOP
171 * We don't have pcap_breakloop(), which is the only way to ensure that
172 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
173 * won't, if the call to read the next packet or batch of packets is
174 * is interrupted by a signal on UN*X, just go back and try again to
177 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
178 * the signal handler, set a flag to stop capturing; however, without
179 * a guarantee of that sort, we can't guarantee that we'll stop capturing
180 * if the read will be retried and won't time out if no packets arrive.
182 * Therefore, on at least some platforms, we work around the lack of
183 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
184 * to wait for packets to arrive, so that we're probably going to be
185 * blocked in the select() when the signal arrives, and can just bail
186 * out of the loop at that point.
188 * However, we don't want to do that on BSD (because "select()" doesn't work
189 * correctly on BPF devices on at least some releases of some flavors of
190 * BSD), and we don't want to do it on Windows (because "select()" is
191 * something for sockets, not for arbitrary handles). (Note that "Windows"
192 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
193 * using WinPcap, not a UNIX libpcap.)
195 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
196 * on BSD times out even if no packets have arrived, so we'll eventually
197 * exit pcap_dispatch() with an indication that no packets have arrived,
198 * and will break out of the capture loop at that point.
200 * On Windows, we can't send a SIGINT to stop capturing, so none of this
201 * applies in any case.
203 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
204 * want to include it if it's not present on this platform, however.
206 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
207 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
209 # define MUST_DO_SELECT
210 # endif /* avoid select */
211 #endif /* HAVE_PCAP_BREAKLOOP */
213 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
214 * in pcap_dispatch(); on the other hand, select() works just fine there.
215 * Hence we use a select for that come what may.
217 #define MUST_DO_SELECT
220 /** init the capture filter */
223 INITFILTER_BAD_FILTER,
224 INITFILTER_OTHER_ERROR
225 } initfilter_status_t;
227 typedef struct _pcap_options {
231 #ifdef MUST_DO_SELECT
232 int pcap_fd; /* pcap file descriptor */
239 gboolean ts_nsec; /* TRUE if we're using nanosecond precision. */
240 /* capture pipe (unix only "input file") */
241 gboolean from_cap_pipe; /* TRUE if we are capturing data from a capture pipe */
242 gboolean from_cap_socket; /* TRUE if we're capturing from socket */
243 struct pcap_hdr cap_pipe_hdr; /* Pcap header when capturing from a pipe */
244 struct pcaprec_modified_hdr cap_pipe_rechdr; /* Pcap record header when capturing from a pipe */
246 HANDLE cap_pipe_h; /* The handle of the capture pipe */
248 int cap_pipe_fd; /* the file descriptor of the capture pipe */
249 gboolean cap_pipe_modified; /* TRUE if data in the pipe uses modified pcap headers */
250 gboolean cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
252 char * cap_pipe_buf; /* Pointer to the data buffer we read into */
254 int cap_pipe_bytes_to_read; /* Used by cap_pipe_dispatch */
255 int cap_pipe_bytes_read; /* Used by cap_pipe_dispatch */
257 STATE_EXPECT_REC_HDR,
262 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
264 GMutex *cap_pipe_read_mtx;
265 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
269 typedef struct _loop_data {
271 gboolean go; /* TRUE as long as we're supposed to keep capturing */
272 int err; /* if non-zero, error seen while capturing */
273 gint packet_count; /* Number of packets we have already captured */
274 gint packet_max; /* Number of packets we're supposed to capture - 0 means infinite */
275 guint inpkts_to_sync_pipe; /* Packets not already send out to the sync_pipe */
277 gboolean report_packet_count; /* Set by SIGINFO handler; print packet count */
284 guint32 autostop_files;
287 typedef struct _pcap_queue_element {
288 pcap_options *pcap_opts;
289 struct pcap_pkthdr phdr;
291 } pcap_queue_element;
294 * Standard secondary message for unexpected errors.
296 static const char please_report[] =
297 "Please report this to the Wireshark developers.\n"
298 "(This is not a crash; please do not report it as such.)";
301 * This needs to be static, so that the SIGINT handler can clear the "go"
304 static loop_data global_ld;
308 * Timeout, in milliseconds, for reads from the stream of captured packets
309 * from a capture device.
311 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
312 * 64-bit applications, with sub-second timeouts not to work. The bug is
313 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
315 #if defined(__APPLE__) && defined(__LP64__)
316 static gboolean need_timeout_workaround;
318 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
320 #define CAP_READ_TIMEOUT 250
324 * Timeout, in microseconds, for reads from the stream of captured packets
325 * from a pipe. Pipes don't have the same problem that BPF devices do
326 * in OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
327 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
328 * of the offending versions of Snow Leopard.
330 * On Windows this value is converted to milliseconds and passed to
331 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
332 * will return immediately.
335 #define PIPE_READ_TIMEOUT 100000
337 #define PIPE_READ_TIMEOUT 250000
340 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
343 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
344 const char *message, gpointer user_data _U_);
346 /* capture related options */
347 static capture_options global_capture_opts;
348 static gboolean quiet = FALSE;
349 static gboolean use_threads = FALSE;
350 static guint64 start_time;
352 static void capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
354 static void capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
356 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
357 int err, gboolean is_close);
359 static void WS_MSVC_NORETURN exit_main(int err) G_GNUC_NORETURN;
361 static void report_new_capture_file(const char *filename);
362 static void report_packet_count(unsigned int packet_count);
363 static void report_packet_drops(guint32 received, guint32 drops, gchar *name);
364 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
365 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
367 #define MSG_MAX_LENGTH 4096
369 /* Copied from pcapio.c libpcap_write_interface_statistics_block()*/
371 create_timestamp(void) {
381 * Current time, represented as 100-nanosecond intervals since
382 * January 1, 1601, 00:00:00 UTC.
384 * I think DWORD might be signed, so cast both parts of "now"
385 * to guint32 so that the sign bit doesn't get treated specially.
387 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
388 * might want to use instead.
390 GetSystemTimeAsFileTime(&now);
391 timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
392 (guint32)now.dwLowDateTime;
395 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
401 * Subtract difference, in microseconds, between January 1, 1601
402 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
404 timestamp -= G_GINT64_CONSTANT(11644473600000000U);
407 * Current time, represented as seconds and microseconds since
408 * January 1, 1970, 00:00:00 UTC.
410 gettimeofday(&now, NULL);
413 * Convert to delta in microseconds.
415 timestamp = (guint64)(now.tv_sec) * 1000000 +
416 (guint64)(now.tv_usec);
422 print_usage(gboolean print_ver)
429 "Dumpcap " VERSION "%s\n"
430 "Capture network packets and dump them into a pcapng file.\n"
431 "See http://www.wireshark.org for more information.\n",
432 wireshark_svnversion);
436 fprintf(output, "\nUsage: dumpcap [options] ...\n");
437 fprintf(output, "\n");
438 fprintf(output, "Capture interface:\n");
439 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback),\n"
440 " or for remote capturing, use one of these formats:\n"
441 " rpcap://<host>/<interface>\n"
442 " TCP@<host>:<port>\n");
443 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
444 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
445 fprintf(output, " -p don't capture in promiscuous mode\n");
446 #ifdef HAVE_PCAP_CREATE
447 fprintf(output, " -I capture in monitor mode, if available\n");
449 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
450 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
452 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
453 fprintf(output, " -D print list of interfaces and exit\n");
454 fprintf(output, " -L print list of link-layer types of iface and exit\n");
455 #ifdef HAVE_BPF_IMAGE
456 fprintf(output, " -d print generated BPF code for capture filter\n");
458 fprintf(output, " -k set channel on wifi interface <freq>,[<type>]\n");
459 fprintf(output, " -S print statistics for each interface once per second\n");
460 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
461 fprintf(output, "\n");
462 #ifdef HAVE_PCAP_REMOTE
463 fprintf(output, "RPCAP options:\n");
464 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
465 fprintf(output, " -u use UDP for RPCAP data transfer\n");
466 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
467 #ifdef HAVE_PCAP_SETSAMPLING
468 fprintf(output, " -m <sampling type> use packet sampling\n");
469 fprintf(output, " count:NUM - capture one packet of every NUM\n");
470 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
473 fprintf(output, "Stop conditions:\n");
474 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
475 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
476 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
477 fprintf(output, " files:NUM - stop after NUM files\n");
478 /*fprintf(output, "\n");*/
479 fprintf(output, "Output (files):\n");
480 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
481 fprintf(output, " -g enable group read access on the output file(s)\n");
482 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
483 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
484 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
485 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
486 fprintf(output, " -P use libpcap format instead of pcapng\n");
487 fprintf(output, "\n");
488 fprintf(output, "Miscellaneous:\n");
489 fprintf(output, " -t use a separate thread per interface\n");
490 fprintf(output, " -q don't report packet capture counts\n");
491 fprintf(output, " -v print version information and exit\n");
492 fprintf(output, " -h display this help and exit\n");
493 fprintf(output, "\n");
494 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
495 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
496 fprintf(output, "\n");
497 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
501 show_version(GString *comp_info_str, GString *runtime_info_str)
504 "Dumpcap " VERSION "%s\n"
509 "See http://www.wireshark.org for more information.\n",
510 wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
514 * Print to the standard error. This is a command-line tool, so there's
515 * no need to pop up a console.
518 vfprintf_stderr(const char *fmt, va_list ap)
520 vfprintf(stderr, fmt, ap);
524 fprintf_stderr(const char *fmt, ...)
529 vfprintf_stderr(fmt, ap);
534 * Report an error in command-line arguments.
537 cmdarg_err(const char *fmt, ...)
543 /* Generate a 'special format' message back to parent */
545 msg = g_strdup_vprintf(fmt, ap);
546 sync_pipe_errmsg_to_parent(2, msg, "");
551 fprintf(stderr, "dumpcap: ");
552 vfprintf(stderr, fmt, ap);
553 fprintf(stderr, "\n");
559 * Report additional information for an error in command-line arguments.
562 cmdarg_err_cont(const char *fmt, ...)
569 msg = g_strdup_vprintf(fmt, ap);
570 sync_pipe_errmsg_to_parent(2, msg, "");
575 vfprintf(stderr, fmt, ap);
576 fprintf(stderr, "\n");
583 #if 0 /* Set to enable capability debugging */
584 /* see 'man cap_to_text()' for explanation of output */
585 /* '=' means 'all= ' ie: no capabilities */
586 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
588 print_caps(const char *pfx) {
589 cap_t caps = cap_get_proc();
590 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
591 "%s: EUID: %d Capabilities: %s", pfx,
592 geteuid(), cap_to_text(caps, NULL));
595 print_caps(const char *pfx _U_) {
600 relinquish_all_capabilities(void)
602 /* Drop any and all capabilities this process may have. */
603 /* Allowed whether or not process has any privileges. */
604 cap_t caps = cap_init(); /* all capabilities initialized to off */
605 print_caps("Pre-clear");
606 if (cap_set_proc(caps)) {
607 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
609 print_caps("Post-clear");
615 open_capture_device(interface_options *interface_opts,
616 char (*open_err_str)[PCAP_ERRBUF_SIZE])
619 #ifdef HAVE_PCAP_CREATE
622 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
623 struct pcap_rmtauth auth;
626 /* Open the network interface to capture from it.
627 Some versions of libpcap may put warnings into the error buffer
628 if they succeed; to tell if that's happened, we have to clear
629 the error buffer, and check if it's still a null string. */
630 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Entering open_capture_device().");
631 (*open_err_str)[0] = '\0';
632 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
634 * If we're opening a remote device, use pcap_open(); that's currently
635 * the only open routine that supports remote devices.
637 if (strncmp (interface_opts->name, "rpcap://", 8) == 0) {
638 auth.type = interface_opts->auth_type == CAPTURE_AUTH_PWD ?
639 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
640 auth.username = interface_opts->auth_username;
641 auth.password = interface_opts->auth_password;
643 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
644 "Calling pcap_open() using name %s, snaplen %d, promisc_mode %d, datatx_udp %d, nocap_rpcap %d.",
645 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode,
646 interface_opts->datatx_udp, interface_opts->nocap_rpcap);
647 pcap_h = pcap_open(interface_opts->name, interface_opts->snaplen,
649 (interface_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
650 (interface_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
651 (interface_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
652 CAP_READ_TIMEOUT, &auth, *open_err_str);
653 if (pcap_h == NULL) {
654 /* Error - did pcap actually supply an error message? */
655 if ((*open_err_str)[0] == '\0') {
656 /* Work around known WinPcap bug wherein no error message is
657 filled in on a failure to open an rpcap: URL. */
658 g_strlcpy(*open_err_str,
659 "Unknown error (pcap bug; actual error cause not reported)",
660 sizeof *open_err_str);
663 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
664 "pcap_open() returned %p.", (void *)pcap_h);
669 * If we're not opening a remote device, use pcap_create() and
670 * pcap_activate() if we have them, so that we can set the buffer
671 * size, otherwise use pcap_open_live().
673 #ifdef HAVE_PCAP_CREATE
674 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
675 "Calling pcap_create() using %s.", interface_opts->name);
676 pcap_h = pcap_create(interface_opts->name, *open_err_str);
677 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
678 "pcap_create() returned %p.", (void *)pcap_h);
679 if (pcap_h != NULL) {
680 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
681 "Calling pcap_set_snaplen() with snaplen %d.", interface_opts->snaplen);
682 pcap_set_snaplen(pcap_h, interface_opts->snaplen);
683 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
684 "Calling pcap_set_promisc() with promisc_mode %d.", interface_opts->promisc_mode);
685 pcap_set_promisc(pcap_h, interface_opts->promisc_mode);
686 pcap_set_timeout(pcap_h, CAP_READ_TIMEOUT);
688 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
689 "buffersize %d.", interface_opts->buffer_size);
690 if (interface_opts->buffer_size != 0) {
691 pcap_set_buffer_size(pcap_h, interface_opts->buffer_size * 1024 * 1024);
693 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
694 "monitor_mode %d.", interface_opts->monitor_mode);
695 if (interface_opts->monitor_mode)
696 pcap_set_rfmon(pcap_h, 1);
697 err = pcap_activate(pcap_h);
698 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
699 "pcap_activate() returned %d.", err);
701 /* Failed to activate, set to NULL */
702 if (err == PCAP_ERROR)
703 g_strlcpy(*open_err_str, pcap_geterr(pcap_h), sizeof *open_err_str);
705 g_strlcpy(*open_err_str, pcap_statustostr(err), sizeof *open_err_str);
711 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
712 "pcap_open_live() calling using name %s, snaplen %d, promisc_mode %d.",
713 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode);
714 pcap_h = pcap_open_live(interface_opts->name, interface_opts->snaplen,
715 interface_opts->promisc_mode, CAP_READ_TIMEOUT,
717 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
718 "pcap_open_live() returned %p.", (void *)pcap_h);
721 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "open_capture_device %s : %s", pcap_h ? "SUCCESS" : "FAILURE", interface_opts->name);
726 get_capture_device_open_failure_messages(const char *open_err_str,
732 char *errmsg, size_t errmsg_len,
733 char *secondary_errmsg,
734 size_t secondary_errmsg_len)
737 const char *libpcap_warn;
738 static const char ppamsg[] = "can't find PPA for ";
741 g_snprintf(errmsg, (gulong) errmsg_len,
742 "The capture session could not be initiated (%s).", open_err_str);
745 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
747 "In order to capture packets, WinPcap must be installed; see\n"
749 " http://www.winpcap.org/\n"
753 " http://www.mirrors.wiretapped.net/security/packet-capture/winpcap/\n"
757 " http://winpcap.cs.pu.edu.tw/\n"
759 "for a downloadable version of WinPcap and for instructions on how to install\n"
762 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
764 "Please check that \"%s\" is the proper interface.\n"
767 "Help can be found at:\n"
769 " http://wiki.wireshark.org/WinPcap\n"
770 " http://wiki.wireshark.org/CaptureSetup\n",
774 /* If we got a "can't find PPA for X" message, warn the user (who
775 is running dumpcap on HP-UX) that they don't have a version of
776 libpcap that properly handles HP-UX (libpcap 0.6.x and later
777 versions, which properly handle HP-UX, say "can't find /dev/dlpi
778 PPA for X" rather than "can't find PPA for X"). */
779 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
782 "You are running (T)Wireshark with a version of the libpcap library\n"
783 "that doesn't handle HP-UX network devices well; this means that\n"
784 "(T)Wireshark may not be able to capture packets.\n"
786 "To fix this, you should install libpcap 0.6.2, or a later version\n"
787 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
788 "packaged binary form from the Software Porting And Archive Centre\n"
789 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
790 "at the URL lists a number of mirror sites.";
794 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
795 "Please check to make sure you have sufficient permissions, and that you have "
796 "the proper interface or pipe specified.%s", libpcap_warn);
800 /* Set the data link type on a pcap. */
802 set_pcap_linktype(pcap_t *pcap_h, int linktype,
803 #ifdef HAVE_PCAP_SET_DATALINK
808 char *errmsg, size_t errmsg_len,
809 char *secondary_errmsg, size_t secondary_errmsg_len)
811 char *set_linktype_err_str;
814 return TRUE; /* just use the default */
815 #ifdef HAVE_PCAP_SET_DATALINK
816 if (pcap_set_datalink(pcap_h, linktype) == 0)
817 return TRUE; /* no error */
818 set_linktype_err_str = pcap_geterr(pcap_h);
820 /* Let them set it to the type it is; reject any other request. */
821 if (get_pcap_linktype(pcap_h, name) == linktype)
822 return TRUE; /* no error */
823 set_linktype_err_str =
824 "That DLT isn't one of the DLTs supported by this device";
826 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
827 set_linktype_err_str);
829 * If the error isn't "XXX is not one of the DLTs supported by this device",
830 * tell the user to tell the Wireshark developers about it.
832 if (strstr(set_linktype_err_str, "is not one of the DLTs supported by this device") == NULL)
833 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
835 secondary_errmsg[0] = '\0';
840 compile_capture_filter(const char *iface, pcap_t *pcap_h,
841 struct bpf_program *fcode, const char *cfilter)
843 bpf_u_int32 netnum, netmask;
844 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
846 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
848 * Well, we can't get the netmask for this interface; it's used
849 * only for filters that check for broadcast IP addresses, so
850 * we just punt and use 0. It might be nice to warn the user,
851 * but that's a pain in a GUI application, as it'd involve popping
852 * up a message box, and it's not clear how often this would make
853 * a difference (only filters that check for IP broadcast addresses
857 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
862 * Sigh. Older versions of libpcap don't properly declare the
863 * third argument to pcap_compile() as a const pointer. Cast
866 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
871 #ifdef HAVE_BPF_IMAGE
873 show_filter_code(capture_options *capture_opts)
875 interface_options interface_opts;
877 gchar open_err_str[PCAP_ERRBUF_SIZE];
878 char errmsg[MSG_MAX_LENGTH+1];
879 char secondary_errmsg[MSG_MAX_LENGTH+1];
880 struct bpf_program fcode;
881 struct bpf_insn *insn;
885 for (j = 0; j < capture_opts->ifaces->len; j++) {
886 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
887 pcap_h = open_capture_device(&interface_opts, &open_err_str);
888 if (pcap_h == NULL) {
889 /* Open failed; get messages */
890 get_capture_device_open_failure_messages(open_err_str,
892 errmsg, sizeof errmsg,
894 sizeof secondary_errmsg);
895 /* And report them */
896 report_capture_error(errmsg, secondary_errmsg);
900 /* Set the link-layer type. */
901 if (!set_pcap_linktype(pcap_h, interface_opts.linktype, interface_opts.name,
902 errmsg, sizeof errmsg,
903 secondary_errmsg, sizeof secondary_errmsg)) {
905 report_capture_error(errmsg, secondary_errmsg);
909 /* OK, try to compile the capture filter. */
910 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
911 interface_opts.cfilter)) {
913 report_cfilter_error(capture_opts, j, errmsg);
918 /* Now print the filter code. */
919 insn = fcode.bf_insns;
921 for (i = 0; i < fcode.bf_len; insn++, i++)
922 printf("%s\n", bpf_image(insn, i));
924 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
925 /* to remove any suid privileges. */
926 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
927 /* (euid/egid have already previously been set to ruid/rgid. */
928 /* (See comment in main() for details) */
930 relinquish_special_privs_perm();
932 relinquish_all_capabilities();
935 /* Let our parent know we succeeded. */
936 pipe_write_block(2, SP_SUCCESS, NULL);
943 * capture_interface_list() is expected to do the right thing to get
944 * a list of interfaces.
946 * In most of the programs in the Wireshark suite, "the right thing"
947 * is to run dumpcap and ask it for the list, because dumpcap may
948 * be the only program in the suite with enough privileges to get
951 * In dumpcap itself, however, we obviously can't run dumpcap to
952 * ask for the list. Therefore, our capture_interface_list() should
953 * just call get_interface_list().
956 capture_interface_list(int *err, char **err_str)
958 return get_interface_list(err, err_str);
962 * Get the data-link type for a libpcap device.
963 * This works around AIX 5.x's non-standard and incompatible-with-the-
964 * rest-of-the-universe libpcap.
967 get_pcap_linktype(pcap_t *pch, const char *devicename
975 const char *ifacename;
978 linktype = pcap_datalink(pch);
982 * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
983 * rather than DLT_ values for link-layer types; the ifType values
984 * for LAN devices are:
991 * and the ifType value for a loopback device is 24.
993 * The AIX names for LAN devices begin with:
1000 * and the AIX names for loopback devices begin with "lo".
1002 * (The difference between "Ethernet" and "802.3" is presumably
1003 * whether packets have an Ethernet header, with a packet type,
1004 * or an 802.3 header, with a packet length, followed by an 802.2
1005 * header and possibly a SNAP header.)
1007 * If the device name matches "linktype" interpreted as an ifType
1008 * value, rather than as a DLT_ value, we will assume this is AIX's
1009 * non-standard, incompatible libpcap, rather than a standard libpcap,
1010 * and will map the link-layer type to the standard DLT_ value for
1011 * that link-layer type, as that's what the rest of Wireshark expects.
1013 * (This means the capture files won't be readable by a tcpdump
1014 * linked with AIX's non-standard libpcap, but so it goes. They
1015 * *will* be readable by standard versions of tcpdump, Wireshark,
1018 * XXX - if we conclude we're using AIX libpcap, should we also
1019 * set a flag to cause us to assume the time stamps are in
1020 * seconds-and-nanoseconds form, and to convert them to
1021 * seconds-and-microseconds form before processing them and
1026 * Find the last component of the device name, which is the
1029 ifacename = strchr(devicename, '/');
1030 if (ifacename == NULL)
1031 ifacename = devicename;
1033 /* See if it matches any of the LAN device names. */
1034 if (strncmp(ifacename, "en", 2) == 0) {
1035 if (linktype == 6) {
1037 * That's the RFC 1573 value for Ethernet; map it to DLT_EN10MB.
1041 } else if (strncmp(ifacename, "et", 2) == 0) {
1042 if (linktype == 7) {
1044 * That's the RFC 1573 value for 802.3; map it to DLT_EN10MB.
1045 * (libpcap, tcpdump, Wireshark, etc. don't care if it's Ethernet
1050 } else if (strncmp(ifacename, "tr", 2) == 0) {
1051 if (linktype == 9) {
1053 * That's the RFC 1573 value for 802.5 (Token Ring); map it to
1054 * DLT_IEEE802, which is what's used for Token Ring.
1058 } else if (strncmp(ifacename, "fi", 2) == 0) {
1059 if (linktype == 15) {
1061 * That's the RFC 1573 value for FDDI; map it to DLT_FDDI.
1065 } else if (strncmp(ifacename, "lo", 2) == 0) {
1066 if (linktype == 24) {
1068 * That's the RFC 1573 value for "software loopback" devices; map it
1069 * to DLT_NULL, which is what's used for loopback devices on BSD.
1079 static data_link_info_t *
1080 create_data_link_info(int dlt)
1082 data_link_info_t *data_link_info;
1085 data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
1086 data_link_info->dlt = dlt;
1087 text = pcap_datalink_val_to_name(dlt);
1089 data_link_info->name = g_strdup(text);
1091 data_link_info->name = g_strdup_printf("DLT %d", dlt);
1092 text = pcap_datalink_val_to_description(dlt);
1094 data_link_info->description = g_strdup(text);
1096 data_link_info->description = NULL;
1097 return data_link_info;
1101 * Get the capabilities of a network device.
1103 static if_capabilities_t *
1104 get_if_capabilities(const char *devicename, gboolean monitor_mode
1105 #ifndef HAVE_PCAP_CREATE
1110 if_capabilities_t *caps;
1111 char errbuf[PCAP_ERRBUF_SIZE];
1113 #ifdef HAVE_PCAP_CREATE
1117 #ifdef HAVE_PCAP_LIST_DATALINKS
1121 data_link_info_t *data_link_info;
1124 * Allocate the interface capabilities structure.
1126 caps = g_malloc(sizeof *caps);
1129 * WinPcap 4.1.2, and possibly earlier versions, have a bug
1130 * wherein, when an open with an rpcap: URL fails, the error
1131 * message for the error is not copied to errbuf and whatever
1132 * on-the-stack junk is in errbuf is treated as the error
1135 * To work around that (and any other bugs of that sort, we
1136 * initialize errbuf to an empty string. If we get an error
1137 * and the string is empty, we report it as an unknown error.
1138 * (If we *don't* get an error, and the string is *non*-empty,
1139 * that could be a warning returned, such as "can't turn
1140 * promiscuous mode on"; we currently don't do so.)
1143 #ifdef HAVE_PCAP_OPEN
1144 pch = pcap_open(devicename, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1145 caps->can_set_rfmon = FALSE;
1147 if (err_str != NULL)
1148 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1152 #elif defined(HAVE_PCAP_CREATE)
1153 pch = pcap_create(devicename, errbuf);
1155 if (err_str != NULL)
1156 *err_str = g_strdup(errbuf);
1160 status = pcap_can_set_rfmon(pch);
1163 if (status == PCAP_ERROR)
1164 *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
1167 *err_str = g_strdup(pcap_statustostr(status));
1173 caps->can_set_rfmon = FALSE;
1174 else if (status == 1) {
1175 caps->can_set_rfmon = TRUE;
1177 pcap_set_rfmon(pch, 1);
1179 if (err_str != NULL) {
1180 *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
1188 status = pcap_activate(pch);
1190 /* Error. We ignore warnings (status > 0). */
1191 if (err_str != NULL) {
1192 if (status == PCAP_ERROR)
1193 *err_str = g_strdup_printf("pcap_activate() failed: %s",
1196 *err_str = g_strdup(pcap_statustostr(status));
1203 pch = pcap_open_live(devicename, MIN_PACKET_SIZE, 0, 0, errbuf);
1204 caps->can_set_rfmon = FALSE;
1206 if (err_str != NULL)
1207 *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1212 deflt = get_pcap_linktype(pch, devicename);
1213 #ifdef HAVE_PCAP_LIST_DATALINKS
1214 nlt = pcap_list_datalinks(pch, &linktypes);
1215 if (nlt == 0 || linktypes == NULL) {
1217 if (err_str != NULL)
1218 *err_str = NULL; /* an empty list doesn't mean an error */
1222 caps->data_link_types = NULL;
1223 for (i = 0; i < nlt; i++) {
1224 data_link_info = create_data_link_info(linktypes[i]);
1227 * XXX - for 802.11, make the most detailed 802.11
1228 * version the default, rather than the one the
1229 * device has as the default?
1231 if (linktypes[i] == deflt)
1232 caps->data_link_types = g_list_prepend(caps->data_link_types,
1235 caps->data_link_types = g_list_append(caps->data_link_types,
1238 #ifdef HAVE_PCAP_FREE_DATALINKS
1239 pcap_free_datalinks(linktypes);
1242 * In Windows, there's no guarantee that if you have a library
1243 * built with one version of the MSVC++ run-time library, and
1244 * it returns a pointer to allocated data, you can free that
1245 * data from a program linked with another version of the
1246 * MSVC++ run-time library.
1248 * This is not an issue on UN*X.
1250 * See the mail threads starting at
1252 * http://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
1256 * http://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
1259 #define xx_free free /* hack so checkAPIs doesn't complain */
1262 #endif /* HAVE_PCAP_FREE_DATALINKS */
1263 #else /* HAVE_PCAP_LIST_DATALINKS */
1265 data_link_info = create_data_link_info(deflt);
1266 caps->data_link_types = g_list_append(caps->data_link_types,
1268 #endif /* HAVE_PCAP_LIST_DATALINKS */
1272 if (err_str != NULL)
1277 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
1279 * Output a machine readable list of the interfaces
1280 * This list is retrieved by the sync_interface_list_open() function
1281 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
1284 print_machine_readable_interfaces(GList *if_list)
1291 char addr_str[ADDRSTRLEN];
1293 if (capture_child) {
1294 /* Let our parent know we succeeded. */
1295 pipe_write_block(2, SP_SUCCESS, NULL);
1298 i = 1; /* Interface id number */
1299 for (if_entry = g_list_first(if_list); if_entry != NULL;
1300 if_entry = g_list_next(if_entry)) {
1301 if_info = (if_info_t *)if_entry->data;
1302 printf("%d. %s", i++, if_info->name);
1305 * Print the contents of the if_entry struct in a parseable format.
1306 * Each if_entry element is tab-separated. Addresses are comma-
1309 /* XXX - Make sure our description doesn't contain a tab */
1310 if (if_info->vendor_description != NULL)
1311 printf("\t%s\t", if_info->vendor_description);
1315 /* XXX - Make sure our friendly name doesn't contain a tab */
1316 if (if_info->friendly_name != NULL)
1317 printf("%s\t", if_info->friendly_name);
1321 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
1322 addr = g_slist_next(addr)) {
1323 if (addr != g_slist_nth(if_info->addrs, 0))
1326 if_addr = (if_addr_t *)addr->data;
1327 switch(if_addr->ifat_type) {
1329 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
1331 printf("%s", addr_str);
1333 printf("<unknown IPv4>");
1337 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
1338 addr_str, ADDRSTRLEN)) {
1339 printf("%s", addr_str);
1341 printf("<unknown IPv6>");
1345 printf("<type unknown %u>", if_addr->ifat_type);
1349 if (if_info->loopback)
1350 printf("\tloopback");
1352 printf("\tnetwork");
1359 * If you change the machine-readable output format of this function,
1360 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
1363 print_machine_readable_if_capabilities(if_capabilities_t *caps)
1366 data_link_info_t *data_link_info;
1367 const gchar *desc_str;
1369 if (capture_child) {
1370 /* Let our parent know we succeeded. */
1371 pipe_write_block(2, SP_SUCCESS, NULL);
1374 if (caps->can_set_rfmon)
1378 for (lt_entry = caps->data_link_types; lt_entry != NULL;
1379 lt_entry = g_list_next(lt_entry)) {
1380 data_link_info = (data_link_info_t *)lt_entry->data;
1381 if (data_link_info->description != NULL)
1382 desc_str = data_link_info->description;
1384 desc_str = "(not supported)";
1385 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
1395 /* Print the number of packets captured for each interface until we're killed. */
1397 print_statistics_loop(gboolean machine_readable)
1399 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1405 char errbuf[PCAP_ERRBUF_SIZE];
1406 struct pcap_stat ps;
1408 if_list = get_interface_list(&err, &err_str);
1409 if (if_list == NULL) {
1411 case CANT_GET_INTERFACE_LIST:
1412 case DONT_HAVE_PCAP:
1413 cmdarg_err("%s", err_str);
1417 case NO_INTERFACES_FOUND:
1418 cmdarg_err("There are no interfaces on which a capture can be done");
1424 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1425 if_info = (if_info_t *)if_entry->data;
1426 #ifdef HAVE_PCAP_OPEN
1427 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1429 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1433 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
1434 if_stat->name = g_strdup(if_info->name);
1436 stat_list = g_list_append(stat_list, if_stat);
1441 cmdarg_err("There are no interfaces on which a capture can be done");
1445 if (capture_child) {
1446 /* Let our parent know we succeeded. */
1447 pipe_write_block(2, SP_SUCCESS, NULL);
1450 if (!machine_readable) {
1451 printf("%-15s %10s %10s\n", "Interface", "Received",
1455 global_ld.go = TRUE;
1456 while (global_ld.go) {
1457 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1458 if_stat = (if_stat_t *)stat_entry->data;
1459 pcap_stats(if_stat->pch, &ps);
1461 if (!machine_readable) {
1462 printf("%-15s %10u %10u\n", if_stat->name,
1463 ps.ps_recv, ps.ps_drop);
1465 printf("%s\t%u\t%u\n", if_stat->name,
1466 ps.ps_recv, ps.ps_drop);
1477 /* XXX - Not reached. Should we look for 'q' in stdin? */
1478 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1479 if_stat = (if_stat_t *)stat_entry->data;
1480 pcap_close(if_stat->pch);
1481 g_free(if_stat->name);
1484 g_list_free(stat_list);
1485 free_interface_list(if_list);
1493 capture_cleanup_handler(DWORD dwCtrlType)
1495 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1496 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1497 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1498 like SIGTERM at least when the machine's shutting down.
1500 For now, if we're running as a command rather than a capture child,
1501 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1502 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1503 in that way on UN*X.
1505 If we're not running as a capture child, we might be running as
1506 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1507 user logs out. (XXX - can we explicitly check whether we're
1508 running as a service?) */
1510 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1511 "Console: Control signal");
1512 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1513 "Console: Control signal, CtrlType: %u", dwCtrlType);
1515 /* Keep capture running if we're a service and a user logs off */
1516 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1517 capture_loop_stop();
1525 capture_cleanup_handler(int signum _U_)
1527 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1528 SIGTERM. We assume that if the user wanted it to keep running
1529 after they logged out, they'd have nohupped it. */
1531 /* Note: don't call g_log() in the signal handler: if we happened to be in
1532 * g_log() in process context when the signal came in, g_log will detect
1533 * the "recursion" and abort.
1536 capture_loop_stop();
1542 report_capture_count(gboolean reportit)
1544 /* Don't print this if we're a capture child. */
1545 if (!capture_child && reportit) {
1546 fprintf(stderr, "\rPackets captured: %u\n", global_ld.packet_count);
1547 /* stderr could be line buffered */
1555 report_counts_for_siginfo(void)
1557 report_capture_count(quiet);
1558 infoprint = FALSE; /* we just reported it */
1562 report_counts_siginfo(int signum _U_)
1564 int sav_errno = errno;
1566 /* If we've been told to delay printing, just set a flag asking
1567 that we print counts (if we're supposed to), otherwise print
1568 the count of packets captured (if we're supposed to). */
1572 report_counts_for_siginfo();
1575 #endif /* SIGINFO */
1578 exit_main(int status)
1581 /* Shutdown windows sockets */
1584 /* can be helpful for debugging */
1585 #ifdef DEBUG_DUMPCAP
1586 printf("Press any key\n");
1597 * If we were linked with libcap (not related to libpcap), make sure we have
1598 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1599 * (See comment in main() for details)
1602 relinquish_privs_except_capture(void)
1604 /* If 'started_with_special_privs' (ie: suid) then enable for
1605 * ourself the NET_ADMIN and NET_RAW capabilities and then
1606 * drop our suid privileges.
1608 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1609 * stuff we don't need (and shouldn't have).
1610 * CAP_NET_RAW: Packet capture (raw sockets).
1613 if (started_with_special_privs()) {
1614 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1615 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1617 cap_t caps = cap_init(); /* all capabilities initialized to off */
1619 print_caps("Pre drop, pre set");
1621 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1622 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1625 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1626 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1628 if (cap_set_proc(caps)) {
1629 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1631 print_caps("Pre drop, post set");
1633 relinquish_special_privs_perm();
1635 print_caps("Post drop, pre set");
1636 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1637 if (cap_set_proc(caps)) {
1638 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1640 print_caps("Post drop, post set");
1646 #endif /* HAVE_LIBCAP */
1648 /* Take care of byte order in the libpcap headers read from pipes.
1649 * (function taken from wiretap/libpcap.c) */
1651 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1654 /* Byte-swap the record header fields. */
1655 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
1656 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
1657 rechdr->incl_len = BSWAP32(rechdr->incl_len);
1658 rechdr->orig_len = BSWAP32(rechdr->orig_len);
1661 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1662 swapped, in order to match the BPF header layout.
1664 Unfortunately, some files were, according to a comment in the "libpcap"
1665 source, written with version 2.3 in their headers but without the
1666 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1667 would make no sense - we assume that we need to swap them. */
1668 if (hdr->version_major == 2 &&
1669 (hdr->version_minor < 3 ||
1670 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1673 temp = rechdr->orig_len;
1674 rechdr->orig_len = rechdr->incl_len;
1675 rechdr->incl_len = temp;
1679 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1683 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1687 return recv(pipe_fd, buf, (int)sz, 0);
1692 return ws_read(pipe_fd, buf, sz);
1698 * Thread function that reads from a pipe and pushes the data
1699 * to the main application thread.
1702 * XXX Right now we use async queues for basic signaling. The main thread
1703 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1704 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1705 * Iff the read is successful cap_pipe_read pushes an item onto
1706 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1707 * the queues themselves (yet).
1709 * We might want to move some of the cap_pipe_dispatch logic here so that
1710 * we can let cap_thread_read run independently, queuing up multiple reads
1711 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1713 static void *cap_thread_read(void *arg)
1715 pcap_options *pcap_opts;
1724 pcap_opts = (pcap_options *)arg;
1725 while (pcap_opts->cap_pipe_err == PIPOK) {
1726 g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1727 g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1729 while (bytes_read < (int) pcap_opts->cap_pipe_bytes_to_read) {
1730 if ((pcap_opts->from_cap_socket)
1736 b = cap_pipe_read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1737 pcap_opts->cap_pipe_bytes_to_read - bytes_read, pcap_opts->from_cap_socket);
1740 pcap_opts->cap_pipe_err = PIPEOF;
1744 pcap_opts->cap_pipe_err = PIPERR;
1755 /* If we try to use read() on a named pipe on Windows with partial
1756 * data it appears to return EOF.
1758 res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1759 pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1764 last_err = GetLastError();
1765 if (last_err == ERROR_MORE_DATA) {
1767 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1768 pcap_opts->cap_pipe_err = PIPEOF;
1772 pcap_opts->cap_pipe_err = PIPERR;
1775 } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1776 pcap_opts->cap_pipe_err = PIPEOF;
1783 pcap_opts->cap_pipe_bytes_read = bytes_read;
1784 if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1785 g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1787 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1793 /* Provide select() functionality for a single file descriptor
1794 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1796 * Returns the same values as select.
1799 cap_pipe_select(int pipe_fd)
1802 struct timeval timeout;
1805 FD_SET(pipe_fd, &rfds);
1807 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1808 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1810 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1813 #define DEF_TCP_PORT 19000
1816 cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errmsgl)
1818 char *sockname = pipename + 4;
1819 struct sockaddr_in sa;
1826 memset(&sa, 0, sizeof(sa));
1828 p = strchr(sockname, ':');
1830 len = strlen(sockname);
1831 port = DEF_TCP_PORT;
1835 port = strtoul(p + 1, &p, 10);
1836 if (*p || port > 65535) {
1845 strncpy(buf, sockname, len);
1847 if (!inet_pton(AF_INET, buf, &sa.sin_addr)) {
1851 sa.sin_family = AF_INET;
1852 sa.sin_port = htons((u_short)port);
1854 if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1855 (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1857 LPTSTR errorText = NULL;
1860 lastError = WSAGetLastError();
1861 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1862 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1863 FORMAT_MESSAGE_IGNORE_INSERTS,
1864 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1865 (LPTSTR)&errorText, 0, NULL);
1867 g_snprintf(errmsg, errmsgl,
1868 "The capture session could not be initiated due to the socket error: \n"
1870 " %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
1872 LocalFree(errorText);
1874 " %d: %s", errno, strerror(errno));
1876 pcap_opts->cap_pipe_err = PIPERR;
1879 cap_pipe_close(fd, TRUE);
1883 pcap_opts->from_cap_socket = TRUE;
1887 g_snprintf(errmsg, errmsgl,
1888 "The capture session could not be initiated because\n"
1889 "\"%s\" is not a valid socket specification", pipename);
1890 pcap_opts->cap_pipe_err = PIPERR;
1894 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1898 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1902 closesocket(pipe_fd);
1909 /* Mimic pcap_open_live() for pipe captures
1911 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1912 * open it, and read the header.
1914 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1915 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1917 cap_pipe_open_live(char *pipename,
1918 pcap_options *pcap_opts,
1919 struct pcap_hdr *hdr,
1920 char *errmsg, int errmsgl)
1923 ws_statb64 pipe_stat;
1924 struct sockaddr_un sa;
1930 unsigned int bytes_read;
1933 pcap_opts->cap_pipe_fd = -1;
1935 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
1937 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1940 * XXX - this blocks until a pcap per-file header has been written to
1941 * the pipe, so it could block indefinitely.
1943 if (strcmp(pipename, "-") == 0) {
1945 fd = 0; /* read from stdin */
1947 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1949 } else if (!strncmp(pipename, "TCP@", 4)) {
1950 if ((fd = cap_open_socket(pipename, pcap_opts, errmsg, errmsgl)) < 0) {
1955 if (ws_stat64(pipename, &pipe_stat) < 0) {
1956 if (errno == ENOENT || errno == ENOTDIR)
1957 pcap_opts->cap_pipe_err = PIPNEXIST;
1959 g_snprintf(errmsg, errmsgl,
1960 "The capture session could not be initiated "
1961 "due to error getting information on pipe/socket: %s", g_strerror(errno));
1962 pcap_opts->cap_pipe_err = PIPERR;
1966 if (S_ISFIFO(pipe_stat.st_mode)) {
1967 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1969 g_snprintf(errmsg, errmsgl,
1970 "The capture session could not be initiated "
1971 "due to error on pipe open: %s", g_strerror(errno));
1972 pcap_opts->cap_pipe_err = PIPERR;
1975 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1976 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1978 g_snprintf(errmsg, errmsgl,
1979 "The capture session could not be initiated "
1980 "due to error on socket create: %s", g_strerror(errno));
1981 pcap_opts->cap_pipe_err = PIPERR;
1984 sa.sun_family = AF_UNIX;
1986 * The Single UNIX Specification says:
1988 * The size of sun_path has intentionally been left undefined.
1989 * This is because different implementations use different sizes.
1990 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1991 * of 104. Since most implementations originate from BSD versions,
1992 * the size is typically in the range 92 to 108.
1994 * Applications should not assume a particular length for sun_path
1995 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1999 * The <sys/un.h> header shall define the sockaddr_un structure,
2000 * which shall include at least the following members:
2002 * sa_family_t sun_family Address family.
2003 * char sun_path[] Socket pathname.
2005 * so we assume that it's an array, with a specified size,
2006 * and that the size reflects the maximum path length.
2008 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
2009 /* Path name too long */
2010 g_snprintf(errmsg, errmsgl,
2011 "The capture session coud not be initiated "
2012 "due to error on socket connect: Path name too long");
2013 pcap_opts->cap_pipe_err = PIPERR;
2017 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
2019 g_snprintf(errmsg, errmsgl,
2020 "The capture session coud not be initiated "
2021 "due to error on socket connect: %s", g_strerror(errno));
2022 pcap_opts->cap_pipe_err = PIPERR;
2027 if (S_ISCHR(pipe_stat.st_mode)) {
2029 * Assume the user specified an interface on a system where
2030 * interfaces are in /dev. Pretend we haven't seen it.
2032 pcap_opts->cap_pipe_err = PIPNEXIST;
2035 g_snprintf(errmsg, errmsgl,
2036 "The capture session could not be initiated because\n"
2037 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
2038 pcap_opts->cap_pipe_err = PIPERR;
2043 #define PIPE_STR "\\pipe\\"
2044 /* Under Windows, named pipes _must_ have the form
2045 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
2047 pncopy = g_strdup(pipename);
2048 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
2049 pos = strchr(pncopy + 3, '\\');
2050 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
2057 g_snprintf(errmsg, errmsgl,
2058 "The capture session could not be initiated because\n"
2059 "\"%s\" is neither an interface nor a pipe", pipename);
2060 pcap_opts->cap_pipe_err = PIPNEXIST;
2064 /* Wait for the pipe to appear */
2066 pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
2067 OPEN_EXISTING, 0, NULL);
2069 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
2072 if (GetLastError() != ERROR_PIPE_BUSY) {
2073 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2074 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2075 g_snprintf(errmsg, errmsgl,
2076 "The capture session on \"%s\" could not be started "
2077 "due to error on pipe open: %s (error %d)",
2078 pipename, utf_16to8(err_str), GetLastError());
2080 pcap_opts->cap_pipe_err = PIPERR;
2084 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
2085 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2086 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2087 g_snprintf(errmsg, errmsgl,
2088 "The capture session on \"%s\" timed out during "
2089 "pipe open: %s (error %d)",
2090 pipename, utf_16to8(err_str), GetLastError());
2092 pcap_opts->cap_pipe_err = PIPERR;
2099 pcap_opts->from_cap_pipe = TRUE;
2101 if ((pcap_opts->from_cap_socket)
2107 /* read the pcap header */
2109 while (bytes_read < sizeof magic) {
2110 sel_ret = cap_pipe_select(fd);
2112 g_snprintf(errmsg, errmsgl,
2113 "Unexpected error from select: %s", g_strerror(errno));
2115 } else if (sel_ret > 0) {
2116 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read, pcap_opts->from_cap_socket);
2119 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2121 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2131 #if GLIB_CHECK_VERSION(2,31,0)
2132 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_opts);
2134 g_thread_create(&cap_thread_read, pcap_opts, FALSE, NULL);
2137 pcap_opts->cap_pipe_buf = (char *) &magic;
2138 pcap_opts->cap_pipe_bytes_read = 0;
2139 pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
2140 /* We don't have to worry about cap_pipe_read_mtx here */
2141 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2142 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2143 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2144 if (pcap_opts->cap_pipe_bytes_read == 0)
2145 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2147 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2156 case PCAP_NSEC_MAGIC:
2157 /* Host that wrote it has our byte order, and was running
2158 a program using either standard or ss990417 libpcap. */
2159 pcap_opts->cap_pipe_byte_swapped = FALSE;
2160 pcap_opts->cap_pipe_modified = FALSE;
2161 pcap_opts->ts_nsec = magic == PCAP_NSEC_MAGIC;
2163 case PCAP_MODIFIED_MAGIC:
2164 /* Host that wrote it has our byte order, but was running
2165 a program using either ss990915 or ss991029 libpcap. */
2166 pcap_opts->cap_pipe_byte_swapped = FALSE;
2167 pcap_opts->cap_pipe_modified = TRUE;
2169 case PCAP_SWAPPED_MAGIC:
2170 case PCAP_SWAPPED_NSEC_MAGIC:
2171 /* Host that wrote it has a byte order opposite to ours,
2172 and was running a program using either standard or
2173 ss990417 libpcap. */
2174 pcap_opts->cap_pipe_byte_swapped = TRUE;
2175 pcap_opts->cap_pipe_modified = FALSE;
2176 pcap_opts->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
2178 case PCAP_SWAPPED_MODIFIED_MAGIC:
2179 /* Host that wrote it out has a byte order opposite to
2180 ours, and was running a program using either ss990915
2181 or ss991029 libpcap. */
2182 pcap_opts->cap_pipe_byte_swapped = TRUE;
2183 pcap_opts->cap_pipe_modified = TRUE;
2186 /* Not a "libpcap" type we know about. */
2187 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
2191 if ((pcap_opts->from_cap_socket)
2197 /* Read the rest of the header */
2199 while (bytes_read < sizeof(struct pcap_hdr)) {
2200 sel_ret = cap_pipe_select(fd);
2202 g_snprintf(errmsg, errmsgl,
2203 "Unexpected error from select: %s", g_strerror(errno));
2205 } else if (sel_ret > 0) {
2206 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
2207 sizeof(struct pcap_hdr) - bytes_read, pcap_opts->from_cap_socket);
2210 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2212 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
2222 pcap_opts->cap_pipe_buf = (char *) hdr;
2223 pcap_opts->cap_pipe_bytes_read = 0;
2224 pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
2225 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2226 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2227 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2228 if (pcap_opts->cap_pipe_bytes_read == 0)
2229 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2231 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
2238 if (pcap_opts->cap_pipe_byte_swapped) {
2239 /* Byte-swap the header fields about which we care. */
2240 hdr->version_major = BSWAP16(hdr->version_major);
2241 hdr->version_minor = BSWAP16(hdr->version_minor);
2242 hdr->snaplen = BSWAP32(hdr->snaplen);
2243 hdr->network = BSWAP32(hdr->network);
2245 pcap_opts->linktype = hdr->network;
2247 if (hdr->version_major < 2) {
2248 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
2252 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2253 pcap_opts->cap_pipe_err = PIPOK;
2254 pcap_opts->cap_pipe_fd = fd;
2258 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
2259 pcap_opts->cap_pipe_err = PIPERR;
2260 cap_pipe_close(fd, pcap_opts->from_cap_socket);
2261 pcap_opts->cap_pipe_fd = -1;
2267 /* We read one record from the pipe, take care of byte order in the record
2268 * header, write the record to the capture file, and update capture statistics. */
2270 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
2272 struct pcap_pkthdr phdr;
2273 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2276 #if !GLIB_CHECK_VERSION(2,31,18)
2284 #ifdef LOG_CAPTURE_VERBOSE
2285 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
2288 switch (pcap_opts->cap_pipe_state) {
2290 case STATE_EXPECT_REC_HDR:
2292 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2295 pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
2296 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
2297 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2298 pcap_opts->cap_pipe_bytes_read = 0;
2301 pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
2302 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2303 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2308 case STATE_READ_REC_HDR:
2309 if ((pcap_opts->from_cap_socket)
2314 b = cap_pipe_read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
2315 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
2318 result = PD_PIPE_EOF;
2320 result = PD_PIPE_ERR;
2323 pcap_opts->cap_pipe_bytes_read += b;
2327 #if GLIB_CHECK_VERSION(2,31,18)
2328 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2330 g_get_current_time(&wait_time);
2331 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2332 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2334 if (pcap_opts->cap_pipe_err == PIPEOF) {
2335 result = PD_PIPE_EOF;
2337 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2338 result = PD_PIPE_ERR;
2346 if ((pcap_opts->cap_pipe_bytes_read) < pcap_opts->cap_pipe_bytes_to_read)
2348 result = PD_REC_HDR_READ;
2351 case STATE_EXPECT_DATA:
2353 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2356 pcap_opts->cap_pipe_state = STATE_READ_DATA;
2357 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2358 pcap_opts->cap_pipe_bytes_read = 0;
2361 pcap_opts->cap_pipe_buf = (char *) data;
2362 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2363 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2368 case STATE_READ_DATA:
2369 if ((pcap_opts->from_cap_socket)
2374 b = cap_pipe_read(pcap_opts->cap_pipe_fd, data+pcap_opts->cap_pipe_bytes_read,
2375 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
2378 result = PD_PIPE_EOF;
2380 result = PD_PIPE_ERR;
2383 pcap_opts->cap_pipe_bytes_read += b;
2388 #if GLIB_CHECK_VERSION(2,31,18)
2389 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2391 g_get_current_time(&wait_time);
2392 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2393 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2395 if (pcap_opts->cap_pipe_err == PIPEOF) {
2396 result = PD_PIPE_EOF;
2398 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2399 result = PD_PIPE_ERR;
2407 if ((pcap_opts->cap_pipe_bytes_read) < pcap_opts->cap_pipe_bytes_to_read)
2409 result = PD_DATA_READ;
2413 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2416 } /* switch (pcap_opts->cap_pipe_state) */
2419 * We've now read as much data as we were expecting, so process it.
2423 case PD_REC_HDR_READ:
2424 /* We've read the header. Take care of byte order. */
2425 cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
2426 &pcap_opts->cap_pipe_rechdr.hdr);
2427 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2428 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2429 ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
2433 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2434 pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2437 /* no data to read? fall through */
2440 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2441 phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2442 phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2443 phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2444 phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2447 capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2449 capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2451 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2455 pcap_opts->cap_pipe_err = PIPEOF;
2460 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2461 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2462 g_snprintf(errmsg, errmsgl,
2463 "Error reading from pipe: %s (error %d)",
2464 utf_16to8(err_str), GetLastError());
2467 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2475 pcap_opts->cap_pipe_err = PIPERR;
2476 /* Return here rather than inside the switch to prevent GCC warning */
2481 /** Open the capture input file (pcap or capture pipe).
2482 * Returns TRUE if it succeeds, FALSE otherwise. */
2484 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2485 char *errmsg, size_t errmsg_len,
2486 char *secondary_errmsg, size_t secondary_errmsg_len)
2488 gchar open_err_str[PCAP_ERRBUF_SIZE];
2489 gchar *sync_msg_str;
2490 interface_options interface_opts;
2491 pcap_options *pcap_opts;
2495 gchar *sync_secondary_msg_str;
2496 WORD wVersionRequested;
2500 /* XXX - opening Winsock on tshark? */
2502 /* Initialize Windows Socket if we are in a WIN32 OS
2503 This needs to be done before querying the interface for network/netmask */
2505 /* XXX - do we really require 1.1 or earlier?
2506 Are there any versions that support only 2.0 or higher? */
2507 wVersionRequested = MAKEWORD(1, 1);
2508 err = WSAStartup(wVersionRequested, &wsaData);
2512 case WSASYSNOTREADY:
2513 g_snprintf(errmsg, (gulong) errmsg_len,
2514 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2517 case WSAVERNOTSUPPORTED:
2518 g_snprintf(errmsg, (gulong) errmsg_len,
2519 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2520 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2523 case WSAEINPROGRESS:
2524 g_snprintf(errmsg, (gulong) errmsg_len,
2525 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2529 g_snprintf(errmsg, (gulong) errmsg_len,
2530 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2534 g_snprintf(errmsg, (gulong) errmsg_len,
2535 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2539 g_snprintf(errmsg, (gulong) errmsg_len,
2540 "Couldn't initialize Windows Sockets: error %d", err);
2543 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2547 if ((use_threads == FALSE) &&
2548 (capture_opts->ifaces->len > 1)) {
2549 g_snprintf(errmsg, (gulong) errmsg_len,
2550 "Using threads is required for capturing on multiple interfaces!");
2554 for (i = 0; i < capture_opts->ifaces->len; i++) {
2555 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2556 pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2557 if (pcap_opts == NULL) {
2558 g_snprintf(errmsg, (gulong) errmsg_len,
2559 "Could not allocate memory.");
2562 pcap_opts->received = 0;
2563 pcap_opts->dropped = 0;
2564 pcap_opts->pcap_h = NULL;
2565 #ifdef MUST_DO_SELECT
2566 pcap_opts->pcap_fd = -1;
2568 pcap_opts->pcap_err = FALSE;
2569 pcap_opts->interface_id = i;
2570 pcap_opts->tid = NULL;
2571 pcap_opts->snaplen = 0;
2572 pcap_opts->linktype = -1;
2573 pcap_opts->ts_nsec = FALSE;
2574 pcap_opts->from_cap_pipe = FALSE;
2575 pcap_opts->from_cap_socket = FALSE;
2576 memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2577 memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2579 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2581 pcap_opts->cap_pipe_fd = -1;
2582 pcap_opts->cap_pipe_modified = FALSE;
2583 pcap_opts->cap_pipe_byte_swapped = FALSE;
2585 pcap_opts->cap_pipe_buf = NULL;
2587 pcap_opts->cap_pipe_bytes_to_read = 0;
2588 pcap_opts->cap_pipe_bytes_read = 0;
2589 pcap_opts->cap_pipe_state = 0;
2590 pcap_opts->cap_pipe_err = PIPOK;
2592 #if GLIB_CHECK_VERSION(2,31,0)
2593 pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2594 g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2596 pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2598 pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2599 pcap_opts->cap_pipe_done_q = g_async_queue_new();
2601 g_array_append_val(ld->pcaps, pcap_opts);
2603 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2604 pcap_opts->pcap_h = open_capture_device(&interface_opts, &open_err_str);
2606 if (pcap_opts->pcap_h != NULL) {
2607 /* we've opened "iface" as a network device */
2609 /* try to set the capture buffer size */
2610 if (interface_opts.buffer_size > 1 &&
2611 pcap_setbuff(pcap_opts->pcap_h, interface_opts.buffer_size * 1024 * 1024) != 0) {
2612 sync_secondary_msg_str = g_strdup_printf(
2613 "The capture buffer size of %dMB seems to be too high for your machine,\n"
2614 "the default of 1MB will be used.\n"
2616 "Nonetheless, the capture is started.\n",
2617 interface_opts.buffer_size);
2618 report_capture_error("Couldn't set the capture buffer size!",
2619 sync_secondary_msg_str);
2620 g_free(sync_secondary_msg_str);
2624 #if defined(HAVE_PCAP_SETSAMPLING)
2625 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2626 struct pcap_samp *samp;
2628 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2629 switch (interface_opts.sampling_method) {
2630 case CAPTURE_SAMP_BY_COUNT:
2631 samp->method = PCAP_SAMP_1_EVERY_N;
2634 case CAPTURE_SAMP_BY_TIMER:
2635 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2639 sync_msg_str = g_strdup_printf(
2640 "Unknown sampling method %d specified,\n"
2641 "continue without packet sampling",
2642 interface_opts.sampling_method);
2643 report_capture_error("Couldn't set the capture "
2644 "sampling", sync_msg_str);
2645 g_free(sync_msg_str);
2647 samp->value = interface_opts.sampling_param;
2649 report_capture_error("Couldn't set the capture sampling",
2650 "Cannot get packet sampling data structure");
2655 /* setting the data link type only works on real interfaces */
2656 if (!set_pcap_linktype(pcap_opts->pcap_h, interface_opts.linktype, interface_opts.name,
2658 secondary_errmsg, secondary_errmsg_len)) {
2661 pcap_opts->linktype = get_pcap_linktype(pcap_opts->pcap_h, interface_opts.name);
2663 /* We couldn't open "iface" as a network device. */
2664 /* Try to open it as a pipe */
2665 cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2668 if (pcap_opts->cap_pipe_fd == -1) {
2670 if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2672 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2673 /* Pipe doesn't exist, so output message for interface */
2674 get_capture_device_open_failure_messages(open_err_str,
2675 interface_opts.name,
2679 secondary_errmsg_len);
2682 * Else pipe (or file) does exist and cap_pipe_open_live() has
2687 /* cap_pipe_open_live() succeeded; don't want
2688 error message from pcap_open_live() */
2689 open_err_str[0] = '\0';
2693 /* XXX - will this work for tshark? */
2694 #ifdef MUST_DO_SELECT
2695 if (!pcap_opts->from_cap_pipe) {
2696 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2697 pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2699 pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2704 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2705 returned a warning; print it, but keep capturing. */
2706 if (open_err_str[0] != '\0') {
2707 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2708 report_capture_error(sync_msg_str, "");
2709 g_free(sync_msg_str);
2711 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2712 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2715 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2716 /* to remove any suid privileges. */
2717 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2718 /* (euid/egid have already previously been set to ruid/rgid. */
2719 /* (See comment in main() for details) */
2721 relinquish_special_privs_perm();
2723 relinquish_all_capabilities();
2728 /* close the capture input file (pcap or capture pipe) */
2729 static void capture_loop_close_input(loop_data *ld)
2732 pcap_options *pcap_opts;
2734 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2736 for (i = 0; i < ld->pcaps->len; i++) {
2737 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2738 /* if open, close the capture pipe "input file" */
2739 if (pcap_opts->cap_pipe_fd >= 0) {
2740 g_assert(pcap_opts->from_cap_pipe);
2741 cap_pipe_close(pcap_opts->cap_pipe_fd, pcap_opts->from_cap_socket);
2742 pcap_opts->cap_pipe_fd = -1;
2745 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2746 CloseHandle(pcap_opts->cap_pipe_h);
2747 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2750 /* if open, close the pcap "input file" */
2751 if (pcap_opts->pcap_h != NULL) {
2752 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2753 pcap_close(pcap_opts->pcap_h);
2754 pcap_opts->pcap_h = NULL;
2761 /* Shut down windows sockets */
2767 /* init the capture filter */
2768 static initfilter_status_t
2769 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2770 const gchar * name, const gchar * cfilter)
2772 struct bpf_program fcode;
2774 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2776 /* capture filters only work on real interfaces */
2777 if (cfilter && !from_cap_pipe) {
2778 /* A capture filter was specified; set it up. */
2779 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2780 /* Treat this specially - our caller might try to compile this
2781 as a display filter and, if that succeeds, warn the user that
2782 the display and capture filter syntaxes are different. */
2783 return INITFILTER_BAD_FILTER;
2785 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2786 #ifdef HAVE_PCAP_FREECODE
2787 pcap_freecode(&fcode);
2789 return INITFILTER_OTHER_ERROR;
2791 #ifdef HAVE_PCAP_FREECODE
2792 pcap_freecode(&fcode);
2796 return INITFILTER_NO_ERROR;
2800 /* set up to write to the already-opened capture output file/files */
2802 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2806 pcap_options *pcap_opts;
2807 interface_options interface_opts;
2808 gboolean successful;
2810 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2812 if ((capture_opts->use_pcapng == FALSE) &&
2813 (capture_opts->ifaces->len > 1)) {
2814 g_snprintf(errmsg, errmsg_len,
2815 "Using PCAPNG is required for capturing on multiple interfaces! Use the -n option.");
2819 /* Set up to write to the capture file. */
2820 if (capture_opts->multi_files_on) {
2821 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2823 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2824 if (ld->pdh == NULL) {
2829 if (capture_opts->use_pcapng) {
2831 GString *os_info_str;
2833 os_info_str = g_string_new("");
2834 get_os_version_info(os_info_str);
2836 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2837 successful = libpcap_write_session_header_block(ld->pdh,
2840 os_info_str->str, /* OS*/
2842 -1, /* section_length */
2846 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2847 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2848 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2849 if (pcap_opts->from_cap_pipe) {
2850 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2852 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2854 successful = libpcap_write_interface_description_block(global_ld.pdh,
2855 NULL, /* OPT_COMMENT 1 */
2856 interface_opts.name, /* IDB_NAME 2 */
2857 interface_opts.descr, /* IDB_DESCRIPTION 3 */
2858 interface_opts.cfilter, /* IDB_FILTER 11 */
2859 os_info_str->str, /* IDB_OS 12 */
2860 pcap_opts->linktype,
2862 &(global_ld.bytes_written),
2863 0, /* IDB_IF_SPEED 8 */
2864 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
2868 g_string_free(os_info_str, TRUE);
2871 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
2872 if (pcap_opts->from_cap_pipe) {
2873 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2875 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2877 successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
2878 pcap_opts->ts_nsec, &ld->bytes_written, &err);
2886 if (ld->pdh == NULL) {
2887 /* We couldn't set up to write to the capture file. */
2888 /* XXX - use cf_open_error_message from tshark instead? */
2893 g_snprintf(errmsg, errmsg_len,
2894 "The file to which the capture would be"
2895 " saved (\"%s\") could not be opened: Error %d.",
2896 capture_opts->save_file, err);
2898 g_snprintf(errmsg, errmsg_len,
2899 "The file to which the capture would be"
2900 " saved (\"%s\") could not be opened: %s.",
2901 capture_opts->save_file, g_strerror(err));
2913 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2917 pcap_options *pcap_opts;
2918 guint64 end_time = create_timestamp();
2920 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2922 if (capture_opts->multi_files_on) {
2923 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2925 if (capture_opts->use_pcapng) {
2926 for (i = 0; i < global_ld.pcaps->len; i++) {
2927 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2928 if (!pcap_opts->from_cap_pipe) {
2929 guint64 isb_ifrecv, isb_ifdrop;
2930 struct pcap_stat stats;
2932 if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
2933 isb_ifrecv = pcap_opts->received;
2934 isb_ifdrop = stats.ps_drop + pcap_opts->dropped;
2936 isb_ifrecv = G_MAXUINT64;
2937 isb_ifdrop = G_MAXUINT64;
2939 libpcap_write_interface_statistics_block(ld->pdh,
2942 "Counters provided by dumpcap",
2951 if (fclose(ld->pdh) == EOF) {
2952 if (err_close != NULL) {
2962 /* dispatch incoming packets (pcap or capture pipe)
2964 * Waits for incoming packets to be available, and calls pcap_dispatch()
2965 * to cause them to be processed.
2967 * Returns the number of packets which were processed.
2969 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2970 * packet-batching behaviour does not cause packets to get held back
2974 capture_loop_dispatch(loop_data *ld,
2975 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
2978 gint packet_count_before;
2979 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
2984 packet_count_before = ld->packet_count;
2985 if (pcap_opts->from_cap_pipe) {
2986 /* dispatch from capture pipe */
2987 #ifdef LOG_CAPTURE_VERBOSE
2988 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2991 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
2993 if (sel_ret < 0 && errno != EINTR) {
2994 g_snprintf(errmsg, errmsg_len,
2995 "Unexpected error from select: %s", g_strerror(errno));
2996 report_capture_error(errmsg, please_report);
3001 * "select()" says we can read from the pipe without blocking
3004 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
3014 /* dispatch from pcap */
3015 #ifdef MUST_DO_SELECT
3017 * If we have "pcap_get_selectable_fd()", we use it to get the
3018 * descriptor on which to select; if that's -1, it means there
3019 * is no descriptor on which you can do a "select()" (perhaps
3020 * because you're capturing on a special device, and that device's
3021 * driver unfortunately doesn't support "select()", in which case
3022 * we don't do the select - which means it might not be possible
3023 * to stop a capture until a packet arrives. If that's unacceptable,
3024 * plead with whoever supplies the software for that device to add
3025 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3026 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3027 * later, so it can use pcap_breakloop().
3029 #ifdef LOG_CAPTURE_VERBOSE
3030 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3032 if (pcap_opts->pcap_fd != -1) {
3033 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
3036 * "select()" says we can read from it without blocking; go for
3039 * We don't have pcap_breakloop(), so we only process one packet
3040 * per pcap_dispatch() call, to allow a signal to stop the
3041 * processing immediately, rather than processing all packets
3042 * in a batch before quitting.
3045 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3047 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3051 /* Error, rather than pcap_breakloop(). */
3052 pcap_opts->pcap_err = TRUE;
3054 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3057 if (sel_ret < 0 && errno != EINTR) {
3058 g_snprintf(errmsg, errmsg_len,
3059 "Unexpected error from select: %s", g_strerror(errno));
3060 report_capture_error(errmsg, please_report);
3066 #endif /* MUST_DO_SELECT */
3068 /* dispatch from pcap without select */
3070 #ifdef LOG_CAPTURE_VERBOSE
3071 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3075 * On Windows, we don't support asynchronously telling a process to
3076 * stop capturing; instead, we check for an indication on a pipe
3077 * after processing packets. We therefore process only one packet
3078 * at a time, so that we can check the pipe after every packet.
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 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3089 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3094 /* Error, rather than pcap_breakloop(). */
3095 pcap_opts->pcap_err = TRUE;
3097 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3099 #else /* pcap_next_ex */
3100 #ifdef LOG_CAPTURE_VERBOSE
3101 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3103 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3106 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3107 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
3108 * This should be fixed in the WinPcap 4.0 alpha release.
3110 * For reference, an example remote interface:
3111 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3114 /* emulate dispatch from pcap */
3117 struct pcap_pkthdr *pkt_header;
3122 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
3124 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3126 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3131 pcap_opts->pcap_err = TRUE;
3135 #endif /* pcap_next_ex */
3139 #ifdef LOG_CAPTURE_VERBOSE
3140 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3143 return ld->packet_count - packet_count_before;
3147 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3148 * want to grab only the characters between the '{' and '}' delimiters.
3150 * Returns a GString that must be freed with g_string_free(). */
3152 isolate_uuid(const char *iface)
3157 ptr = strchr(iface, '{');
3159 return g_string_new(iface);
3160 gstr = g_string_new(ptr + 1);
3162 ptr = strchr(gstr->str, '}');
3166 gstr = g_string_truncate(gstr, ptr - gstr->str);
3171 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3172 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3174 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3175 char *errmsg, int errmsg_len)
3178 gchar *capfile_name;
3180 gboolean is_tempfile;
3182 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3183 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3185 if (capture_opts->save_file != NULL) {
3186 /* We return to the caller while the capture is in progress.
3187 * Therefore we need to take a copy of save_file in
3188 * case the caller destroys it after we return.
3190 capfile_name = g_strdup(capture_opts->save_file);
3192 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3193 if (capture_opts->multi_files_on) {
3194 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3195 g_snprintf(errmsg, errmsg_len,
3196 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3197 g_free(capfile_name);
3200 if (strcmp(capfile_name, "-") == 0) {
3201 /* write to stdout */
3204 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3205 _setmode(1, O_BINARY);
3208 } /* if (...output_to_pipe ... */
3211 if (capture_opts->multi_files_on) {
3212 /* ringbuffer is enabled */
3213 *save_file_fd = ringbuf_init(capfile_name,
3214 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3215 capture_opts->group_read_access);
3217 /* we need the ringbuf name */
3218 if (*save_file_fd != -1) {
3219 g_free(capfile_name);
3220 capfile_name = g_strdup(ringbuf_current_filename());
3223 /* Try to open/create the specified file for use as a capture buffer. */
3224 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
3225 (capture_opts->group_read_access) ? 0640 : 0600);
3228 is_tempfile = FALSE;
3230 /* Choose a random name for the temporary capture buffer */
3231 if (global_capture_opts.ifaces->len > 1) {
3232 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3235 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
3237 /* use the generic portion of the interface guid to form the basis of the filename */
3238 if (strncmp("NPF_{", basename, 5)==0)
3240 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
3242 iface = isolate_uuid(basename);
3244 basename = g_strdup(iface->str);
3245 g_string_free(iface, TRUE);
3248 /* generate the temp file name prefix...
3249 * It would be nice if we could specify a pcapng/pcap filename suffix,
3250 * create_tempfile() however currently uses mkstemp() which doesn't allow this - one day perhaps*/
3251 if (capture_opts->use_pcapng) {
3252 prefix = g_strconcat("wireshark_pcapng_", basename, NULL);
3254 prefix = g_strconcat("wireshark_pcap_", basename, NULL);
3258 *save_file_fd = create_tempfile(&tmpname, prefix);
3260 capfile_name = g_strdup(tmpname);
3264 /* did we fail to open the output file? */
3265 if (*save_file_fd == -1) {
3267 g_snprintf(errmsg, errmsg_len,
3268 "The temporary file to which the capture would be saved (\"%s\") "
3269 "could not be opened: %s.", capfile_name, g_strerror(errno));
3271 if (capture_opts->multi_files_on) {
3272 ringbuf_error_cleanup();
3275 g_snprintf(errmsg, errmsg_len,
3276 "The file to which the capture would be saved (\"%s\") "
3277 "could not be opened: %s.", capfile_name,
3280 g_free(capfile_name);
3284 if (capture_opts->save_file != NULL) {
3285 g_free(capture_opts->save_file);
3287 capture_opts->save_file = capfile_name;
3288 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3289 "g_free(capfile_name)". */
3295 /* Do the work of handling either the file size or file duration capture
3296 conditions being reached, and switching files or stopping. */
3298 do_file_switch_or_stop(capture_options *capture_opts,
3299 condition *cnd_autostop_files,
3300 condition *cnd_autostop_size,
3301 condition *cnd_file_duration)
3304 pcap_options *pcap_opts;
3305 interface_options interface_opts;
3306 gboolean successful;
3308 if (capture_opts->multi_files_on) {
3309 if (cnd_autostop_files != NULL &&
3310 cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
3311 /* no files left: stop here */
3312 global_ld.go = FALSE;
3316 /* Switch to the next ringbuffer file */
3317 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3318 &global_ld.save_file_fd, &global_ld.err)) {
3320 /* File switch succeeded: reset the conditions */
3321 global_ld.bytes_written = 0;
3322 if (capture_opts->use_pcapng) {
3324 GString *os_info_str;
3326 os_info_str = g_string_new("");
3327 get_os_version_info(os_info_str);
3329 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
3330 successful = libpcap_write_session_header_block(global_ld.pdh,
3333 os_info_str->str, /* OS */
3335 -1, /* section_length */
3336 &(global_ld.bytes_written),
3339 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3340 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3341 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3342 successful = libpcap_write_interface_description_block(global_ld.pdh,
3343 NULL, /* OPT_COMMENT 1 */
3344 interface_opts.name, /* IDB_NAME 2 */
3345 interface_opts.descr, /* IDB_DESCRIPTION 3 */
3346 interface_opts.cfilter, /* IDB_FILTER 11 */
3347 os_info_str->str, /* IDB_OS 12 */
3348 pcap_opts->linktype,
3350 &(global_ld.bytes_written),
3351 0, /* IDB_IF_SPEED 8 */
3352 pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3356 g_string_free(os_info_str, TRUE);
3359 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3360 successful = libpcap_write_file_header(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
3361 pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3364 fclose(global_ld.pdh);
3365 global_ld.pdh = NULL;
3366 global_ld.go = FALSE;
3369 if (cnd_autostop_size)
3370 cnd_reset(cnd_autostop_size);
3371 if (cnd_file_duration)
3372 cnd_reset(cnd_file_duration);
3373 fflush(global_ld.pdh);
3375 report_packet_count(global_ld.inpkts_to_sync_pipe);
3376 global_ld.inpkts_to_sync_pipe = 0;
3377 report_new_capture_file(capture_opts->save_file);
3379 /* File switch failed: stop here */
3380 global_ld.go = FALSE;
3384 /* single file, stop now */
3385 global_ld.go = FALSE;
3392 pcap_read_handler(void* arg)
3394 pcap_options *pcap_opts;
3395 char errmsg[MSG_MAX_LENGTH+1];
3397 pcap_opts = (pcap_options *)arg;
3399 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3400 pcap_opts->interface_id);
3402 while (global_ld.go) {
3403 /* dispatch incoming packets */
3404 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3406 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3407 pcap_opts->interface_id);
3408 g_thread_exit(NULL);
3412 /* Do the low-level work of a capture.
3413 Returns TRUE if it succeeds, FALSE otherwise. */
3415 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3418 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3420 struct timeval upd_time, cur_time;
3424 condition *cnd_file_duration = NULL;
3425 condition *cnd_autostop_files = NULL;
3426 condition *cnd_autostop_size = NULL;
3427 condition *cnd_autostop_duration = NULL;
3430 gboolean cfilter_error = FALSE;
3431 char errmsg[MSG_MAX_LENGTH+1];
3432 char secondary_errmsg[MSG_MAX_LENGTH+1];
3433 pcap_options *pcap_opts;
3434 interface_options interface_opts;
3435 guint i, error_index = 0;
3438 *secondary_errmsg = '\0';
3440 /* init the loop data */
3441 global_ld.go = TRUE;
3442 global_ld.packet_count = 0;
3444 global_ld.report_packet_count = FALSE;
3446 if (capture_opts->has_autostop_packets)
3447 global_ld.packet_max = capture_opts->autostop_packets;
3449 global_ld.packet_max = 0; /* no limit */
3450 global_ld.inpkts_to_sync_pipe = 0;
3451 global_ld.err = 0; /* no error seen yet */
3452 global_ld.pdh = NULL;
3453 global_ld.autostop_files = 0;
3454 global_ld.save_file_fd = -1;
3456 /* We haven't yet gotten the capture statistics. */
3457 *stats_known = FALSE;
3459 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3460 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3462 /* open the "input file" from network interface or capture pipe */
3463 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3464 secondary_errmsg, sizeof(secondary_errmsg))) {
3467 for (i = 0; i < capture_opts->ifaces->len; i++) {
3468 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3469 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3470 /* init the input filter from the network interface (capture pipe will do nothing) */
3472 * When remote capturing WinPCap crashes when the capture filter
3473 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3476 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3477 interface_opts.name,
3478 interface_opts.cfilter?interface_opts.cfilter:"")) {
3480 case INITFILTER_NO_ERROR:
3483 case INITFILTER_BAD_FILTER:
3484 cfilter_error = TRUE;
3486 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3489 case INITFILTER_OTHER_ERROR:
3490 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3491 pcap_geterr(pcap_opts->pcap_h));
3492 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3497 /* If we're supposed to write to a capture file, open it for output
3498 (temporary/specified name/ringbuffer) */
3499 if (capture_opts->saving_to_file) {
3500 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3501 errmsg, sizeof(errmsg))) {
3505 /* set up to write to the already-opened capture output file/files */
3506 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3511 /* XXX - capture SIGTERM and close the capture, in case we're on a
3512 Linux 2.0[.x] system and you have to explicitly close the capture
3513 stream in order to turn promiscuous mode off? We need to do that
3514 in other places as well - and I don't think that works all the
3515 time in any case, due to libpcap bugs. */
3517 /* Well, we should be able to start capturing.
3519 Sync out the capture file, so the header makes it to the file system,
3520 and send a "capture started successfully and capture file created"
3521 message to our parent so that they'll open the capture file and
3522 update its windows to indicate that we have a live capture in
3524 fflush(global_ld.pdh);
3525 report_new_capture_file(capture_opts->save_file);
3528 /* initialize capture stop (and alike) conditions */
3529 init_capture_stop_conditions();
3530 /* create stop conditions */
3531 if (capture_opts->has_autostop_filesize)
3533 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
3534 if (capture_opts->has_autostop_duration)
3535 cnd_autostop_duration =
3536 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3538 if (capture_opts->multi_files_on) {
3539 if (capture_opts->has_file_duration)
3541 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3543 if (capture_opts->has_autostop_files)
3544 cnd_autostop_files =
3545 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
3548 /* init the time values */
3550 upd_time = GetTickCount();
3552 gettimeofday(&upd_time, NULL);
3554 start_time = create_timestamp();
3555 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
3557 /* WOW, everything is prepared! */
3558 /* please fasten your seat belts, we will enter now the actual capture loop */
3560 pcap_queue = g_async_queue_new();
3561 pcap_queue_bytes = 0;
3562 pcap_queue_packets = 0;
3563 for (i = 0; i < global_ld.pcaps->len; i++) {
3564 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3565 #if GLIB_CHECK_VERSION(2,31,0)
3566 /* XXX - Add an interface name here? */
3567 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3569 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3573 while (global_ld.go) {
3574 /* dispatch incoming packets */
3576 pcap_queue_element *queue_element;
3577 #if GLIB_CHECK_VERSION(2,31,18)
3579 g_async_queue_lock(pcap_queue);
3580 queue_element = g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3582 GTimeVal write_thread_time;
3584 g_get_current_time(&write_thread_time);
3585 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3586 g_async_queue_lock(pcap_queue);
3587 queue_element = g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3589 if (queue_element) {
3590 pcap_queue_bytes -= queue_element->phdr.caplen;
3591 pcap_queue_packets -= 1;
3593 g_async_queue_unlock(pcap_queue);
3594 if (queue_element) {
3595 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3596 "Dequeued a packet of length %d captured on interface %d.",
3597 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3599 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3600 &queue_element->phdr,
3602 g_free(queue_element->pd);
3603 g_free(queue_element);
3609 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3610 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3611 sizeof(errmsg), pcap_opts);
3614 /* Were we asked to print packet counts by the SIGINFO handler? */
3615 if (global_ld.report_packet_count) {
3616 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3617 plurality(global_ld.packet_count, "", "s"));
3618 global_ld.report_packet_count = FALSE;
3623 /* any news from our parent (signal pipe)? -> just stop the capture */
3624 if (!signal_pipe_check_running()) {
3625 global_ld.go = FALSE;
3630 global_ld.inpkts_to_sync_pipe += inpkts;
3632 /* check capture size condition */
3633 if (cnd_autostop_size != NULL &&
3634 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)) {
3635 /* Capture size limit reached, do we have another file? */
3636 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3637 cnd_autostop_size, cnd_file_duration))
3639 } /* cnd_autostop_size */
3640 if (capture_opts->output_to_pipe) {
3641 fflush(global_ld.pdh);
3645 /* Only update once every 500ms so as not to overload slow displays.
3646 * This also prevents too much context-switching between the dumpcap
3647 * and wireshark processes.
3649 #define DUMPCAP_UPD_TIME 500
3652 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3653 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3655 gettimeofday(&cur_time, NULL);
3656 if ((cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3657 (upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3660 upd_time = cur_time;
3663 if (pcap_stats(pch, stats) >= 0) {
3664 *stats_known = TRUE;
3667 /* Let the parent process know. */
3668 if (global_ld.inpkts_to_sync_pipe) {
3670 fflush(global_ld.pdh);
3672 /* Send our parent a message saying we've written out
3673 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3675 report_packet_count(global_ld.inpkts_to_sync_pipe);
3677 global_ld.inpkts_to_sync_pipe = 0;
3680 /* check capture duration condition */
3681 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3682 /* The maximum capture time has elapsed; stop the capture. */
3683 global_ld.go = FALSE;
3687 /* check capture file duration condition */
3688 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3689 /* duration limit reached, do we have another file? */
3690 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3691 cnd_autostop_size, cnd_file_duration))
3693 } /* cnd_file_duration */
3697 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3699 pcap_queue_element *queue_element;
3701 for (i = 0; i < global_ld.pcaps->len; i++) {
3702 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3703 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3704 pcap_opts->interface_id);
3705 g_thread_join(pcap_opts->tid);
3706 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3707 pcap_opts->interface_id);
3710 g_async_queue_lock(pcap_queue);
3711 queue_element = g_async_queue_try_pop_unlocked(pcap_queue);
3712 if (queue_element) {
3713 pcap_queue_bytes -= queue_element->phdr.caplen;
3714 pcap_queue_packets -= 1;
3716 g_async_queue_unlock(pcap_queue);
3717 if (queue_element == NULL) {
3720 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3721 "Dequeued a packet of length %d captured on interface %d.",
3722 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3723 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3724 &queue_element->phdr,
3726 g_free(queue_element->pd);
3727 g_free(queue_element);
3728 global_ld.inpkts_to_sync_pipe += 1;
3729 if (capture_opts->output_to_pipe) {
3730 fflush(global_ld.pdh);
3736 /* delete stop conditions */
3737 if (cnd_file_duration != NULL)
3738 cnd_delete(cnd_file_duration);
3739 if (cnd_autostop_files != NULL)
3740 cnd_delete(cnd_autostop_files);
3741 if (cnd_autostop_size != NULL)
3742 cnd_delete(cnd_autostop_size);
3743 if (cnd_autostop_duration != NULL)
3744 cnd_delete(cnd_autostop_duration);
3746 /* did we have a pcap (input) error? */
3747 for (i = 0; i < capture_opts->ifaces->len; i++) {
3748 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3749 if (pcap_opts->pcap_err) {
3750 /* On Linux, if an interface goes down while you're capturing on it,
3751 you'll get a "recvfrom: Network is down" or
3752 "The interface went down" error (ENETDOWN).
3753 (At least you will if g_strerror() doesn't show a local translation
3756 On FreeBSD and OS X, if a network adapter disappears while
3757 you're capturing on it, you'll get a "read: Device not configured"
3758 error (ENXIO). (See previous parenthetical note.)
3760 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3762 These should *not* be reported to the Wireshark developers. */
3765 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3766 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3767 strcmp(cap_err_str, "The interface went down") == 0 ||
3768 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3769 strcmp(cap_err_str, "read: I/O error") == 0 ||
3770 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3771 report_capture_error("The network adapter on which the capture was being done "
3772 "is no longer running; the capture has stopped.",
3775 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3777 report_capture_error(errmsg, please_report);
3780 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3781 report_capture_error(errmsg, "");
3785 /* did we have an output error while capturing? */
3786 if (global_ld.err == 0) {
3789 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3790 global_ld.err, FALSE);
3791 report_capture_error(errmsg, please_report);
3795 if (capture_opts->saving_to_file) {
3796 /* close the output file */
3797 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3801 /* there might be packets not yet notified to the parent */
3802 /* (do this after closing the file, so all packets are already flushed) */
3803 if (global_ld.inpkts_to_sync_pipe) {
3805 report_packet_count(global_ld.inpkts_to_sync_pipe);
3806 global_ld.inpkts_to_sync_pipe = 0;
3809 /* If we've displayed a message about a write error, there's no point
3810 in displaying another message about an error on close. */
3811 if (!close_ok && write_ok) {
3812 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3814 report_capture_error(errmsg, "");
3818 * XXX We exhibit different behaviour between normal mode and sync mode
3819 * when the pipe is stdin and not already at EOF. If we're a child, the
3820 * parent's stdin isn't closed, so if the user starts another capture,
3821 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3822 * will say "Unrecognized libpcap format". On the other hand, in normal
3823 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3826 report_capture_count(TRUE);
3828 /* get packet drop statistics from pcap */
3829 for (i = 0; i < capture_opts->ifaces->len; i++) {
3833 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3834 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3835 received = pcap_opts->received;
3836 dropped = pcap_opts->dropped;
3837 if (pcap_opts->pcap_h != NULL) {
3838 g_assert(!pcap_opts->from_cap_pipe);
3839 /* Get the capture statistics, so we know how many packets were dropped. */
3840 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3841 *stats_known = TRUE;
3842 /* Let the parent process know. */
3843 dropped += stats->ps_drop;
3845 g_snprintf(errmsg, sizeof(errmsg),
3846 "Can't get packet-drop statistics: %s",
3847 pcap_geterr(pcap_opts->pcap_h));
3848 report_capture_error(errmsg, please_report);
3851 report_packet_drops(received, dropped, interface_opts.console_display_name);
3854 /* close the input file (pcap or capture pipe) */
3855 capture_loop_close_input(&global_ld);
3857 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
3859 /* ok, if the write and the close were successful. */
3860 return write_ok && close_ok;
3863 if (capture_opts->multi_files_on) {
3864 /* cleanup ringbuffer */
3865 ringbuf_error_cleanup();
3867 /* We can't use the save file, and we have no FILE * for the stream
3868 to close in order to close it, so close the FD directly. */
3869 if (global_ld.save_file_fd != -1) {
3870 ws_close(global_ld.save_file_fd);
3873 /* We couldn't even start the capture, so get rid of the capture
3875 if (capture_opts->save_file != NULL) {
3876 ws_unlink(capture_opts->save_file);
3877 g_free(capture_opts->save_file);
3880 capture_opts->save_file = NULL;
3882 report_cfilter_error(capture_opts, error_index, errmsg);
3884 report_capture_error(errmsg, secondary_errmsg);
3886 /* close the input file (pcap or cap_pipe) */
3887 capture_loop_close_input(&global_ld);
3889 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3896 capture_loop_stop(void)
3898 #ifdef HAVE_PCAP_BREAKLOOP
3900 pcap_options *pcap_opts;
3902 for (i = 0; i < global_ld.pcaps->len; i++) {
3903 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3904 if (pcap_opts->pcap_h != NULL)
3905 pcap_breakloop(pcap_opts->pcap_h);
3908 global_ld.go = FALSE;
3913 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3914 int err, gboolean is_close)
3919 g_snprintf(errmsg, errmsglen,
3920 "Not all the packets could be written to the file"
3921 " to which the capture was being saved\n"
3922 "(\"%s\") because there is no space left on the file system\n"
3923 "on which that file resides.",
3929 g_snprintf(errmsg, errmsglen,
3930 "Not all the packets could be written to the file"
3931 " to which the capture was being saved\n"
3932 "(\"%s\") because you are too close to, or over,"
3933 " your disk quota\n"
3934 "on the file system on which that file resides.",
3941 g_snprintf(errmsg, errmsglen,
3942 "The file to which the capture was being saved\n"
3943 "(\"%s\") could not be closed: %s.",
3944 fname, g_strerror(err));
3946 g_snprintf(errmsg, errmsglen,
3947 "An error occurred while writing to the file"
3948 " to which the capture was being saved\n"
3950 fname, g_strerror(err));
3957 /* one packet was captured, process it */
3959 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3962 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3964 guint ts_mul = pcap_opts->ts_nsec ? 1000000000 : 1000000;
3966 /* We may be called multiple times from pcap_dispatch(); if we've set
3967 the "stop capturing" flag, ignore this packet, as we're not
3968 supposed to be saving any more packets. */
3969 if (!global_ld.go) {
3970 pcap_opts->dropped++;
3974 if (global_ld.pdh) {
3975 gboolean successful;
3977 /* We're supposed to write the packet to a file; do so.
3978 If this fails, set "ld->go" to FALSE, to stop the capture, and set
3979 "ld->err" to the error. */
3980 if (global_capture_opts.use_pcapng) {
3981 successful = libpcap_write_enhanced_packet_block(global_ld.pdh,
3982 phdr->ts.tv_sec, phdr->ts.tv_usec,
3983 phdr->caplen, phdr->len,
3984 pcap_opts->interface_id,
3987 &global_ld.bytes_written, &err);
3989 successful = libpcap_write_packet(global_ld.pdh,
3990 phdr->ts.tv_sec, phdr->ts.tv_usec,
3991 phdr->caplen, phdr->len,
3993 &global_ld.bytes_written, &err);
3996 global_ld.go = FALSE;
3997 global_ld.err = err;
3998 pcap_opts->dropped++;
4000 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4001 "Wrote a packet of length %d captured on interface %u.",
4002 phdr->caplen, pcap_opts->interface_id);
4003 global_ld.packet_count++;
4004 pcap_opts->received++;
4005 /* if the user told us to stop after x packets, do we already have enough? */
4006 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
4007 global_ld.go = FALSE;
4013 /* one packet was captured, queue it */
4015 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4018 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4019 pcap_queue_element *queue_element;
4020 gboolean limit_reached;
4022 /* We may be called multiple times from pcap_dispatch(); if we've set
4023 the "stop capturing" flag, ignore this packet, as we're not
4024 supposed to be saving any more packets. */
4025 if (!global_ld.go) {
4026 pcap_opts->dropped++;
4030 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4031 if (queue_element == NULL) {
4032 pcap_opts->dropped++;
4035 queue_element->pcap_opts = pcap_opts;
4036 queue_element->phdr = *phdr;
4037 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4038 if (queue_element->pd == NULL) {
4039 pcap_opts->dropped++;
4040 g_free(queue_element);
4043 memcpy(queue_element->pd, pd, phdr->caplen);
4044 g_async_queue_lock(pcap_queue);
4045 if (((pcap_queue_byte_limit > 0) && (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4046 ((pcap_queue_packet_limit > 0) && (pcap_queue_packets < pcap_queue_packet_limit))) {
4047 limit_reached = FALSE;
4048 g_async_queue_push_unlocked(pcap_queue, queue_element);
4049 pcap_queue_bytes += phdr->caplen;
4050 pcap_queue_packets += 1;
4052 limit_reached = TRUE;
4054 g_async_queue_unlock(pcap_queue);
4055 if (limit_reached) {
4056 pcap_opts->dropped++;
4057 g_free(queue_element->pd);
4058 g_free(queue_element);
4059 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4060 "Dropped a packet of length %d captured on interface %u.",
4061 phdr->caplen, pcap_opts->interface_id);
4063 pcap_opts->received++;
4064 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4065 "Queued a packet of length %d captured on interface %u.",
4066 phdr->caplen, pcap_opts->interface_id);
4068 /* I don't want to hold the mutex over the debug output. So the
4069 output may be wrong */
4070 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4071 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4072 pcap_queue_bytes, pcap_queue_packets);
4076 set_80211_channel(const char *iface, const char *opt)
4078 int freq = 0, type, ret;
4079 gchar **options = NULL;
4081 options = g_strsplit_set(opt, ",", 2);
4084 freq = atoi(options[0]);
4087 type = ws80211_str_to_chan_type(options[1]);
4096 ret = ws80211_init();
4098 cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4102 ret = ws80211_set_freq(iface, freq, type);
4105 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4111 pipe_write_block(2, SP_SUCCESS, NULL);
4115 g_strfreev(options);
4119 /* And now our feature presentation... [ fade to music ] */
4121 main(int argc, char *argv[])
4124 gboolean arg_error = FALSE;
4129 struct sigaction action, oldaction;
4132 gboolean start_capture = TRUE;
4133 gboolean stats_known;
4134 struct pcap_stat stats;
4135 GLogLevelFlags log_flags;
4136 gboolean list_interfaces = FALSE;
4137 gboolean list_link_layer_types = FALSE;
4138 #ifdef HAVE_BPF_IMAGE
4139 gboolean print_bpf_code = FALSE;
4141 gboolean set_chan = FALSE;
4142 gchar *set_chan_arg = NULL;
4143 gboolean machine_readable = FALSE;
4144 gboolean print_statistics = FALSE;
4145 int status, run_once_args = 0;
4148 #if defined(__APPLE__) && defined(__LP64__)
4149 struct utsname osinfo;
4154 arg_list_utf_16to8(argc, argv);
4159 * Initialize our DLL search path. MUST be called before LoadLibrary
4162 ws_init_dll_search_path();
4165 #ifdef HAVE_PCAP_REMOTE
4166 #define OPTSTRING_A "A:"
4167 #define OPTSTRING_r "r"
4168 #define OPTSTRING_u "u"
4170 #define OPTSTRING_A ""
4171 #define OPTSTRING_r ""
4172 #define OPTSTRING_u ""
4175 #ifdef HAVE_PCAP_SETSAMPLING
4176 #define OPTSTRING_m "m:"
4178 #define OPTSTRING_m ""
4181 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4182 #define OPTSTRING_B "B:"
4184 #define OPTSTRING_B ""
4185 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4187 #ifdef HAVE_PCAP_CREATE
4188 #define OPTSTRING_I "I"
4190 #define OPTSTRING_I ""
4193 #ifdef HAVE_BPF_IMAGE
4194 #define OPTSTRING_d "d"
4196 #define OPTSTRING_d ""
4199 #define OPTSTRING "a:" OPTSTRING_A "b:" OPTSTRING_B "c:" OPTSTRING_d "Df:ghi:" OPTSTRING_I "k:L" OPTSTRING_m "MnpPq" OPTSTRING_r "Ss:t" OPTSTRING_u "vw:y:Z:"
4201 #ifdef DEBUG_CHILD_DUMPCAP
4202 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4203 fprintf (stderr, "Unable to open debug log file !\n");
4208 #if defined(__APPLE__) && defined(__LP64__)
4210 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
4211 * a bug workaround - timeouts less than 1 second don't work with libpcap
4212 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
4213 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4214 * The problem is extremely unlikely to be reintroduced in a future
4217 if (uname(&osinfo) == 0) {
4219 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
4220 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4221 * number of 10.0.0, not 10.1.0 - go figure).
4223 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
4224 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
4225 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
4226 need_timeout_workaround = TRUE;
4231 * Determine if dumpcap is being requested to run in a special
4232 * capture_child mode by going thru the command line args to see if
4233 * a -Z is present. (-Z is a hidden option).
4235 * The primary result of running in capture_child mode is that
4236 * all messages sent out on stderr are in a special type/len/string
4237 * format to allow message processing by type. These messages include
4238 * error messages if dumpcap fails to start the operation it was
4239 * requested to do, as well as various "status" messages which are sent
4240 * when an actual capture is in progress, and a "success" message sent
4241 * if dumpcap was requested to perform an operation other than a
4244 * Capture_child mode would normally be requested by a parent process
4245 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4246 * to which dumpcap stderr has been redirected. It might also have
4247 * another pipe to obtain dumpcap stdout output; for operations other
4248 * than a capture, that information is formatted specially for easier
4249 * parsing by the parent process.
4251 * Capture_child mode needs to be determined immediately upon
4252 * startup so that any messages generated by dumpcap in this mode
4253 * (eg: during initialization) will be formatted properly.
4256 for (i=1; i<argc; i++) {
4257 if (strcmp("-Z", argv[i]) == 0) {
4258 capture_child = TRUE;
4259 machine_readable = TRUE; /* request machine-readable output */
4261 /* set output pipe to binary mode, to avoid ugly text conversions */
4262 _setmode(2, O_BINARY);
4267 /* The default_log_handler will use stdout, which makes trouble in */
4268 /* capture child mode, as it uses stdout for it's sync_pipe. */
4269 /* So: the filtering is done in the console_log_handler and not here.*/
4270 /* We set the log handlers right up front to make sure that any log */
4271 /* messages when running as child will be sent back to the parent */
4272 /* with the correct format. */
4276 G_LOG_LEVEL_CRITICAL|
4277 G_LOG_LEVEL_WARNING|
4278 G_LOG_LEVEL_MESSAGE|
4281 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
4283 g_log_set_handler(NULL,
4285 console_log_handler, NULL /* user_data */);
4286 g_log_set_handler(LOG_DOMAIN_MAIN,
4288 console_log_handler, NULL /* user_data */);
4289 g_log_set_handler(LOG_DOMAIN_CAPTURE,
4291 console_log_handler, NULL /* user_data */);
4292 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4294 console_log_handler, NULL /* user_data */);
4296 /* Initialize the pcaps list */
4297 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
4299 #if !GLIB_CHECK_VERSION(2,31,0)
4300 /* Initialize the thread system */
4301 g_thread_init(NULL);
4305 /* Load wpcap if possible. Do this before collecting the run-time version information */
4308 /* ... and also load the packet.dll from wpcap */
4309 /* XXX - currently not required, may change later. */
4310 /*wpcap_packet_load();*/
4312 /* Start windows sockets */
4313 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4315 /* Set handler for Ctrl+C key */
4316 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4318 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4319 and exit. Do the same with SIGPIPE, in case, for example,
4320 we're writing to our standard output and it's a pipe.
4321 Do the same with SIGHUP if it's not being ignored (if we're
4322 being run under nohup, it might be ignored, in which case we
4323 should leave it ignored).
4325 XXX - apparently, Coverity complained that part of action
4326 wasn't initialized. Perhaps it's running on Linux, where
4327 struct sigaction has an ignored "sa_restorer" element and
4328 where "sa_handler" and "sa_sigaction" might not be two
4329 members of a union. */
4330 memset(&action, 0, sizeof(action));
4331 action.sa_handler = capture_cleanup_handler;
4333 * Arrange that system calls not get restarted, because when
4334 * our signal handler returns we don't want to restart
4335 * a call that was waiting for packets to arrive.
4337 action.sa_flags = 0;
4338 sigemptyset(&action.sa_mask);
4339 sigaction(SIGTERM, &action, NULL);
4340 sigaction(SIGINT, &action, NULL);
4341 sigaction(SIGPIPE, &action, NULL);
4342 sigaction(SIGHUP, NULL, &oldaction);
4343 if (oldaction.sa_handler == SIG_DFL)
4344 sigaction(SIGHUP, &action, NULL);
4347 /* Catch SIGINFO and, if we get it and we're capturing in
4348 quiet mode, report the number of packets we've captured. */
4349 action.sa_handler = report_counts_siginfo;
4350 action.sa_flags = SA_RESTART;
4351 sigemptyset(&action.sa_mask);
4352 sigaction(SIGINFO, &action, NULL);
4353 #endif /* SIGINFO */
4356 /* ----------------------------------------------------------------- */
4357 /* Privilege and capability handling */
4359 /* 1. Running not as root or suid root; no special capabilities. */
4362 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4365 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4367 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4368 /* capabilities; Drop all other capabilities; */
4369 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4370 /* else: after pcap_open_live() in capture_loop_open_input() */
4371 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4372 /* (Note: this means that the process, although logged in */
4373 /* as root, does not have various permissions such as the */
4374 /* ability to bypass file access permissions). */
4375 /* XXX: Should we just leave capabilities alone in this case */
4376 /* so that user gets expected effect that root can do */
4379 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4381 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4382 /* else: after pcap_open_live() in capture_loop_open_input() */
4383 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4384 /* pcap_open_live). */
4386 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4388 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4389 /* capabilities; Drop all other capabilities; */
4390 /* Drop suid privileges (euid=ruid); */
4391 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4392 /* else: after pcap_open_live() in capture_loop_open_input() */
4393 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4395 /* XXX: For some Linux versions/distros with capabilities */
4396 /* a 'normal' process with any capabilities cannot be */
4397 /* 'killed' (signaled) from another (same uid) non-privileged */
4399 /* For example: If (non-suid) Wireshark forks a */
4400 /* child suid dumpcap which acts as described here (case 5), */
4401 /* Wireshark will be unable to kill (signal) the child */
4402 /* dumpcap process until the capabilities have been dropped */
4403 /* (after pcap_open_live()). */
4404 /* This behaviour will apparently be changed in the kernel */
4405 /* to allow the kill (signal) in this case. */
4406 /* See the following for details: */
4407 /* http://www.mail-archive.com/ [wrapped] */
4408 /* linux-security-module@vger.kernel.org/msg02913.html */
4410 /* It is therefore conceivable that if dumpcap somehow hangs */
4411 /* in pcap_open_live or before that wireshark will not */
4412 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4413 /* In this case, exiting wireshark will kill the child */
4414 /* dumpcap process. */
4416 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4417 /* capabilities; Using libcap. Note: capset cmd (which see) */
4418 /* used to assign capabilities to file. */
4420 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4421 /* else: after pcap_open_live() in capture_loop_open_input() */
4422 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4424 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4425 /* longer required (similar to capture). */
4427 /* ----------------------------------------------------------------- */
4429 init_process_policies();
4432 /* If 'started with special privileges' (and using libcap) */
4433 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4434 /* Set euid/egid = ruid/rgid to remove suid privileges */
4435 relinquish_privs_except_capture();
4438 /* Set the initial values in the capture options. This might be overwritten
4439 by the command line parameters. */
4440 capture_opts_init(&global_capture_opts, NULL);
4442 /* We always save to a file - if no file was specified, we save to a
4444 global_capture_opts.saving_to_file = TRUE;
4445 global_capture_opts.has_ring_num_files = TRUE;
4447 /* Now get our args */
4448 while ((opt = getopt(argc, argv, OPTSTRING)) != -1) {
4450 case 'h': /* Print help and exit */
4454 case 'v': /* Show version and exit */
4456 GString *comp_info_str;
4457 GString *runtime_info_str;
4458 /* Assemble the compile-time version information string */
4459 comp_info_str = g_string_new("Compiled ");
4460 get_compiled_version_info(comp_info_str, NULL, NULL);
4462 /* Assemble the run-time version information string */
4463 runtime_info_str = g_string_new("Running ");
4464 get_runtime_version_info(runtime_info_str, NULL);
4465 show_version(comp_info_str, runtime_info_str);
4466 g_string_free(comp_info_str, TRUE);
4467 g_string_free(runtime_info_str, TRUE);
4471 /*** capture option specific ***/
4472 case 'a': /* autostop criteria */
4473 case 'b': /* Ringbuffer option */
4474 case 'c': /* Capture x packets */
4475 case 'f': /* capture filter */
4476 case 'g': /* enable group read access on file(s) */
4477 case 'i': /* Use interface x */
4478 case 'n': /* Use pcapng format */
4479 case 'p': /* Don't capture in promiscuous mode */
4480 case 'P': /* Use pcap format */
4481 case 's': /* Set the snapshot (capture) length */
4482 case 'w': /* Write to capture file x */
4483 case 'y': /* Set the pcap data link type */
4484 #ifdef HAVE_PCAP_REMOTE
4485 case 'u': /* Use UDP for data transfer */
4486 case 'r': /* Capture own RPCAP traffic too */
4487 case 'A': /* Authentication */
4489 #ifdef HAVE_PCAP_SETSAMPLING
4490 case 'm': /* Sampling */
4492 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4493 case 'B': /* Buffer size */
4494 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4495 #ifdef HAVE_PCAP_CREATE
4496 case 'I': /* Monitor mode */
4498 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4503 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4505 capture_child = TRUE;
4507 /* set output pipe to binary mode, to avoid ugly text conversions */
4508 _setmode(2, O_BINARY);
4510 * optarg = the control ID, aka the PPID, currently used for the
4513 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4514 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4515 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4516 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4518 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4519 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4520 "Signal pipe: Unable to open %s. Dead parent?",
4528 case 'q': /* Quiet */
4534 /*** all non capture option specific ***/
4535 case 'D': /* Print a list of capture devices and exit */
4536 list_interfaces = TRUE;
4539 case 'L': /* Print list of link-layer types and exit */
4540 list_link_layer_types = TRUE;
4543 #ifdef HAVE_BPF_IMAGE
4544 case 'd': /* Print BPF code for capture filter and exit */
4545 print_bpf_code = TRUE;
4549 case 'S': /* Print interface statistics once a second */
4550 print_statistics = TRUE;
4553 case 'k': /* Set wireless channel */
4555 set_chan_arg = optarg;
4558 case 'M': /* For -D, -L, and -S, print machine-readable output */
4559 machine_readable = TRUE;
4562 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4564 case '?': /* Bad flag - print usage message */
4573 /* user specified file name as regular command-line argument */
4574 /* XXX - use it as the capture file name (or something else)? */
4580 * Extra command line arguments were specified; complain.
4581 * XXX - interpret as capture filter, as tcpdump and tshark do?
4583 cmdarg_err("Invalid argument: %s", argv[0]);
4593 if (run_once_args > 1) {
4594 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
4596 } else if (run_once_args == 1) {
4597 /* We're supposed to print some information, rather than
4598 to capture traffic; did they specify a ring buffer option? */
4599 if (global_capture_opts.multi_files_on) {
4600 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4604 /* We're supposed to capture traffic; */
4605 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4606 if (global_capture_opts.ifaces->len > 1) {
4608 global_capture_opts.use_pcapng = TRUE;
4610 /* Was the ring buffer option specified and, if so, does it make sense? */
4611 if (global_capture_opts.multi_files_on) {
4612 /* Ring buffer works only under certain conditions:
4613 a) ring buffer does not work with temporary files;
4614 b) it makes no sense to enable the ring buffer if the maximum
4615 file size is set to "infinite". */
4616 if (global_capture_opts.save_file == NULL) {
4617 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4618 global_capture_opts.multi_files_on = FALSE;
4620 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4621 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4623 /* XXX - this must be redesigned as the conditions changed */
4624 global_capture_opts.multi_files_on = FALSE;
4631 * "-D" requires no interface to be selected; it's supposed to list
4634 if (list_interfaces) {
4635 /* Get the list of interfaces */
4640 if_list = capture_interface_list(&err, &err_str);
4641 if (if_list == NULL) {
4643 case CANT_GET_INTERFACE_LIST:
4644 case DONT_HAVE_PCAP:
4645 cmdarg_err("%s", err_str);
4650 case NO_INTERFACES_FOUND:
4652 * If we're being run by another program, just give them
4653 * an empty list of interfaces, don't report this as
4654 * an error; that lets them decide whether to report
4655 * this as an error or not.
4657 if (!machine_readable) {
4658 cmdarg_err("There are no interfaces on which a capture can be done");
4665 if (machine_readable) /* tab-separated values to stdout */
4666 print_machine_readable_interfaces(if_list);
4668 capture_opts_print_interfaces(if_list);
4669 free_interface_list(if_list);
4674 * "-S" requires no interface to be selected; it gives statistics
4675 * for all interfaces.
4677 if (print_statistics) {
4678 status = print_statistics_loop(machine_readable);
4683 interface_options interface_opts;
4685 if (global_capture_opts.ifaces->len != 1) {
4686 cmdarg_err("Need one interface");
4690 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4691 status = set_80211_channel(interface_opts.name, set_chan_arg);
4696 * "-L", "-d", and capturing act on a particular interface, so we have to
4697 * have an interface; if none was specified, pick a default.
4699 status = capture_opts_trim_iface(&global_capture_opts, NULL);
4701 /* cmdarg_err() already called .... */
4705 /* Let the user know what interfaces were chosen. */
4706 if (capture_child) {
4707 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4708 interface_options interface_opts;
4710 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4711 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4712 interface_opts.name);
4715 str = g_string_new("");
4717 if (global_capture_opts.ifaces->len < 2)
4719 if (global_capture_opts.ifaces->len < 4)
4722 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4723 interface_options interface_opts;
4725 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4727 if (global_capture_opts.ifaces->len > 2) {
4728 g_string_append_printf(str, ",");
4730 g_string_append_printf(str, " ");
4731 if (j == global_capture_opts.ifaces->len - 1) {
4732 g_string_append_printf(str, "and ");
4735 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
4738 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4740 fprintf(stderr, "Capturing on %s\n", str->str);
4741 g_string_free(str, TRUE);
4744 if (list_link_layer_types) {
4745 /* Get the list of link-layer types for the capture device. */
4746 if_capabilities_t *caps;
4750 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4751 interface_options interface_opts;
4753 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4754 caps = get_if_capabilities(interface_opts.name,
4755 interface_opts.monitor_mode, &err_str);
4757 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4758 "Please check to make sure you have sufficient permissions, and that\n"
4759 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4763 if (caps->data_link_types == NULL) {
4764 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4767 if (machine_readable) /* tab-separated values to stdout */
4768 /* XXX: We need to change the format and adopt consumers */
4769 print_machine_readable_if_capabilities(caps);
4771 /* XXX: We might want to print also the interface name */
4772 capture_opts_print_if_capabilities(caps, interface_opts.name,
4773 interface_opts.monitor_mode);
4774 free_if_capabilities(caps);
4779 /* We're supposed to do a capture, or print the BPF code for a filter.
4780 Process the snapshot length, as that affects the generated BPF code. */
4781 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4783 #ifdef HAVE_BPF_IMAGE
4784 if (print_bpf_code) {
4785 show_filter_code(&global_capture_opts);
4790 /* We're supposed to do a capture. Process the ring buffer arguments. */
4791 capture_opts_trim_ring_num_files(&global_capture_opts);
4793 /* flush stderr prior to starting the main capture loop */
4796 /* Now start the capture. */
4798 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4802 /* capture failed */
4805 return 0; /* never here, make compiler happy */
4810 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4811 const char *message, gpointer user_data _U_)
4818 /* ignore log message, if log_level isn't interesting */
4819 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4820 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4825 /* create a "timestamp" */
4827 today = localtime(&curr);
4829 switch(log_level & G_LOG_LEVEL_MASK) {
4830 case G_LOG_LEVEL_ERROR:
4833 case G_LOG_LEVEL_CRITICAL:
4836 case G_LOG_LEVEL_WARNING:
4839 case G_LOG_LEVEL_MESSAGE:
4842 case G_LOG_LEVEL_INFO:
4845 case G_LOG_LEVEL_DEBUG:
4849 fprintf(stderr, "unknown log_level %u\n", log_level);
4851 g_assert_not_reached();
4854 /* Generate the output message */
4855 if (log_level & G_LOG_LEVEL_MESSAGE) {
4856 /* normal user messages without additional infos */
4857 msg = g_strdup_printf("%s\n", message);
4859 /* info/debug messages with additional infos */
4860 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4861 today->tm_hour, today->tm_min, today->tm_sec,
4862 log_domain != NULL ? log_domain : "",
4866 /* DEBUG & INFO msgs (if we're debugging today) */
4867 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4868 if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4869 #ifdef DEBUG_DUMPCAP
4870 fprintf(stderr, "%s", msg);
4873 #ifdef DEBUG_CHILD_DUMPCAP
4874 fprintf(debug_log, "%s", msg);
4882 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4883 /* to parent especially formatted if dumpcap running as child. */
4884 if (capture_child) {
4885 sync_pipe_errmsg_to_parent(2, msg, "");
4887 fprintf(stderr, "%s", msg);
4894 /****************************************************************************************************************/
4895 /* indication report routines */
4899 report_packet_count(unsigned int packet_count)
4901 char tmp[SP_DECISIZE+1+1];
4902 static unsigned int count = 0;
4904 if (capture_child) {
4905 g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
4906 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
4907 pipe_write_block(2, SP_PACKET_COUNT, tmp);
4909 count += packet_count;
4910 fprintf(stderr, "\rPackets: %u ", count);
4911 /* stderr could be line buffered */
4917 report_new_capture_file(const char *filename)
4919 if (capture_child) {
4920 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
4921 pipe_write_block(2, SP_FILE, filename);
4925 * Prevent a SIGINFO handler from writing to the standard error
4926 * while we're doing so; instead, have it just set a flag telling
4927 * us to print that information when we're done.
4930 #endif /* SIGINFO */
4931 fprintf(stderr, "File: %s\n", filename);
4932 /* stderr could be line buffered */
4937 * Allow SIGINFO handlers to write.
4942 * If a SIGINFO handler asked us to write out capture counts, do so.
4945 report_counts_for_siginfo();
4946 #endif /* SIGINFO */
4951 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
4953 interface_options interface_opts;
4954 char tmp[MSG_MAX_LENGTH+1+6];
4956 if (i < capture_opts->ifaces->len) {
4957 if (capture_child) {
4958 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
4959 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
4960 pipe_write_block(2, SP_BAD_FILTER, tmp);
4963 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
4964 * the error message below.
4966 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
4968 "Invalid capture filter \"%s\" for interface %s!\n"
4970 "That string isn't a valid capture filter (%s).\n"
4971 "See the User's Guide for a description of the capture filter syntax.",
4972 interface_opts.cfilter, interface_opts.name, errmsg);
4978 report_capture_error(const char *error_msg, const char *secondary_error_msg)
4980 if (capture_child) {
4981 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4982 "Primary Error: %s", error_msg);
4983 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4984 "Secondary Error: %s", secondary_error_msg);
4985 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
4987 cmdarg_err("%s", error_msg);
4988 if (secondary_error_msg[0] != '\0')
4989 cmdarg_err_cont("%s", secondary_error_msg);
4994 report_packet_drops(guint32 received, guint32 drops, gchar *name)
4996 char tmp[SP_DECISIZE+1+1];
4998 g_snprintf(tmp, sizeof(tmp), "%u", drops);
5000 if (capture_child) {
5001 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5002 "Packets received/dropped on interface %s: %u/%u",
5003 name, received, drops);
5004 /* XXX: Need to provide interface id, changes to consumers required. */
5005 pipe_write_block(2, SP_DROPS, tmp);
5008 "Packets received/dropped on interface '%s': %u/%u (%.1f%%)\n",
5009 name, received, drops,
5010 received ? 100.0 * received / (received + drops) : 0.0);
5011 /* stderr could be line buffered */
5017 /************************************************************************************************/
5018 /* signal_pipe handling */
5023 signal_pipe_check_running(void)
5025 /* any news from our parent? -> just stop the capture */
5029 /* if we are running standalone, no check required */
5030 if (!capture_child) {
5034 if (!sig_pipe_name || !sig_pipe_handle) {
5035 /* This shouldn't happen */
5036 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5037 "Signal pipe: No name or handle");
5042 * XXX - We should have the process ID of the parent (from the "-Z" flag)
5043 * at this point. Should we check to see if the parent is still alive,
5044 * e.g. by using OpenProcess?
5047 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5049 if (!result || avail > 0) {
5050 /* peek failed or some bytes really available */
5051 /* (if not piping from stdin this would fail) */
5052 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5053 "Signal pipe: Stop capture: %s", sig_pipe_name);
5054 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5055 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
5056 sig_pipe_handle, result, avail);
5059 /* pipe ok and no bytes available */
5066 * Editor modelines - http://www.wireshark.org/tools/modelines.html
5071 * indent-tabs-mode: nil
5074 * vi: set shiftwidth=4 tabstop=8 expandtab:
5075 * :indentSize=4:tabSize=8:noTabs=true: