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>
65 #include "wsutil/wsgetopt.h"
73 # include <sys/prctl.h>
74 # include <sys/capability.h>
77 #include "ringbuffer.h"
78 #include "clopts_common.h"
79 #include "console_io.h"
80 #include "cmdarg_err.h"
81 #include "version_info.h"
83 #include "capture-pcap-util.h"
88 #include "capture-wpcap.h"
89 #include <wsutil/unicode-utils.h>
93 #include <sys/socket.h>
97 #ifdef NEED_INET_V6DEFS_H
98 # include "wsutil/inet_v6defs.h"
101 #include <wsutil/privileges.h>
103 #include "sync_pipe.h"
105 #include "capture_opts.h"
106 #include "capture_ifinfo.h"
107 #include "capture_sync.h"
109 #include "conditions.h"
110 #include "capture_stop_conditions.h"
112 #include "tempfile.h"
114 #include "wsutil/file_util.h"
117 * Get information about libpcap format from "wiretap/libpcap.h".
118 * XXX - can we just use pcap_open_offline() to read the pipe?
120 #include "wiretap/libpcap.h"
122 /**#define DEBUG_DUMPCAP**/
123 /**#define DEBUG_CHILD_DUMPCAP**/
125 #ifdef DEBUG_CHILD_DUMPCAP
126 FILE *debug_log; /* for logging debug messages to */
127 /* a file if DEBUG_CHILD_DUMPCAP */
135 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
137 static gchar *sig_pipe_name = NULL;
138 static HANDLE sig_pipe_handle = NULL;
139 static gboolean signal_pipe_check_running(void);
143 static GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
144 static GMutex *cap_pipe_read_mtx;
148 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
149 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
152 /** Stop a low-level capture (stops the capture child). */
153 static void capture_loop_stop(void);
155 #if !defined (__linux__)
156 #ifndef HAVE_PCAP_BREAKLOOP
158 * We don't have pcap_breakloop(), which is the only way to ensure that
159 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
160 * won't, if the call to read the next packet or batch of packets is
161 * is interrupted by a signal on UN*X, just go back and try again to
164 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
165 * the signal handler, set a flag to stop capturing; however, without
166 * a guarantee of that sort, we can't guarantee that we'll stop capturing
167 * if the read will be retried and won't time out if no packets arrive.
169 * Therefore, on at least some platforms, we work around the lack of
170 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
171 * to wait for packets to arrive, so that we're probably going to be
172 * blocked in the select() when the signal arrives, and can just bail
173 * out of the loop at that point.
175 * However, we don't want to that on BSD (because "select()" doesn't work
176 * correctly on BPF devices on at least some releases of some flavors of
177 * BSD), and we don't want to do it on Windows (because "select()" is
178 * something for sockets, not for arbitrary handles). (Note that "Windows"
179 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
180 * using WinPcap, not a UNIX libpcap.)
182 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
183 * on BSD times out even if no packets have arrived, so we'll eventually
184 * exit pcap_dispatch() with an indication that no packets have arrived,
185 * and will break out of the capture loop at that point.
187 * On Windows, we can't send a SIGINT to stop capturing, so none of this
188 * applies in any case.
190 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
191 * want to include it if it's not present on this platform, however.
193 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
194 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
196 # define MUST_DO_SELECT
197 # endif /* avoid select */
198 #endif /* HAVE_PCAP_BREAKLOOP */
200 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
201 * in pcap_dispatch(); on the other hand, select() works just fine there.
202 * Hence we use a select for that come what may.
204 #define MUST_DO_SELECT
207 /** init the capture filter */
210 INITFILTER_BAD_FILTER,
211 INITFILTER_OTHER_ERROR
212 } initfilter_status_t;
214 typedef struct _loop_data {
216 gboolean go; /* TRUE as long as we're supposed to keep capturing */
217 int err; /* if non-zero, error seen while capturing */
218 gint packet_count; /* Number of packets we have already captured */
219 gint packet_max; /* Number of packets we're supposed to capture - 0 means infinite */
220 gint inpkts_to_sync_pipe; /* Packets not already send out to the sync_pipe */
222 gboolean report_packet_count; /* Set by SIGINFO handler; print packet count */
225 /* pcap "input file" */
226 pcap_t *pcap_h; /* pcap handle */
227 gboolean pcap_err; /* TRUE if error from pcap */
228 #ifdef MUST_DO_SELECT
229 int pcap_fd; /* pcap file descriptor */
232 /* capture pipe (unix only "input file") */
233 gboolean from_cap_pipe; /* TRUE if we are capturing data from a capture pipe */
234 struct pcap_hdr cap_pipe_hdr; /* Pcap header when capturing from a pipe */
235 struct pcaprec_modified_hdr cap_pipe_rechdr; /* Pcap record header when capturing from a pipe */
237 HANDLE cap_pipe_h; /* The handle of the capture pipe */
239 int cap_pipe_fd; /* the file descriptor of the capture pipe */
241 gboolean cap_pipe_modified; /* TRUE if data in the pipe uses modified pcap headers */
242 gboolean cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
244 char * cap_pipe_buf; /* Pointer to the data buffer we read into */
245 #endif /* USE_THREADS */
246 int cap_pipe_bytes_to_read;/* Used by cap_pipe_dispatch */
247 int cap_pipe_bytes_read; /* Used by cap_pipe_dispatch */
249 STATE_EXPECT_REC_HDR,
254 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
263 guint32 autostop_files;
267 * Standard secondary message for unexpected errors.
269 static const char please_report[] =
270 "Please report this to the Wireshark developers.\n"
271 "(This is not a crash; please do not report it as such.)";
274 * This needs to be static, so that the SIGINT handler can clear the "go"
277 static loop_data global_ld;
281 * Timeout, in milliseconds, for reads from the stream of captured packets.
283 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
284 * 64-bit applications, with sub-second timeouts not to work. The bug is
287 #if defined(__APPLE__) && defined(__LP64__)
288 static gboolean need_timeout_workaround;
290 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
292 #define CAP_READ_TIMEOUT 250
296 * Timeout, in microseconds, for threaded reads from a pipe.
298 #define THREAD_READ_TIMEOUT 100
299 static const char *cap_pipe_err_str;
302 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
303 const char *message, gpointer user_data _U_);
305 /* capture related options */
306 static capture_options global_capture_opts;
307 static gboolean quiet;
309 static void capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
311 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
312 int err, gboolean is_close);
314 static void exit_main(int err) G_GNUC_NORETURN;
316 static void report_new_capture_file(const char *filename);
317 static void report_packet_count(int packet_count);
318 static void report_packet_drops(guint32 drops);
319 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
320 static void report_cfilter_error(const char *cfilter, const char *errmsg);
323 print_usage(gboolean print_ver) {
331 "Dumpcap " VERSION "%s\n"
332 "Capture network packets and dump them into a libpcap file.\n"
333 "See http://www.wireshark.org for more information.\n",
334 wireshark_svnversion);
338 fprintf(output, "\nUsage: dumpcap [options] ...\n");
339 fprintf(output, "\n");
340 fprintf(output, "Capture interface:\n");
341 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
342 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
343 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
344 fprintf(output, " -p don't capture in promiscuous mode\n");
345 #ifdef HAVE_PCAP_CREATE
346 fprintf(output, " -I capture in monitor mode, if available\n");
348 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
349 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
351 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
352 fprintf(output, " -D print list of interfaces and exit\n");
353 fprintf(output, " -L print list of link-layer types of iface and exit\n");
354 fprintf(output, " -S print statistics for each interface once every second\n");
355 fprintf(output, " -M for -D, -L, and -S produce machine-readable output\n");
356 fprintf(output, "\n");
357 #ifdef HAVE_PCAP_REMOTE
358 fprintf(output, "\nRPCAP options:\n");
359 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
360 fprintf(output, " -u use UDP for RPCAP data transfer\n");
361 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
362 #ifdef HAVE_PCAP_SETSAMPLING
363 fprintf(output, " -m <sampling type> use packet sampling\n");
364 fprintf(output, " count:NUM - capture one packet of every NUM\n");
365 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
368 fprintf(output, "Stop conditions:\n");
369 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
370 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
371 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
372 fprintf(output, " files:NUM - stop after NUM files\n");
373 /*fprintf(output, "\n");*/
374 fprintf(output, "Output (files):\n");
375 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
376 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
377 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
378 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
379 fprintf(output, " -n use pcapng format instead of pcap\n");
380 /*fprintf(output, "\n");*/
381 fprintf(output, "Miscellaneous:\n");
382 fprintf(output, " -q don't report packet capture counts\n");
383 fprintf(output, " -v print version information and exit\n");
384 fprintf(output, " -h display this help and exit\n");
385 fprintf(output, "\n");
386 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcap\n");
387 fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcap\"\n");
388 fprintf(output, "\n");
389 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
393 show_version(GString *comp_info_str, GString *runtime_info_str)
397 "Dumpcap " VERSION "%s\n"
402 "See http://www.wireshark.org for more information.\n",
403 wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
407 * Print to the standard error. This is a command-line tool, so there's
408 * no need to pop up a console.
411 vfprintf_stderr(const char *fmt, va_list ap)
413 vfprintf(stderr, fmt, ap);
417 fprintf_stderr(const char *fmt, ...)
422 vfprintf_stderr(fmt, ap);
427 * Report an error in command-line arguments.
430 cmdarg_err(const char *fmt, ...)
436 /* Generate a 'special format' message back to parent */
438 msg = g_strdup_vprintf(fmt, ap);
439 sync_pipe_errmsg_to_parent(2, msg, "");
444 fprintf(stderr, "dumpcap: ");
445 vfprintf(stderr, fmt, ap);
446 fprintf(stderr, "\n");
452 * Report additional information for an error in command-line arguments.
455 cmdarg_err_cont(const char *fmt, ...)
462 msg = g_strdup_vprintf(fmt, ap);
463 sync_pipe_errmsg_to_parent(2, msg, "");
468 vfprintf(stderr, fmt, ap);
469 fprintf(stderr, "\n");
475 * capture_interface_list() is expected to do the right thing to get
476 * a list of interfaces.
478 * In most of the programs in the Wireshark suite, "the right thing"
479 * is to run dumpcap and ask it for the list, because dumpcap may
480 * be the only program in the suite with enough privileges to get
483 * In dumpcap itself, however, we obviously can't run dumpcap to
484 * ask for the list. Therefore, our capture_interface_list() should
485 * just call get_interface_list().
488 capture_interface_list(int *err, char **err_str)
490 return get_interface_list(err, err_str);
494 * Get the data-link type for a libpcap device.
495 * This works around AIX 5.x's non-standard and incompatible-with-the-
496 * rest-of-the-universe libpcap.
499 get_pcap_linktype(pcap_t *pch, const char *devname
507 const char *ifacename;
510 linktype = pcap_datalink(pch);
514 * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
515 * rather than DLT_ values for link-layer types; the ifType values
516 * for LAN devices are:
523 * and the ifType value for a loopback device is 24.
525 * The AIX names for LAN devices begin with:
532 * and the AIX names for loopback devices begin with "lo".
534 * (The difference between "Ethernet" and "802.3" is presumably
535 * whether packets have an Ethernet header, with a packet type,
536 * or an 802.3 header, with a packet length, followed by an 802.2
537 * header and possibly a SNAP header.)
539 * If the device name matches "linktype" interpreted as an ifType
540 * value, rather than as a DLT_ value, we will assume this is AIX's
541 * non-standard, incompatible libpcap, rather than a standard libpcap,
542 * and will map the link-layer type to the standard DLT_ value for
543 * that link-layer type, as that's what the rest of Wireshark expects.
545 * (This means the capture files won't be readable by a tcpdump
546 * linked with AIX's non-standard libpcap, but so it goes. They
547 * *will* be readable by standard versions of tcpdump, Wireshark,
550 * XXX - if we conclude we're using AIX libpcap, should we also
551 * set a flag to cause us to assume the time stamps are in
552 * seconds-and-nanoseconds form, and to convert them to
553 * seconds-and-microseconds form before processing them and
558 * Find the last component of the device name, which is the
561 ifacename = strchr(devname, '/');
562 if (ifacename == NULL)
565 /* See if it matches any of the LAN device names. */
566 if (strncmp(ifacename, "en", 2) == 0) {
569 * That's the RFC 1573 value for Ethernet; map it to DLT_EN10MB.
573 } else if (strncmp(ifacename, "et", 2) == 0) {
576 * That's the RFC 1573 value for 802.3; map it to DLT_EN10MB.
577 * (libpcap, tcpdump, Wireshark, etc. don't care if it's Ethernet
582 } else if (strncmp(ifacename, "tr", 2) == 0) {
585 * That's the RFC 1573 value for 802.5 (Token Ring); map it to
586 * DLT_IEEE802, which is what's used for Token Ring.
590 } else if (strncmp(ifacename, "fi", 2) == 0) {
591 if (linktype == 15) {
593 * That's the RFC 1573 value for FDDI; map it to DLT_FDDI.
597 } else if (strncmp(ifacename, "lo", 2) == 0) {
598 if (linktype == 24) {
600 * That's the RFC 1573 value for "software loopback" devices; map it
601 * to DLT_NULL, which is what's used for loopback devices on BSD.
611 static data_link_info_t *
612 create_data_link_info(int dlt)
614 data_link_info_t *data_link_info;
617 data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
618 data_link_info->dlt = dlt;
619 text = pcap_datalink_val_to_name(dlt);
621 data_link_info->name = g_strdup(text);
623 data_link_info->name = g_strdup_printf("DLT %d", dlt);
624 text = pcap_datalink_val_to_description(dlt);
626 data_link_info->description = g_strdup(text);
628 data_link_info->description = NULL;
629 return data_link_info;
633 * Get the capabilities of a network device.
635 static if_capabilities_t *
636 get_if_capabilities(const char *devname, gboolean monitor_mode
637 #ifndef HAVE_PCAP_CREATE
642 if_capabilities_t *caps;
643 char errbuf[PCAP_ERRBUF_SIZE];
645 #ifdef HAVE_PCAP_CREATE
649 #ifdef HAVE_PCAP_LIST_DATALINKS
653 data_link_info_t *data_link_info;
656 * Allocate the interface capabilities structure.
658 caps = g_malloc(sizeof *caps);
660 #ifdef HAVE_PCAP_OPEN
661 pch = pcap_open(devname, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
662 caps->can_set_rfmon = FALSE;
665 *err_str = g_strdup(errbuf);
669 #elif defined(HAVE_PCAP_CREATE)
670 pch = pcap_create(devname, errbuf);
673 *err_str = g_strdup(errbuf);
677 status = pcap_can_set_rfmon(pch);
680 if (status == PCAP_ERROR)
681 *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
684 *err_str = g_strdup(pcap_statustostr(status));
690 caps->can_set_rfmon = FALSE;
691 else if (status == 1) {
692 caps->can_set_rfmon = TRUE;
694 pcap_set_rfmon(pch, 1);
696 if (err_str != NULL) {
697 *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
705 status = pcap_activate(pch);
707 /* Error. We ignore warnings (status > 0). */
708 if (err_str != NULL) {
709 if (status == PCAP_ERROR)
710 *err_str = g_strdup_printf("pcap_activate() failed: %s",
713 *err_str = g_strdup(pcap_statustostr(status));
720 pch = pcap_open_live(devname, MIN_PACKET_SIZE, 0, 0, errbuf);
721 caps->can_set_rfmon = FALSE;
724 *err_str = g_strdup(errbuf);
729 deflt = get_pcap_linktype(pch, devname);
730 #ifdef HAVE_PCAP_LIST_DATALINKS
731 nlt = pcap_list_datalinks(pch, &linktypes);
732 if (nlt == 0 || linktypes == NULL) {
735 *err_str = NULL; /* an empty list doesn't mean an error */
738 caps->data_link_types = NULL;
739 for (i = 0; i < nlt; i++) {
740 data_link_info = create_data_link_info(linktypes[i]);
743 * XXX - for 802.11, make the most detailed 802.11
744 * version the default, rather than the one the
745 * device has as the default?
747 if (linktypes[i] == deflt)
748 caps->data_link_types = g_list_prepend(caps->data_link_types,
751 caps->data_link_types = g_list_append(caps->data_link_types,
754 #ifdef HAVE_PCAP_FREE_DATALINKS
755 pcap_free_datalinks(linktypes);
758 * In Windows, there's no guarantee that if you have a library
759 * built with one version of the MSVC++ run-time library, and
760 * it returns a pointer to allocated data, you can free that
761 * data from a program linked with another version of the
762 * MSVC++ run-time library.
764 * This is not an issue on UN*X.
766 * See the mail threads starting at
768 * http://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
772 * http://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
775 #define xx_free free /* hack so checkAPIs doesn't complain */
778 #endif /* HAVE_PCAP_FREE_DATALINKS */
779 #else /* HAVE_PCAP_LIST_DATALINKS */
781 data_link_info = create_data_link_info(deflt);
782 caps->data_link_types = g_list_append(caps->data_link_types,
784 #endif /* HAVE_PCAP_LIST_DATALINKS */
793 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
795 print_machine_readable_interfaces(GList *if_list)
802 char addr_str[ADDRSTRLEN];
805 /* Let our parent know we succeeded. */
806 pipe_write_block(2, SP_SUCCESS, NULL);
809 i = 1; /* Interface id number */
810 for (if_entry = g_list_first(if_list); if_entry != NULL;
811 if_entry = g_list_next(if_entry)) {
812 if_info = (if_info_t *)if_entry->data;
813 printf("%d. %s", i++, if_info->name);
816 * Print the contents of the if_entry struct in a parseable format.
817 * Each if_entry element is tab-separated. Addresses are comma-
820 /* XXX - Make sure our description doesn't contain a tab */
821 if (if_info->description != NULL)
822 printf("\t%s\t", if_info->description);
826 for(addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
827 addr = g_slist_next(addr)) {
828 if (addr != g_slist_nth(if_info->addrs, 0))
831 if_addr = (if_addr_t *)addr->data;
832 switch(if_addr->ifat_type) {
834 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
836 printf("%s", addr_str);
838 printf("<unknown IPv4>");
842 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
843 addr_str, ADDRSTRLEN)) {
844 printf("%s", addr_str);
846 printf("<unknown IPv6>");
850 printf("<type unknown %u>", if_addr->ifat_type);
854 if (if_info->loopback)
855 printf("\tloopback");
864 * If you change the machine-readable output format of this function,
865 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
868 print_machine_readable_if_capabilities(if_capabilities_t *caps)
871 data_link_info_t *data_link_info;
872 const gchar *desc_str;
875 /* Let our parent know we succeeded. */
876 pipe_write_block(2, SP_SUCCESS, NULL);
879 if (caps->can_set_rfmon)
883 for (lt_entry = caps->data_link_types; lt_entry != NULL;
884 lt_entry = g_list_next(lt_entry)) {
885 data_link_info = (data_link_info_t *)lt_entry->data;
886 if (data_link_info->description != NULL)
887 desc_str = data_link_info->description;
889 desc_str = "(not supported)";
890 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
900 /* Print the number of packets captured for each interface until we're killed. */
902 print_statistics_loop(gboolean machine_readable)
904 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
910 char errbuf[PCAP_ERRBUF_SIZE];
913 if_list = get_interface_list(&err, &err_str);
914 if (if_list == NULL) {
916 case CANT_GET_INTERFACE_LIST:
917 cmdarg_err("%s", err_str);
921 case NO_INTERFACES_FOUND:
922 cmdarg_err("There are no interfaces on which a capture can be done");
928 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
929 if_info = (if_info_t *)if_entry->data;
930 #ifdef HAVE_PCAP_OPEN
931 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
933 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
937 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
938 if_stat->name = g_strdup(if_info->name);
940 stat_list = g_list_append(stat_list, if_stat);
945 cmdarg_err("There are no interfaces on which a capture can be done");
950 /* Let our parent know we succeeded. */
951 pipe_write_block(2, SP_SUCCESS, NULL);
954 if (!machine_readable) {
955 printf("%-15s %10s %10s\n", "Interface", "Received",
960 while (global_ld.go) {
961 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
962 if_stat = (if_stat_t *)stat_entry->data;
963 pcap_stats(if_stat->pch, &ps);
965 if (!machine_readable) {
966 printf("%-15s %10u %10u\n", if_stat->name,
967 ps.ps_recv, ps.ps_drop);
969 printf("%s\t%u\t%u\n", if_stat->name,
970 ps.ps_recv, ps.ps_drop);
975 if (! global_ld.from_cap_pipe)
982 /* XXX - Not reached. Should we look for 'q' in stdin? */
983 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
984 if_stat = (if_stat_t *)stat_entry->data;
985 pcap_close(if_stat->pch);
986 g_free(if_stat->name);
989 g_list_free(stat_list);
990 free_interface_list(if_list);
998 capture_cleanup_handler(DWORD dwCtrlType)
1000 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1001 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1002 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1003 like SIGTERM at least when the machine's shutting down.
1005 For now, if we're running as a command rather than a capture child,
1006 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1007 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1008 in that way on UN*X.
1010 If we're not running as a capture child, we might be running as
1011 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1012 user logs out. (XXX - can we explicitly check whether we're
1013 running as a service?) */
1015 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1016 "Console: Control signal");
1017 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1018 "Console: Control signal, CtrlType: %u", dwCtrlType);
1020 /* Keep capture running if we're a service and a user logs off */
1021 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1022 capture_loop_stop();
1030 capture_cleanup_handler(int signum _U_)
1032 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1033 SIGTERM. We assume that if the user wanted it to keep running
1034 after they logged out, they'd have nohupped it. */
1036 /* Note: don't call g_log() in the signal handler: if we happened to be in
1037 * g_log() in process context when the signal came in, g_log will detect
1038 * the "recursion" and abort.
1041 capture_loop_stop();
1050 /* Don't print this if we're a capture child. */
1051 if (!capture_child) {
1053 /* Report the count only if we aren't printing a packet count
1054 as packets arrive. */
1055 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
1056 plurality(global_ld.packet_count, "", "s"));
1059 infoprint = FALSE; /* we just reported it */
1063 report_counts_siginfo(int signum _U_)
1065 int sav_errno = errno;
1067 /* If we've been told to delay printing, just set a flag asking
1068 that we print counts (if we're supposed to), otherwise print
1069 the count of packets captured (if we're supposed to). */
1076 #endif /* SIGINFO */
1078 static void exit_main(int status)
1081 /* Shutdown windows sockets */
1084 /* can be helpful for debugging */
1085 #ifdef DEBUG_DUMPCAP
1086 printf("Press any key\n");
1097 * If we were linked with libcap (not libpcap), make sure we have
1098 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1099 * (See comment in main() for details)
1103 #if 0 /* Set to enable capability debugging */
1104 /* see 'man cap_to_text()' for explanation of output */
1105 /* '=' means 'all= ' ie: no capabilities */
1106 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
1108 print_caps(const char *pfx) {
1109 cap_t caps = cap_get_proc();
1110 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1111 "%s: EUID: %d Capabilities: %s", pfx,
1112 geteuid(), cap_to_text(caps, NULL));
1115 print_caps(const char *pfx _U_) {
1120 relinquish_privs_except_capture(void)
1122 /* If 'started_with_special_privs' (ie: suid) then enable for
1123 * ourself the NET_ADMIN and NET_RAW capabilities and then
1124 * drop our suid privileges.
1126 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1127 * stuff we don't need (and shouldn't have).
1128 * CAP_NET_RAW: Packet capture (raw sockets).
1131 if (started_with_special_privs()) {
1132 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1133 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1135 cap_t caps = cap_init(); /* all capabilities initialized to off */
1137 print_caps("Pre drop, pre set");
1139 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1140 cmdarg_err("prctl() fail return: %s", strerror(errno));
1143 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1144 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1146 if (cap_set_proc(caps)) {
1147 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
1149 print_caps("Pre drop, post set");
1151 relinquish_special_privs_perm();
1153 print_caps("Post drop, pre set");
1154 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1155 if (cap_set_proc(caps)) {
1156 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
1158 print_caps("Post drop, post set");
1166 relinquish_all_capabilities(void)
1168 /* Drop any and all capabilities this process may have. */
1169 /* Allowed whether or not process has any privileges. */
1170 cap_t caps = cap_init(); /* all capabilities initialized to off */
1171 print_caps("Pre-clear");
1172 if (cap_set_proc(caps)) {
1173 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
1175 print_caps("Post-clear");
1179 #endif /* HAVE_LIBCAP */
1181 /* Set the data link type on a pcap. */
1183 set_pcap_linktype(pcap_t *pch, char *devname
1184 #ifdef HAVE_PCAP_SET_DATALINK
1189 #ifdef HAVE_PCAP_SET_DATALINK
1190 if (pcap_set_datalink(pch, dlt) == 0)
1191 return NULL; /* no error */
1192 return pcap_geterr(pch);
1194 /* Let them set it to the type it is; reject any other request. */
1195 if (get_pcap_linktype(pch, devname) == dlt)
1196 return NULL; /* no error */
1197 return "That DLT isn't one of the DLTs supported by this device";
1201 /* Take care of byte order in the libpcap headers read from pipes.
1202 * (function taken from wiretap/libpcap.c) */
1204 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1207 /* Byte-swap the record header fields. */
1208 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
1209 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
1210 rechdr->incl_len = BSWAP32(rechdr->incl_len);
1211 rechdr->orig_len = BSWAP32(rechdr->orig_len);
1214 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1215 swapped, in order to match the BPF header layout.
1217 Unfortunately, some files were, according to a comment in the "libpcap"
1218 source, written with version 2.3 in their headers but without the
1219 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1220 would make no sense - we assume that we need to swap them. */
1221 if (hdr->version_major == 2 &&
1222 (hdr->version_minor < 3 ||
1223 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1226 temp = rechdr->orig_len;
1227 rechdr->orig_len = rechdr->incl_len;
1228 rechdr->incl_len = temp;
1234 * Thread function that reads from a pipe and pushes the data
1235 * to the main application thread.
1238 * XXX Right now we use async queues for basic signaling. The main thread
1239 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1240 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1241 * Iff the read is successful cap_pipe_read pushes an item onto
1242 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1243 * the queues themselves (yet).
1245 * We might want to move some of the cap_pipe_dispatch logic here so that
1246 * we can let cap_pipe_read run independently, queuing up multiple reads
1247 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1249 static void *cap_pipe_read(void *ld_ptr) {
1250 loop_data *ld = (loop_data *)ld_ptr;
1259 while (ld->cap_pipe_err == PIPOK) {
1260 g_async_queue_pop(cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1261 g_mutex_lock(cap_pipe_read_mtx);
1263 while (bytes_read < (int) ld->cap_pipe_bytes_to_read) {
1265 /* If we try to use read() on a named pipe on Windows with partial
1266 * data it appears to return EOF.
1268 res = ReadFile(ld->cap_pipe_h, ld->cap_pipe_buf+bytes_read,
1269 ld->cap_pipe_bytes_to_read - bytes_read,
1274 last_err = GetLastError();
1275 if (last_err == ERROR_MORE_DATA) {
1277 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1278 ld->cap_pipe_err = PIPEOF;
1282 ld->cap_pipe_err = PIPERR;
1285 } else if (b == 0 && ld->cap_pipe_bytes_to_read > 0) {
1286 ld->cap_pipe_err = PIPEOF;
1291 b = read(ld->cap_pipe_fd, ld->cap_pipe_buf+bytes_read,
1292 ld->cap_pipe_bytes_to_read - bytes_read);
1295 ld->cap_pipe_err = PIPEOF;
1299 ld->cap_pipe_err = PIPERR;
1308 ld->cap_pipe_bytes_read = bytes_read;
1309 if (ld->cap_pipe_bytes_read >= ld->cap_pipe_bytes_to_read) {
1310 g_async_queue_push(cap_pipe_done_q, ld->cap_pipe_buf); /* Any non-NULL value will do */
1312 g_mutex_unlock(cap_pipe_read_mtx);
1316 #endif /* USE_THREADS */
1318 /* Provide select() functionality for a single file descriptor
1319 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1321 * Returns the same values as select. If an error is returned,
1322 * the string cap_pipe_err_str should be used instead of errno.
1325 cap_pipe_select(int pipe_fd) {
1327 struct timeval timeout, *pto;
1330 cap_pipe_err_str = "Unknown error";
1333 FD_SET(pipe_fd, &rfds);
1336 timeout.tv_usec = CAP_READ_TIMEOUT * 1000;
1339 sel_ret = select(pipe_fd+1, &rfds, NULL, NULL, pto);
1341 cap_pipe_err_str = strerror(errno);
1346 /* Mimic pcap_open_live() for pipe captures
1348 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1349 * open it, and read the header.
1351 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1352 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1354 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
1355 char *errmsg, int errmsgl)
1358 struct stat pipe_stat;
1359 struct sockaddr_un sa;
1362 unsigned int bytes_read;
1373 ld->cap_pipe_fd = -1;
1375 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
1377 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1380 * XXX - this blocks until a pcap per-file header has been written to
1381 * the pipe, so it could block indefinitely.
1383 if (strcmp(pipename, "-") == 0) {
1385 fd = 0; /* read from stdin */
1387 ld->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1391 if (ws_stat(pipename, &pipe_stat) < 0) {
1392 if (errno == ENOENT || errno == ENOTDIR)
1393 ld->cap_pipe_err = PIPNEXIST;
1395 g_snprintf(errmsg, errmsgl,
1396 "The capture session could not be initiated "
1397 "due to error getting information on pipe/socket: %s", strerror(errno));
1398 ld->cap_pipe_err = PIPERR;
1402 if (S_ISFIFO(pipe_stat.st_mode)) {
1403 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1405 g_snprintf(errmsg, errmsgl,
1406 "The capture session could not be initiated "
1407 "due to error on pipe open: %s", strerror(errno));
1408 ld->cap_pipe_err = PIPERR;
1411 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1412 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1414 g_snprintf(errmsg, errmsgl,
1415 "The capture session could not be initiated "
1416 "due to error on socket create: %s", strerror(errno));
1417 ld->cap_pipe_err = PIPERR;
1420 sa.sun_family = AF_UNIX;
1422 * The Single UNIX Specification says:
1424 * The size of sun_path has intentionally been left undefined.
1425 * This is because different implementations use different sizes.
1426 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1427 * of 104. Since most implementations originate from BSD versions,
1428 * the size is typically in the range 92 to 108.
1430 * Applications should not assume a particular length for sun_path
1431 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1435 * The <sys/un.h> header shall define the sockaddr_un structure,
1436 * which shall include at least the following members:
1438 * sa_family_t sun_family Address family.
1439 * char sun_path[] Socket pathname.
1441 * so we assume that it's an array, with a specified size,
1442 * and that the size reflects the maximum path length.
1444 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1445 /* Path name too long */
1446 g_snprintf(errmsg, errmsgl,
1447 "The capture session coud not be initiated "
1448 "due to error on socket connect: Path name too long");
1449 ld->cap_pipe_err = PIPERR;
1452 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1454 g_snprintf(errmsg, errmsgl,
1455 "The capture session coud not be initiated "
1456 "due to error on socket connect: %s", strerror(errno));
1457 ld->cap_pipe_err = PIPERR;
1461 if (S_ISCHR(pipe_stat.st_mode)) {
1463 * Assume the user specified an interface on a system where
1464 * interfaces are in /dev. Pretend we haven't seen it.
1466 ld->cap_pipe_err = PIPNEXIST;
1469 g_snprintf(errmsg, errmsgl,
1470 "The capture session could not be initiated because\n"
1471 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
1472 ld->cap_pipe_err = PIPERR;
1477 #define PIPE_STR "\\pipe\\"
1478 /* Under Windows, named pipes _must_ have the form
1479 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1481 pncopy = g_strdup(pipename);
1482 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1483 pos = strchr(pncopy + 3, '\\');
1484 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1491 g_snprintf(errmsg, errmsgl,
1492 "The capture session could not be initiated because\n"
1493 "\"%s\" is neither an interface nor a pipe", pipename);
1494 ld->cap_pipe_err = PIPNEXIST;
1498 /* Wait for the pipe to appear */
1500 ld->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1501 OPEN_EXISTING, 0, NULL);
1503 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE)
1506 if (GetLastError() != ERROR_PIPE_BUSY) {
1507 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1508 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1509 g_snprintf(errmsg, errmsgl,
1510 "The capture session on \"%s\" could not be started "
1511 "due to error on pipe open: %s (error %d)",
1512 pipename, utf_16to8(err_str), GetLastError());
1514 ld->cap_pipe_err = PIPERR;
1518 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1519 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1520 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1521 g_snprintf(errmsg, errmsgl,
1522 "The capture session on \"%s\" timed out during "
1523 "pipe open: %s (error %d)",
1524 pipename, utf_16to8(err_str), GetLastError());
1526 ld->cap_pipe_err = PIPERR;
1533 ld->from_cap_pipe = TRUE;
1536 /* read the pcap header */
1538 while (bytes_read < sizeof magic) {
1539 sel_ret = cap_pipe_select(fd);
1541 g_snprintf(errmsg, errmsgl,
1542 "Unexpected error from select: %s", strerror(errno));
1544 } else if (sel_ret > 0) {
1545 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
1548 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1550 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1557 #else /* USE_THREADS */
1558 g_thread_create(&cap_pipe_read, ld, FALSE, NULL);
1560 ld->cap_pipe_buf = (char *) &magic;
1561 ld->cap_pipe_bytes_read = 0;
1562 ld->cap_pipe_bytes_to_read = sizeof(magic);
1563 /* We don't have to worry about cap_pipe_read_mtx here */
1564 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1565 g_async_queue_pop(cap_pipe_done_q);
1566 if (ld->cap_pipe_bytes_read <= 0) {
1567 if (ld->cap_pipe_bytes_read == 0)
1568 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1570 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1575 #endif /* USE_THREADS */
1579 /* Host that wrote it has our byte order, and was running
1580 a program using either standard or ss990417 libpcap. */
1581 ld->cap_pipe_byte_swapped = FALSE;
1582 ld->cap_pipe_modified = FALSE;
1584 case PCAP_MODIFIED_MAGIC:
1585 /* Host that wrote it has our byte order, but was running
1586 a program using either ss990915 or ss991029 libpcap. */
1587 ld->cap_pipe_byte_swapped = FALSE;
1588 ld->cap_pipe_modified = TRUE;
1590 case PCAP_SWAPPED_MAGIC:
1591 /* Host that wrote it has a byte order opposite to ours,
1592 and was running a program using either standard or
1593 ss990417 libpcap. */
1594 ld->cap_pipe_byte_swapped = TRUE;
1595 ld->cap_pipe_modified = FALSE;
1597 case PCAP_SWAPPED_MODIFIED_MAGIC:
1598 /* Host that wrote it out has a byte order opposite to
1599 ours, and was running a program using either ss990915
1600 or ss991029 libpcap. */
1601 ld->cap_pipe_byte_swapped = TRUE;
1602 ld->cap_pipe_modified = TRUE;
1605 /* Not a "libpcap" type we know about. */
1606 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
1611 /* Read the rest of the header */
1613 while (bytes_read < sizeof(struct pcap_hdr)) {
1614 sel_ret = cap_pipe_select(fd);
1616 g_snprintf(errmsg, errmsgl,
1617 "Unexpected error from select: %s", strerror(errno));
1619 } else if (sel_ret > 0) {
1620 b = read(fd, ((char *)hdr)+bytes_read,
1621 sizeof(struct pcap_hdr) - bytes_read);
1624 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1626 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
1633 #else /* USE_THREADS */
1634 ld->cap_pipe_buf = (char *) hdr;
1635 ld->cap_pipe_bytes_read = 0;
1636 ld->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1637 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1638 g_async_queue_pop(cap_pipe_done_q);
1639 if (ld->cap_pipe_bytes_read <= 0) {
1640 if (ld->cap_pipe_bytes_read == 0)
1641 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1643 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
1647 #endif /* USE_THREADS */
1649 if (ld->cap_pipe_byte_swapped) {
1650 /* Byte-swap the header fields about which we care. */
1651 hdr->version_major = BSWAP16(hdr->version_major);
1652 hdr->version_minor = BSWAP16(hdr->version_minor);
1653 hdr->snaplen = BSWAP32(hdr->snaplen);
1654 hdr->network = BSWAP32(hdr->network);
1656 ld->linktype = hdr->network;
1658 if (hdr->version_major < 2) {
1659 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1663 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1664 ld->cap_pipe_err = PIPOK;
1666 ld->cap_pipe_fd = fd;
1671 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1672 ld->cap_pipe_err = PIPERR;
1675 ld->cap_pipe_fd = -1;
1682 /* We read one record from the pipe, take care of byte order in the record
1683 * header, write the record to the capture file, and update capture statistics. */
1685 cap_pipe_dispatch(loop_data *ld, guchar *data, char *errmsg, int errmsgl)
1687 struct pcap_pkthdr phdr;
1688 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1700 #ifdef LOG_CAPTURE_VERBOSE
1701 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1704 switch (ld->cap_pipe_state) {
1706 case STATE_EXPECT_REC_HDR:
1708 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1711 ld->cap_pipe_state = STATE_READ_REC_HDR;
1712 ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
1713 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1714 ld->cap_pipe_bytes_read = 0;
1717 ld->cap_pipe_buf = (char *) &ld->cap_pipe_rechdr;
1718 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1719 g_mutex_unlock(cap_pipe_read_mtx);
1724 case STATE_READ_REC_HDR:
1726 b = read(ld->cap_pipe_fd, ((char *)&ld->cap_pipe_rechdr)+ld->cap_pipe_bytes_read,
1727 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1730 result = PD_PIPE_EOF;
1732 result = PD_PIPE_ERR;
1735 ld->cap_pipe_bytes_read += b;
1736 #else /* USE_THREADS */
1737 g_get_current_time(&wait_time);
1738 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1739 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1740 if (ld->cap_pipe_err == PIPEOF) {
1741 result = PD_PIPE_EOF;
1743 } else if (ld->cap_pipe_err == PIPERR) {
1744 result = PD_PIPE_ERR;
1750 #endif /* USE_THREADS */
1751 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1753 result = PD_REC_HDR_READ;
1756 case STATE_EXPECT_DATA:
1758 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1761 ld->cap_pipe_state = STATE_READ_DATA;
1762 ld->cap_pipe_bytes_to_read = ld->cap_pipe_rechdr.hdr.incl_len;
1763 ld->cap_pipe_bytes_read = 0;
1766 ld->cap_pipe_buf = (char *) data;
1767 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1768 g_mutex_unlock(cap_pipe_read_mtx);
1773 case STATE_READ_DATA:
1775 b = read(ld->cap_pipe_fd, data+ld->cap_pipe_bytes_read,
1776 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1779 result = PD_PIPE_EOF;
1781 result = PD_PIPE_ERR;
1784 ld->cap_pipe_bytes_read += b;
1785 #else /* USE_THREADS */
1786 g_get_current_time(&wait_time);
1787 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1788 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1789 if (ld->cap_pipe_err == PIPEOF) {
1790 result = PD_PIPE_EOF;
1792 } else if (ld->cap_pipe_err == PIPERR) {
1793 result = PD_PIPE_ERR;
1799 #endif /* USE_THREADS */
1800 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1802 result = PD_DATA_READ;
1806 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
1809 } /* switch (ld->cap_pipe_state) */
1812 * We've now read as much data as we were expecting, so process it.
1816 case PD_REC_HDR_READ:
1817 /* We've read the header. Take care of byte order. */
1818 cap_pipe_adjust_header(ld->cap_pipe_byte_swapped, &ld->cap_pipe_hdr,
1819 &ld->cap_pipe_rechdr.hdr);
1820 if (ld->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1821 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
1822 ld->packet_count+1, ld->cap_pipe_rechdr.hdr.incl_len);
1825 ld->cap_pipe_state = STATE_EXPECT_DATA;
1829 /* Fill in a "struct pcap_pkthdr", and process the packet. */
1830 phdr.ts.tv_sec = ld->cap_pipe_rechdr.hdr.ts_sec;
1831 phdr.ts.tv_usec = ld->cap_pipe_rechdr.hdr.ts_usec;
1832 phdr.caplen = ld->cap_pipe_rechdr.hdr.incl_len;
1833 phdr.len = ld->cap_pipe_rechdr.hdr.orig_len;
1835 capture_loop_packet_cb((u_char *)ld, &phdr, data);
1837 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1841 ld->cap_pipe_err = PIPEOF;
1846 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1847 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1848 g_snprintf(errmsg, errmsgl,
1849 "Error reading from pipe: %s (error %d)",
1850 utf_16to8(err_str), GetLastError());
1853 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
1861 ld->cap_pipe_err = PIPERR;
1862 /* Return here rather than inside the switch to prevent GCC warning */
1867 /** Open the capture input file (pcap or capture pipe).
1868 * Returns TRUE if it succeeds, FALSE otherwise. */
1870 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
1871 char *errmsg, size_t errmsg_len,
1872 char *secondary_errmsg, size_t secondary_errmsg_len)
1874 gchar open_err_str[PCAP_ERRBUF_SIZE];
1875 gchar *sync_msg_str;
1876 static const char ppamsg[] = "can't find PPA for ";
1877 const char *set_linktype_err_str;
1878 const char *libpcap_warn;
1879 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
1883 gchar *sync_secondary_msg_str;
1884 WORD wVersionRequested;
1887 #ifdef HAVE_PCAP_REMOTE
1888 struct pcap_rmtauth auth;
1892 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
1895 /* XXX - opening Winsock on tshark? */
1897 /* Initialize Windows Socket if we are in a WIN32 OS
1898 This needs to be done before querying the interface for network/netmask */
1900 /* XXX - do we really require 1.1 or earlier?
1901 Are there any versions that support only 2.0 or higher? */
1902 wVersionRequested = MAKEWORD(1, 1);
1903 err = WSAStartup(wVersionRequested, &wsaData);
1907 case WSASYSNOTREADY:
1908 g_snprintf(errmsg, (gulong) errmsg_len,
1909 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
1912 case WSAVERNOTSUPPORTED:
1913 g_snprintf(errmsg, (gulong) errmsg_len,
1914 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
1915 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
1918 case WSAEINPROGRESS:
1919 g_snprintf(errmsg, (gulong) errmsg_len,
1920 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
1924 g_snprintf(errmsg, (gulong) errmsg_len,
1925 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
1929 g_snprintf(errmsg, (gulong) errmsg_len,
1930 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
1934 g_snprintf(errmsg, (gulong) errmsg_len,
1935 "Couldn't initialize Windows Sockets: error %d", err);
1938 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
1943 /* Open the network interface to capture from it.
1944 Some versions of libpcap may put warnings into the error buffer
1945 if they succeed; to tell if that's happened, we have to clear
1946 the error buffer, and check if it's still a null string. */
1947 open_err_str[0] = '\0';
1948 #ifdef HAVE_PCAP_OPEN
1950 * If we're opening a remote device, use pcap_open(); that's currently
1951 * the only open routine that supports remote devices.
1953 if (strncmp (capture_opts->iface, "rpcap://", 8) == 0) {
1954 auth.type = capture_opts->auth_type == CAPTURE_AUTH_PWD ?
1955 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
1956 auth.username = capture_opts->auth_username;
1957 auth.password = capture_opts->auth_password;
1959 ld->pcap_h = pcap_open(capture_opts->iface,
1960 capture_opts->has_snaplen ? capture_opts->snaplen :
1961 WTAP_MAX_PACKET_SIZE,
1963 (capture_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
1964 (capture_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
1965 (capture_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
1966 CAP_READ_TIMEOUT, &auth, open_err_str);
1968 #endif /* HAVE_PCAP_OPEN */
1971 * If we're not opening a remote device, use pcap_create() and
1972 * pcap_activate() if we have them, so that we can set the buffer
1973 * size, otherwise use pcap_open_live().
1975 #ifdef HAVE_PCAP_CREATE
1976 ld->pcap_h = pcap_create(capture_opts->iface, open_err_str);
1977 if (ld->pcap_h != NULL) {
1978 pcap_set_snaplen(ld->pcap_h, capture_opts->has_snaplen ? capture_opts->snaplen : WTAP_MAX_PACKET_SIZE);
1979 pcap_set_promisc(ld->pcap_h, capture_opts->promisc_mode);
1980 pcap_set_timeout(ld->pcap_h, CAP_READ_TIMEOUT);
1982 if (capture_opts->buffer_size > 1) {
1983 pcap_set_buffer_size(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024);
1985 if (capture_opts->monitor_mode)
1986 pcap_set_rfmon(ld->pcap_h, 1);
1987 err = pcap_activate(ld->pcap_h);
1989 /* Failed to activate, set to NULL */
1990 if (err == PCAP_ERROR)
1991 g_strlcpy(open_err_str, pcap_geterr(ld->pcap_h), sizeof open_err_str);
1993 g_strlcpy(open_err_str, pcap_statustostr(err), sizeof open_err_str);
1994 pcap_close(ld->pcap_h);
1999 ld->pcap_h = pcap_open_live(capture_opts->iface,
2000 capture_opts->has_snaplen ? capture_opts->snaplen :
2001 WTAP_MAX_PACKET_SIZE,
2002 capture_opts->promisc_mode, CAP_READ_TIMEOUT,
2007 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2008 /* to remove any suid privileges. */
2009 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2010 /* (euid/egid have already previously been set to ruid/rgid. */
2011 /* (See comment in main() for details) */
2013 relinquish_special_privs_perm();
2015 relinquish_all_capabilities();
2018 if (ld->pcap_h != NULL) {
2019 /* we've opened "iface" as a network device */
2021 /* try to set the capture buffer size */
2022 if (capture_opts->buffer_size > 1 &&
2023 pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
2024 sync_secondary_msg_str = g_strdup_printf(
2025 "The capture buffer size of %dMB seems to be too high for your machine,\n"
2026 "the default of 1MB will be used.\n"
2028 "Nonetheless, the capture is started.\n",
2029 capture_opts->buffer_size);
2030 report_capture_error("Couldn't set the capture buffer size!",
2031 sync_secondary_msg_str);
2032 g_free(sync_secondary_msg_str);
2036 #if defined(HAVE_PCAP_REMOTE) && defined(HAVE_PCAP_SETSAMPLING)
2037 if ((capture_opts->sampling_method != CAPTURE_SAMP_NONE) &&
2038 (strncmp (capture_opts->iface, "rpcap://", 8) == 0))
2040 struct pcap_samp *samp;
2042 if ((samp = pcap_setsampling(ld->pcap_h)) != NULL)
2044 switch (capture_opts->sampling_method)
2046 case CAPTURE_SAMP_BY_COUNT:
2047 samp->method = PCAP_SAMP_1_EVERY_N;
2050 case CAPTURE_SAMP_BY_TIMER:
2051 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2055 sync_msg_str = g_strdup_printf(
2056 "Unknown sampling method %d specified,\n"
2057 "continue without packet sampling",
2058 capture_opts->sampling_method);
2059 report_capture_error("Couldn't set the capture "
2060 "sampling", sync_msg_str);
2061 g_free(sync_msg_str);
2063 samp->value = capture_opts->sampling_param;
2067 report_capture_error("Couldn't set the capture sampling",
2068 "Cannot get packet sampling data structure");
2074 /* setting the data link type only works on real interfaces */
2075 if (capture_opts->linktype != -1) {
2076 set_linktype_err_str = set_pcap_linktype(ld->pcap_h, capture_opts->iface,
2077 capture_opts->linktype);
2078 if (set_linktype_err_str != NULL) {
2079 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
2080 set_linktype_err_str);
2081 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2085 ld->linktype = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
2087 /* We couldn't open "iface" as a network device. */
2088 /* Try to open it as a pipe */
2089 cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, (int) errmsg_len);
2092 if (ld->cap_pipe_fd == -1) {
2094 if (ld->cap_pipe_h == INVALID_HANDLE_VALUE) {
2097 if (ld->cap_pipe_err == PIPNEXIST) {
2098 /* Pipe doesn't exist, so output message for interface */
2100 /* If we got a "can't find PPA for X" message, warn the user (who
2101 is running (T)Wireshark on HP-UX) that they don't have a version
2102 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
2103 versions, which properly handle HP-UX, say "can't find /dev/dlpi
2104 PPA for X" rather than "can't find PPA for X"). */
2105 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
2108 "You are running (T)Wireshark with a version of the libpcap library\n"
2109 "that doesn't handle HP-UX network devices well; this means that\n"
2110 "(T)Wireshark may not be able to capture packets.\n"
2112 "To fix this, you should install libpcap 0.6.2, or a later version\n"
2113 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
2114 "packaged binary form from the Software Porting And Archive Centre\n"
2115 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
2116 "at the URL lists a number of mirror sites.";
2119 g_snprintf(errmsg, (gulong) errmsg_len,
2120 "The capture session could not be initiated (%s).", open_err_str);
2122 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
2123 "Please check to make sure you have sufficient permissions, and that you have "
2124 "the proper interface or pipe specified.%s", libpcap_warn);
2126 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
2128 "Please check that \"%s\" is the proper interface.\n"
2131 "Help can be found at:\n"
2133 " http://wiki.wireshark.org/WinPcap\n"
2134 " http://wiki.wireshark.org/CaptureSetup\n",
2135 capture_opts->iface);
2139 * Else pipe (or file) does exist and cap_pipe_open_live() has
2144 /* cap_pipe_open_live() succeeded; don't want
2145 error message from pcap_open_live() */
2146 open_err_str[0] = '\0';
2149 /* XXX - will this work for tshark? */
2150 #ifdef MUST_DO_SELECT
2151 if (!ld->from_cap_pipe) {
2152 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2153 ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
2155 ld->pcap_fd = pcap_fileno(ld->pcap_h);
2160 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2161 returned a warning; print it, but keep capturing. */
2162 if (open_err_str[0] != '\0') {
2163 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2164 report_capture_error(sync_msg_str, "");
2165 g_free(sync_msg_str);
2172 /* close the capture input file (pcap or capture pipe) */
2173 static void capture_loop_close_input(loop_data *ld) {
2175 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2177 /* if open, close the capture pipe "input file" */
2179 if (ld->cap_pipe_fd >= 0) {
2180 g_assert(ld->from_cap_pipe);
2181 ws_close(ld->cap_pipe_fd);
2182 ld->cap_pipe_fd = 0;
2185 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE) {
2186 CloseHandle(ld->cap_pipe_h);
2187 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
2191 /* if open, close the pcap "input file" */
2192 if(ld->pcap_h != NULL) {
2193 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)ld->pcap_h);
2194 g_assert(!ld->from_cap_pipe);
2195 pcap_close(ld->pcap_h);
2202 /* Shut down windows sockets */
2208 /* init the capture filter */
2209 static initfilter_status_t
2210 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe, gchar * iface, gchar * cfilter) {
2211 bpf_u_int32 netnum, netmask;
2212 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
2213 struct bpf_program fcode;
2216 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2218 /* capture filters only work on real interfaces */
2219 if (cfilter && !from_cap_pipe) {
2220 /* A capture filter was specified; set it up. */
2221 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
2223 * Well, we can't get the netmask for this interface; it's used
2224 * only for filters that check for broadcast IP addresses, so
2225 * we just punt and use 0. It might be nice to warn the user,
2226 * but that's a pain in a GUI application, as it'd involve popping
2227 * up a message box, and it's not clear how often this would make
2228 * a difference (only filters that check for IP broadcast addresses
2232 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
2235 if (pcap_compile(pcap_h, &fcode, cfilter, 1, netmask) < 0) {
2236 /* Treat this specially - our caller might try to compile this
2237 as a display filter and, if that succeeds, warn the user that
2238 the display and capture filter syntaxes are different. */
2239 return INITFILTER_BAD_FILTER;
2241 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2242 #ifdef HAVE_PCAP_FREECODE
2243 pcap_freecode(&fcode);
2245 return INITFILTER_OTHER_ERROR;
2247 #ifdef HAVE_PCAP_FREECODE
2248 pcap_freecode(&fcode);
2252 return INITFILTER_NO_ERROR;
2256 /* set up to write to the already-opened capture output file/files */
2258 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len) {
2262 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2265 if (ld->from_cap_pipe) {
2266 ld->file_snaplen = ld->cap_pipe_hdr.snaplen;
2269 ld->file_snaplen = pcap_snapshot(ld->pcap_h);
2272 /* Set up to write to the capture file. */
2273 if (capture_opts->multi_files_on) {
2274 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2276 ld->pdh = libpcap_fdopen(ld->save_file_fd, &err);
2279 gboolean successful;
2281 ld->bytes_written = 0;
2282 if (capture_opts->use_pcapng) {
2285 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2286 successful = libpcap_write_session_header_block(ld->pdh, appname, &ld->bytes_written, &err) &&
2287 libpcap_write_interface_description_block(ld->pdh, capture_opts->iface, capture_opts->cfilter, ld->linktype, ld->file_snaplen, &ld->bytes_written, &err);
2289 successful = libpcap_write_file_header(ld->pdh, ld->linktype, ld->file_snaplen,
2290 &ld->bytes_written, &err);
2298 if (ld->pdh == NULL) {
2299 /* We couldn't set up to write to the capture file. */
2300 /* XXX - use cf_open_error_message from tshark instead? */
2303 case WTAP_ERR_CANT_OPEN:
2304 g_snprintf(errmsg, errmsg_len, "The file to which the capture would be saved"
2305 " couldn't be created for some unknown reason.");
2308 case WTAP_ERR_SHORT_WRITE:
2309 g_snprintf(errmsg, errmsg_len, "A full header couldn't be written to the file"
2310 " to which the capture would be saved.");
2315 g_snprintf(errmsg, errmsg_len,
2316 "The file to which the capture would be"
2317 " saved (\"%s\") could not be opened: Error %d.",
2318 capture_opts->save_file, err);
2320 g_snprintf(errmsg, errmsg_len,
2321 "The file to which the capture would be"
2322 " saved (\"%s\") could not be opened: %s.",
2323 capture_opts->save_file, strerror(err));
2335 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
2337 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2339 if (capture_opts->multi_files_on) {
2340 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2342 if (capture_opts->use_pcapng) {
2343 libpcap_write_interface_statistics_block(ld->pdh, 0, ld->pcap_h, &ld->bytes_written, err_close);
2345 return libpcap_dump_close(ld->pdh, err_close);
2349 /* dispatch incoming packets (pcap or capture pipe)
2351 * Waits for incoming packets to be available, and calls pcap_dispatch()
2352 * to cause them to be processed.
2354 * Returns the number of packets which were processed.
2356 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2357 * packet-batching behaviour does not cause packets to get held back
2361 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
2362 char *errmsg, int errmsg_len)
2365 gint packet_count_before;
2366 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
2371 packet_count_before = ld->packet_count;
2372 if (ld->from_cap_pipe) {
2373 /* dispatch from capture pipe */
2374 #ifdef LOG_CAPTURE_VERBOSE
2375 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2378 sel_ret = cap_pipe_select(ld->cap_pipe_fd);
2381 if (sel_ret < 0 && errno != EINTR) {
2382 g_snprintf(errmsg, errmsg_len,
2383 "Unexpected error from select: %s", strerror(errno));
2384 report_capture_error(errmsg, please_report);
2389 * "select()" says we can read from the pipe without blocking
2391 #endif /* USE_THREADS */
2392 inpkts = cap_pipe_dispatch(ld, pcap_data, errmsg, errmsg_len);
2402 /* dispatch from pcap */
2403 #ifdef MUST_DO_SELECT
2405 * If we have "pcap_get_selectable_fd()", we use it to get the
2406 * descriptor on which to select; if that's -1, it means there
2407 * is no descriptor on which you can do a "select()" (perhaps
2408 * because you're capturing on a special device, and that device's
2409 * driver unfortunately doesn't support "select()", in which case
2410 * we don't do the select - which means it might not be possible
2411 * to stop a capture until a packet arrives. If that's unacceptable,
2412 * plead with whoever supplies the software for that device to add
2413 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2414 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2415 * later, so it can use pcap_breakloop().
2417 #ifdef LOG_CAPTURE_VERBOSE
2418 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2420 if (ld->pcap_fd != -1) {
2421 sel_ret = cap_pipe_select(ld->pcap_fd);
2424 * "select()" says we can read from it without blocking; go for
2427 * We don't have pcap_breakloop(), so we only process one packet
2428 * per pcap_dispatch() call, to allow a signal to stop the
2429 * processing immediately, rather than processing all packets
2430 * in a batch before quitting.
2432 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb,
2436 /* Error, rather than pcap_breakloop(). */
2437 ld->pcap_err = TRUE;
2439 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2442 if (sel_ret < 0 && errno != EINTR) {
2443 g_snprintf(errmsg, errmsg_len,
2444 "Unexpected error from select: %s", strerror(errno));
2445 report_capture_error(errmsg, please_report);
2451 #endif /* MUST_DO_SELECT */
2453 /* dispatch from pcap without select */
2455 #ifdef LOG_CAPTURE_VERBOSE
2456 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2460 * On Windows, we don't support asynchronously telling a process to
2461 * stop capturing; instead, we check for an indication on a pipe
2462 * after processing packets. We therefore process only one packet
2463 * at a time, so that we can check the pipe after every packet.
2465 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb, (u_char *) ld);
2467 inpkts = pcap_dispatch(ld->pcap_h, -1, capture_loop_packet_cb, (u_char *) ld);
2471 /* Error, rather than pcap_breakloop(). */
2472 ld->pcap_err = TRUE;
2474 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2476 #else /* pcap_next_ex */
2477 #ifdef LOG_CAPTURE_VERBOSE
2478 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2480 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2483 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2484 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
2485 * This should be fixed in the WinPcap 4.0 alpha release.
2487 * For reference, an example remote interface:
2488 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2491 /* emulate dispatch from pcap */
2494 struct pcap_pkthdr *pkt_header;
2499 (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1)
2500 capture_loop_packet_cb( (u_char *) ld, pkt_header, pkt_data);
2503 ld->pcap_err = TRUE;
2507 #endif /* pcap_next_ex */
2511 #ifdef LOG_CAPTURE_VERBOSE
2512 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2515 return ld->packet_count - packet_count_before;
2519 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2520 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2522 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2523 char *errmsg, int errmsg_len) {
2526 gchar *capfile_name;
2527 gboolean is_tempfile;
2532 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2533 (capture_opts->save_file) ? capture_opts->save_file : "");
2535 if (capture_opts->save_file != NULL) {
2536 /* We return to the caller while the capture is in progress.
2537 * Therefore we need to take a copy of save_file in
2538 * case the caller destroys it after we return.
2540 capfile_name = g_strdup(capture_opts->save_file);
2542 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2543 if (capture_opts->multi_files_on) {
2544 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2545 g_snprintf(errmsg, errmsg_len,
2546 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2547 g_free(capfile_name);
2550 if (strcmp(capfile_name, "-") == 0) {
2551 /* write to stdout */
2554 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
2555 _setmode(1, O_BINARY);
2558 } /* if (...output_to_pipe ... */
2561 if (capture_opts->multi_files_on) {
2562 /* ringbuffer is enabled */
2563 *save_file_fd = ringbuf_init(capfile_name,
2564 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
2566 /* we need the ringbuf name */
2567 if(*save_file_fd != -1) {
2568 g_free(capfile_name);
2569 capfile_name = g_strdup(ringbuf_current_filename());
2572 /* Try to open/create the specified file for use as a capture buffer. */
2573 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
2577 is_tempfile = FALSE;
2579 /* Choose a random name for the temporary capture buffer */
2580 *save_file_fd = create_tempfile(&tmpname, "wireshark");
2581 capfile_name = g_strdup(tmpname);
2585 /* did we fail to open the output file? */
2586 if (*save_file_fd == -1) {
2588 g_snprintf(errmsg, errmsg_len,
2589 "The temporary file to which the capture would be saved (\"%s\") "
2590 "could not be opened: %s.", capfile_name, strerror(errno));
2592 if (capture_opts->multi_files_on) {
2593 ringbuf_error_cleanup();
2596 g_snprintf(errmsg, errmsg_len,
2597 "The file to which the capture would be saved (\"%s\") "
2598 "could not be opened: %s.", capfile_name,
2601 g_free(capfile_name);
2605 if(capture_opts->save_file != NULL) {
2606 g_free(capture_opts->save_file);
2608 capture_opts->save_file = capfile_name;
2609 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2610 "g_free(capfile_name)". */
2612 ret = fchown(*save_file_fd, capture_opts->owner, capture_opts->group);
2620 #define TIME_GET() GetTickCount()
2622 #define TIME_GET() time(NULL)
2625 /* Do the work of handling either the file size or file duration capture
2626 conditions being reached, and switching files or stopping. */
2628 do_file_switch_or_stop(capture_options *capture_opts,
2629 condition *cnd_autostop_files,
2630 condition *cnd_autostop_size,
2631 condition *cnd_file_duration)
2633 if (capture_opts->multi_files_on) {
2634 if (cnd_autostop_files != NULL &&
2635 cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
2636 /* no files left: stop here */
2637 global_ld.go = FALSE;
2641 /* Switch to the next ringbuffer file */
2642 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2643 &global_ld.save_file_fd, &global_ld.err)) {
2644 gboolean successful;
2646 /* File switch succeeded: reset the conditions */
2647 global_ld.bytes_written = 0;
2648 if (capture_opts->use_pcapng) {
2651 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2652 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2653 libpcap_write_interface_description_block(global_ld.pdh, capture_opts->iface, capture_opts->cfilter, global_ld.linktype, global_ld.file_snaplen, &global_ld.bytes_written, &global_ld.err);
2655 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2656 &global_ld.bytes_written, &global_ld.err);
2659 fclose(global_ld.pdh);
2660 global_ld.pdh = NULL;
2661 global_ld.go = FALSE;
2664 if(cnd_autostop_size)
2665 cnd_reset(cnd_autostop_size);
2666 if(cnd_file_duration)
2667 cnd_reset(cnd_file_duration);
2668 libpcap_dump_flush(global_ld.pdh, NULL);
2670 report_packet_count(global_ld.inpkts_to_sync_pipe);
2671 global_ld.inpkts_to_sync_pipe = 0;
2672 report_new_capture_file(capture_opts->save_file);
2674 /* File switch failed: stop here */
2675 global_ld.go = FALSE;
2679 /* single file, stop now */
2680 global_ld.go = FALSE;
2686 /* Do the low-level work of a capture.
2687 Returns TRUE if it succeeds, FALSE otherwise. */
2689 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
2691 time_t upd_time, cur_time;
2695 condition *cnd_file_duration = NULL;
2696 condition *cnd_autostop_files = NULL;
2697 condition *cnd_autostop_size = NULL;
2698 condition *cnd_autostop_duration = NULL;
2701 gboolean cfilter_error = FALSE;
2702 #define MSG_MAX_LENGTH 4096
2703 char errmsg[MSG_MAX_LENGTH+1];
2704 char secondary_errmsg[MSG_MAX_LENGTH+1];
2707 *secondary_errmsg = '\0';
2709 /* init the loop data */
2710 global_ld.go = TRUE;
2711 global_ld.packet_count = 0;
2713 global_ld.report_packet_count = FALSE;
2715 if (capture_opts->has_autostop_packets)
2716 global_ld.packet_max = capture_opts->autostop_packets;
2718 global_ld.packet_max = 0; /* no limit */
2719 global_ld.inpkts_to_sync_pipe = 0;
2720 global_ld.err = 0; /* no error seen yet */
2721 global_ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
2722 global_ld.pcap_err = FALSE;
2723 global_ld.from_cap_pipe = FALSE;
2724 global_ld.pdh = NULL;
2726 global_ld.cap_pipe_fd = -1;
2728 global_ld.cap_pipe_h = INVALID_HANDLE_VALUE;
2730 #ifdef MUST_DO_SELECT
2731 global_ld.pcap_fd = 0;
2733 global_ld.autostop_files = 0;
2734 global_ld.save_file_fd = -1;
2736 /* We haven't yet gotten the capture statistics. */
2737 *stats_known = FALSE;
2739 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
2740 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
2742 /* open the "input file" from network interface or capture pipe */
2743 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
2744 secondary_errmsg, sizeof(secondary_errmsg))) {
2748 /* init the input filter from the network interface (capture pipe will do nothing) */
2749 switch (capture_loop_init_filter(global_ld.pcap_h, global_ld.from_cap_pipe,
2750 capture_opts->iface,
2751 capture_opts->cfilter)) {
2753 case INITFILTER_NO_ERROR:
2756 case INITFILTER_BAD_FILTER:
2757 cfilter_error = TRUE;
2758 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(global_ld.pcap_h));
2761 case INITFILTER_OTHER_ERROR:
2762 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
2763 pcap_geterr(global_ld.pcap_h));
2764 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
2768 /* If we're supposed to write to a capture file, open it for output
2769 (temporary/specified name/ringbuffer) */
2770 if (capture_opts->saving_to_file) {
2771 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
2772 errmsg, sizeof(errmsg))) {
2776 /* set up to write to the already-opened capture output file/files */
2777 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
2782 /* XXX - capture SIGTERM and close the capture, in case we're on a
2783 Linux 2.0[.x] system and you have to explicitly close the capture
2784 stream in order to turn promiscuous mode off? We need to do that
2785 in other places as well - and I don't think that works all the
2786 time in any case, due to libpcap bugs. */
2788 /* Well, we should be able to start capturing.
2790 Sync out the capture file, so the header makes it to the file system,
2791 and send a "capture started successfully and capture file created"
2792 message to our parent so that they'll open the capture file and
2793 update its windows to indicate that we have a live capture in
2795 libpcap_dump_flush(global_ld.pdh, NULL);
2796 report_new_capture_file(capture_opts->save_file);
2799 /* initialize capture stop (and alike) conditions */
2800 init_capture_stop_conditions();
2801 /* create stop conditions */
2802 if (capture_opts->has_autostop_filesize)
2804 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
2805 if (capture_opts->has_autostop_duration)
2806 cnd_autostop_duration =
2807 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
2809 if (capture_opts->multi_files_on) {
2810 if (capture_opts->has_file_duration)
2812 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
2814 if (capture_opts->has_autostop_files)
2815 cnd_autostop_files =
2816 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
2819 /* init the time values */
2820 start_time = TIME_GET();
2821 upd_time = TIME_GET();
2823 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
2825 /* WOW, everything is prepared! */
2826 /* please fasten your seat belts, we will enter now the actual capture loop */
2827 while (global_ld.go) {
2828 /* dispatch incoming packets */
2829 inpkts = capture_loop_dispatch(capture_opts, &global_ld, errmsg,
2833 /* Were we asked to print packet counts by the SIGINFO handler? */
2834 if (global_ld.report_packet_count) {
2835 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
2836 plurality(global_ld.packet_count, "", "s"));
2837 global_ld.report_packet_count = FALSE;
2842 /* any news from our parent (signal pipe)? -> just stop the capture */
2843 if (!signal_pipe_check_running()) {
2844 global_ld.go = FALSE;
2849 global_ld.inpkts_to_sync_pipe += inpkts;
2851 /* check capture size condition */
2852 if (cnd_autostop_size != NULL &&
2853 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)) {
2854 /* Capture size limit reached, do we have another file? */
2855 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
2856 cnd_autostop_size, cnd_file_duration))
2858 } /* cnd_autostop_size */
2859 if (capture_opts->output_to_pipe) {
2860 libpcap_dump_flush(global_ld.pdh, NULL);
2864 /* Only update once a second (Win32: 500ms) so as not to overload slow
2865 * displays. This also prevents too much context-switching between the
2866 * dumpcap and wireshark processes */
2867 cur_time = TIME_GET();
2869 if ( (cur_time - upd_time) > 500) {
2871 if (cur_time - upd_time > 0) {
2873 upd_time = cur_time;
2875 /*if (pcap_stats(pch, stats) >= 0) {
2876 *stats_known = TRUE;
2879 /* Let the parent process know. */
2880 if (global_ld.inpkts_to_sync_pipe) {
2882 libpcap_dump_flush(global_ld.pdh, NULL);
2884 /* Send our parent a message saying we've written out
2885 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
2887 report_packet_count(global_ld.inpkts_to_sync_pipe);
2889 global_ld.inpkts_to_sync_pipe = 0;
2892 /* check capture duration condition */
2893 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
2894 /* The maximum capture time has elapsed; stop the capture. */
2895 global_ld.go = FALSE;
2899 /* check capture file duration condition */
2900 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
2901 /* duration limit reached, do we have another file? */
2902 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
2903 cnd_autostop_size, cnd_file_duration))
2905 } /* cnd_file_duration */
2908 } /* while (global_ld.go) */
2910 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
2912 /* delete stop conditions */
2913 if (cnd_file_duration != NULL)
2914 cnd_delete(cnd_file_duration);
2915 if (cnd_autostop_files != NULL)
2916 cnd_delete(cnd_autostop_files);
2917 if (cnd_autostop_size != NULL)
2918 cnd_delete(cnd_autostop_size);
2919 if (cnd_autostop_duration != NULL)
2920 cnd_delete(cnd_autostop_duration);
2922 /* did we had a pcap (input) error? */
2923 if (global_ld.pcap_err) {
2924 /* On Linux, if an interface goes down while you're capturing on it,
2925 you'll get a "recvfrom: Network is down" error (ENETDOWN).
2926 (At least you will if strerror() doesn't show a local translation
2929 On FreeBSD and OS X, if a network adapter disappears while
2930 you're capturing on it, you'll get a "read: Device not configured"
2931 error (ENXIO). (See previous parenthetical note.)
2933 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
2935 These should *not* be reported to the Wireshark developers. */
2938 cap_err_str = pcap_geterr(global_ld.pcap_h);
2939 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
2940 strcmp(cap_err_str, "read: Device not configured") == 0 ||
2941 strcmp(cap_err_str, "read: I/O error") == 0) {
2942 report_capture_error("The network adapter on which the capture was being done "
2943 "is no longer running; the capture has stopped.",
2946 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
2948 report_capture_error(errmsg, please_report);
2951 else if (global_ld.from_cap_pipe && global_ld.cap_pipe_err == PIPERR)
2952 report_capture_error(errmsg, "");
2954 /* did we had an error while capturing? */
2955 if (global_ld.err == 0) {
2958 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
2959 global_ld.err, FALSE);
2960 report_capture_error(errmsg, please_report);
2964 if (capture_opts->saving_to_file) {
2965 /* close the wiretap (output) file */
2966 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
2970 /* there might be packets not yet notified to the parent */
2971 /* (do this after closing the file, so all packets are already flushed) */
2972 if(global_ld.inpkts_to_sync_pipe) {
2974 report_packet_count(global_ld.inpkts_to_sync_pipe);
2975 global_ld.inpkts_to_sync_pipe = 0;
2978 /* If we've displayed a message about a write error, there's no point
2979 in displaying another message about an error on close. */
2980 if (!close_ok && write_ok) {
2981 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
2983 report_capture_error(errmsg, "");
2987 * XXX We exhibit different behaviour between normal mode and sync mode
2988 * when the pipe is stdin and not already at EOF. If we're a child, the
2989 * parent's stdin isn't closed, so if the user starts another capture,
2990 * cap_pipe_open_live() will very likely not see the expected magic bytes and
2991 * will say "Unrecognized libpcap format". On the other hand, in normal
2992 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
2995 /* get packet drop statistics from pcap */
2996 if(global_ld.pcap_h != NULL) {
2997 g_assert(!global_ld.from_cap_pipe);
2998 /* Get the capture statistics, so we know how many packets were
3000 if (pcap_stats(global_ld.pcap_h, stats) >= 0) {
3001 *stats_known = TRUE;
3002 /* Let the parent process know. */
3003 report_packet_drops(stats->ps_drop);
3005 g_snprintf(errmsg, sizeof(errmsg),
3006 "Can't get packet-drop statistics: %s",
3007 pcap_geterr(global_ld.pcap_h));
3008 report_capture_error(errmsg, please_report);
3012 /* close the input file (pcap or capture pipe) */
3013 capture_loop_close_input(&global_ld);
3015 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
3017 /* ok, if the write and the close were successful. */
3018 return write_ok && close_ok;
3021 if (capture_opts->multi_files_on) {
3022 /* cleanup ringbuffer */
3023 ringbuf_error_cleanup();
3025 /* We can't use the save file, and we have no FILE * for the stream
3026 to close in order to close it, so close the FD directly. */
3027 if(global_ld.save_file_fd != -1) {
3028 ws_close(global_ld.save_file_fd);
3031 /* We couldn't even start the capture, so get rid of the capture
3033 if(capture_opts->save_file != NULL) {
3034 ws_unlink(capture_opts->save_file);
3035 g_free(capture_opts->save_file);
3038 capture_opts->save_file = NULL;
3040 report_cfilter_error(capture_opts->cfilter, errmsg);
3042 report_capture_error(errmsg, secondary_errmsg);
3044 /* close the input file (pcap or cap_pipe) */
3045 capture_loop_close_input(&global_ld);
3047 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3053 static void capture_loop_stop(void)
3055 #ifdef HAVE_PCAP_BREAKLOOP
3056 if(global_ld.pcap_h != NULL)
3057 pcap_breakloop(global_ld.pcap_h);
3059 global_ld.go = FALSE;
3064 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3065 int err, gboolean is_close)
3070 g_snprintf(errmsg, errmsglen,
3071 "Not all the packets could be written to the file"
3072 " to which the capture was being saved\n"
3073 "(\"%s\") because there is no space left on the file system\n"
3074 "on which that file resides.",
3080 g_snprintf(errmsg, errmsglen,
3081 "Not all the packets could be written to the file"
3082 " to which the capture was being saved\n"
3083 "(\"%s\") because you are too close to, or over,"
3084 " your disk quota\n"
3085 "on the file system on which that file resides.",
3090 case WTAP_ERR_CANT_CLOSE:
3091 g_snprintf(errmsg, errmsglen,
3092 "The file to which the capture was being saved"
3093 " couldn't be closed for some unknown reason.");
3096 case WTAP_ERR_SHORT_WRITE:
3097 g_snprintf(errmsg, errmsglen,
3098 "Not all the packets could be written to the file"
3099 " to which the capture was being saved\n"
3106 g_snprintf(errmsg, errmsglen,
3107 "The file to which the capture was being saved\n"
3108 "(\"%s\") could not be closed: %s.",
3109 fname, wtap_strerror(err));
3111 g_snprintf(errmsg, errmsglen,
3112 "An error occurred while writing to the file"
3113 " to which the capture was being saved\n"
3115 fname, wtap_strerror(err));
3122 /* one packet was captured, process it */
3124 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
3127 loop_data *ld = (loop_data *) (void *) user;
3130 /* We may be called multiple times from pcap_dispatch(); if we've set
3131 the "stop capturing" flag, ignore this packet, as we're not
3132 supposed to be saving any more packets. */
3137 gboolean successful;
3138 /* We're supposed to write the packet to a file; do so.
3139 If this fails, set "ld->go" to FALSE, to stop the capture, and set
3140 "ld->err" to the error. */
3141 if (global_capture_opts.use_pcapng) {
3142 successful = libpcap_write_enhanced_packet_block(ld->pdh, phdr, 0, pd, &ld->bytes_written, &err);
3144 successful = libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err);
3151 /* if the user told us to stop after x packets, do we already have enough? */
3152 if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
3161 /* And now our feature presentation... [ fade to music ] */
3163 main(int argc, char *argv[])
3166 gboolean arg_error = FALSE;
3171 struct sigaction action, oldaction;
3174 gboolean start_capture = TRUE;
3175 gboolean stats_known;
3176 struct pcap_stat stats;
3177 GLogLevelFlags log_flags;
3178 gboolean list_interfaces = FALSE;
3179 gboolean list_link_layer_types = FALSE;
3180 gboolean machine_readable = FALSE;
3181 gboolean print_statistics = FALSE;
3182 int status, run_once_args = 0;
3184 #if defined(__APPLE__) && defined(__LP64__)
3185 struct utsname osinfo;
3188 #ifdef HAVE_PCAP_REMOTE
3189 #define OPTSTRING_A "A:"
3190 #define OPTSTRING_r "r"
3191 #define OPTSTRING_u "u"
3193 #define OPTSTRING_A ""
3194 #define OPTSTRING_r ""
3195 #define OPTSTRING_u ""
3198 #ifdef HAVE_PCAP_SETSAMPLING
3199 #define OPTSTRING_m "m:"
3201 #define OPTSTRING_m ""
3204 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
3205 #define OPTSTRING_B "B:"
3207 #define OPTSTRING_B ""
3208 #endif /* _WIN32 or HAVE_PCAP_CREATE */
3210 #ifdef HAVE_PCAP_CREATE
3211 #define OPTSTRING_I "I"
3213 #define OPTSTRING_I ""
3216 #define OPTSTRING "a:" OPTSTRING_A "b:" OPTSTRING_B "c:Df:hi:" OPTSTRING_I "L" OPTSTRING_m "Mnpq" OPTSTRING_r "Ss:" OPTSTRING_u "vw:y:Z:"
3218 #ifdef DEBUG_CHILD_DUMPCAP
3219 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
3220 fprintf (stderr, "Unable to open debug log file !\n");
3225 #if defined(__APPLE__) && defined(__LP64__)
3227 * Is this Mac OS X 10.6.x, other than 10.6.2? If so, we need a bug
3228 * workaround - timeouts less than 1 second don't work with libpcap
3229 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
3230 * and re-introduced in 10.6.3. We don't know whether it'll be fixed
3231 * again in a later 10.6.x release; we'll assume that it'll be fixed
3232 * in any future major releases.)
3234 if (uname(&osinfo) == 0) {
3236 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
3237 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
3238 * number of 10.0.0, not 10.1.0 - go figure).
3240 if (strncmp(osinfo.release, "10.", 3) == 0) {
3242 * OK, it's Snow Leopard - which version?
3244 if (strcmp(osinfo.release, "10.2.0") != 0) {
3246 need_timeout_workaround = TRUE;
3253 * Determine if dumpcap is being requested to run in a special
3254 * capture_child mode by going thru the command line args to see if
3255 * a -Z is present. (-Z is a hidden option).
3257 * The primary result of running in capture_child mode is that
3258 * all messages sent out on stderr are in a special type/len/string
3259 * format to allow message processing by type. These messages include
3260 * error messages if dumpcap fails to start the operation it was
3261 * requested to do, as well as various "status" messages which are sent
3262 * when an actual capture is in progress, and a "success" message sent
3263 * if dumpcap was requested to perform an operation other than a
3266 * Capture_child mode would normally be requested by a parent process
3267 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
3268 * to which dumpcap stderr has been redirected. It might also have
3269 * another pipe to obtain dumpcap stdout output; for operations other
3270 * than a capture, that information is formatted specially for easier
3271 * parsing by the parent process.
3273 * Capture_child mode needs to be determined immediately upon
3274 * startup so that any messages generated by dumpcap in this mode
3275 * (eg: during initialization) will be formatted properly.
3278 for (i=1; i<argc; i++) {
3279 if (strcmp("-Z", argv[i]) == 0) {
3280 capture_child = TRUE;
3281 machine_readable = TRUE; /* request machine-readable output */
3283 /* set output pipe to binary mode, to avoid ugly text conversions */
3284 _setmode(2, O_BINARY);
3289 /* The default_log_handler will use stdout, which makes trouble in */
3290 /* capture child mode, as it uses stdout for it's sync_pipe. */
3291 /* So: the filtering is done in the console_log_handler and not here.*/
3292 /* We set the log handlers right up front to make sure that any log */
3293 /* messages when running as child will be sent back to the parent */
3294 /* with the correct format. */
3298 G_LOG_LEVEL_CRITICAL|
3299 G_LOG_LEVEL_WARNING|
3300 G_LOG_LEVEL_MESSAGE|
3303 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
3305 g_log_set_handler(NULL,
3307 console_log_handler, NULL /* user_data */);
3308 g_log_set_handler(LOG_DOMAIN_MAIN,
3310 console_log_handler, NULL /* user_data */);
3311 g_log_set_handler(LOG_DOMAIN_CAPTURE,
3313 console_log_handler, NULL /* user_data */);
3314 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
3316 console_log_handler, NULL /* user_data */);
3319 /* Load wpcap if possible. Do this before collecting the run-time version information */
3322 /* ... and also load the packet.dll from wpcap */
3323 /* XXX - currently not required, may change later. */
3324 /*wpcap_packet_load();*/
3326 /* Start windows sockets */
3327 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
3329 /* Set handler for Ctrl+C key */
3330 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
3332 /* Prepare to read from a pipe */
3333 if (!g_thread_supported ())
3334 g_thread_init (NULL);
3335 cap_pipe_pending_q = g_async_queue_new();
3336 cap_pipe_done_q = g_async_queue_new();
3337 cap_pipe_read_mtx = g_mutex_new();
3340 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
3342 action.sa_handler = capture_cleanup_handler;
3344 * Arrange that system calls not get restarted, because when
3345 * our signal handler returns we don't want to restart
3346 * a call that was waiting for packets to arrive.
3348 action.sa_flags = 0;
3349 sigemptyset(&action.sa_mask);
3350 sigaction(SIGTERM, &action, NULL);
3351 sigaction(SIGINT, &action, NULL);
3352 sigaction(SIGPIPE, &action, NULL);
3353 sigaction(SIGHUP, NULL, &oldaction);
3354 if (oldaction.sa_handler == SIG_DFL)
3355 sigaction(SIGHUP, &action, NULL);
3358 /* Catch SIGINFO and, if we get it and we're capturing in
3359 quiet mode, report the number of packets we've captured. */
3360 action.sa_handler = report_counts_siginfo;
3361 action.sa_flags = SA_RESTART;
3362 sigemptyset(&action.sa_mask);
3363 sigaction(SIGINFO, &action, NULL);
3364 #endif /* SIGINFO */
3367 /* ----------------------------------------------------------------- */
3368 /* Privilege and capability handling */
3370 /* 1. Running not as root or suid root; no special capabilities. */
3373 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
3376 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
3378 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
3379 /* capabilities; Drop all other capabilities; */
3380 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3381 /* else: after pcap_open_live() in capture_loop_open_input() */
3382 /* drop all capabilities (NET_RAW and NET_ADMIN); */
3383 /* (Note: this means that the process, although logged in */
3384 /* as root, does not have various permissions such as the */
3385 /* ability to bypass file access permissions). */
3386 /* XXX: Should we just leave capabilities alone in this case */
3387 /* so that user gets expected effect that root can do */
3390 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
3392 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3393 /* else: after pcap_open_live() in capture_loop_open_input() */
3394 /* drop suid root (set euid=ruid).(ie: keep suid until after */
3395 /* pcap_open_live). */
3397 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
3399 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
3400 /* capabilities; Drop all other capabilities; */
3401 /* Drop suid privileges (euid=ruid); */
3402 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3403 /* else: after pcap_open_live() in capture_loop_open_input() */
3404 /* drop all capabilities (NET_RAW and NET_ADMIN). */
3406 /* XXX: For some Linux versions/distros with capabilities */
3407 /* a 'normal' process with any capabilities cannot be */
3408 /* 'killed' (signaled) from another (same uid) non-privileged */
3410 /* For example: If (non-suid) Wireshark forks a */
3411 /* child suid dumpcap which acts as described here (case 5), */
3412 /* Wireshark will be unable to kill (signal) the child */
3413 /* dumpcap process until the capabilities have been dropped */
3414 /* (after pcap_open_live()). */
3415 /* This behaviour will apparently be changed in the kernel */
3416 /* to allow the kill (signal) in this case. */
3417 /* See the following for details: */
3418 /* http://www.mail-archive.com/ [wrapped] */
3419 /* linux-security-module@vger.kernel.org/msg02913.html */
3421 /* It is therefore conceivable that if dumpcap somehow hangs */
3422 /* in pcap_open_live or before that wireshark will not */
3423 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
3424 /* In this case, exiting wireshark will kill the child */
3425 /* dumpcap process. */
3427 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
3428 /* capabilities; Using libcap. Note: capset cmd (which see) */
3429 /* used to assign capabilities to file. */
3431 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3432 /* else: after pcap_open_live() in capture_loop_open_input() */
3433 /* drop all capabilities (NET_RAW and NET_ADMIN) */
3435 /* ToDo: -S (stats) should drop privileges/capabilities when no */
3436 /* longer required (similar to capture). */
3438 /* ----------------------------------------------------------------- */
3440 get_credential_info();
3443 /* If 'started with special privileges' (and using libcap) */
3444 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
3445 /* Set euid/egid = ruid/rgid to remove suid privileges */
3446 relinquish_privs_except_capture();
3449 /* Set the initial values in the capture options. This might be overwritten
3450 by the command line parameters. */
3451 capture_opts_init(&global_capture_opts, NULL);
3453 /* Default to capturing the entire packet. */
3454 global_capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
3456 /* We always save to a file - if no file was specified, we save to a
3458 global_capture_opts.saving_to_file = TRUE;
3459 global_capture_opts.has_ring_num_files = TRUE;
3461 /* Now get our args */
3462 while ((opt = getopt(argc, argv, OPTSTRING)) != -1) {
3464 case 'h': /* Print help and exit */
3468 case 'v': /* Show version and exit */
3470 GString *comp_info_str;
3471 GString *runtime_info_str;
3472 /* Assemble the compile-time version information string */
3473 comp_info_str = g_string_new("Compiled ");
3474 get_compiled_version_info(comp_info_str, NULL);
3476 /* Assemble the run-time version information string */
3477 runtime_info_str = g_string_new("Running ");
3478 get_runtime_version_info(runtime_info_str, NULL);
3479 show_version(comp_info_str, runtime_info_str);
3480 g_string_free(comp_info_str, TRUE);
3481 g_string_free(runtime_info_str, TRUE);
3485 /*** capture option specific ***/
3486 case 'a': /* autostop criteria */
3487 case 'b': /* Ringbuffer option */
3488 case 'c': /* Capture x packets */
3489 case 'f': /* capture filter */
3490 case 'i': /* Use interface x */
3491 case 'n': /* Use pcapng format */
3492 case 'p': /* Don't capture in promiscuous mode */
3493 case 's': /* Set the snapshot (capture) length */
3494 case 'w': /* Write to capture file x */
3495 case 'y': /* Set the pcap data link type */
3496 #ifdef HAVE_PCAP_REMOTE
3497 case 'u': /* Use UDP for data transfer */
3498 case 'r': /* Capture own RPCAP traffic too */
3499 case 'A': /* Authentication */
3501 #ifdef HAVE_PCAP_SETSAMPLING
3502 case 'm': /* Sampling */
3504 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
3505 case 'B': /* Buffer size */
3506 #endif /* _WIN32 or HAVE_PCAP_CREATE */
3507 #ifdef HAVE_PCAP_CREATE
3508 case 'I': /* Monitor mode */
3510 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
3515 /*** hidden option: Wireshark child mode (using binary output messages) ***/
3517 capture_child = TRUE;
3519 /* set output pipe to binary mode, to avoid ugly text conversions */
3520 _setmode(2, O_BINARY);
3522 * optarg = the control ID, aka the PPID, currently used for the
3525 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
3526 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
3527 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
3528 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
3530 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
3531 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3532 "Signal pipe: Unable to open %s. Dead parent?",
3540 case 'q': /* Quiet */
3544 /*** all non capture option specific ***/
3545 case 'D': /* Print a list of capture devices and exit */
3546 list_interfaces = TRUE;
3549 case 'L': /* Print list of link-layer types and exit */
3550 list_link_layer_types = TRUE;
3553 case 'S': /* Print interface statistics once a second */
3554 print_statistics = TRUE;
3557 case 'M': /* For -D, -L, and -S, print machine-readable output */
3558 machine_readable = TRUE;
3561 case '?': /* Bad flag - print usage message */
3562 cmdarg_err("Invalid Option: %s", argv[optind-1]);
3570 /* user specified file name as regular command-line argument */
3571 /* XXX - use it as the capture file name (or something else)? */
3578 * Extra command line arguments were specified; complain.
3579 * XXX - interpret as capture filter, as tcpdump and tshark do?
3581 cmdarg_err("Invalid argument: %s", argv[0]);
3590 if (run_once_args > 1) {
3591 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
3593 } else if (run_once_args == 1) {
3594 /* We're supposed to print some information, rather than
3595 to capture traffic; did they specify a ring buffer option? */
3596 if (global_capture_opts.multi_files_on) {
3597 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
3601 /* We're supposed to capture traffic; was the ring buffer option
3602 specified and, if so, does it make sense? */
3603 if (global_capture_opts.multi_files_on) {
3604 /* Ring buffer works only under certain conditions:
3605 a) ring buffer does not work with temporary files;
3606 b) it makes no sense to enable the ring buffer if the maximum
3607 file size is set to "infinite". */
3608 if (global_capture_opts.save_file == NULL) {
3609 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
3610 global_capture_opts.multi_files_on = FALSE;
3612 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
3613 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
3614 /* XXX - this must be redesigned as the conditions changed */
3615 /* global_capture_opts.multi_files_on = FALSE;*/
3621 * "-D" requires no interface to be selected; it's supposed to list
3624 if (list_interfaces) {
3625 /* Get the list of interfaces */
3630 if_list = capture_interface_list(&err, &err_str);
3631 if (if_list == NULL) {
3633 case CANT_GET_INTERFACE_LIST:
3634 cmdarg_err("%s", err_str);
3639 case NO_INTERFACES_FOUND:
3641 * If we're being run by another program, just give them
3642 * an empty list of interfaces, don't report this as
3643 * an error; that lets them decide whether to report
3644 * this as an error or not.
3646 if (!machine_readable) {
3647 cmdarg_err("There are no interfaces on which a capture can be done");
3654 if (machine_readable) /* tab-separated values to stdout */
3655 print_machine_readable_interfaces(if_list);
3657 capture_opts_print_interfaces(if_list);
3658 free_interface_list(if_list);
3663 * "-S" requires no interface to be selected; it gives statistics
3664 * for all interfaces.
3666 if (print_statistics) {
3667 status = print_statistics_loop(machine_readable);
3672 * "-L", and capturing, act on a particular interface, so we have to
3673 * have an interface; if none was specified, pick a default.
3675 if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
3676 /* cmdarg_err() already called .... */
3680 /* Let the user know what interface was chosen. */
3681 /* get_interface_descriptive_name() is not available! */
3682 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", global_capture_opts.iface);
3684 if (list_link_layer_types) {
3685 /* Get the list of link-layer types for the capture device. */
3686 if_capabilities_t *caps;
3689 caps = get_if_capabilities(global_capture_opts.iface,
3690 global_capture_opts.monitor_mode, &err_str);
3692 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
3693 "Please check to make sure you have sufficient permissions, and that\n"
3694 "you have the proper interface or pipe specified.", global_capture_opts.iface, err_str);
3698 if (caps->data_link_types == NULL) {
3699 cmdarg_err("The capture device \"%s\" has no data link types.", global_capture_opts.iface);
3702 if (machine_readable) /* tab-separated values to stdout */
3703 print_machine_readable_if_capabilities(caps);
3705 capture_opts_print_if_capabilities(caps,
3706 global_capture_opts.monitor_mode);
3707 free_if_capabilities(caps);
3711 /* We're supposed to do a capture. Process the remaining arguments. */
3712 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
3713 capture_opts_trim_ring_num_files(&global_capture_opts);
3715 /* Now start the capture. */
3717 if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
3721 /* capture failed */
3728 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
3729 const char *message, gpointer user_data _U_)
3736 /* ignore log message, if log_level isn't interesting */
3737 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3738 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
3743 /* create a "timestamp" */
3745 today = localtime(&curr);
3747 switch(log_level & G_LOG_LEVEL_MASK) {
3748 case G_LOG_LEVEL_ERROR:
3751 case G_LOG_LEVEL_CRITICAL:
3754 case G_LOG_LEVEL_WARNING:
3757 case G_LOG_LEVEL_MESSAGE:
3760 case G_LOG_LEVEL_INFO:
3763 case G_LOG_LEVEL_DEBUG:
3767 fprintf(stderr, "unknown log_level %u\n", log_level);
3769 g_assert_not_reached();
3772 /* Generate the output message */
3773 if(log_level & G_LOG_LEVEL_MESSAGE) {
3774 /* normal user messages without additional infos */
3775 msg = g_strdup_printf("%s\n", message);
3777 /* info/debug messages with additional infos */
3778 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
3779 today->tm_hour, today->tm_min, today->tm_sec,
3780 log_domain != NULL ? log_domain : "",
3784 /* DEBUG & INFO msgs (if we're debugging today) */
3785 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3786 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3787 #ifdef DEBUG_DUMPCAP
3788 fprintf(stderr, "%s", msg);
3791 #ifdef DEBUG_CHILD_DUMPCAP
3792 fprintf(debug_log, "%s", msg);
3800 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
3801 /* to parent especially formatted if dumpcap running as child. */
3802 if (capture_child) {
3803 sync_pipe_errmsg_to_parent(2, msg, "");
3805 fprintf(stderr, "%s", msg);
3812 /****************************************************************************************************************/
3813 /* indication report routines */
3817 report_packet_count(int packet_count)
3819 char tmp[SP_DECISIZE+1+1];
3820 static int count = 0;
3823 g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
3824 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
3825 pipe_write_block(2, SP_PACKET_COUNT, tmp);
3827 count += packet_count;
3828 fprintf(stderr, "\rPackets: %u ", count);
3829 /* stderr could be line buffered */
3835 report_new_capture_file(const char *filename)
3838 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
3839 pipe_write_block(2, SP_FILE, filename);
3843 * Prevent a SIGINFO handler from writing to the standard error
3844 * while we're doing so; instead, have it just set a flag telling
3845 * us to print that information when we're done.
3848 #endif /* SIGINFO */
3849 fprintf(stderr, "File: %s\n", filename);
3850 /* stderr could be line buffered */
3855 * Allow SIGINFO handlers to write.
3860 * If a SIGINFO handler asked us to write out capture counts, do so.
3864 #endif /* SIGINFO */
3869 report_cfilter_error(const char *cfilter, const char *errmsg)
3871 if (capture_child) {
3872 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
3873 pipe_write_block(2, SP_BAD_FILTER, errmsg);
3876 "Invalid capture filter: \"%s\"!\n"
3878 "That string isn't a valid capture filter (%s).\n"
3879 "See the User's Guide for a description of the capture filter syntax.\n",
3885 report_capture_error(const char *error_msg, const char *secondary_error_msg)
3888 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3889 "Primary Error: %s", error_msg);
3890 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3891 "Secondary Error: %s", secondary_error_msg);
3892 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
3894 fprintf(stderr, "%s\n%s\n", error_msg, secondary_error_msg);
3899 report_packet_drops(guint32 drops)
3901 char tmp[SP_DECISIZE+1+1];
3903 g_snprintf(tmp, sizeof(tmp), "%u", drops);
3906 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
3907 pipe_write_block(2, SP_DROPS, tmp);
3909 fprintf(stderr, "Packets dropped: %s\n", tmp);
3910 /* stderr could be line buffered */
3916 /****************************************************************************************************************/
3917 /* signal_pipe handling */
3922 signal_pipe_check_running(void)
3924 /* any news from our parent? -> just stop the capture */
3928 /* if we are running standalone, no check required */
3929 if(!capture_child) {
3933 if(!sig_pipe_name || !sig_pipe_handle) {
3934 /* This shouldn't happen */
3935 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3936 "Signal pipe: No name or handle");
3941 * XXX - We should have the process ID of the parent (from the "-Z" flag)
3942 * at this point. Should we check to see if the parent is still alive,
3943 * e.g. by using OpenProcess?
3946 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
3948 if(!result || avail > 0) {
3949 /* peek failed or some bytes really available */
3950 /* (if not piping from stdin this would fail) */
3951 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3952 "Signal pipe: Stop capture: %s", sig_pipe_name);
3953 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3954 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
3955 sig_pipe_handle, result, avail);
3958 /* pipe ok and no bytes available */
3965 * Editor modelines - http://www.wireshark.org/tools/modelines.html
3970 * indent-tabs-mode: nil
3973 * vi: set shiftwidth=4 tabstop=8 expandtab
3974 * :indentSize=4:tabSize=8:noTabs=true: