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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 #include <stdlib.h> /* for exit() */
35 #ifdef HAVE_SYS_TYPES_H
36 # include <sys/types.h>
39 #ifdef HAVE_SYS_STAT_H
40 # include <sys/stat.h>
51 #ifdef HAVE_ARPA_INET_H
52 #include <arpa/inet.h>
55 #if defined(__APPLE__) && defined(__LP64__)
56 #include <sys/utsname.h>
63 #include "wsutil/wsgetopt.h"
71 # include <sys/prctl.h>
72 # include <sys/capability.h>
75 #include "ringbuffer.h"
76 #include "clopts_common.h"
77 #include "console_io.h"
78 #include "cmdarg_err.h"
79 #include "version_info.h"
81 #include "capture-pcap-util.h"
83 #include "capture-wpcap.h"
89 #include "capture-wpcap.h"
90 #include <wsutil/unicode-utils.h>
94 #include <sys/socket.h>
98 #ifdef NEED_INET_V6DEFS_H
99 # include "wsutil/inet_v6defs.h"
102 #include <wsutil/privileges.h>
104 #include "sync_pipe.h"
106 #include "capture_opts.h"
107 #include "capture_ifinfo.h"
108 #include "capture_sync.h"
110 #include "conditions.h"
111 #include "capture_stop_conditions.h"
113 #include "tempfile.h"
115 #include "wsutil/file_util.h"
118 * Get information about libpcap format from "wiretap/libpcap.h".
119 * XXX - can we just use pcap_open_offline() to read the pipe?
121 #include "wiretap/libpcap.h"
123 /**#define DEBUG_DUMPCAP**/
124 /**#define DEBUG_CHILD_DUMPCAP**/
128 #include <conio.h> /* _getch() */
132 #ifdef DEBUG_CHILD_DUMPCAP
133 FILE *debug_log; /* for logging debug messages to */
134 /* a file if DEBUG_CHILD_DUMPCAP */
138 static GAsyncQueue *pcap_queue;
139 static gint64 pcap_queue_bytes;
140 static gint64 pcap_queue_packets;
141 static gint64 pcap_queue_byte_limit = 1024 * 1024;
142 static gint64 pcap_queue_packet_limit = 1000;
144 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
146 static gchar *sig_pipe_name = NULL;
147 static HANDLE sig_pipe_handle = NULL;
148 static gboolean signal_pipe_check_running(void);
152 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
153 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
156 /** Stop a low-level capture (stops the capture child). */
157 static void capture_loop_stop(void);
159 #if !defined (__linux__)
160 #ifndef HAVE_PCAP_BREAKLOOP
162 * We don't have pcap_breakloop(), which is the only way to ensure that
163 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
164 * won't, if the call to read the next packet or batch of packets is
165 * is interrupted by a signal on UN*X, just go back and try again to
168 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
169 * the signal handler, set a flag to stop capturing; however, without
170 * a guarantee of that sort, we can't guarantee that we'll stop capturing
171 * if the read will be retried and won't time out if no packets arrive.
173 * Therefore, on at least some platforms, we work around the lack of
174 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
175 * to wait for packets to arrive, so that we're probably going to be
176 * blocked in the select() when the signal arrives, and can just bail
177 * out of the loop at that point.
179 * However, we don't want to do that on BSD (because "select()" doesn't work
180 * correctly on BPF devices on at least some releases of some flavors of
181 * BSD), and we don't want to do it on Windows (because "select()" is
182 * something for sockets, not for arbitrary handles). (Note that "Windows"
183 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
184 * using WinPcap, not a UNIX libpcap.)
186 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
187 * on BSD times out even if no packets have arrived, so we'll eventually
188 * exit pcap_dispatch() with an indication that no packets have arrived,
189 * and will break out of the capture loop at that point.
191 * On Windows, we can't send a SIGINT to stop capturing, so none of this
192 * applies in any case.
194 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
195 * want to include it if it's not present on this platform, however.
197 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
198 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
200 # define MUST_DO_SELECT
201 # endif /* avoid select */
202 #endif /* HAVE_PCAP_BREAKLOOP */
204 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
205 * in pcap_dispatch(); on the other hand, select() works just fine there.
206 * Hence we use a select for that come what may.
208 #define MUST_DO_SELECT
211 /** init the capture filter */
214 INITFILTER_BAD_FILTER,
215 INITFILTER_OTHER_ERROR
216 } initfilter_status_t;
218 typedef struct _pcap_options {
222 #ifdef MUST_DO_SELECT
223 int pcap_fd; /* pcap file descriptor */
230 /* capture pipe (unix only "input file") */
231 gboolean from_cap_pipe; /* TRUE if we are capturing data from a capture pipe */
232 struct pcap_hdr cap_pipe_hdr; /* Pcap header when capturing from a pipe */
233 struct pcaprec_modified_hdr cap_pipe_rechdr; /* Pcap record header when capturing from a pipe */
235 HANDLE cap_pipe_h; /* The handle of the capture pipe */
237 int cap_pipe_fd; /* the file descriptor of the capture pipe */
239 gboolean cap_pipe_modified; /* TRUE if data in the pipe uses modified pcap headers */
240 gboolean cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
242 char * cap_pipe_buf; /* Pointer to the data buffer we read into */
244 int cap_pipe_bytes_to_read;/* Used by cap_pipe_dispatch */
245 int cap_pipe_bytes_read; /* Used by cap_pipe_dispatch */
247 STATE_EXPECT_REC_HDR,
252 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
254 GMutex *cap_pipe_read_mtx;
255 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
259 typedef struct _loop_data {
261 gboolean go; /* TRUE as long as we're supposed to keep capturing */
262 int err; /* if non-zero, error seen while capturing */
263 gint packet_count; /* Number of packets we have already captured */
264 gint packet_max; /* Number of packets we're supposed to capture - 0 means infinite */
265 gint inpkts_to_sync_pipe; /* Packets not already send out to the sync_pipe */
267 gboolean report_packet_count; /* Set by SIGINFO handler; print packet count */
274 guint32 autostop_files;
277 typedef struct _pcap_queue_element {
278 pcap_options *pcap_opts;
279 struct pcap_pkthdr phdr;
281 } pcap_queue_element;
284 * Standard secondary message for unexpected errors.
286 static const char please_report[] =
287 "Please report this to the Wireshark developers.\n"
288 "(This is not a crash; please do not report it as such.)";
291 * This needs to be static, so that the SIGINT handler can clear the "go"
294 static loop_data global_ld;
298 * Timeout, in milliseconds, for reads from the stream of captured packets
299 * from a capture device.
301 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
302 * 64-bit applications, with sub-second timeouts not to work. The bug is
303 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
305 #if defined(__APPLE__) && defined(__LP64__)
306 static gboolean need_timeout_workaround;
308 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
310 #define CAP_READ_TIMEOUT 250
314 * Timeout, in microseconds, for reads from the stream of captured packets
315 * from a pipe. Pipes don't have the same problem that BPF devices do
316 * in OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
317 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
318 * of the offending versions of Snow Leopard.
320 * On Windows this value is converted to milliseconds and passed to
321 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
322 * will return immediately.
325 #define PIPE_READ_TIMEOUT 100000
327 #define PIPE_READ_TIMEOUT 250000
330 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
333 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
334 const char *message, gpointer user_data _U_);
336 /* capture related options */
337 static capture_options global_capture_opts;
338 static gboolean quiet = FALSE;
339 static gboolean use_threads = FALSE;
340 static guint64 start_time;
342 static void capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
344 static void capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
346 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
347 int err, gboolean is_close);
349 static void WS_MSVC_NORETURN exit_main(int err) G_GNUC_NORETURN;
351 static void report_new_capture_file(const char *filename);
352 static void report_packet_count(int packet_count);
353 static void report_packet_drops(guint32 received, guint32 drops, gchar *name);
354 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
355 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
357 #define MSG_MAX_LENGTH 4096
359 /* Copied from pcapio.c libpcap_write_interface_statistics_block()*/
361 create_timestamp(void) {
371 * Current time, represented as 100-nanosecond intervals since
372 * January 1, 1601, 00:00:00 UTC.
374 * I think DWORD might be signed, so cast both parts of "now"
375 * to guint32 so that the sign bit doesn't get treated specially.
377 * Windows 8 provides GetSystemTimePreciseAsFileTime which we
378 * might want to use instead.
380 GetSystemTimeAsFileTime(&now);
381 timestamp = (((guint64)(guint32)now.dwHighDateTime) << 32) +
382 (guint32)now.dwLowDateTime;
385 * Convert to same thing but as 1-microsecond, i.e. 1000-nanosecond,
391 * Subtract difference, in microseconds, between January 1, 1601
392 * 00:00:00 UTC and January 1, 1970, 00:00:00 UTC.
394 timestamp -= G_GINT64_CONSTANT(11644473600000000U);
397 * Current time, represented as seconds and microseconds since
398 * January 1, 1970, 00:00:00 UTC.
400 gettimeofday(&now, NULL);
403 * Convert to delta in microseconds.
405 timestamp = (guint64)(now.tv_sec) * 1000000 +
406 (guint64)(now.tv_usec);
412 print_usage(gboolean print_ver)
419 "Dumpcap " VERSION "%s\n"
420 "Capture network packets and dump them into a pcapng file.\n"
421 "See http://www.wireshark.org for more information.\n",
422 wireshark_svnversion);
426 fprintf(output, "\nUsage: dumpcap [options] ...\n");
427 fprintf(output, "\n");
428 fprintf(output, "Capture interface:\n");
429 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
430 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
431 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
432 fprintf(output, " -p don't capture in promiscuous mode\n");
433 #ifdef HAVE_PCAP_CREATE
434 fprintf(output, " -I capture in monitor mode, if available\n");
436 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
437 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
439 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
440 fprintf(output, " -D print list of interfaces and exit\n");
441 fprintf(output, " -L print list of link-layer types of iface and exit\n");
442 #ifdef HAVE_BPF_IMAGE
443 fprintf(output, " -d print generated BPF code for capture filter\n");
445 fprintf(output, " -S print statistics for each interface once per second\n");
446 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
447 fprintf(output, "\n");
448 #ifdef HAVE_PCAP_REMOTE
449 fprintf(output, "RPCAP options:\n");
450 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
451 fprintf(output, " -u use UDP for RPCAP data transfer\n");
452 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
453 #ifdef HAVE_PCAP_SETSAMPLING
454 fprintf(output, " -m <sampling type> use packet sampling\n");
455 fprintf(output, " count:NUM - capture one packet of every NUM\n");
456 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
459 fprintf(output, "Stop conditions:\n");
460 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
461 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
462 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
463 fprintf(output, " files:NUM - stop after NUM files\n");
464 /*fprintf(output, "\n");*/
465 fprintf(output, "Output (files):\n");
466 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
467 fprintf(output, " -g enable group read access on the output file(s)\n");
468 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
469 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
470 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
471 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
472 fprintf(output, " -P use libpcap format instead of pcapng\n");
473 fprintf(output, "\n");
474 fprintf(output, "Miscellaneous:\n");
475 fprintf(output, " -t use a separate thread per interface\n");
476 fprintf(output, " -q don't report packet capture counts\n");
477 fprintf(output, " -v print version information and exit\n");
478 fprintf(output, " -h display this help and exit\n");
479 fprintf(output, "\n");
480 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
481 fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcapng\"\n");
482 fprintf(output, "\n");
483 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
487 show_version(GString *comp_info_str, GString *runtime_info_str)
490 "Dumpcap " VERSION "%s\n"
495 "See http://www.wireshark.org for more information.\n",
496 wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
500 * Print to the standard error. This is a command-line tool, so there's
501 * no need to pop up a console.
504 vfprintf_stderr(const char *fmt, va_list ap)
506 vfprintf(stderr, fmt, ap);
510 fprintf_stderr(const char *fmt, ...)
515 vfprintf_stderr(fmt, ap);
520 * Report an error in command-line arguments.
523 cmdarg_err(const char *fmt, ...)
529 /* Generate a 'special format' message back to parent */
531 msg = g_strdup_vprintf(fmt, ap);
532 sync_pipe_errmsg_to_parent(2, msg, "");
537 fprintf(stderr, "dumpcap: ");
538 vfprintf(stderr, fmt, ap);
539 fprintf(stderr, "\n");
545 * Report additional information for an error in command-line arguments.
548 cmdarg_err_cont(const char *fmt, ...)
555 msg = g_strdup_vprintf(fmt, ap);
556 sync_pipe_errmsg_to_parent(2, msg, "");
561 vfprintf(stderr, fmt, ap);
562 fprintf(stderr, "\n");
569 #if 0 /* Set to enable capability debugging */
570 /* see 'man cap_to_text()' for explanation of output */
571 /* '=' means 'all= ' ie: no capabilities */
572 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
574 print_caps(const char *pfx) {
575 cap_t caps = cap_get_proc();
576 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
577 "%s: EUID: %d Capabilities: %s", pfx,
578 geteuid(), cap_to_text(caps, NULL));
581 print_caps(const char *pfx _U_) {
586 relinquish_all_capabilities(void)
588 /* Drop any and all capabilities this process may have. */
589 /* Allowed whether or not process has any privileges. */
590 cap_t caps = cap_init(); /* all capabilities initialized to off */
591 print_caps("Pre-clear");
592 if (cap_set_proc(caps)) {
593 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
595 print_caps("Post-clear");
601 open_capture_device(interface_options *interface_opts,
602 char (*open_err_str)[PCAP_ERRBUF_SIZE])
605 #ifdef HAVE_PCAP_CREATE
608 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
609 struct pcap_rmtauth auth;
612 /* Open the network interface to capture from it.
613 Some versions of libpcap may put warnings into the error buffer
614 if they succeed; to tell if that's happened, we have to clear
615 the error buffer, and check if it's still a null string. */
616 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Entering open_capture_device().");
617 (*open_err_str)[0] = '\0';
618 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
620 * If we're opening a remote device, use pcap_open(); that's currently
621 * the only open routine that supports remote devices.
623 if (strncmp (interface_opts->name, "rpcap://", 8) == 0) {
624 auth.type = interface_opts->auth_type == CAPTURE_AUTH_PWD ?
625 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
626 auth.username = interface_opts->auth_username;
627 auth.password = interface_opts->auth_password;
629 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
630 "Calling pcap_open() using name %s, snaplen %d, promisc_mode %d, datatx_udp %d, nocap_rpcap %d.",
631 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode,
632 interface_opts->datatx_udp, interface_opts->nocap_rpcap);
633 pcap_h = pcap_open(interface_opts->name, interface_opts->snaplen,
635 (interface_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
636 (interface_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
637 (interface_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
638 CAP_READ_TIMEOUT, &auth, *open_err_str);
639 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
640 "pcap_open() returned %p.", (void *)pcap_h);
645 * If we're not opening a remote device, use pcap_create() and
646 * pcap_activate() if we have them, so that we can set the buffer
647 * size, otherwise use pcap_open_live().
649 #ifdef HAVE_PCAP_CREATE
650 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
651 "Calling pcap_create() using %s.", interface_opts->name);
652 pcap_h = pcap_create(interface_opts->name, *open_err_str);
653 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
654 "pcap_create() returned %p.", (void *)pcap_h);
655 if (pcap_h != NULL) {
656 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
657 "Calling pcap_set_snaplen() with snaplen %d.", interface_opts->snaplen);
658 pcap_set_snaplen(pcap_h, interface_opts->snaplen);
659 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
660 "Calling pcap_set_snaplen() with promisc_mode %d.", interface_opts->promisc_mode);
661 pcap_set_promisc(pcap_h, interface_opts->promisc_mode);
662 pcap_set_timeout(pcap_h, CAP_READ_TIMEOUT);
664 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
665 "buffersize %d.", interface_opts->buffer_size);
666 if (interface_opts->buffer_size > 1) {
667 pcap_set_buffer_size(pcap_h, interface_opts->buffer_size * 1024 * 1024);
669 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
670 "monitor_mode %d.", interface_opts->monitor_mode);
671 if (interface_opts->monitor_mode)
672 pcap_set_rfmon(pcap_h, 1);
673 err = pcap_activate(pcap_h);
674 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
675 "pcap_activate() returned %d.", err);
677 /* Failed to activate, set to NULL */
678 if (err == PCAP_ERROR)
679 g_strlcpy(*open_err_str, pcap_geterr(pcap_h), sizeof *open_err_str);
681 g_strlcpy(*open_err_str, pcap_statustostr(err), sizeof *open_err_str);
687 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
688 "pcap_open_live() calling using name %s, snaplen %d, promisc_mode %d.",
689 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode);
690 pcap_h = pcap_open_live(interface_opts->name, interface_opts->snaplen,
691 interface_opts->promisc_mode, CAP_READ_TIMEOUT,
693 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
694 "pcap_open_live() returned %p.", (void *)pcap_h);
697 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "open_capture_device %s : %s", pcap_h ? "SUCCESS" : "FAILURE", interface_opts->name);
702 get_capture_device_open_failure_messages(const char *open_err_str,
708 char *errmsg, size_t errmsg_len,
709 char *secondary_errmsg,
710 size_t secondary_errmsg_len)
712 const char *libpcap_warn;
713 static const char ppamsg[] = "can't find PPA for ";
715 /* If we got a "can't find PPA for X" message, warn the user (who
716 is running dumpcap on HP-UX) that they don't have a version of
717 libpcap that properly handles HP-UX (libpcap 0.6.x and later
718 versions, which properly handle HP-UX, say "can't find /dev/dlpi
719 PPA for X" rather than "can't find PPA for X"). */
720 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
723 "You are running (T)Wireshark with a version of the libpcap library\n"
724 "that doesn't handle HP-UX network devices well; this means that\n"
725 "(T)Wireshark may not be able to capture packets.\n"
727 "To fix this, you should install libpcap 0.6.2, or a later version\n"
728 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
729 "packaged binary form from the Software Porting And Archive Centre\n"
730 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
731 "at the URL lists a number of mirror sites.";
734 g_snprintf(errmsg, (gulong) errmsg_len,
735 "The capture session could not be initiated (%s).", open_err_str);
738 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
740 "In order to capture packets, WinPcap must be installed; see\n"
742 " http://www.winpcap.org/\n"
746 " http://www.mirrors.wiretapped.net/security/packet-capture/winpcap/\n"
750 " http://winpcap.cs.pu.edu.tw/\n"
752 "for a downloadable version of WinPcap and for instructions on how to install\n"
755 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
757 "Please check that \"%s\" is the proper interface.\n"
760 "Help can be found at:\n"
762 " http://wiki.wireshark.org/WinPcap\n"
763 " http://wiki.wireshark.org/CaptureSetup\n",
767 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
768 "Please check to make sure you have sufficient permissions, and that you have "
769 "the proper interface or pipe specified.%s", libpcap_warn);
773 /* Set the data link type on a pcap. */
775 set_pcap_linktype(pcap_t *pcap_h, int linktype,
776 #ifdef HAVE_PCAP_SET_DATALINK
781 char *errmsg, size_t errmsg_len,
782 char *secondary_errmsg, size_t secondary_errmsg_len)
784 char *set_linktype_err_str;
787 return TRUE; /* just use the default */
788 #ifdef HAVE_PCAP_SET_DATALINK
789 if (pcap_set_datalink(pcap_h, linktype) == 0)
790 return TRUE; /* no error */
791 set_linktype_err_str = pcap_geterr(pcap_h);
793 /* Let them set it to the type it is; reject any other request. */
794 if (get_pcap_linktype(pcap_h, name) == linktype)
795 return TRUE; /* no error */
796 set_linktype_err_str =
797 "That DLT isn't one of the DLTs supported by this device";
799 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
800 set_linktype_err_str);
802 * If the error isn't "XXX is not one of the DLTs supported by this device",
803 * tell the user to tell the Wireshark developers about it.
805 if (strstr(set_linktype_err_str, "is not one of the DLTs supported by this device") == NULL)
806 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
808 secondary_errmsg[0] = '\0';
813 compile_capture_filter(const char *iface, pcap_t *pcap_h,
814 struct bpf_program *fcode, const char *cfilter)
816 bpf_u_int32 netnum, netmask;
817 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
819 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
821 * Well, we can't get the netmask for this interface; it's used
822 * only for filters that check for broadcast IP addresses, so
823 * we just punt and use 0. It might be nice to warn the user,
824 * but that's a pain in a GUI application, as it'd involve popping
825 * up a message box, and it's not clear how often this would make
826 * a difference (only filters that check for IP broadcast addresses
830 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
835 * Sigh. Older versions of libpcap don't properly declare the
836 * third argument to pcap_compile() as a const pointer. Cast
839 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
844 #ifdef HAVE_BPF_IMAGE
846 show_filter_code(capture_options *capture_opts)
848 interface_options interface_opts;
850 gchar open_err_str[PCAP_ERRBUF_SIZE];
851 char errmsg[MSG_MAX_LENGTH+1];
852 char secondary_errmsg[MSG_MAX_LENGTH+1];
853 struct bpf_program fcode;
854 struct bpf_insn *insn;
858 for (j = 0; j < capture_opts->ifaces->len; j++) {
859 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
860 pcap_h = open_capture_device(&interface_opts, &open_err_str);
861 if (pcap_h == NULL) {
862 /* Open failed; get messages */
863 get_capture_device_open_failure_messages(open_err_str,
865 errmsg, sizeof errmsg,
867 sizeof secondary_errmsg);
868 /* And report them */
869 report_capture_error(errmsg, secondary_errmsg);
873 /* Set the link-layer type. */
874 if (!set_pcap_linktype(pcap_h, interface_opts.linktype, interface_opts.name,
875 errmsg, sizeof errmsg,
876 secondary_errmsg, sizeof secondary_errmsg)) {
878 report_capture_error(errmsg, secondary_errmsg);
882 /* OK, try to compile the capture filter. */
883 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
884 interface_opts.cfilter)) {
886 report_cfilter_error(capture_opts, j, errmsg);
891 /* Now print the filter code. */
892 insn = fcode.bf_insns;
894 for (i = 0; i < fcode.bf_len; insn++, i++)
895 printf("%s\n", bpf_image(insn, i));
897 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
898 /* to remove any suid privileges. */
899 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
900 /* (euid/egid have already previously been set to ruid/rgid. */
901 /* (See comment in main() for details) */
903 relinquish_special_privs_perm();
905 relinquish_all_capabilities();
908 /* Let our parent know we succeeded. */
909 pipe_write_block(2, SP_SUCCESS, NULL);
916 * capture_interface_list() is expected to do the right thing to get
917 * a list of interfaces.
919 * In most of the programs in the Wireshark suite, "the right thing"
920 * is to run dumpcap and ask it for the list, because dumpcap may
921 * be the only program in the suite with enough privileges to get
924 * In dumpcap itself, however, we obviously can't run dumpcap to
925 * ask for the list. Therefore, our capture_interface_list() should
926 * just call get_interface_list().
929 capture_interface_list(int *err, char **err_str)
931 return get_interface_list(err, err_str);
935 * Get the data-link type for a libpcap device.
936 * This works around AIX 5.x's non-standard and incompatible-with-the-
937 * rest-of-the-universe libpcap.
940 get_pcap_linktype(pcap_t *pch, const char *devname
948 const char *ifacename;
951 linktype = pcap_datalink(pch);
955 * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
956 * rather than DLT_ values for link-layer types; the ifType values
957 * for LAN devices are:
964 * and the ifType value for a loopback device is 24.
966 * The AIX names for LAN devices begin with:
973 * and the AIX names for loopback devices begin with "lo".
975 * (The difference between "Ethernet" and "802.3" is presumably
976 * whether packets have an Ethernet header, with a packet type,
977 * or an 802.3 header, with a packet length, followed by an 802.2
978 * header and possibly a SNAP header.)
980 * If the device name matches "linktype" interpreted as an ifType
981 * value, rather than as a DLT_ value, we will assume this is AIX's
982 * non-standard, incompatible libpcap, rather than a standard libpcap,
983 * and will map the link-layer type to the standard DLT_ value for
984 * that link-layer type, as that's what the rest of Wireshark expects.
986 * (This means the capture files won't be readable by a tcpdump
987 * linked with AIX's non-standard libpcap, but so it goes. They
988 * *will* be readable by standard versions of tcpdump, Wireshark,
991 * XXX - if we conclude we're using AIX libpcap, should we also
992 * set a flag to cause us to assume the time stamps are in
993 * seconds-and-nanoseconds form, and to convert them to
994 * seconds-and-microseconds form before processing them and
999 * Find the last component of the device name, which is the
1002 ifacename = strchr(devname, '/');
1003 if (ifacename == NULL)
1004 ifacename = devname;
1006 /* See if it matches any of the LAN device names. */
1007 if (strncmp(ifacename, "en", 2) == 0) {
1008 if (linktype == 6) {
1010 * That's the RFC 1573 value for Ethernet; map it to DLT_EN10MB.
1014 } else if (strncmp(ifacename, "et", 2) == 0) {
1015 if (linktype == 7) {
1017 * That's the RFC 1573 value for 802.3; map it to DLT_EN10MB.
1018 * (libpcap, tcpdump, Wireshark, etc. don't care if it's Ethernet
1023 } else if (strncmp(ifacename, "tr", 2) == 0) {
1024 if (linktype == 9) {
1026 * That's the RFC 1573 value for 802.5 (Token Ring); map it to
1027 * DLT_IEEE802, which is what's used for Token Ring.
1031 } else if (strncmp(ifacename, "fi", 2) == 0) {
1032 if (linktype == 15) {
1034 * That's the RFC 1573 value for FDDI; map it to DLT_FDDI.
1038 } else if (strncmp(ifacename, "lo", 2) == 0) {
1039 if (linktype == 24) {
1041 * That's the RFC 1573 value for "software loopback" devices; map it
1042 * to DLT_NULL, which is what's used for loopback devices on BSD.
1052 static data_link_info_t *
1053 create_data_link_info(int dlt)
1055 data_link_info_t *data_link_info;
1058 data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
1059 data_link_info->dlt = dlt;
1060 text = pcap_datalink_val_to_name(dlt);
1062 data_link_info->name = g_strdup(text);
1064 data_link_info->name = g_strdup_printf("DLT %d", dlt);
1065 text = pcap_datalink_val_to_description(dlt);
1067 data_link_info->description = g_strdup(text);
1069 data_link_info->description = NULL;
1070 return data_link_info;
1074 * Get the capabilities of a network device.
1076 static if_capabilities_t *
1077 get_if_capabilities(const char *devname, gboolean monitor_mode
1078 #ifndef HAVE_PCAP_CREATE
1083 if_capabilities_t *caps;
1084 char errbuf[PCAP_ERRBUF_SIZE];
1086 #ifdef HAVE_PCAP_CREATE
1090 #ifdef HAVE_PCAP_LIST_DATALINKS
1094 data_link_info_t *data_link_info;
1097 * Allocate the interface capabilities structure.
1099 caps = g_malloc(sizeof *caps);
1101 #ifdef HAVE_PCAP_OPEN
1102 pch = pcap_open(devname, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1103 caps->can_set_rfmon = FALSE;
1105 if (err_str != NULL)
1106 *err_str = g_strdup(errbuf);
1110 #elif defined(HAVE_PCAP_CREATE)
1111 pch = pcap_create(devname, errbuf);
1113 if (err_str != NULL)
1114 *err_str = g_strdup(errbuf);
1118 status = pcap_can_set_rfmon(pch);
1121 if (status == PCAP_ERROR)
1122 *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
1125 *err_str = g_strdup(pcap_statustostr(status));
1131 caps->can_set_rfmon = FALSE;
1132 else if (status == 1) {
1133 caps->can_set_rfmon = TRUE;
1135 pcap_set_rfmon(pch, 1);
1137 if (err_str != NULL) {
1138 *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
1146 status = pcap_activate(pch);
1148 /* Error. We ignore warnings (status > 0). */
1149 if (err_str != NULL) {
1150 if (status == PCAP_ERROR)
1151 *err_str = g_strdup_printf("pcap_activate() failed: %s",
1154 *err_str = g_strdup(pcap_statustostr(status));
1161 pch = pcap_open_live(devname, MIN_PACKET_SIZE, 0, 0, errbuf);
1162 caps->can_set_rfmon = FALSE;
1164 if (err_str != NULL)
1165 *err_str = g_strdup(errbuf);
1170 deflt = get_pcap_linktype(pch, devname);
1171 #ifdef HAVE_PCAP_LIST_DATALINKS
1172 nlt = pcap_list_datalinks(pch, &linktypes);
1173 if (nlt == 0 || linktypes == NULL) {
1175 if (err_str != NULL)
1176 *err_str = NULL; /* an empty list doesn't mean an error */
1179 caps->data_link_types = NULL;
1180 for (i = 0; i < nlt; i++) {
1181 data_link_info = create_data_link_info(linktypes[i]);
1184 * XXX - for 802.11, make the most detailed 802.11
1185 * version the default, rather than the one the
1186 * device has as the default?
1188 if (linktypes[i] == deflt)
1189 caps->data_link_types = g_list_prepend(caps->data_link_types,
1192 caps->data_link_types = g_list_append(caps->data_link_types,
1195 #ifdef HAVE_PCAP_FREE_DATALINKS
1196 pcap_free_datalinks(linktypes);
1199 * In Windows, there's no guarantee that if you have a library
1200 * built with one version of the MSVC++ run-time library, and
1201 * it returns a pointer to allocated data, you can free that
1202 * data from a program linked with another version of the
1203 * MSVC++ run-time library.
1205 * This is not an issue on UN*X.
1207 * See the mail threads starting at
1209 * http://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
1213 * http://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
1216 #define xx_free free /* hack so checkAPIs doesn't complain */
1219 #endif /* HAVE_PCAP_FREE_DATALINKS */
1220 #else /* HAVE_PCAP_LIST_DATALINKS */
1222 data_link_info = create_data_link_info(deflt);
1223 caps->data_link_types = g_list_append(caps->data_link_types,
1225 #endif /* HAVE_PCAP_LIST_DATALINKS */
1229 if (err_str != NULL)
1234 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
1236 print_machine_readable_interfaces(GList *if_list)
1243 char addr_str[ADDRSTRLEN];
1245 if (capture_child) {
1246 /* Let our parent know we succeeded. */
1247 pipe_write_block(2, SP_SUCCESS, NULL);
1250 i = 1; /* Interface id number */
1251 for (if_entry = g_list_first(if_list); if_entry != NULL;
1252 if_entry = g_list_next(if_entry)) {
1253 if_info = (if_info_t *)if_entry->data;
1254 printf("%d. %s", i++, if_info->name);
1257 * Print the contents of the if_entry struct in a parseable format.
1258 * Each if_entry element is tab-separated. Addresses are comma-
1261 /* XXX - Make sure our description doesn't contain a tab */
1262 if (if_info->description != NULL)
1263 printf("\t%s\t", if_info->description);
1267 for(addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
1268 addr = g_slist_next(addr)) {
1269 if (addr != g_slist_nth(if_info->addrs, 0))
1272 if_addr = (if_addr_t *)addr->data;
1273 switch(if_addr->ifat_type) {
1275 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
1277 printf("%s", addr_str);
1279 printf("<unknown IPv4>");
1283 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
1284 addr_str, ADDRSTRLEN)) {
1285 printf("%s", addr_str);
1287 printf("<unknown IPv6>");
1291 printf("<type unknown %u>", if_addr->ifat_type);
1295 if (if_info->loopback)
1296 printf("\tloopback");
1298 printf("\tnetwork");
1305 * If you change the machine-readable output format of this function,
1306 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
1309 print_machine_readable_if_capabilities(if_capabilities_t *caps)
1312 data_link_info_t *data_link_info;
1313 const gchar *desc_str;
1315 if (capture_child) {
1316 /* Let our parent know we succeeded. */
1317 pipe_write_block(2, SP_SUCCESS, NULL);
1320 if (caps->can_set_rfmon)
1324 for (lt_entry = caps->data_link_types; lt_entry != NULL;
1325 lt_entry = g_list_next(lt_entry)) {
1326 data_link_info = (data_link_info_t *)lt_entry->data;
1327 if (data_link_info->description != NULL)
1328 desc_str = data_link_info->description;
1330 desc_str = "(not supported)";
1331 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
1341 /* Print the number of packets captured for each interface until we're killed. */
1343 print_statistics_loop(gboolean machine_readable)
1345 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1351 char errbuf[PCAP_ERRBUF_SIZE];
1352 struct pcap_stat ps;
1354 if_list = get_interface_list(&err, &err_str);
1355 if (if_list == NULL) {
1357 case CANT_GET_INTERFACE_LIST:
1358 case DONT_HAVE_PCAP:
1359 cmdarg_err("%s", err_str);
1363 case NO_INTERFACES_FOUND:
1364 cmdarg_err("There are no interfaces on which a capture can be done");
1370 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1371 if_info = (if_info_t *)if_entry->data;
1372 #ifdef HAVE_PCAP_OPEN
1373 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1375 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1379 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
1380 if_stat->name = g_strdup(if_info->name);
1382 stat_list = g_list_append(stat_list, if_stat);
1387 cmdarg_err("There are no interfaces on which a capture can be done");
1391 if (capture_child) {
1392 /* Let our parent know we succeeded. */
1393 pipe_write_block(2, SP_SUCCESS, NULL);
1396 if (!machine_readable) {
1397 printf("%-15s %10s %10s\n", "Interface", "Received",
1401 global_ld.go = TRUE;
1402 while (global_ld.go) {
1403 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1404 if_stat = (if_stat_t *)stat_entry->data;
1405 pcap_stats(if_stat->pch, &ps);
1407 if (!machine_readable) {
1408 printf("%-15s %10u %10u\n", if_stat->name,
1409 ps.ps_recv, ps.ps_drop);
1411 printf("%s\t%u\t%u\n", if_stat->name,
1412 ps.ps_recv, ps.ps_drop);
1423 /* XXX - Not reached. Should we look for 'q' in stdin? */
1424 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1425 if_stat = (if_stat_t *)stat_entry->data;
1426 pcap_close(if_stat->pch);
1427 g_free(if_stat->name);
1430 g_list_free(stat_list);
1431 free_interface_list(if_list);
1439 capture_cleanup_handler(DWORD dwCtrlType)
1441 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1442 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1443 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1444 like SIGTERM at least when the machine's shutting down.
1446 For now, if we're running as a command rather than a capture child,
1447 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1448 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1449 in that way on UN*X.
1451 If we're not running as a capture child, we might be running as
1452 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1453 user logs out. (XXX - can we explicitly check whether we're
1454 running as a service?) */
1456 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1457 "Console: Control signal");
1458 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1459 "Console: Control signal, CtrlType: %u", dwCtrlType);
1461 /* Keep capture running if we're a service and a user logs off */
1462 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1463 capture_loop_stop();
1471 capture_cleanup_handler(int signum _U_)
1473 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1474 SIGTERM. We assume that if the user wanted it to keep running
1475 after they logged out, they'd have nohupped it. */
1477 /* Note: don't call g_log() in the signal handler: if we happened to be in
1478 * g_log() in process context when the signal came in, g_log will detect
1479 * the "recursion" and abort.
1482 capture_loop_stop();
1488 report_capture_count(gboolean reportit)
1490 /* Don't print this if we're a capture child. */
1491 if (!capture_child && reportit) {
1492 fprintf(stderr, "\rPackets captured: %u\n", global_ld.packet_count);
1493 /* stderr could be line buffered */
1501 report_counts_for_siginfo(void)
1503 report_capture_count(quiet);
1504 infoprint = FALSE; /* we just reported it */
1508 report_counts_siginfo(int signum _U_)
1510 int sav_errno = errno;
1512 /* If we've been told to delay printing, just set a flag asking
1513 that we print counts (if we're supposed to), otherwise print
1514 the count of packets captured (if we're supposed to). */
1518 report_counts_for_siginfo();
1521 #endif /* SIGINFO */
1524 exit_main(int status)
1527 /* Shutdown windows sockets */
1530 /* can be helpful for debugging */
1531 #ifdef DEBUG_DUMPCAP
1532 printf("Press any key\n");
1543 * If we were linked with libcap (not libpcap), make sure we have
1544 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1545 * (See comment in main() for details)
1548 relinquish_privs_except_capture(void)
1550 /* If 'started_with_special_privs' (ie: suid) then enable for
1551 * ourself the NET_ADMIN and NET_RAW capabilities and then
1552 * drop our suid privileges.
1554 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1555 * stuff we don't need (and shouldn't have).
1556 * CAP_NET_RAW: Packet capture (raw sockets).
1559 if (started_with_special_privs()) {
1560 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1561 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1563 cap_t caps = cap_init(); /* all capabilities initialized to off */
1565 print_caps("Pre drop, pre set");
1567 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1568 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1571 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1572 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1574 if (cap_set_proc(caps)) {
1575 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1577 print_caps("Pre drop, post set");
1579 relinquish_special_privs_perm();
1581 print_caps("Post drop, pre set");
1582 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1583 if (cap_set_proc(caps)) {
1584 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1586 print_caps("Post drop, post set");
1592 #endif /* HAVE_LIBCAP */
1594 /* Take care of byte order in the libpcap headers read from pipes.
1595 * (function taken from wiretap/libpcap.c) */
1597 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1600 /* Byte-swap the record header fields. */
1601 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
1602 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
1603 rechdr->incl_len = BSWAP32(rechdr->incl_len);
1604 rechdr->orig_len = BSWAP32(rechdr->orig_len);
1607 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1608 swapped, in order to match the BPF header layout.
1610 Unfortunately, some files were, according to a comment in the "libpcap"
1611 source, written with version 2.3 in their headers but without the
1612 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1613 would make no sense - we assume that we need to swap them. */
1614 if (hdr->version_major == 2 &&
1615 (hdr->version_minor < 3 ||
1616 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1619 temp = rechdr->orig_len;
1620 rechdr->orig_len = rechdr->incl_len;
1621 rechdr->incl_len = temp;
1627 * Thread function that reads from a pipe and pushes the data
1628 * to the main application thread.
1631 * XXX Right now we use async queues for basic signaling. The main thread
1632 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1633 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1634 * Iff the read is successful cap_pipe_read pushes an item onto
1635 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1636 * the queues themselves (yet).
1638 * We might want to move some of the cap_pipe_dispatch logic here so that
1639 * we can let cap_pipe_read run independently, queuing up multiple reads
1640 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1642 static void *cap_pipe_read(void *arg)
1644 pcap_options *pcap_opts;
1653 pcap_opts = (pcap_options *)arg;
1654 while (pcap_opts->cap_pipe_err == PIPOK) {
1655 g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1656 g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1658 while (bytes_read < (int) pcap_opts->cap_pipe_bytes_to_read) {
1660 /* If we try to use read() on a named pipe on Windows with partial
1661 * data it appears to return EOF.
1663 res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1664 pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1669 last_err = GetLastError();
1670 if (last_err == ERROR_MORE_DATA) {
1672 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1673 pcap_opts->cap_pipe_err = PIPEOF;
1677 pcap_opts->cap_pipe_err = PIPERR;
1680 } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1681 pcap_opts->cap_pipe_err = PIPEOF;
1686 b = read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1687 pcap_opts->cap_pipe_bytes_to_read - bytes_read);
1690 pcap_opts->cap_pipe_err = PIPEOF;
1694 pcap_opts->cap_pipe_err = PIPERR;
1703 pcap_opts->cap_pipe_bytes_read = bytes_read;
1704 if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1705 g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1707 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1713 #if !defined(_WIN32) || defined(MUST_DO_SELECT)
1714 /* Provide select() functionality for a single file descriptor
1715 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1717 * Returns the same values as select.
1720 cap_pipe_select(int pipe_fd)
1723 struct timeval timeout;
1726 FD_SET(pipe_fd, &rfds);
1728 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1729 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1731 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1736 /* Mimic pcap_open_live() for pipe captures
1738 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1739 * open it, and read the header.
1741 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1742 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1744 cap_pipe_open_live(char *pipename,
1745 pcap_options *pcap_opts,
1746 struct pcap_hdr *hdr,
1747 char *errmsg, int errmsgl)
1750 ws_statb64 pipe_stat;
1751 struct sockaddr_un sa;
1762 unsigned int bytes_read;
1767 pcap_opts->cap_pipe_fd = -1;
1769 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
1771 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1774 * XXX - this blocks until a pcap per-file header has been written to
1775 * the pipe, so it could block indefinitely.
1777 if (strcmp(pipename, "-") == 0) {
1779 fd = 0; /* read from stdin */
1781 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1785 if (ws_stat64(pipename, &pipe_stat) < 0) {
1786 if (errno == ENOENT || errno == ENOTDIR)
1787 pcap_opts->cap_pipe_err = PIPNEXIST;
1789 g_snprintf(errmsg, errmsgl,
1790 "The capture session could not be initiated "
1791 "due to error getting information on pipe/socket: %s", g_strerror(errno));
1792 pcap_opts->cap_pipe_err = PIPERR;
1796 if (S_ISFIFO(pipe_stat.st_mode)) {
1797 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1799 g_snprintf(errmsg, errmsgl,
1800 "The capture session could not be initiated "
1801 "due to error on pipe open: %s", g_strerror(errno));
1802 pcap_opts->cap_pipe_err = PIPERR;
1805 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1806 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1808 g_snprintf(errmsg, errmsgl,
1809 "The capture session could not be initiated "
1810 "due to error on socket create: %s", g_strerror(errno));
1811 pcap_opts->cap_pipe_err = PIPERR;
1814 sa.sun_family = AF_UNIX;
1816 * The Single UNIX Specification says:
1818 * The size of sun_path has intentionally been left undefined.
1819 * This is because different implementations use different sizes.
1820 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1821 * of 104. Since most implementations originate from BSD versions,
1822 * the size is typically in the range 92 to 108.
1824 * Applications should not assume a particular length for sun_path
1825 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1829 * The <sys/un.h> header shall define the sockaddr_un structure,
1830 * which shall include at least the following members:
1832 * sa_family_t sun_family Address family.
1833 * char sun_path[] Socket pathname.
1835 * so we assume that it's an array, with a specified size,
1836 * and that the size reflects the maximum path length.
1838 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1839 /* Path name too long */
1840 g_snprintf(errmsg, errmsgl,
1841 "The capture session coud not be initiated "
1842 "due to error on socket connect: Path name too long");
1843 pcap_opts->cap_pipe_err = PIPERR;
1846 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1848 g_snprintf(errmsg, errmsgl,
1849 "The capture session coud not be initiated "
1850 "due to error on socket connect: %s", g_strerror(errno));
1851 pcap_opts->cap_pipe_err = PIPERR;
1855 if (S_ISCHR(pipe_stat.st_mode)) {
1857 * Assume the user specified an interface on a system where
1858 * interfaces are in /dev. Pretend we haven't seen it.
1860 pcap_opts->cap_pipe_err = PIPNEXIST;
1863 g_snprintf(errmsg, errmsgl,
1864 "The capture session could not be initiated because\n"
1865 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
1866 pcap_opts->cap_pipe_err = PIPERR;
1871 #define PIPE_STR "\\pipe\\"
1872 /* Under Windows, named pipes _must_ have the form
1873 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1875 pncopy = g_strdup(pipename);
1876 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1877 pos = strchr(pncopy + 3, '\\');
1878 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1885 g_snprintf(errmsg, errmsgl,
1886 "The capture session could not be initiated because\n"
1887 "\"%s\" is neither an interface nor a pipe", pipename);
1888 pcap_opts->cap_pipe_err = PIPNEXIST;
1892 /* Wait for the pipe to appear */
1894 pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1895 OPEN_EXISTING, 0, NULL);
1897 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
1900 if (GetLastError() != ERROR_PIPE_BUSY) {
1901 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1902 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1903 g_snprintf(errmsg, errmsgl,
1904 "The capture session on \"%s\" could not be started "
1905 "due to error on pipe open: %s (error %d)",
1906 pipename, utf_16to8(err_str), GetLastError());
1908 pcap_opts->cap_pipe_err = PIPERR;
1912 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1913 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1914 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1915 g_snprintf(errmsg, errmsgl,
1916 "The capture session on \"%s\" timed out during "
1917 "pipe open: %s (error %d)",
1918 pipename, utf_16to8(err_str), GetLastError());
1920 pcap_opts->cap_pipe_err = PIPERR;
1927 pcap_opts->from_cap_pipe = TRUE;
1930 /* read the pcap header */
1932 while (bytes_read < sizeof magic) {
1933 sel_ret = cap_pipe_select(fd);
1935 g_snprintf(errmsg, errmsgl,
1936 "Unexpected error from select: %s", g_strerror(errno));
1938 } else if (sel_ret > 0) {
1939 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
1942 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1944 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1952 g_thread_create(&cap_pipe_read, pcap_opts, FALSE, NULL);
1954 pcap_opts->cap_pipe_buf = (char *) &magic;
1955 pcap_opts->cap_pipe_bytes_read = 0;
1956 pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
1957 /* We don't have to worry about cap_pipe_read_mtx here */
1958 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
1959 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
1960 if (pcap_opts->cap_pipe_bytes_read <= 0) {
1961 if (pcap_opts->cap_pipe_bytes_read == 0)
1962 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1964 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1973 /* Host that wrote it has our byte order, and was running
1974 a program using either standard or ss990417 libpcap. */
1975 pcap_opts->cap_pipe_byte_swapped = FALSE;
1976 pcap_opts->cap_pipe_modified = FALSE;
1978 case PCAP_MODIFIED_MAGIC:
1979 /* Host that wrote it has our byte order, but was running
1980 a program using either ss990915 or ss991029 libpcap. */
1981 pcap_opts->cap_pipe_byte_swapped = FALSE;
1982 pcap_opts->cap_pipe_modified = TRUE;
1984 case PCAP_SWAPPED_MAGIC:
1985 /* Host that wrote it has a byte order opposite to ours,
1986 and was running a program using either standard or
1987 ss990417 libpcap. */
1988 pcap_opts->cap_pipe_byte_swapped = TRUE;
1989 pcap_opts->cap_pipe_modified = FALSE;
1991 case PCAP_SWAPPED_MODIFIED_MAGIC:
1992 /* Host that wrote it out has a byte order opposite to
1993 ours, and was running a program using either ss990915
1994 or ss991029 libpcap. */
1995 pcap_opts->cap_pipe_byte_swapped = TRUE;
1996 pcap_opts->cap_pipe_modified = TRUE;
1998 /* XXX - Add support for PCAP_NSEC_MAGIC and PCAP_SWAPPED_NSEC_MAGIC? */
2000 /* Not a "libpcap" type we know about. */
2001 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
2006 /* Read the rest of the header */
2008 while (bytes_read < sizeof(struct pcap_hdr)) {
2009 sel_ret = cap_pipe_select(fd);
2011 g_snprintf(errmsg, errmsgl,
2012 "Unexpected error from select: %s", g_strerror(errno));
2014 } else if (sel_ret > 0) {
2015 b = read(fd, ((char *)hdr)+bytes_read,
2016 sizeof(struct pcap_hdr) - bytes_read);
2019 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2021 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
2029 pcap_opts->cap_pipe_buf = (char *) hdr;
2030 pcap_opts->cap_pipe_bytes_read = 0;
2031 pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
2032 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2033 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2034 if (pcap_opts->cap_pipe_bytes_read <= 0) {
2035 if (pcap_opts->cap_pipe_bytes_read == 0)
2036 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2038 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
2044 if (pcap_opts->cap_pipe_byte_swapped) {
2045 /* Byte-swap the header fields about which we care. */
2046 hdr->version_major = BSWAP16(hdr->version_major);
2047 hdr->version_minor = BSWAP16(hdr->version_minor);
2048 hdr->snaplen = BSWAP32(hdr->snaplen);
2049 hdr->network = BSWAP32(hdr->network);
2051 pcap_opts->linktype = hdr->network;
2053 if (hdr->version_major < 2) {
2054 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
2058 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2059 pcap_opts->cap_pipe_err = PIPOK;
2061 pcap_opts->cap_pipe_fd = fd;
2066 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
2067 pcap_opts->cap_pipe_err = PIPERR;
2070 pcap_opts->cap_pipe_fd = -1;
2077 /* We read one record from the pipe, take care of byte order in the record
2078 * header, write the record to the capture file, and update capture statistics. */
2080 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
2082 struct pcap_pkthdr phdr;
2083 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2086 #if !GLIB_CHECK_VERSION(2,31,18)
2097 #ifdef LOG_CAPTURE_VERBOSE
2098 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
2101 switch (pcap_opts->cap_pipe_state) {
2103 case STATE_EXPECT_REC_HDR:
2105 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2108 pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
2109 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
2110 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2111 pcap_opts->cap_pipe_bytes_read = 0;
2114 pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
2115 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2116 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2121 case STATE_READ_REC_HDR:
2123 b = read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
2124 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read);
2127 result = PD_PIPE_EOF;
2129 result = PD_PIPE_ERR;
2132 pcap_opts->cap_pipe_bytes_read += b;
2134 #if GLIB_CHECK_VERSION(2,31,18)
2135 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2137 g_get_current_time(&wait_time);
2138 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2139 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2141 if (pcap_opts->cap_pipe_err == PIPEOF) {
2142 result = PD_PIPE_EOF;
2144 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2145 result = PD_PIPE_ERR;
2152 if ((pcap_opts->cap_pipe_bytes_read) < pcap_opts->cap_pipe_bytes_to_read)
2154 result = PD_REC_HDR_READ;
2157 case STATE_EXPECT_DATA:
2159 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2162 pcap_opts->cap_pipe_state = STATE_READ_DATA;
2163 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2164 pcap_opts->cap_pipe_bytes_read = 0;
2167 pcap_opts->cap_pipe_buf = (char *) data;
2168 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2169 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2174 case STATE_READ_DATA:
2176 b = read(pcap_opts->cap_pipe_fd, data+pcap_opts->cap_pipe_bytes_read,
2177 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read);
2180 result = PD_PIPE_EOF;
2182 result = PD_PIPE_ERR;
2185 pcap_opts->cap_pipe_bytes_read += b;
2187 #if GLIB_CHECK_VERSION(2,31,18)
2188 q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2190 g_get_current_time(&wait_time);
2191 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2192 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2194 if (pcap_opts->cap_pipe_err == PIPEOF) {
2195 result = PD_PIPE_EOF;
2197 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2198 result = PD_PIPE_ERR;
2205 if ((pcap_opts->cap_pipe_bytes_read) < pcap_opts->cap_pipe_bytes_to_read)
2207 result = PD_DATA_READ;
2211 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2214 } /* switch (pcap_opts->cap_pipe_state) */
2217 * We've now read as much data as we were expecting, so process it.
2221 case PD_REC_HDR_READ:
2222 /* We've read the header. Take care of byte order. */
2223 cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
2224 &pcap_opts->cap_pipe_rechdr.hdr);
2225 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2226 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2227 ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
2231 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2232 pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2235 /* no data to read? fall through */
2238 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2239 phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2240 phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2241 phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2242 phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2245 capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2247 capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2249 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2253 pcap_opts->cap_pipe_err = PIPEOF;
2258 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
2259 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2260 g_snprintf(errmsg, errmsgl,
2261 "Error reading from pipe: %s (error %d)",
2262 utf_16to8(err_str), GetLastError());
2265 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2273 pcap_opts->cap_pipe_err = PIPERR;
2274 /* Return here rather than inside the switch to prevent GCC warning */
2279 /** Open the capture input file (pcap or capture pipe).
2280 * Returns TRUE if it succeeds, FALSE otherwise. */
2282 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2283 char *errmsg, size_t errmsg_len,
2284 char *secondary_errmsg, size_t secondary_errmsg_len)
2286 gchar open_err_str[PCAP_ERRBUF_SIZE];
2287 gchar *sync_msg_str;
2288 interface_options interface_opts;
2289 pcap_options *pcap_opts;
2293 gchar *sync_secondary_msg_str;
2294 WORD wVersionRequested;
2298 /* XXX - opening Winsock on tshark? */
2300 /* Initialize Windows Socket if we are in a WIN32 OS
2301 This needs to be done before querying the interface for network/netmask */
2303 /* XXX - do we really require 1.1 or earlier?
2304 Are there any versions that support only 2.0 or higher? */
2305 wVersionRequested = MAKEWORD(1, 1);
2306 err = WSAStartup(wVersionRequested, &wsaData);
2310 case WSASYSNOTREADY:
2311 g_snprintf(errmsg, (gulong) errmsg_len,
2312 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2315 case WSAVERNOTSUPPORTED:
2316 g_snprintf(errmsg, (gulong) errmsg_len,
2317 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2318 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2321 case WSAEINPROGRESS:
2322 g_snprintf(errmsg, (gulong) errmsg_len,
2323 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2327 g_snprintf(errmsg, (gulong) errmsg_len,
2328 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2332 g_snprintf(errmsg, (gulong) errmsg_len,
2333 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2337 g_snprintf(errmsg, (gulong) errmsg_len,
2338 "Couldn't initialize Windows Sockets: error %d", err);
2341 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2345 if ((use_threads == FALSE) &&
2346 (capture_opts->ifaces->len > 1)) {
2347 g_snprintf(errmsg, (gulong) errmsg_len,
2348 "Using threads is required for capturing on multiple interfaces!");
2352 for (i = 0; i < capture_opts->ifaces->len; i++) {
2353 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2354 pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2355 if (pcap_opts == NULL) {
2356 g_snprintf(errmsg, (gulong) errmsg_len,
2357 "Could not allocate memory.");
2360 pcap_opts->received = 0;
2361 pcap_opts->dropped = 0;
2362 pcap_opts->pcap_h = NULL;
2363 #ifdef MUST_DO_SELECT
2364 pcap_opts->pcap_fd = -1;
2366 pcap_opts->pcap_err = FALSE;
2367 pcap_opts->interface_id = i;
2368 pcap_opts->tid = NULL;
2369 pcap_opts->snaplen = 0;
2370 pcap_opts->linktype = -1;
2371 pcap_opts->from_cap_pipe = FALSE;
2372 memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2373 memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2375 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2377 pcap_opts->cap_pipe_fd = -1;
2379 pcap_opts->cap_pipe_modified = FALSE;
2380 pcap_opts->cap_pipe_byte_swapped = FALSE;
2382 pcap_opts->cap_pipe_buf = NULL;
2384 pcap_opts->cap_pipe_bytes_to_read = 0;
2385 pcap_opts->cap_pipe_bytes_read = 0;
2386 pcap_opts->cap_pipe_state = 0;
2387 pcap_opts->cap_pipe_err = PIPOK;
2389 #if GLIB_CHECK_VERSION(2,31,0)
2390 pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2391 g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2393 pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2395 pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2396 pcap_opts->cap_pipe_done_q = g_async_queue_new();
2398 g_array_append_val(ld->pcaps, pcap_opts);
2400 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2401 pcap_opts->pcap_h = open_capture_device(&interface_opts, &open_err_str);
2403 if (pcap_opts->pcap_h != NULL) {
2404 /* we've opened "iface" as a network device */
2406 /* try to set the capture buffer size */
2407 if (interface_opts.buffer_size > 1 &&
2408 pcap_setbuff(pcap_opts->pcap_h, interface_opts.buffer_size * 1024 * 1024) != 0) {
2409 sync_secondary_msg_str = g_strdup_printf(
2410 "The capture buffer size of %dMB seems to be too high for your machine,\n"
2411 "the default of 1MB will be used.\n"
2413 "Nonetheless, the capture is started.\n",
2414 interface_opts.buffer_size);
2415 report_capture_error("Couldn't set the capture buffer size!",
2416 sync_secondary_msg_str);
2417 g_free(sync_secondary_msg_str);
2421 #if defined(HAVE_PCAP_SETSAMPLING)
2422 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2423 struct pcap_samp *samp;
2425 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2426 switch (interface_opts.sampling_method) {
2427 case CAPTURE_SAMP_BY_COUNT:
2428 samp->method = PCAP_SAMP_1_EVERY_N;
2431 case CAPTURE_SAMP_BY_TIMER:
2432 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2436 sync_msg_str = g_strdup_printf(
2437 "Unknown sampling method %d specified,\n"
2438 "continue without packet sampling",
2439 interface_opts.sampling_method);
2440 report_capture_error("Couldn't set the capture "
2441 "sampling", sync_msg_str);
2442 g_free(sync_msg_str);
2444 samp->value = interface_opts.sampling_param;
2446 report_capture_error("Couldn't set the capture sampling",
2447 "Cannot get packet sampling data structure");
2452 /* setting the data link type only works on real interfaces */
2453 if (!set_pcap_linktype(pcap_opts->pcap_h, interface_opts.linktype, interface_opts.name,
2455 secondary_errmsg, secondary_errmsg_len)) {
2458 pcap_opts->linktype = get_pcap_linktype(pcap_opts->pcap_h, interface_opts.name);
2460 /* We couldn't open "iface" as a network device. */
2461 /* Try to open it as a pipe */
2462 cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2465 if (pcap_opts->cap_pipe_fd == -1) {
2467 if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2469 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2470 /* Pipe doesn't exist, so output message for interface */
2471 get_capture_device_open_failure_messages(open_err_str,
2472 interface_opts.name,
2476 secondary_errmsg_len);
2479 * Else pipe (or file) does exist and cap_pipe_open_live() has
2484 /* cap_pipe_open_live() succeeded; don't want
2485 error message from pcap_open_live() */
2486 open_err_str[0] = '\0';
2490 /* XXX - will this work for tshark? */
2491 #ifdef MUST_DO_SELECT
2492 if (!pcap_opts->from_cap_pipe) {
2493 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2494 pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2496 pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2501 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2502 returned a warning; print it, but keep capturing. */
2503 if (open_err_str[0] != '\0') {
2504 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2505 report_capture_error(sync_msg_str, "");
2506 g_free(sync_msg_str);
2508 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2509 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2512 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2513 /* to remove any suid privileges. */
2514 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2515 /* (euid/egid have already previously been set to ruid/rgid. */
2516 /* (See comment in main() for details) */
2518 relinquish_special_privs_perm();
2520 relinquish_all_capabilities();
2525 /* close the capture input file (pcap or capture pipe) */
2526 static void capture_loop_close_input(loop_data *ld)
2529 pcap_options *pcap_opts;
2531 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2533 for (i = 0; i < ld->pcaps->len; i++) {
2534 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2535 /* if open, close the capture pipe "input file" */
2537 if (pcap_opts->cap_pipe_fd >= 0) {
2538 g_assert(pcap_opts->from_cap_pipe);
2539 ws_close(pcap_opts->cap_pipe_fd);
2540 pcap_opts->cap_pipe_fd = -1;
2543 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2544 CloseHandle(pcap_opts->cap_pipe_h);
2545 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2548 /* if open, close the pcap "input file" */
2549 if (pcap_opts->pcap_h != NULL) {
2550 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2551 pcap_close(pcap_opts->pcap_h);
2552 pcap_opts->pcap_h = NULL;
2559 /* Shut down windows sockets */
2565 /* init the capture filter */
2566 static initfilter_status_t
2567 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2568 const gchar * name, const gchar * cfilter)
2570 struct bpf_program fcode;
2572 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2574 /* capture filters only work on real interfaces */
2575 if (cfilter && !from_cap_pipe) {
2576 /* A capture filter was specified; set it up. */
2577 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2578 /* Treat this specially - our caller might try to compile this
2579 as a display filter and, if that succeeds, warn the user that
2580 the display and capture filter syntaxes are different. */
2581 return INITFILTER_BAD_FILTER;
2583 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2584 #ifdef HAVE_PCAP_FREECODE
2585 pcap_freecode(&fcode);
2587 return INITFILTER_OTHER_ERROR;
2589 #ifdef HAVE_PCAP_FREECODE
2590 pcap_freecode(&fcode);
2594 return INITFILTER_NO_ERROR;
2598 /* set up to write to the already-opened capture output file/files */
2600 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2604 pcap_options *pcap_opts;
2605 interface_options interface_opts;
2606 gboolean successful;
2608 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2610 if ((capture_opts->use_pcapng == FALSE) &&
2611 (capture_opts->ifaces->len > 1)) {
2612 g_snprintf(errmsg, errmsg_len,
2613 "Using PCAPNG is required for capturing on multiple interfaces! Use the -n option.");
2617 /* Set up to write to the capture file. */
2618 if (capture_opts->multi_files_on) {
2619 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2621 ld->pdh = libpcap_fdopen(ld->save_file_fd, &err);
2624 if (capture_opts->use_pcapng) {
2626 GString *os_info_str;
2628 os_info_str = g_string_new("");
2629 get_os_version_info(os_info_str);
2631 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2632 successful = libpcap_write_session_header_block(ld->pdh,
2635 os_info_str->str, /* OS*/
2637 -1, /* section_length */
2641 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2642 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2643 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2644 if (pcap_opts->from_cap_pipe) {
2645 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2647 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2649 successful = libpcap_write_interface_description_block(global_ld.pdh,
2650 NULL, /* OPT_COMMENT 1 */
2651 interface_opts.name, /* IDB_NAME 2 */
2652 NULL, /* IDB_DESCRIPTION 3 */
2653 interface_opts.cfilter?interface_opts.cfilter:"", /* IDB_FILTER 11 */
2654 os_info_str->str, /* IDB_OS 12 */
2655 pcap_opts->linktype,
2657 &(global_ld.bytes_written),
2658 0, /* IDB_IF_SPEED 8 */
2659 6, /* IDB_TSRESOL 9 */
2663 g_string_free(os_info_str, TRUE);
2666 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
2667 if (pcap_opts->from_cap_pipe) {
2668 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2670 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2672 successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
2673 &ld->bytes_written, &err);
2681 if (ld->pdh == NULL) {
2682 /* We couldn't set up to write to the capture file. */
2683 /* XXX - use cf_open_error_message from tshark instead? */
2688 g_snprintf(errmsg, errmsg_len,
2689 "The file to which the capture would be"
2690 " saved (\"%s\") could not be opened: Error %d.",
2691 capture_opts->save_file, err);
2693 g_snprintf(errmsg, errmsg_len,
2694 "The file to which the capture would be"
2695 " saved (\"%s\") could not be opened: %s.",
2696 capture_opts->save_file, g_strerror(err));
2708 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2712 pcap_options *pcap_opts;
2713 guint64 end_time = create_timestamp();
2715 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2717 if (capture_opts->multi_files_on) {
2718 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2720 if (capture_opts->use_pcapng) {
2721 for (i = 0; i < global_ld.pcaps->len; i++) {
2722 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2723 if (!pcap_opts->from_cap_pipe) {
2724 libpcap_write_interface_statistics_block(ld->pdh,
2728 "Counters provided by libpcap",
2735 return libpcap_dump_close(ld->pdh, err_close);
2739 /* dispatch incoming packets (pcap or capture pipe)
2741 * Waits for incoming packets to be available, and calls pcap_dispatch()
2742 * to cause them to be processed.
2744 * Returns the number of packets which were processed.
2746 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2747 * packet-batching behaviour does not cause packets to get held back
2751 capture_loop_dispatch(loop_data *ld,
2752 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
2755 gint packet_count_before;
2756 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
2761 packet_count_before = ld->packet_count;
2762 if (pcap_opts->from_cap_pipe) {
2763 /* dispatch from capture pipe */
2764 #ifdef LOG_CAPTURE_VERBOSE
2765 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2768 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
2770 if (sel_ret < 0 && errno != EINTR) {
2771 g_snprintf(errmsg, errmsg_len,
2772 "Unexpected error from select: %s", g_strerror(errno));
2773 report_capture_error(errmsg, please_report);
2778 * "select()" says we can read from the pipe without blocking
2781 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
2791 /* dispatch from pcap */
2792 #ifdef MUST_DO_SELECT
2794 * If we have "pcap_get_selectable_fd()", we use it to get the
2795 * descriptor on which to select; if that's -1, it means there
2796 * is no descriptor on which you can do a "select()" (perhaps
2797 * because you're capturing on a special device, and that device's
2798 * driver unfortunately doesn't support "select()", in which case
2799 * we don't do the select - which means it might not be possible
2800 * to stop a capture until a packet arrives. If that's unacceptable,
2801 * plead with whoever supplies the software for that device to add
2802 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2803 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2804 * later, so it can use pcap_breakloop().
2806 #ifdef LOG_CAPTURE_VERBOSE
2807 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2809 if (pcap_opts->pcap_fd != -1) {
2810 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
2813 * "select()" says we can read from it without blocking; go for
2816 * We don't have pcap_breakloop(), so we only process one packet
2817 * per pcap_dispatch() call, to allow a signal to stop the
2818 * processing immediately, rather than processing all packets
2819 * in a batch before quitting.
2822 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2824 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2828 /* Error, rather than pcap_breakloop(). */
2829 pcap_opts->pcap_err = TRUE;
2831 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2834 if (sel_ret < 0 && errno != EINTR) {
2835 g_snprintf(errmsg, errmsg_len,
2836 "Unexpected error from select: %s", g_strerror(errno));
2837 report_capture_error(errmsg, please_report);
2843 #endif /* MUST_DO_SELECT */
2845 /* dispatch from pcap without select */
2847 #ifdef LOG_CAPTURE_VERBOSE
2848 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2852 * On Windows, we don't support asynchronously telling a process to
2853 * stop capturing; instead, we check for an indication on a pipe
2854 * after processing packets. We therefore process only one packet
2855 * at a time, so that we can check the pipe after every packet.
2858 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2860 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2864 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2866 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2871 /* Error, rather than pcap_breakloop(). */
2872 pcap_opts->pcap_err = TRUE;
2874 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2876 #else /* pcap_next_ex */
2877 #ifdef LOG_CAPTURE_VERBOSE
2878 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2880 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2883 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2884 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
2885 * This should be fixed in the WinPcap 4.0 alpha release.
2887 * For reference, an example remote interface:
2888 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2891 /* emulate dispatch from pcap */
2894 struct pcap_pkthdr *pkt_header;
2899 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
2901 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
2903 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
2908 pcap_opts->pcap_err = TRUE;
2912 #endif /* pcap_next_ex */
2916 #ifdef LOG_CAPTURE_VERBOSE
2917 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2920 return ld->packet_count - packet_count_before;
2924 /* Isolate the Universally Unique Identifier from the interface. Basically, we
2925 * want to grab only the characters between the '{' and '}' delimiters.
2927 * Returns a GString that must be freed with g_string_free(). */
2929 isolate_uuid(const char *iface)
2934 ptr = strchr(iface, '{');
2936 return g_string_new(iface);
2937 gstr = g_string_new(ptr + 1);
2939 ptr = strchr(gstr->str, '}');
2943 gstr = g_string_truncate(gstr, ptr - gstr->str);
2948 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2949 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2951 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2952 char *errmsg, int errmsg_len)
2955 gchar *capfile_name;
2957 gboolean is_tempfile;
2959 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2960 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
2962 if (capture_opts->save_file != NULL) {
2963 /* We return to the caller while the capture is in progress.
2964 * Therefore we need to take a copy of save_file in
2965 * case the caller destroys it after we return.
2967 capfile_name = g_strdup(capture_opts->save_file);
2969 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2970 if (capture_opts->multi_files_on) {
2971 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2972 g_snprintf(errmsg, errmsg_len,
2973 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2974 g_free(capfile_name);
2977 if (strcmp(capfile_name, "-") == 0) {
2978 /* write to stdout */
2981 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
2982 _setmode(1, O_BINARY);
2985 } /* if (...output_to_pipe ... */
2988 if (capture_opts->multi_files_on) {
2989 /* ringbuffer is enabled */
2990 *save_file_fd = ringbuf_init(capfile_name,
2991 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
2992 capture_opts->group_read_access);
2994 /* we need the ringbuf name */
2995 if(*save_file_fd != -1) {
2996 g_free(capfile_name);
2997 capfile_name = g_strdup(ringbuf_current_filename());
3000 /* Try to open/create the specified file for use as a capture buffer. */
3001 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
3002 (capture_opts->group_read_access) ? 0640 : 0600);
3005 is_tempfile = FALSE;
3007 /* Choose a random name for the temporary capture buffer */
3008 if (global_capture_opts.ifaces->len > 1) {
3009 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3014 iface = isolate_uuid(g_array_index(global_capture_opts.ifaces, interface_options, 0).name);
3015 basename = g_path_get_basename(iface->str);
3016 g_string_free(iface, TRUE);
3018 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).name);
3020 prefix = g_strconcat("wireshark_", basename, NULL);
3023 *save_file_fd = create_tempfile(&tmpname, prefix);
3025 capfile_name = g_strdup(tmpname);
3029 /* did we fail to open the output file? */
3030 if (*save_file_fd == -1) {
3032 g_snprintf(errmsg, errmsg_len,
3033 "The temporary file to which the capture would be saved (\"%s\") "
3034 "could not be opened: %s.", capfile_name, g_strerror(errno));
3036 if (capture_opts->multi_files_on) {
3037 ringbuf_error_cleanup();
3040 g_snprintf(errmsg, errmsg_len,
3041 "The file to which the capture would be saved (\"%s\") "
3042 "could not be opened: %s.", capfile_name,
3045 g_free(capfile_name);
3049 if(capture_opts->save_file != NULL) {
3050 g_free(capture_opts->save_file);
3052 capture_opts->save_file = capfile_name;
3053 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3054 "g_free(capfile_name)". */
3060 /* Do the work of handling either the file size or file duration capture
3061 conditions being reached, and switching files or stopping. */
3063 do_file_switch_or_stop(capture_options *capture_opts,
3064 condition *cnd_autostop_files,
3065 condition *cnd_autostop_size,
3066 condition *cnd_file_duration)
3069 pcap_options *pcap_opts;
3070 interface_options interface_opts;
3071 gboolean successful;
3073 if (capture_opts->multi_files_on) {
3074 if (cnd_autostop_files != NULL &&
3075 cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
3076 /* no files left: stop here */
3077 global_ld.go = FALSE;
3081 /* Switch to the next ringbuffer file */
3082 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3083 &global_ld.save_file_fd, &global_ld.err)) {
3085 /* File switch succeeded: reset the conditions */
3086 global_ld.bytes_written = 0;
3087 if (capture_opts->use_pcapng) {
3089 GString *os_info_str;
3091 os_info_str = g_string_new("");
3092 get_os_version_info(os_info_str);
3094 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
3095 successful = libpcap_write_session_header_block(global_ld.pdh,
3098 os_info_str->str, /* OS */
3100 -1, /* section_length */
3101 &(global_ld.bytes_written),
3104 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3105 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3106 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3107 successful = libpcap_write_interface_description_block(global_ld.pdh,
3108 NULL, /* OPT_COMMENT 1 */
3109 interface_opts.name, /* IDB_NAME 2 */
3110 NULL, /* IDB_DESCRIPTION 3 */
3111 interface_opts.cfilter?interface_opts.cfilter:"", /* IDB_FILTER 11 */
3112 os_info_str->str, /* IDB_OS 12 */
3113 pcap_opts->linktype,
3115 &(global_ld.bytes_written),
3116 0, /* IDB_IF_SPEED 8 */
3117 0, /* IDB_TSRESOL 9 */
3121 g_string_free(os_info_str, TRUE);
3124 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3125 successful = libpcap_write_file_header(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
3126 &global_ld.bytes_written, &global_ld.err);
3129 fclose(global_ld.pdh);
3130 global_ld.pdh = NULL;
3131 global_ld.go = FALSE;
3134 if (cnd_autostop_size)
3135 cnd_reset(cnd_autostop_size);
3136 if (cnd_file_duration)
3137 cnd_reset(cnd_file_duration);
3138 libpcap_dump_flush(global_ld.pdh, NULL);
3140 report_packet_count(global_ld.inpkts_to_sync_pipe);
3141 global_ld.inpkts_to_sync_pipe = 0;
3142 report_new_capture_file(capture_opts->save_file);
3144 /* File switch failed: stop here */
3145 global_ld.go = FALSE;
3149 /* single file, stop now */
3150 global_ld.go = FALSE;
3157 pcap_read_handler(void* arg)
3159 pcap_options *pcap_opts;
3160 char errmsg[MSG_MAX_LENGTH+1];
3162 pcap_opts = (pcap_options *)arg;
3164 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3165 pcap_opts->interface_id);
3167 while (global_ld.go) {
3168 /* dispatch incoming packets */
3169 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3171 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3172 pcap_opts->interface_id);
3173 g_thread_exit(NULL);
3177 /* Do the low-level work of a capture.
3178 Returns TRUE if it succeeds, FALSE otherwise. */
3180 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3183 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3185 struct timeval upd_time, cur_time;
3189 condition *cnd_file_duration = NULL;
3190 condition *cnd_autostop_files = NULL;
3191 condition *cnd_autostop_size = NULL;
3192 condition *cnd_autostop_duration = NULL;
3195 gboolean cfilter_error = FALSE;
3196 char errmsg[MSG_MAX_LENGTH+1];
3197 char secondary_errmsg[MSG_MAX_LENGTH+1];
3198 pcap_options *pcap_opts;
3199 interface_options interface_opts;
3200 guint i, error_index = 0;
3203 *secondary_errmsg = '\0';
3205 /* init the loop data */
3206 global_ld.go = TRUE;
3207 global_ld.packet_count = 0;
3209 global_ld.report_packet_count = FALSE;
3211 if (capture_opts->has_autostop_packets)
3212 global_ld.packet_max = capture_opts->autostop_packets;
3214 global_ld.packet_max = 0; /* no limit */
3215 global_ld.inpkts_to_sync_pipe = 0;
3216 global_ld.err = 0; /* no error seen yet */
3217 global_ld.pdh = NULL;
3218 global_ld.autostop_files = 0;
3219 global_ld.save_file_fd = -1;
3221 /* We haven't yet gotten the capture statistics. */
3222 *stats_known = FALSE;
3224 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3225 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3227 /* open the "input file" from network interface or capture pipe */
3228 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3229 secondary_errmsg, sizeof(secondary_errmsg))) {
3232 for (i = 0; i < capture_opts->ifaces->len; i++) {
3233 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3234 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3235 /* init the input filter from the network interface (capture pipe will do nothing) */
3237 * When remote capturing WinPCap crashes when the capture filter
3238 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3241 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3242 interface_opts.name,
3243 interface_opts.cfilter?interface_opts.cfilter:"")) {
3245 case INITFILTER_NO_ERROR:
3248 case INITFILTER_BAD_FILTER:
3249 cfilter_error = TRUE;
3251 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3254 case INITFILTER_OTHER_ERROR:
3255 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3256 pcap_geterr(pcap_opts->pcap_h));
3257 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3262 /* If we're supposed to write to a capture file, open it for output
3263 (temporary/specified name/ringbuffer) */
3264 if (capture_opts->saving_to_file) {
3265 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3266 errmsg, sizeof(errmsg))) {
3270 /* set up to write to the already-opened capture output file/files */
3271 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3276 /* XXX - capture SIGTERM and close the capture, in case we're on a
3277 Linux 2.0[.x] system and you have to explicitly close the capture
3278 stream in order to turn promiscuous mode off? We need to do that
3279 in other places as well - and I don't think that works all the
3280 time in any case, due to libpcap bugs. */
3282 /* Well, we should be able to start capturing.
3284 Sync out the capture file, so the header makes it to the file system,
3285 and send a "capture started successfully and capture file created"
3286 message to our parent so that they'll open the capture file and
3287 update its windows to indicate that we have a live capture in
3289 libpcap_dump_flush(global_ld.pdh, NULL);
3290 report_new_capture_file(capture_opts->save_file);
3293 /* initialize capture stop (and alike) conditions */
3294 init_capture_stop_conditions();
3295 /* create stop conditions */
3296 if (capture_opts->has_autostop_filesize)
3298 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
3299 if (capture_opts->has_autostop_duration)
3300 cnd_autostop_duration =
3301 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3303 if (capture_opts->multi_files_on) {
3304 if (capture_opts->has_file_duration)
3306 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3308 if (capture_opts->has_autostop_files)
3309 cnd_autostop_files =
3310 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
3313 /* init the time values */
3315 upd_time = GetTickCount();
3317 gettimeofday(&upd_time, NULL);
3319 start_time = create_timestamp();
3320 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
3322 /* WOW, everything is prepared! */
3323 /* please fasten your seat belts, we will enter now the actual capture loop */
3325 pcap_queue = g_async_queue_new();
3326 pcap_queue_bytes = 0;
3327 pcap_queue_packets = 0;
3328 for (i = 0; i < global_ld.pcaps->len; i++) {
3329 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3330 #if GLIB_CHECK_VERSION(2,31,0)
3331 /* XXX - Add an interface name here? */
3332 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3334 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3338 while (global_ld.go) {
3339 /* dispatch incoming packets */
3341 pcap_queue_element *queue_element;
3342 #if GLIB_CHECK_VERSION(2,31,18)
3344 queue_element = g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3346 GTimeVal write_thread_time;
3348 g_get_current_time(&write_thread_time);
3349 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3350 g_async_queue_lock(pcap_queue);
3351 queue_element = g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3353 if (queue_element) {
3354 pcap_queue_bytes -= queue_element->phdr.caplen;
3355 pcap_queue_packets -= 1;
3357 g_async_queue_unlock(pcap_queue);
3358 if (queue_element) {
3359 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3360 "Dequeued a packet of length %d captured on interface %d.",
3361 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3363 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3364 &queue_element->phdr,
3366 g_free(queue_element->pd);
3367 g_free(queue_element);
3373 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3374 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3375 sizeof(errmsg), pcap_opts);
3378 /* Were we asked to print packet counts by the SIGINFO handler? */
3379 if (global_ld.report_packet_count) {
3380 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3381 plurality(global_ld.packet_count, "", "s"));
3382 global_ld.report_packet_count = FALSE;
3387 /* any news from our parent (signal pipe)? -> just stop the capture */
3388 if (!signal_pipe_check_running()) {
3389 global_ld.go = FALSE;
3394 global_ld.inpkts_to_sync_pipe += inpkts;
3396 /* check capture size condition */
3397 if (cnd_autostop_size != NULL &&
3398 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)) {
3399 /* Capture size limit reached, do we have another file? */
3400 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3401 cnd_autostop_size, cnd_file_duration))
3403 } /* cnd_autostop_size */
3404 if (capture_opts->output_to_pipe) {
3405 libpcap_dump_flush(global_ld.pdh, NULL);
3409 /* Only update once every 500ms so as not to overload slow displays.
3410 * This also prevents too much context-switching between the dumpcap
3411 * and wireshark processes.
3413 #define DUMPCAP_UPD_TIME 500
3416 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3417 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3419 gettimeofday(&cur_time, NULL);
3420 if ((cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3421 (upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3424 upd_time = cur_time;
3427 if (pcap_stats(pch, stats) >= 0) {
3428 *stats_known = TRUE;
3431 /* Let the parent process know. */
3432 if (global_ld.inpkts_to_sync_pipe) {
3434 libpcap_dump_flush(global_ld.pdh, NULL);
3436 /* Send our parent a message saying we've written out
3437 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3439 report_packet_count(global_ld.inpkts_to_sync_pipe);
3441 global_ld.inpkts_to_sync_pipe = 0;
3444 /* check capture duration condition */
3445 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3446 /* The maximum capture time has elapsed; stop the capture. */
3447 global_ld.go = FALSE;
3451 /* check capture file duration condition */
3452 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3453 /* duration limit reached, do we have another file? */
3454 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3455 cnd_autostop_size, cnd_file_duration))
3457 } /* cnd_file_duration */
3461 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3463 pcap_queue_element *queue_element;
3465 for (i = 0; i < global_ld.pcaps->len; i++) {
3466 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3467 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3468 pcap_opts->interface_id);
3469 g_thread_join(pcap_opts->tid);
3470 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3471 pcap_opts->interface_id);
3474 g_async_queue_lock(pcap_queue);
3475 queue_element = g_async_queue_try_pop_unlocked(pcap_queue);
3476 if (queue_element) {
3477 pcap_queue_bytes -= queue_element->phdr.caplen;
3478 pcap_queue_packets -= 1;
3480 g_async_queue_unlock(pcap_queue);
3481 if (queue_element == NULL) {
3484 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3485 "Dequeued a packet of length %d captured on interface %d.",
3486 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3487 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3488 &queue_element->phdr,
3490 g_free(queue_element->pd);
3491 g_free(queue_element);
3492 global_ld.inpkts_to_sync_pipe += 1;
3493 if (capture_opts->output_to_pipe) {
3494 libpcap_dump_flush(global_ld.pdh, NULL);
3500 /* delete stop conditions */
3501 if (cnd_file_duration != NULL)
3502 cnd_delete(cnd_file_duration);
3503 if (cnd_autostop_files != NULL)
3504 cnd_delete(cnd_autostop_files);
3505 if (cnd_autostop_size != NULL)
3506 cnd_delete(cnd_autostop_size);
3507 if (cnd_autostop_duration != NULL)
3508 cnd_delete(cnd_autostop_duration);
3510 /* did we have a pcap (input) error? */
3511 for (i = 0; i < capture_opts->ifaces->len; i++) {
3512 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3513 if (pcap_opts->pcap_err) {
3514 /* On Linux, if an interface goes down while you're capturing on it,
3515 you'll get a "recvfrom: Network is down" or
3516 "The interface went down" error (ENETDOWN).
3517 (At least you will if g_strerror() doesn't show a local translation
3520 On FreeBSD and OS X, if a network adapter disappears while
3521 you're capturing on it, you'll get a "read: Device not configured"
3522 error (ENXIO). (See previous parenthetical note.)
3524 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3526 These should *not* be reported to the Wireshark developers. */
3529 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3530 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3531 strcmp(cap_err_str, "The interface went down") == 0 ||
3532 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3533 strcmp(cap_err_str, "read: I/O error") == 0 ||
3534 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3535 report_capture_error("The network adapter on which the capture was being done "
3536 "is no longer running; the capture has stopped.",
3539 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3541 report_capture_error(errmsg, please_report);
3544 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3545 report_capture_error(errmsg, "");
3549 /* did we have an output error while capturing? */
3550 if (global_ld.err == 0) {
3553 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3554 global_ld.err, FALSE);
3555 report_capture_error(errmsg, please_report);
3559 if (capture_opts->saving_to_file) {
3560 /* close the output file */
3561 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3565 /* there might be packets not yet notified to the parent */
3566 /* (do this after closing the file, so all packets are already flushed) */
3567 if(global_ld.inpkts_to_sync_pipe) {
3569 report_packet_count(global_ld.inpkts_to_sync_pipe);
3570 global_ld.inpkts_to_sync_pipe = 0;
3573 /* If we've displayed a message about a write error, there's no point
3574 in displaying another message about an error on close. */
3575 if (!close_ok && write_ok) {
3576 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3578 report_capture_error(errmsg, "");
3582 * XXX We exhibit different behaviour between normal mode and sync mode
3583 * when the pipe is stdin and not already at EOF. If we're a child, the
3584 * parent's stdin isn't closed, so if the user starts another capture,
3585 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3586 * will say "Unrecognized libpcap format". On the other hand, in normal
3587 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3590 report_capture_count(TRUE);
3592 /* get packet drop statistics from pcap */
3593 for (i = 0; i < capture_opts->ifaces->len; i++) {
3597 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3598 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3599 received = pcap_opts->received;
3600 dropped = pcap_opts->dropped;
3601 if (pcap_opts->pcap_h != NULL) {
3602 g_assert(!pcap_opts->from_cap_pipe);
3603 /* Get the capture statistics, so we know how many packets were dropped. */
3604 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3605 *stats_known = TRUE;
3606 /* Let the parent process know. */
3607 dropped += stats->ps_drop;
3609 g_snprintf(errmsg, sizeof(errmsg),
3610 "Can't get packet-drop statistics: %s",
3611 pcap_geterr(pcap_opts->pcap_h));
3612 report_capture_error(errmsg, please_report);
3615 report_packet_drops(received, dropped, interface_opts.name);
3618 /* close the input file (pcap or capture pipe) */
3619 capture_loop_close_input(&global_ld);
3621 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
3623 /* ok, if the write and the close were successful. */
3624 return write_ok && close_ok;
3627 if (capture_opts->multi_files_on) {
3628 /* cleanup ringbuffer */
3629 ringbuf_error_cleanup();
3631 /* We can't use the save file, and we have no FILE * for the stream
3632 to close in order to close it, so close the FD directly. */
3633 if (global_ld.save_file_fd != -1) {
3634 ws_close(global_ld.save_file_fd);
3637 /* We couldn't even start the capture, so get rid of the capture
3639 if (capture_opts->save_file != NULL) {
3640 ws_unlink(capture_opts->save_file);
3641 g_free(capture_opts->save_file);
3644 capture_opts->save_file = NULL;
3646 report_cfilter_error(capture_opts, error_index, errmsg);
3648 report_capture_error(errmsg, secondary_errmsg);
3650 /* close the input file (pcap or cap_pipe) */
3651 capture_loop_close_input(&global_ld);
3653 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3659 static void capture_loop_stop(void)
3661 #ifdef HAVE_PCAP_BREAKLOOP
3663 pcap_options *pcap_opts;
3665 for (i = 0; i < global_ld.pcaps->len; i++) {
3666 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3667 if (pcap_opts->pcap_h != NULL)
3668 pcap_breakloop(pcap_opts->pcap_h);
3671 global_ld.go = FALSE;
3676 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3677 int err, gboolean is_close)
3682 g_snprintf(errmsg, errmsglen,
3683 "Not all the packets could be written to the file"
3684 " to which the capture was being saved\n"
3685 "(\"%s\") because there is no space left on the file system\n"
3686 "on which that file resides.",
3692 g_snprintf(errmsg, errmsglen,
3693 "Not all the packets could be written to the file"
3694 " to which the capture was being saved\n"
3695 "(\"%s\") because you are too close to, or over,"
3696 " your disk quota\n"
3697 "on the file system on which that file resides.",
3704 g_snprintf(errmsg, errmsglen,
3705 "The file to which the capture was being saved\n"
3706 "(\"%s\") could not be closed: %s.",
3707 fname, g_strerror(err));
3709 g_snprintf(errmsg, errmsglen,
3710 "An error occurred while writing to the file"
3711 " to which the capture was being saved\n"
3713 fname, g_strerror(err));
3720 /* one packet was captured, process it */
3722 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3725 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3728 /* We may be called multiple times from pcap_dispatch(); if we've set
3729 the "stop capturing" flag, ignore this packet, as we're not
3730 supposed to be saving any more packets. */
3734 if (global_ld.pdh) {
3735 gboolean successful;
3737 /* We're supposed to write the packet to a file; do so.
3738 If this fails, set "ld->go" to FALSE, to stop the capture, and set
3739 "ld->err" to the error. */
3740 if (global_capture_opts.use_pcapng) {
3741 successful = libpcap_write_enhanced_packet_block(global_ld.pdh, phdr, pcap_opts->interface_id, pd, &global_ld.bytes_written, &err);
3743 successful = libpcap_write_packet(global_ld.pdh, phdr, pd, &global_ld.bytes_written, &err);
3746 global_ld.go = FALSE;
3747 global_ld.err = err;
3749 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3750 "Wrote a packet of length %d captured on interface %u.",
3751 phdr->caplen, pcap_opts->interface_id);
3752 global_ld.packet_count++;
3753 pcap_opts->received++;
3754 /* if the user told us to stop after x packets, do we already have enough? */
3755 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
3756 global_ld.go = FALSE;
3762 /* one packet was captured, queue it */
3764 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3767 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3768 pcap_queue_element *queue_element;
3769 gboolean limit_reached;
3771 /* We may be called multiple times from pcap_dispatch(); if we've set
3772 the "stop capturing" flag, ignore this packet, as we're not
3773 supposed to be saving any more packets. */
3777 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
3778 if (queue_element == NULL) {
3779 pcap_opts->dropped++;
3782 queue_element->pcap_opts = pcap_opts;
3783 queue_element->phdr = *phdr;
3784 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
3785 if (queue_element->pd == NULL) {
3786 pcap_opts->dropped++;
3787 g_free(queue_element);
3790 memcpy(queue_element->pd, pd, phdr->caplen);
3791 g_async_queue_lock(pcap_queue);
3792 if (((pcap_queue_byte_limit > 0) && (pcap_queue_bytes < pcap_queue_byte_limit)) &&
3793 ((pcap_queue_packet_limit > 0) && (pcap_queue_packets < pcap_queue_packet_limit))) {
3794 limit_reached = FALSE;
3795 g_async_queue_push_unlocked(pcap_queue, queue_element);
3796 pcap_queue_bytes += phdr->caplen;
3797 pcap_queue_packets += 1;
3799 limit_reached = TRUE;
3801 g_async_queue_unlock(pcap_queue);
3802 if (limit_reached) {
3803 pcap_opts->dropped++;
3804 g_free(queue_element->pd);
3805 g_free(queue_element);
3806 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3807 "Dropped a packet of length %d captured on interface %u.",
3808 phdr->caplen, pcap_opts->interface_id);
3810 pcap_opts->received++;
3811 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3812 "Queued a packet of length %d captured on interface %u.",
3813 phdr->caplen, pcap_opts->interface_id);
3815 /* I don't want to hold the mutex over the debug output. So the
3816 output may be wrong */
3817 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3818 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
3819 pcap_queue_bytes, pcap_queue_packets);
3822 /* And now our feature presentation... [ fade to music ] */
3824 main(int argc, char *argv[])
3827 gboolean arg_error = FALSE;
3832 struct sigaction action, oldaction;
3835 gboolean start_capture = TRUE;
3836 gboolean stats_known;
3837 struct pcap_stat stats;
3838 GLogLevelFlags log_flags;
3839 gboolean list_interfaces = FALSE;
3840 gboolean list_link_layer_types = FALSE;
3841 #ifdef HAVE_BPF_IMAGE
3842 gboolean print_bpf_code = FALSE;
3844 gboolean machine_readable = FALSE;
3845 gboolean print_statistics = FALSE;
3846 int status, run_once_args = 0;
3849 #if defined(__APPLE__) && defined(__LP64__)
3850 struct utsname osinfo;
3855 arg_list_utf_16to8(argc, argv);
3860 * Initialize our DLL search path. MUST be called before LoadLibrary
3863 ws_init_dll_search_path();
3866 #ifdef HAVE_PCAP_REMOTE
3867 #define OPTSTRING_A "A:"
3868 #define OPTSTRING_r "r"
3869 #define OPTSTRING_u "u"
3871 #define OPTSTRING_A ""
3872 #define OPTSTRING_r ""
3873 #define OPTSTRING_u ""
3876 #ifdef HAVE_PCAP_SETSAMPLING
3877 #define OPTSTRING_m "m:"
3879 #define OPTSTRING_m ""
3882 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
3883 #define OPTSTRING_B "B:"
3885 #define OPTSTRING_B ""
3886 #endif /* _WIN32 or HAVE_PCAP_CREATE */
3888 #ifdef HAVE_PCAP_CREATE
3889 #define OPTSTRING_I "I"
3891 #define OPTSTRING_I ""
3894 #ifdef HAVE_BPF_IMAGE
3895 #define OPTSTRING_d "d"
3897 #define OPTSTRING_d ""
3900 #define OPTSTRING "a:" OPTSTRING_A "b:" OPTSTRING_B "c:" OPTSTRING_d "Df:ghi:" OPTSTRING_I "L" OPTSTRING_m "MnpPq" OPTSTRING_r "Ss:t" OPTSTRING_u "vw:y:Z:"
3902 #ifdef DEBUG_CHILD_DUMPCAP
3903 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
3904 fprintf (stderr, "Unable to open debug log file !\n");
3909 #if defined(__APPLE__) && defined(__LP64__)
3911 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
3912 * a bug workaround - timeouts less than 1 second don't work with libpcap
3913 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
3914 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
3915 * The problem is extremely unlikely to be reintroduced in a future
3918 if (uname(&osinfo) == 0) {
3920 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
3921 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
3922 * number of 10.0.0, not 10.1.0 - go figure).
3924 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
3925 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
3926 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
3927 need_timeout_workaround = TRUE;
3932 * Determine if dumpcap is being requested to run in a special
3933 * capture_child mode by going thru the command line args to see if
3934 * a -Z is present. (-Z is a hidden option).
3936 * The primary result of running in capture_child mode is that
3937 * all messages sent out on stderr are in a special type/len/string
3938 * format to allow message processing by type. These messages include
3939 * error messages if dumpcap fails to start the operation it was
3940 * requested to do, as well as various "status" messages which are sent
3941 * when an actual capture is in progress, and a "success" message sent
3942 * if dumpcap was requested to perform an operation other than a
3945 * Capture_child mode would normally be requested by a parent process
3946 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
3947 * to which dumpcap stderr has been redirected. It might also have
3948 * another pipe to obtain dumpcap stdout output; for operations other
3949 * than a capture, that information is formatted specially for easier
3950 * parsing by the parent process.
3952 * Capture_child mode needs to be determined immediately upon
3953 * startup so that any messages generated by dumpcap in this mode
3954 * (eg: during initialization) will be formatted properly.
3957 for (i=1; i<argc; i++) {
3958 if (strcmp("-Z", argv[i]) == 0) {
3959 capture_child = TRUE;
3960 machine_readable = TRUE; /* request machine-readable output */
3962 /* set output pipe to binary mode, to avoid ugly text conversions */
3963 _setmode(2, O_BINARY);
3968 /* The default_log_handler will use stdout, which makes trouble in */
3969 /* capture child mode, as it uses stdout for it's sync_pipe. */
3970 /* So: the filtering is done in the console_log_handler and not here.*/
3971 /* We set the log handlers right up front to make sure that any log */
3972 /* messages when running as child will be sent back to the parent */
3973 /* with the correct format. */
3977 G_LOG_LEVEL_CRITICAL|
3978 G_LOG_LEVEL_WARNING|
3979 G_LOG_LEVEL_MESSAGE|
3982 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
3984 g_log_set_handler(NULL,
3986 console_log_handler, NULL /* user_data */);
3987 g_log_set_handler(LOG_DOMAIN_MAIN,
3989 console_log_handler, NULL /* user_data */);
3990 g_log_set_handler(LOG_DOMAIN_CAPTURE,
3992 console_log_handler, NULL /* user_data */);
3993 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
3995 console_log_handler, NULL /* user_data */);
3997 /* Initialize the pcaps list */
3998 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
4000 #if !GLIB_CHECK_VERSION(2,31,0)
4001 /* Initialize the thread system */
4002 g_thread_init(NULL);
4006 /* Load wpcap if possible. Do this before collecting the run-time version information */
4009 /* ... and also load the packet.dll from wpcap */
4010 /* XXX - currently not required, may change later. */
4011 /*wpcap_packet_load();*/
4013 /* Start windows sockets */
4014 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4016 /* Set handler for Ctrl+C key */
4017 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4019 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4021 action.sa_handler = capture_cleanup_handler;
4023 * Arrange that system calls not get restarted, because when
4024 * our signal handler returns we don't want to restart
4025 * a call that was waiting for packets to arrive.
4027 action.sa_flags = 0;
4028 sigemptyset(&action.sa_mask);
4029 sigaction(SIGTERM, &action, NULL);
4030 sigaction(SIGINT, &action, NULL);
4031 sigaction(SIGPIPE, &action, NULL);
4032 sigaction(SIGHUP, NULL, &oldaction);
4033 if (oldaction.sa_handler == SIG_DFL)
4034 sigaction(SIGHUP, &action, NULL);
4037 /* Catch SIGINFO and, if we get it and we're capturing in
4038 quiet mode, report the number of packets we've captured. */
4039 action.sa_handler = report_counts_siginfo;
4040 action.sa_flags = SA_RESTART;
4041 sigemptyset(&action.sa_mask);
4042 sigaction(SIGINFO, &action, NULL);
4043 #endif /* SIGINFO */
4046 /* ----------------------------------------------------------------- */
4047 /* Privilege and capability handling */
4049 /* 1. Running not as root or suid root; no special capabilities. */
4052 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
4055 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
4057 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4058 /* capabilities; Drop all other capabilities; */
4059 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4060 /* else: after pcap_open_live() in capture_loop_open_input() */
4061 /* drop all capabilities (NET_RAW and NET_ADMIN); */
4062 /* (Note: this means that the process, although logged in */
4063 /* as root, does not have various permissions such as the */
4064 /* ability to bypass file access permissions). */
4065 /* XXX: Should we just leave capabilities alone in this case */
4066 /* so that user gets expected effect that root can do */
4069 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
4071 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4072 /* else: after pcap_open_live() in capture_loop_open_input() */
4073 /* drop suid root (set euid=ruid).(ie: keep suid until after */
4074 /* pcap_open_live). */
4076 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4078 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4079 /* capabilities; Drop all other capabilities; */
4080 /* Drop suid privileges (euid=ruid); */
4081 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4082 /* else: after pcap_open_live() in capture_loop_open_input() */
4083 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4085 /* XXX: For some Linux versions/distros with capabilities */
4086 /* a 'normal' process with any capabilities cannot be */
4087 /* 'killed' (signaled) from another (same uid) non-privileged */
4089 /* For example: If (non-suid) Wireshark forks a */
4090 /* child suid dumpcap which acts as described here (case 5), */
4091 /* Wireshark will be unable to kill (signal) the child */
4092 /* dumpcap process until the capabilities have been dropped */
4093 /* (after pcap_open_live()). */
4094 /* This behaviour will apparently be changed in the kernel */
4095 /* to allow the kill (signal) in this case. */
4096 /* See the following for details: */
4097 /* http://www.mail-archive.com/ [wrapped] */
4098 /* linux-security-module@vger.kernel.org/msg02913.html */
4100 /* It is therefore conceivable that if dumpcap somehow hangs */
4101 /* in pcap_open_live or before that wireshark will not */
4102 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4103 /* In this case, exiting wireshark will kill the child */
4104 /* dumpcap process. */
4106 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4107 /* capabilities; Using libcap. Note: capset cmd (which see) */
4108 /* used to assign capabilities to file. */
4110 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4111 /* else: after pcap_open_live() in capture_loop_open_input() */
4112 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4114 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4115 /* longer required (similar to capture). */
4117 /* ----------------------------------------------------------------- */
4119 init_process_policies();
4122 /* If 'started with special privileges' (and using libcap) */
4123 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4124 /* Set euid/egid = ruid/rgid to remove suid privileges */
4125 relinquish_privs_except_capture();
4128 /* Set the initial values in the capture options. This might be overwritten
4129 by the command line parameters. */
4130 capture_opts_init(&global_capture_opts, NULL);
4132 /* We always save to a file - if no file was specified, we save to a
4134 global_capture_opts.saving_to_file = TRUE;
4135 global_capture_opts.has_ring_num_files = TRUE;
4137 /* Now get our args */
4138 while ((opt = getopt(argc, argv, OPTSTRING)) != -1) {
4140 case 'h': /* Print help and exit */
4144 case 'v': /* Show version and exit */
4146 GString *comp_info_str;
4147 GString *runtime_info_str;
4148 /* Assemble the compile-time version information string */
4149 comp_info_str = g_string_new("Compiled ");
4150 get_compiled_version_info(comp_info_str, NULL, NULL);
4152 /* Assemble the run-time version information string */
4153 runtime_info_str = g_string_new("Running ");
4154 get_runtime_version_info(runtime_info_str, NULL);
4155 show_version(comp_info_str, runtime_info_str);
4156 g_string_free(comp_info_str, TRUE);
4157 g_string_free(runtime_info_str, TRUE);
4161 /*** capture option specific ***/
4162 case 'a': /* autostop criteria */
4163 case 'b': /* Ringbuffer option */
4164 case 'c': /* Capture x packets */
4165 case 'f': /* capture filter */
4166 case 'i': /* Use interface x */
4167 case 'n': /* Use pcapng format */
4168 case 'p': /* Don't capture in promiscuous mode */
4169 case 'P': /* Use pcap format */
4170 case 's': /* Set the snapshot (capture) length */
4171 case 'w': /* Write to capture file x */
4172 case 'g': /* enable group read accesson file(s) */
4173 case 'y': /* Set the pcap data link type */
4174 #ifdef HAVE_PCAP_REMOTE
4175 case 'u': /* Use UDP for data transfer */
4176 case 'r': /* Capture own RPCAP traffic too */
4177 case 'A': /* Authentication */
4179 #ifdef HAVE_PCAP_SETSAMPLING
4180 case 'm': /* Sampling */
4182 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4183 case 'B': /* Buffer size */
4184 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4185 #ifdef HAVE_PCAP_CREATE
4186 case 'I': /* Monitor mode */
4188 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4193 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4195 capture_child = TRUE;
4197 /* set output pipe to binary mode, to avoid ugly text conversions */
4198 _setmode(2, O_BINARY);
4200 * optarg = the control ID, aka the PPID, currently used for the
4203 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4204 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4205 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4206 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4208 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4209 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4210 "Signal pipe: Unable to open %s. Dead parent?",
4218 case 'q': /* Quiet */
4224 /*** all non capture option specific ***/
4225 case 'D': /* Print a list of capture devices and exit */
4226 list_interfaces = TRUE;
4229 case 'L': /* Print list of link-layer types and exit */
4230 list_link_layer_types = TRUE;
4233 #ifdef HAVE_BPF_IMAGE
4234 case 'd': /* Print BPF code for capture filter and exit */
4235 print_bpf_code = TRUE;
4239 case 'S': /* Print interface statistics once a second */
4240 print_statistics = TRUE;
4243 case 'M': /* For -D, -L, and -S, print machine-readable output */
4244 machine_readable = TRUE;
4247 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4249 case '?': /* Bad flag - print usage message */
4258 /* user specified file name as regular command-line argument */
4259 /* XXX - use it as the capture file name (or something else)? */
4265 * Extra command line arguments were specified; complain.
4266 * XXX - interpret as capture filter, as tcpdump and tshark do?
4268 cmdarg_err("Invalid argument: %s", argv[0]);
4278 if (run_once_args > 1) {
4279 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
4281 } else if (run_once_args == 1) {
4282 /* We're supposed to print some information, rather than
4283 to capture traffic; did they specify a ring buffer option? */
4284 if (global_capture_opts.multi_files_on) {
4285 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4289 /* We're supposed to capture traffic; */
4290 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4291 if (global_capture_opts.ifaces->len > 1) {
4293 global_capture_opts.use_pcapng = TRUE;
4295 /* Was the ring buffer option specified and, if so, does it make sense? */
4296 if (global_capture_opts.multi_files_on) {
4297 /* Ring buffer works only under certain conditions:
4298 a) ring buffer does not work with temporary files;
4299 b) it makes no sense to enable the ring buffer if the maximum
4300 file size is set to "infinite". */
4301 if (global_capture_opts.save_file == NULL) {
4302 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4303 global_capture_opts.multi_files_on = FALSE;
4305 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4306 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4308 /* XXX - this must be redesigned as the conditions changed */
4309 global_capture_opts.multi_files_on = FALSE;
4316 * "-D" requires no interface to be selected; it's supposed to list
4319 if (list_interfaces) {
4320 /* Get the list of interfaces */
4325 if_list = capture_interface_list(&err, &err_str);
4326 if (if_list == NULL) {
4328 case CANT_GET_INTERFACE_LIST:
4329 case DONT_HAVE_PCAP:
4330 cmdarg_err("%s", err_str);
4335 case NO_INTERFACES_FOUND:
4337 * If we're being run by another program, just give them
4338 * an empty list of interfaces, don't report this as
4339 * an error; that lets them decide whether to report
4340 * this as an error or not.
4342 if (!machine_readable) {
4343 cmdarg_err("There are no interfaces on which a capture can be done");
4350 if (machine_readable) /* tab-separated values to stdout */
4351 print_machine_readable_interfaces(if_list);
4353 capture_opts_print_interfaces(if_list);
4354 free_interface_list(if_list);
4359 * "-S" requires no interface to be selected; it gives statistics
4360 * for all interfaces.
4362 if (print_statistics) {
4363 status = print_statistics_loop(machine_readable);
4368 * "-L", "-d", and capturing act on a particular interface, so we have to
4369 * have an interface; if none was specified, pick a default.
4371 if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
4372 /* cmdarg_err() already called .... */
4376 /* Let the user know what interfaces were chosen. */
4377 /* get_interface_descriptive_name() is not available! */
4378 if (capture_child) {
4379 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4380 interface_options interface_opts;
4382 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4383 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4384 interface_opts.name);
4387 str = g_string_new("");
4389 if (global_capture_opts.ifaces->len < 2) {
4391 if (global_capture_opts.ifaces->len < 4) {
4393 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4394 interface_options interface_opts;
4396 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4398 if (global_capture_opts.ifaces->len > 2) {
4399 g_string_append_printf(str, ",");
4401 g_string_append_printf(str, " ");
4402 if (j == global_capture_opts.ifaces->len - 1) {
4403 g_string_append_printf(str, "and ");
4406 g_string_append_printf(str, "%s", interface_opts.name);
4409 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4411 fprintf(stderr, "Capturing on %s\n", str->str);
4412 g_string_free(str, TRUE);
4415 if (list_link_layer_types) {
4416 /* Get the list of link-layer types for the capture device. */
4417 if_capabilities_t *caps;
4421 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
4422 interface_options interface_opts;
4424 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, i);
4425 caps = get_if_capabilities(interface_opts.name,
4426 interface_opts.monitor_mode, &err_str);
4428 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4429 "Please check to make sure you have sufficient permissions, and that\n"
4430 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4434 if (caps->data_link_types == NULL) {
4435 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4438 if (machine_readable) /* tab-separated values to stdout */
4439 /* XXX: We need to change the format and adopt consumers */
4440 print_machine_readable_if_capabilities(caps);
4442 /* XXX: We might want to print also the interface name */
4443 capture_opts_print_if_capabilities(caps, interface_opts.name,
4444 interface_opts.monitor_mode);
4445 free_if_capabilities(caps);
4450 /* We're supposed to do a capture, or print the BPF code for a filter.
4451 Process the snapshot length, as that affects the generated BPF code. */
4452 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4454 #ifdef HAVE_BPF_IMAGE
4455 if (print_bpf_code) {
4456 show_filter_code(&global_capture_opts);
4461 /* We're supposed to do a capture. Process the ring buffer arguments. */
4462 capture_opts_trim_ring_num_files(&global_capture_opts);
4464 /* Now start the capture. */
4466 if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4470 /* capture failed */
4473 return 0; /* never here, make compiler happy */
4478 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4479 const char *message, gpointer user_data _U_)
4486 /* ignore log message, if log_level isn't interesting */
4487 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4488 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4493 /* create a "timestamp" */
4495 today = localtime(&curr);
4497 switch(log_level & G_LOG_LEVEL_MASK) {
4498 case G_LOG_LEVEL_ERROR:
4501 case G_LOG_LEVEL_CRITICAL:
4504 case G_LOG_LEVEL_WARNING:
4507 case G_LOG_LEVEL_MESSAGE:
4510 case G_LOG_LEVEL_INFO:
4513 case G_LOG_LEVEL_DEBUG:
4517 fprintf(stderr, "unknown log_level %u\n", log_level);
4519 g_assert_not_reached();
4522 /* Generate the output message */
4523 if(log_level & G_LOG_LEVEL_MESSAGE) {
4524 /* normal user messages without additional infos */
4525 msg = g_strdup_printf("%s\n", message);
4527 /* info/debug messages with additional infos */
4528 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4529 today->tm_hour, today->tm_min, today->tm_sec,
4530 log_domain != NULL ? log_domain : "",
4534 /* DEBUG & INFO msgs (if we're debugging today) */
4535 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4536 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4537 #ifdef DEBUG_DUMPCAP
4538 fprintf(stderr, "%s", msg);
4541 #ifdef DEBUG_CHILD_DUMPCAP
4542 fprintf(debug_log, "%s", msg);
4550 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4551 /* to parent especially formatted if dumpcap running as child. */
4552 if (capture_child) {
4553 sync_pipe_errmsg_to_parent(2, msg, "");
4555 fprintf(stderr, "%s", msg);
4562 /****************************************************************************************************************/
4563 /* indication report routines */
4567 report_packet_count(int packet_count)
4569 char tmp[SP_DECISIZE+1+1];
4570 static int count = 0;
4573 g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
4574 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
4575 pipe_write_block(2, SP_PACKET_COUNT, tmp);
4577 count += packet_count;
4578 fprintf(stderr, "\rPackets: %u ", count);
4579 /* stderr could be line buffered */
4585 report_new_capture_file(const char *filename)
4588 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
4589 pipe_write_block(2, SP_FILE, filename);
4593 * Prevent a SIGINFO handler from writing to the standard error
4594 * while we're doing so; instead, have it just set a flag telling
4595 * us to print that information when we're done.
4598 #endif /* SIGINFO */
4599 fprintf(stderr, "File: %s\n", filename);
4600 /* stderr could be line buffered */
4605 * Allow SIGINFO handlers to write.
4610 * If a SIGINFO handler asked us to write out capture counts, do so.
4613 report_counts_for_siginfo();
4614 #endif /* SIGINFO */
4619 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
4621 interface_options interface_opts;
4622 char tmp[MSG_MAX_LENGTH+1+6];
4624 if (i < capture_opts->ifaces->len) {
4625 if (capture_child) {
4626 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
4627 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
4628 pipe_write_block(2, SP_BAD_FILTER, tmp);
4631 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
4632 * the error message below.
4634 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
4636 "Invalid capture filter: \"%s\" for interface %s!\n"
4638 "That string isn't a valid capture filter (%s).\n"
4639 "See the User's Guide for a description of the capture filter syntax.",
4640 interface_opts.cfilter, interface_opts.name, errmsg);
4646 report_capture_error(const char *error_msg, const char *secondary_error_msg)
4649 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4650 "Primary Error: %s", error_msg);
4651 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4652 "Secondary Error: %s", secondary_error_msg);
4653 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
4655 cmdarg_err("%s", error_msg);
4656 if (secondary_error_msg[0] != '\0')
4657 cmdarg_err_cont("%s", secondary_error_msg);
4662 report_packet_drops(guint32 received, guint32 drops, gchar *name)
4664 char tmp[SP_DECISIZE+1+1];
4666 g_snprintf(tmp, sizeof(tmp), "%u", drops);
4669 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4670 "Packets received/dropped on interface %s: %u/%u",
4671 name, received, drops);
4672 /* XXX: Need to provide interface id, changes to consumers required. */
4673 pipe_write_block(2, SP_DROPS, tmp);
4676 "Packets received/dropped on interface %s: %u/%u (%.1f%%)\n",
4677 name, received, drops,
4678 received ? 100.0 * received / (received + drops) : 0.0);
4679 /* stderr could be line buffered */
4685 /****************************************************************************************************************/
4686 /* signal_pipe handling */
4691 signal_pipe_check_running(void)
4693 /* any news from our parent? -> just stop the capture */
4697 /* if we are running standalone, no check required */
4698 if(!capture_child) {
4702 if(!sig_pipe_name || !sig_pipe_handle) {
4703 /* This shouldn't happen */
4704 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4705 "Signal pipe: No name or handle");
4710 * XXX - We should have the process ID of the parent (from the "-Z" flag)
4711 * at this point. Should we check to see if the parent is still alive,
4712 * e.g. by using OpenProcess?
4715 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
4717 if(!result || avail > 0) {
4718 /* peek failed or some bytes really available */
4719 /* (if not piping from stdin this would fail) */
4720 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4721 "Signal pipe: Stop capture: %s", sig_pipe_name);
4722 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4723 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
4724 sig_pipe_handle, result, avail);
4727 /* pipe ok and no bytes available */
4734 * Editor modelines - http://www.wireshark.org/tools/modelines.html
4739 * indent-tabs-mode: nil
4742 * vi: set shiftwidth=4 tabstop=8 expandtab:
4743 * :indentSize=4:tabSize=8:noTabs=true: