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>
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 "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;
147 /** Stop a low-level capture (stops the capture child). */
148 static void capture_loop_stop(void);
150 #if !defined (__linux__)
151 #ifndef HAVE_PCAP_BREAKLOOP
153 * We don't have pcap_breakloop(), which is the only way to ensure that
154 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
155 * won't, if the call to read the next packet or batch of packets is
156 * is interrupted by a signal on UN*X, just go back and try again to
159 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
160 * the signal handler, set a flag to stop capturing; however, without
161 * a guarantee of that sort, we can't guarantee that we'll stop capturing
162 * if the read will be retried and won't time out if no packets arrive.
164 * Therefore, on at least some platforms, we work around the lack of
165 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
166 * to wait for packets to arrive, so that we're probably going to be
167 * blocked in the select() when the signal arrives, and can just bail
168 * out of the loop at that point.
170 * However, we don't want to that on BSD (because "select()" doesn't work
171 * correctly on BPF devices on at least some releases of some flavors of
172 * BSD), and we don't want to do it on Windows (because "select()" is
173 * something for sockets, not for arbitrary handles). (Note that "Windows"
174 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
175 * using WinPcap, not a UNIX libpcap.)
177 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
178 * on BSD times out even if no packets have arrived, so we'll eventually
179 * exit pcap_dispatch() with an indication that no packets have arrived,
180 * and will break out of the capture loop at that point.
182 * On Windows, we can't send a SIGINT to stop capturing, so none of this
183 * applies in any case.
185 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
186 * want to include it if it's not present on this platform, however.
188 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
189 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
191 # define MUST_DO_SELECT
192 # endif /* avoid select */
193 #endif /* HAVE_PCAP_BREAKLOOP */
195 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
196 * in pcap_dispatch(); on the other hand, select() works just fine there.
197 * Hence we use a select for that come what may.
199 #define MUST_DO_SELECT
202 /** init the capture filter */
205 INITFILTER_BAD_FILTER,
206 INITFILTER_OTHER_ERROR
207 } initfilter_status_t;
209 typedef struct _loop_data {
211 gboolean go; /* TRUE as long as we're supposed to keep capturing */
212 int err; /* if non-zero, error seen while capturing */
213 gint packet_count; /* Number of packets we have already captured */
214 gint packet_max; /* Number of packets we're supposed to capture - 0 means infinite */
216 /* pcap "input file" */
217 pcap_t *pcap_h; /* pcap handle */
218 gboolean pcap_err; /* TRUE if error from pcap */
219 #ifdef MUST_DO_SELECT
220 int pcap_fd; /* pcap file descriptor */
223 /* capture pipe (unix only "input file") */
224 gboolean from_cap_pipe; /* TRUE if we are capturing data from a capture pipe */
225 struct pcap_hdr cap_pipe_hdr; /* Pcap header when capturing from a pipe */
226 struct pcaprec_modified_hdr cap_pipe_rechdr; /* Pcap record header when capturing from a pipe */
228 HANDLE cap_pipe_h; /* The handle of the capture pipe */
230 int cap_pipe_fd; /* the file descriptor of the capture pipe */
232 gboolean cap_pipe_modified; /* TRUE if data in the pipe uses modified pcap headers */
233 gboolean cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
235 char * cap_pipe_buf; /* Pointer to the data buffer we read into */
236 #endif /* USE_THREADS */
237 int cap_pipe_bytes_to_read;/* Used by cap_pipe_dispatch */
238 int cap_pipe_bytes_read; /* Used by cap_pipe_dispatch */
240 STATE_EXPECT_REC_HDR,
245 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
257 * Standard secondary message for unexpected errors.
259 static const char please_report[] =
260 "Please report this to the Wireshark developers.\n"
261 "(This is not a crash; please do not report it as such.)";
264 * This needs to be static, so that the SIGINT handler can clear the "go"
267 static loop_data global_ld;
271 * Timeout, in milliseconds, for reads from the stream of captured packets.
273 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
274 * 64-bit applications, with sub-second timeouts not to work. The bug is
277 #if defined(__APPLE__) && defined(__LP64__)
278 static gboolean need_timeout_workaround;
280 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
282 #define CAP_READ_TIMEOUT 250
286 * Timeout, in microseconds, for threaded reads from a pipe.
288 #define THREAD_READ_TIMEOUT 100
289 static const char *cap_pipe_err_str;
292 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
293 const char *message, gpointer user_data _U_);
295 /* capture related options */
296 static capture_options global_capture_opts;
298 static void capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
300 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
301 int err, gboolean is_close);
303 static void exit_main(int err) G_GNUC_NORETURN;
305 static void report_new_capture_file(const char *filename);
306 static void report_packet_count(int packet_count);
307 static void report_packet_drops(guint32 drops);
308 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
309 static void report_cfilter_error(const char *cfilter, const char *errmsg);
312 print_usage(gboolean print_ver) {
320 "Dumpcap " VERSION "%s\n"
321 "Capture network packets and dump them into a libpcap file.\n"
322 "See http://www.wireshark.org for more information.\n",
323 wireshark_svnversion);
327 fprintf(output, "\nUsage: dumpcap [options] ...\n");
328 fprintf(output, "\n");
329 fprintf(output, "Capture interface:\n");
330 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
331 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
332 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
333 fprintf(output, " -p don't capture in promiscuous mode\n");
334 #ifdef HAVE_PCAP_CREATE
335 fprintf(output, " -I capture in monitor mode, if available\n");
337 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
338 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
340 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
341 fprintf(output, " -D print list of interfaces and exit\n");
342 fprintf(output, " -L print list of link-layer types of iface and exit\n");
343 fprintf(output, " -S print statistics for each interface once every second\n");
344 fprintf(output, " -M for -D, -L, and -S produce machine-readable output\n");
345 fprintf(output, "\n");
346 #ifdef HAVE_PCAP_REMOTE
347 fprintf(output, "\nRPCAP options:\n");
348 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
349 fprintf(output, " -u use UDP for RPCAP data transfer\n");
350 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
351 #ifdef HAVE_PCAP_SETSAMPLING
352 fprintf(output, " -m <sampling type> use packet sampling\n");
353 fprintf(output, " count:NUM - capture one packet of every NUM\n");
354 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
357 fprintf(output, "Stop conditions:\n");
358 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
359 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
360 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
361 fprintf(output, " files:NUM - stop after NUM files\n");
362 /*fprintf(output, "\n");*/
363 fprintf(output, "Output (files):\n");
364 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
365 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
366 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
367 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
368 fprintf(output, " -n use pcapng format instead of pcap\n");
369 /*fprintf(output, "\n");*/
370 fprintf(output, "Miscellaneous:\n");
371 fprintf(output, " -v print version information and exit\n");
372 fprintf(output, " -h display this help and exit\n");
373 fprintf(output, "\n");
374 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcap\n");
375 fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcap\"\n");
376 fprintf(output, "\n");
377 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
381 show_version(GString *comp_info_str, GString *runtime_info_str)
385 "Dumpcap " VERSION "%s\n"
390 "See http://www.wireshark.org for more information.\n",
391 wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
395 * Print to the standard error. This is a command-line tool, so there's
396 * no need to pop up a console.
399 vfprintf_stderr(const char *fmt, va_list ap)
401 vfprintf(stderr, fmt, ap);
405 fprintf_stderr(const char *fmt, ...)
410 vfprintf_stderr(fmt, ap);
415 * Report an error in command-line arguments.
418 cmdarg_err(const char *fmt, ...)
424 /* Generate a 'special format' message back to parent */
426 msg = g_strdup_vprintf(fmt, ap);
427 sync_pipe_errmsg_to_parent(2, msg, "");
432 fprintf(stderr, "dumpcap: ");
433 vfprintf(stderr, fmt, ap);
434 fprintf(stderr, "\n");
440 * Report additional information for an error in command-line arguments.
443 cmdarg_err_cont(const char *fmt, ...)
450 msg = g_strdup_vprintf(fmt, ap);
451 sync_pipe_errmsg_to_parent(2, msg, "");
456 vfprintf(stderr, fmt, ap);
457 fprintf(stderr, "\n");
463 * capture_interface_list() is expected to do the right thing to get
464 * a list of interfaces.
466 * In most of the programs in the Wireshark suite, "the right thing"
467 * is to run dumpcap and ask it for the list, because dumpcap may
468 * be the only program in the suite with enough privileges to get
471 * In dumpcap itself, however, we obviously can't run dumpcap to
472 * ask for the list. Therefore, our capture_interface_list() should
473 * just call get_interface_list().
476 capture_interface_list(int *err, char **err_str)
478 return get_interface_list(err, err_str);
482 * Get the data-link type for a libpcap device.
483 * This works around AIX 5.x's non-standard and incompatible-with-the-
484 * rest-of-the-universe libpcap.
487 get_pcap_linktype(pcap_t *pch, const char *devname
495 const char *ifacename;
498 linktype = pcap_datalink(pch);
502 * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
503 * rather than DLT_ values for link-layer types; the ifType values
504 * for LAN devices are:
511 * and the ifType value for a loopback device is 24.
513 * The AIX names for LAN devices begin with:
520 * and the AIX names for loopback devices begin with "lo".
522 * (The difference between "Ethernet" and "802.3" is presumably
523 * whether packets have an Ethernet header, with a packet type,
524 * or an 802.3 header, with a packet length, followed by an 802.2
525 * header and possibly a SNAP header.)
527 * If the device name matches "linktype" interpreted as an ifType
528 * value, rather than as a DLT_ value, we will assume this is AIX's
529 * non-standard, incompatible libpcap, rather than a standard libpcap,
530 * and will map the link-layer type to the standard DLT_ value for
531 * that link-layer type, as that's what the rest of Wireshark expects.
533 * (This means the capture files won't be readable by a tcpdump
534 * linked with AIX's non-standard libpcap, but so it goes. They
535 * *will* be readable by standard versions of tcpdump, Wireshark,
538 * XXX - if we conclude we're using AIX libpcap, should we also
539 * set a flag to cause us to assume the time stamps are in
540 * seconds-and-nanoseconds form, and to convert them to
541 * seconds-and-microseconds form before processing them and
546 * Find the last component of the device name, which is the
549 ifacename = strchr(devname, '/');
550 if (ifacename == NULL)
553 /* See if it matches any of the LAN device names. */
554 if (strncmp(ifacename, "en", 2) == 0) {
557 * That's the RFC 1573 value for Ethernet; map it to DLT_EN10MB.
561 } else if (strncmp(ifacename, "et", 2) == 0) {
564 * That's the RFC 1573 value for 802.3; map it to DLT_EN10MB.
565 * (libpcap, tcpdump, Wireshark, etc. don't care if it's Ethernet
570 } else if (strncmp(ifacename, "tr", 2) == 0) {
573 * That's the RFC 1573 value for 802.5 (Token Ring); map it to
574 * DLT_IEEE802, which is what's used for Token Ring.
578 } else if (strncmp(ifacename, "fi", 2) == 0) {
579 if (linktype == 15) {
581 * That's the RFC 1573 value for FDDI; map it to DLT_FDDI.
585 } else if (strncmp(ifacename, "lo", 2) == 0) {
586 if (linktype == 24) {
588 * That's the RFC 1573 value for "software loopback" devices; map it
589 * to DLT_NULL, which is what's used for loopback devices on BSD.
599 static data_link_info_t *
600 create_data_link_info(int dlt)
602 data_link_info_t *data_link_info;
605 data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
606 data_link_info->dlt = dlt;
607 text = pcap_datalink_val_to_name(dlt);
609 data_link_info->name = g_strdup(text);
611 data_link_info->name = g_strdup_printf("DLT %d", dlt);
612 text = pcap_datalink_val_to_description(dlt);
614 data_link_info->description = g_strdup(text);
616 data_link_info->description = NULL;
617 return data_link_info;
621 * Get the capabilities of a network device.
623 static if_capabilities_t *
624 get_if_capabilities(const char *devname, gboolean monitor_mode
625 #ifndef HAVE_PCAP_CREATE
630 if_capabilities_t *caps;
631 char errbuf[PCAP_ERRBUF_SIZE];
633 #ifdef HAVE_PCAP_CREATE
637 #ifdef HAVE_PCAP_LIST_DATALINKS
641 data_link_info_t *data_link_info;
644 * Allocate the interface capabilities structure.
646 caps = g_malloc(sizeof *caps);
648 #ifdef HAVE_PCAP_OPEN
649 pch = pcap_open(devname, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
650 caps->can_set_rfmon = FALSE;
653 *err_str = g_strdup(errbuf);
657 #elif defined(HAVE_PCAP_CREATE)
658 pch = pcap_create(devname, errbuf);
661 *err_str = g_strdup(errbuf);
665 status = pcap_can_set_rfmon(pch);
668 if (status == PCAP_ERROR)
669 *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
672 *err_str = g_strdup(pcap_statustostr(status));
678 caps->can_set_rfmon = FALSE;
679 else if (status == 1) {
680 caps->can_set_rfmon = TRUE;
682 pcap_set_rfmon(pch, 1);
684 if (err_str != NULL) {
685 *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
693 status = pcap_activate(pch);
695 /* Error. We ignore warnings (status > 0). */
696 if (err_str != NULL) {
697 if (status == PCAP_ERROR)
698 *err_str = g_strdup_printf("pcap_activate() failed: %s",
701 *err_str = g_strdup(pcap_statustostr(status));
708 pch = pcap_open_live(devname, MIN_PACKET_SIZE, 0, 0, errbuf);
709 caps->can_set_rfmon = FALSE;
712 *err_str = g_strdup(errbuf);
717 deflt = get_pcap_linktype(pch, devname);
718 #ifdef HAVE_PCAP_LIST_DATALINKS
719 nlt = pcap_list_datalinks(pch, &linktypes);
720 if (nlt == 0 || linktypes == NULL) {
723 *err_str = NULL; /* an empty list doesn't mean an error */
726 caps->data_link_types = NULL;
727 for (i = 0; i < nlt; i++) {
728 data_link_info = create_data_link_info(linktypes[i]);
731 * XXX - for 802.11, make the most detailed 802.11
732 * version the default, rather than the one the
733 * device has as the default?
735 if (linktypes[i] == deflt)
736 caps->data_link_types = g_list_prepend(caps->data_link_types,
739 caps->data_link_types = g_list_append(caps->data_link_types,
742 #ifdef HAVE_PCAP_FREE_DATALINKS
743 pcap_free_datalinks(linktypes);
746 * In Windows, there's no guarantee that if you have a library
747 * built with one version of the MSVC++ run-time library, and
748 * it returns a pointer to allocated data, you can free that
749 * data from a program linked with another version of the
750 * MSVC++ run-time library.
752 * This is not an issue on UN*X.
754 * See the mail threads starting at
756 * http://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
760 * http://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
763 #define xx_free free /* hack so checkAPIs doesn't complain */
766 #endif /* HAVE_PCAP_FREE_DATALINKS */
767 #else /* HAVE_PCAP_LIST_DATALINKS */
769 data_link_info = create_data_link_info(deflt);
770 caps->data_link_types = g_list_append(caps->data_link_types,
772 #endif /* HAVE_PCAP_LIST_DATALINKS */
781 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
783 print_machine_readable_interfaces(GList *if_list)
790 char addr_str[ADDRSTRLEN];
793 /* Let our parent know we succeeded. */
794 pipe_write_block(2, SP_SUCCESS, NULL);
797 i = 1; /* Interface id number */
798 for (if_entry = g_list_first(if_list); if_entry != NULL;
799 if_entry = g_list_next(if_entry)) {
800 if_info = (if_info_t *)if_entry->data;
801 printf("%d. %s", i++, if_info->name);
804 * Print the contents of the if_entry struct in a parseable format.
805 * Each if_entry element is tab-separated. Addresses are comma-
808 /* XXX - Make sure our description doesn't contain a tab */
809 if (if_info->description != NULL)
810 printf("\t%s\t", if_info->description);
814 for(addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
815 addr = g_slist_next(addr)) {
816 if (addr != g_slist_nth(if_info->addrs, 0))
819 if_addr = (if_addr_t *)addr->data;
820 switch(if_addr->ifat_type) {
822 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
824 printf("%s", addr_str);
826 printf("<unknown IPv4>");
830 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
831 addr_str, ADDRSTRLEN)) {
832 printf("%s", addr_str);
834 printf("<unknown IPv6>");
838 printf("<type unknown %u>", if_addr->ifat_type);
842 if (if_info->loopback)
843 printf("\tloopback");
852 * If you change the machine-readable output format of this function,
853 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
856 print_machine_readable_if_capabilities(if_capabilities_t *caps)
859 data_link_info_t *data_link_info;
860 const gchar *desc_str;
863 /* Let our parent know we succeeded. */
864 pipe_write_block(2, SP_SUCCESS, NULL);
867 if (caps->can_set_rfmon)
871 for (lt_entry = caps->data_link_types; lt_entry != NULL;
872 lt_entry = g_list_next(lt_entry)) {
873 data_link_info = (data_link_info_t *)lt_entry->data;
874 if (data_link_info->description != NULL)
875 desc_str = data_link_info->description;
877 desc_str = "(not supported)";
878 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
888 /* Print the number of packets captured for each interface until we're killed. */
890 print_statistics_loop(gboolean machine_readable)
892 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
898 char errbuf[PCAP_ERRBUF_SIZE];
901 if_list = get_interface_list(&err, &err_str);
902 if (if_list == NULL) {
904 case CANT_GET_INTERFACE_LIST:
905 cmdarg_err("%s", err_str);
909 case NO_INTERFACES_FOUND:
910 cmdarg_err("There are no interfaces on which a capture can be done");
916 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
917 if_info = (if_info_t *)if_entry->data;
918 #ifdef HAVE_PCAP_OPEN
919 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
921 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
925 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
926 if_stat->name = g_strdup(if_info->name);
928 stat_list = g_list_append(stat_list, if_stat);
933 cmdarg_err("There are no interfaces on which a capture can be done");
938 /* Let our parent know we succeeded. */
939 pipe_write_block(2, SP_SUCCESS, NULL);
942 if (!machine_readable) {
943 printf("%-15s %10s %10s\n", "Interface", "Received",
948 while (global_ld.go) {
949 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
950 if_stat = (if_stat_t *)stat_entry->data;
951 pcap_stats(if_stat->pch, &ps);
953 if (!machine_readable) {
954 printf("%-15s %10u %10u\n", if_stat->name,
955 ps.ps_recv, ps.ps_drop);
957 printf("%s\t%u\t%u\n", if_stat->name,
958 ps.ps_recv, ps.ps_drop);
963 if (! global_ld.from_cap_pipe)
970 /* XXX - Not reached. Should we look for 'q' in stdin? */
971 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
972 if_stat = (if_stat_t *)stat_entry->data;
973 pcap_close(if_stat->pch);
974 g_free(if_stat->name);
977 g_list_free(stat_list);
978 free_interface_list(if_list);
986 capture_cleanup_handler(DWORD dwCtrlType)
988 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
989 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
990 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
991 like SIGTERM at least when the machine's shutting down.
993 For now, if we're running as a command rather than a capture child,
994 we handle all but CTRL_LOGOFF_EVENT as indications that we should
995 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
998 If we're not running as a capture child, we might be running as
999 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1000 user logs out. (XXX - can we explicitly check whether we're
1001 running as a service?) */
1003 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1004 "Console: Control signal");
1005 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1006 "Console: Control signal, CtrlType: %u", dwCtrlType);
1008 /* Keep capture running if we're a service and a user logs off */
1009 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1010 capture_loop_stop();
1018 capture_cleanup_handler(int signum _U_)
1020 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1021 SIGTERM. We assume that if the user wanted it to keep running
1022 after they logged out, they'd have nohupped it. */
1024 /* Note: don't call g_log() in the signal handler: if we happened to be in
1025 * g_log() in process context when the signal came in, g_log will detect
1026 * the "recursion" and abort.
1029 capture_loop_stop();
1033 static void exit_main(int status)
1036 /* Shutdown windows sockets */
1039 /* can be helpful for debugging */
1040 #ifdef DEBUG_DUMPCAP
1041 printf("Press any key\n");
1052 * If we were linked with libcap (not libpcap), make sure we have
1053 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1054 * (See comment in main() for details)
1058 #if 0 /* Set to enable capability debugging */
1059 /* see 'man cap_to_text()' for explanation of output */
1060 /* '=' means 'all= ' ie: no capabilities */
1061 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
1063 print_caps(const char *pfx) {
1064 cap_t caps = cap_get_proc();
1065 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1066 "%s: EUID: %d Capabilities: %s", pfx,
1067 geteuid(), cap_to_text(caps, NULL));
1070 print_caps(const char *pfx _U_) {
1075 relinquish_privs_except_capture(void)
1077 /* If 'started_with_special_privs' (ie: suid) then enable for
1078 * ourself the NET_ADMIN and NET_RAW capabilities and then
1079 * drop our suid privileges.
1081 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1082 * stuff we don't need (and shouldn't have).
1083 * CAP_NET_RAW: Packet capture (raw sockets).
1086 if (started_with_special_privs()) {
1087 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1088 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1090 cap_t caps = cap_init(); /* all capabilities initialized to off */
1092 print_caps("Pre drop, pre set");
1094 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1095 cmdarg_err("prctl() fail return: %s", strerror(errno));
1098 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1099 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1101 if (cap_set_proc(caps)) {
1102 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
1104 print_caps("Pre drop, post set");
1106 relinquish_special_privs_perm();
1108 print_caps("Post drop, pre set");
1109 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1110 if (cap_set_proc(caps)) {
1111 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
1113 print_caps("Post drop, post set");
1121 relinquish_all_capabilities(void)
1123 /* Drop any and all capabilities this process may have. */
1124 /* Allowed whether or not process has any privileges. */
1125 cap_t caps = cap_init(); /* all capabilities initialized to off */
1126 print_caps("Pre-clear");
1127 if (cap_set_proc(caps)) {
1128 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
1130 print_caps("Post-clear");
1134 #endif /* HAVE_LIBCAP */
1136 /* Set the data link type on a pcap. */
1138 set_pcap_linktype(pcap_t *pch, char *devname
1139 #ifdef HAVE_PCAP_SET_DATALINK
1144 #ifdef HAVE_PCAP_SET_DATALINK
1145 if (pcap_set_datalink(pch, dlt) == 0)
1146 return NULL; /* no error */
1147 return pcap_geterr(pch);
1149 /* Let them set it to the type it is; reject any other request. */
1150 if (get_pcap_linktype(pch, devname) == dlt)
1151 return NULL; /* no error */
1152 return "That DLT isn't one of the DLTs supported by this device";
1156 /* Take care of byte order in the libpcap headers read from pipes.
1157 * (function taken from wiretap/libpcap.c) */
1159 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1162 /* Byte-swap the record header fields. */
1163 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
1164 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
1165 rechdr->incl_len = BSWAP32(rechdr->incl_len);
1166 rechdr->orig_len = BSWAP32(rechdr->orig_len);
1169 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1170 swapped, in order to match the BPF header layout.
1172 Unfortunately, some files were, according to a comment in the "libpcap"
1173 source, written with version 2.3 in their headers but without the
1174 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1175 would make no sense - we assume that we need to swap them. */
1176 if (hdr->version_major == 2 &&
1177 (hdr->version_minor < 3 ||
1178 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1181 temp = rechdr->orig_len;
1182 rechdr->orig_len = rechdr->incl_len;
1183 rechdr->incl_len = temp;
1189 * Thread function that reads from a pipe and pushes the data
1190 * to the main application thread.
1193 * XXX Right now we use async queues for basic signaling. The main thread
1194 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1195 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1196 * Iff the read is successful cap_pipe_read pushes an item onto
1197 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1198 * the queues themselves (yet).
1200 * We might want to move some of the cap_pipe_dispatch logic here so that
1201 * we can let cap_pipe_read run independently, queuing up multiple reads
1202 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1204 static void *cap_pipe_read(void *ld_ptr) {
1205 loop_data *ld = (loop_data *)ld_ptr;
1214 while (ld->cap_pipe_err == PIPOK) {
1215 g_async_queue_pop(cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1216 g_mutex_lock(cap_pipe_read_mtx);
1218 while (bytes_read < (int) ld->cap_pipe_bytes_to_read) {
1220 /* If we try to use read() on a named pipe on Windows with partial
1221 * data it appears to return EOF.
1223 res = ReadFile(ld->cap_pipe_h, ld->cap_pipe_buf+bytes_read,
1224 ld->cap_pipe_bytes_to_read - bytes_read,
1229 last_err = GetLastError();
1230 if (last_err == ERROR_MORE_DATA) {
1232 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1233 ld->cap_pipe_err = PIPEOF;
1237 ld->cap_pipe_err = PIPERR;
1240 } else if (b == 0 && ld->cap_pipe_bytes_to_read > 0) {
1241 ld->cap_pipe_err = PIPEOF;
1246 b = read(ld->cap_pipe_fd, ld->cap_pipe_buf+bytes_read,
1247 ld->cap_pipe_bytes_to_read - bytes_read);
1250 ld->cap_pipe_err = PIPEOF;
1254 ld->cap_pipe_err = PIPERR;
1263 ld->cap_pipe_bytes_read = bytes_read;
1264 if (ld->cap_pipe_bytes_read >= ld->cap_pipe_bytes_to_read) {
1265 g_async_queue_push(cap_pipe_done_q, ld->cap_pipe_buf); /* Any non-NULL value will do */
1267 g_mutex_unlock(cap_pipe_read_mtx);
1271 #endif /* USE_THREADS */
1273 /* Provide select() functionality for a single file descriptor
1274 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1276 * Returns the same values as select. If an error is returned,
1277 * the string cap_pipe_err_str should be used instead of errno.
1280 cap_pipe_select(int pipe_fd) {
1282 struct timeval timeout, *pto;
1285 cap_pipe_err_str = "Unknown error";
1288 FD_SET(pipe_fd, &rfds);
1291 timeout.tv_usec = CAP_READ_TIMEOUT * 1000;
1294 sel_ret = select(pipe_fd+1, &rfds, NULL, NULL, pto);
1296 cap_pipe_err_str = strerror(errno);
1301 /* Mimic pcap_open_live() for pipe captures
1303 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1304 * open it, and read the header.
1306 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1307 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1309 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
1310 char *errmsg, int errmsgl)
1313 struct stat pipe_stat;
1314 struct sockaddr_un sa;
1317 unsigned int bytes_read;
1328 ld->cap_pipe_fd = -1;
1330 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
1332 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1335 * XXX - this blocks until a pcap per-file header has been written to
1336 * the pipe, so it could block indefinitely.
1338 if (strcmp(pipename, "-") == 0) {
1340 fd = 0; /* read from stdin */
1342 ld->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1346 if (ws_stat(pipename, &pipe_stat) < 0) {
1347 if (errno == ENOENT || errno == ENOTDIR)
1348 ld->cap_pipe_err = PIPNEXIST;
1350 g_snprintf(errmsg, errmsgl,
1351 "The capture session could not be initiated "
1352 "due to error getting information on pipe/socket: %s", strerror(errno));
1353 ld->cap_pipe_err = PIPERR;
1357 if (S_ISFIFO(pipe_stat.st_mode)) {
1358 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1360 g_snprintf(errmsg, errmsgl,
1361 "The capture session could not be initiated "
1362 "due to error on pipe open: %s", strerror(errno));
1363 ld->cap_pipe_err = PIPERR;
1366 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1367 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1369 g_snprintf(errmsg, errmsgl,
1370 "The capture session could not be initiated "
1371 "due to error on socket create: %s", strerror(errno));
1372 ld->cap_pipe_err = PIPERR;
1375 sa.sun_family = AF_UNIX;
1377 * The Single UNIX Specification says:
1379 * The size of sun_path has intentionally been left undefined.
1380 * This is because different implementations use different sizes.
1381 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1382 * of 104. Since most implementations originate from BSD versions,
1383 * the size is typically in the range 92 to 108.
1385 * Applications should not assume a particular length for sun_path
1386 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1390 * The <sys/un.h> header shall define the sockaddr_un structure,
1391 * which shall include at least the following members:
1393 * sa_family_t sun_family Address family.
1394 * char sun_path[] Socket pathname.
1396 * so we assume that it's an array, with a specified size,
1397 * and that the size reflects the maximum path length.
1399 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1400 /* Path name too long */
1401 g_snprintf(errmsg, errmsgl,
1402 "The capture session coud not be initiated "
1403 "due to error on socket connect: Path name too long");
1404 ld->cap_pipe_err = PIPERR;
1407 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1409 g_snprintf(errmsg, errmsgl,
1410 "The capture session coud not be initiated "
1411 "due to error on socket connect: %s", strerror(errno));
1412 ld->cap_pipe_err = PIPERR;
1416 if (S_ISCHR(pipe_stat.st_mode)) {
1418 * Assume the user specified an interface on a system where
1419 * interfaces are in /dev. Pretend we haven't seen it.
1421 ld->cap_pipe_err = PIPNEXIST;
1424 g_snprintf(errmsg, errmsgl,
1425 "The capture session could not be initiated because\n"
1426 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
1427 ld->cap_pipe_err = PIPERR;
1432 #define PIPE_STR "\\pipe\\"
1433 /* Under Windows, named pipes _must_ have the form
1434 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1436 pncopy = g_strdup(pipename);
1437 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1438 pos = strchr(pncopy + 3, '\\');
1439 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1446 g_snprintf(errmsg, errmsgl,
1447 "The capture session could not be initiated because\n"
1448 "\"%s\" is neither an interface nor a pipe", pipename);
1449 ld->cap_pipe_err = PIPNEXIST;
1453 /* Wait for the pipe to appear */
1455 ld->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1456 OPEN_EXISTING, 0, NULL);
1458 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE)
1461 if (GetLastError() != ERROR_PIPE_BUSY) {
1462 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1463 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1464 g_snprintf(errmsg, errmsgl,
1465 "The capture session on \"%s\" could not be started "
1466 "due to error on pipe open: %s (error %d)",
1467 pipename, utf_16to8(err_str), GetLastError());
1469 ld->cap_pipe_err = PIPERR;
1473 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1474 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1475 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1476 g_snprintf(errmsg, errmsgl,
1477 "The capture session on \"%s\" timed out during "
1478 "pipe open: %s (error %d)",
1479 pipename, utf_16to8(err_str), GetLastError());
1481 ld->cap_pipe_err = PIPERR;
1488 ld->from_cap_pipe = TRUE;
1491 /* read the pcap header */
1493 while (bytes_read < sizeof magic) {
1494 sel_ret = cap_pipe_select(fd);
1496 g_snprintf(errmsg, errmsgl,
1497 "Unexpected error from select: %s", strerror(errno));
1499 } else if (sel_ret > 0) {
1500 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
1503 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1505 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1512 #else /* USE_THREADS */
1513 g_thread_create(&cap_pipe_read, ld, FALSE, NULL);
1515 ld->cap_pipe_buf = (char *) &magic;
1516 ld->cap_pipe_bytes_read = 0;
1517 ld->cap_pipe_bytes_to_read = sizeof(magic);
1518 /* We don't have to worry about cap_pipe_read_mtx here */
1519 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1520 g_async_queue_pop(cap_pipe_done_q);
1521 if (ld->cap_pipe_bytes_read <= 0) {
1522 if (ld->cap_pipe_bytes_read == 0)
1523 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1525 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1530 #endif /* USE_THREADS */
1534 /* Host that wrote it has our byte order, and was running
1535 a program using either standard or ss990417 libpcap. */
1536 ld->cap_pipe_byte_swapped = FALSE;
1537 ld->cap_pipe_modified = FALSE;
1539 case PCAP_MODIFIED_MAGIC:
1540 /* Host that wrote it has our byte order, but was running
1541 a program using either ss990915 or ss991029 libpcap. */
1542 ld->cap_pipe_byte_swapped = FALSE;
1543 ld->cap_pipe_modified = TRUE;
1545 case PCAP_SWAPPED_MAGIC:
1546 /* Host that wrote it has a byte order opposite to ours,
1547 and was running a program using either standard or
1548 ss990417 libpcap. */
1549 ld->cap_pipe_byte_swapped = TRUE;
1550 ld->cap_pipe_modified = FALSE;
1552 case PCAP_SWAPPED_MODIFIED_MAGIC:
1553 /* Host that wrote it out has a byte order opposite to
1554 ours, and was running a program using either ss990915
1555 or ss991029 libpcap. */
1556 ld->cap_pipe_byte_swapped = TRUE;
1557 ld->cap_pipe_modified = TRUE;
1560 /* Not a "libpcap" type we know about. */
1561 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
1566 /* Read the rest of the header */
1568 while (bytes_read < sizeof(struct pcap_hdr)) {
1569 sel_ret = cap_pipe_select(fd);
1571 g_snprintf(errmsg, errmsgl,
1572 "Unexpected error from select: %s", strerror(errno));
1574 } else if (sel_ret > 0) {
1575 b = read(fd, ((char *)hdr)+bytes_read,
1576 sizeof(struct pcap_hdr) - bytes_read);
1579 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1581 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
1588 #else /* USE_THREADS */
1589 ld->cap_pipe_buf = (char *) hdr;
1590 ld->cap_pipe_bytes_read = 0;
1591 ld->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1592 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1593 g_async_queue_pop(cap_pipe_done_q);
1594 if (ld->cap_pipe_bytes_read <= 0) {
1595 if (ld->cap_pipe_bytes_read == 0)
1596 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1598 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
1602 #endif /* USE_THREADS */
1604 if (ld->cap_pipe_byte_swapped) {
1605 /* Byte-swap the header fields about which we care. */
1606 hdr->version_major = BSWAP16(hdr->version_major);
1607 hdr->version_minor = BSWAP16(hdr->version_minor);
1608 hdr->snaplen = BSWAP32(hdr->snaplen);
1609 hdr->network = BSWAP32(hdr->network);
1611 ld->linktype = hdr->network;
1613 if (hdr->version_major < 2) {
1614 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1618 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1619 ld->cap_pipe_err = PIPOK;
1621 ld->cap_pipe_fd = fd;
1626 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1627 ld->cap_pipe_err = PIPERR;
1630 ld->cap_pipe_fd = -1;
1637 /* We read one record from the pipe, take care of byte order in the record
1638 * header, write the record to the capture file, and update capture statistics. */
1640 cap_pipe_dispatch(loop_data *ld, guchar *data, char *errmsg, int errmsgl)
1642 struct pcap_pkthdr phdr;
1643 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1655 #ifdef LOG_CAPTURE_VERBOSE
1656 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1659 switch (ld->cap_pipe_state) {
1661 case STATE_EXPECT_REC_HDR:
1663 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1666 ld->cap_pipe_state = STATE_READ_REC_HDR;
1667 ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
1668 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1669 ld->cap_pipe_bytes_read = 0;
1672 ld->cap_pipe_buf = (char *) &ld->cap_pipe_rechdr;
1673 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1674 g_mutex_unlock(cap_pipe_read_mtx);
1679 case STATE_READ_REC_HDR:
1681 b = read(ld->cap_pipe_fd, ((char *)&ld->cap_pipe_rechdr)+ld->cap_pipe_bytes_read,
1682 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1685 result = PD_PIPE_EOF;
1687 result = PD_PIPE_ERR;
1690 ld->cap_pipe_bytes_read += b;
1691 #else /* USE_THREADS */
1692 g_get_current_time(&wait_time);
1693 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1694 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1695 if (ld->cap_pipe_err == PIPEOF) {
1696 result = PD_PIPE_EOF;
1698 } else if (ld->cap_pipe_err == PIPERR) {
1699 result = PD_PIPE_ERR;
1705 #endif /* USE_THREADS */
1706 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1708 result = PD_REC_HDR_READ;
1711 case STATE_EXPECT_DATA:
1713 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1716 ld->cap_pipe_state = STATE_READ_DATA;
1717 ld->cap_pipe_bytes_to_read = ld->cap_pipe_rechdr.hdr.incl_len;
1718 ld->cap_pipe_bytes_read = 0;
1721 ld->cap_pipe_buf = (char *) data;
1722 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1723 g_mutex_unlock(cap_pipe_read_mtx);
1728 case STATE_READ_DATA:
1730 b = read(ld->cap_pipe_fd, data+ld->cap_pipe_bytes_read,
1731 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1734 result = PD_PIPE_EOF;
1736 result = PD_PIPE_ERR;
1739 ld->cap_pipe_bytes_read += b;
1740 #else /* USE_THREADS */
1741 g_get_current_time(&wait_time);
1742 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1743 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1744 if (ld->cap_pipe_err == PIPEOF) {
1745 result = PD_PIPE_EOF;
1747 } else if (ld->cap_pipe_err == PIPERR) {
1748 result = PD_PIPE_ERR;
1754 #endif /* USE_THREADS */
1755 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1757 result = PD_DATA_READ;
1761 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
1764 } /* switch (ld->cap_pipe_state) */
1767 * We've now read as much data as we were expecting, so process it.
1771 case PD_REC_HDR_READ:
1772 /* We've read the header. Take care of byte order. */
1773 cap_pipe_adjust_header(ld->cap_pipe_byte_swapped, &ld->cap_pipe_hdr,
1774 &ld->cap_pipe_rechdr.hdr);
1775 if (ld->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1776 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
1777 ld->packet_count+1, ld->cap_pipe_rechdr.hdr.incl_len);
1780 ld->cap_pipe_state = STATE_EXPECT_DATA;
1784 /* Fill in a "struct pcap_pkthdr", and process the packet. */
1785 phdr.ts.tv_sec = ld->cap_pipe_rechdr.hdr.ts_sec;
1786 phdr.ts.tv_usec = ld->cap_pipe_rechdr.hdr.ts_usec;
1787 phdr.caplen = ld->cap_pipe_rechdr.hdr.incl_len;
1788 phdr.len = ld->cap_pipe_rechdr.hdr.orig_len;
1790 capture_loop_packet_cb((u_char *)ld, &phdr, data);
1792 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1796 ld->cap_pipe_err = PIPEOF;
1801 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1802 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1803 g_snprintf(errmsg, errmsgl,
1804 "Error reading from pipe: %s (error %d)",
1805 utf_16to8(err_str), GetLastError());
1808 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
1816 ld->cap_pipe_err = PIPERR;
1817 /* Return here rather than inside the switch to prevent GCC warning */
1822 /** Open the capture input file (pcap or capture pipe).
1823 * Returns TRUE if it succeeds, FALSE otherwise. */
1825 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
1826 char *errmsg, size_t errmsg_len,
1827 char *secondary_errmsg, size_t secondary_errmsg_len)
1829 gchar open_err_str[PCAP_ERRBUF_SIZE];
1830 gchar *sync_msg_str;
1831 static const char ppamsg[] = "can't find PPA for ";
1832 const char *set_linktype_err_str;
1833 const char *libpcap_warn;
1834 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
1838 gchar *sync_secondary_msg_str;
1839 WORD wVersionRequested;
1842 #ifdef HAVE_PCAP_REMOTE
1843 struct pcap_rmtauth auth;
1847 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
1850 /* XXX - opening Winsock on tshark? */
1852 /* Initialize Windows Socket if we are in a WIN32 OS
1853 This needs to be done before querying the interface for network/netmask */
1855 /* XXX - do we really require 1.1 or earlier?
1856 Are there any versions that support only 2.0 or higher? */
1857 wVersionRequested = MAKEWORD(1, 1);
1858 err = WSAStartup(wVersionRequested, &wsaData);
1862 case WSASYSNOTREADY:
1863 g_snprintf(errmsg, (gulong) errmsg_len,
1864 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
1867 case WSAVERNOTSUPPORTED:
1868 g_snprintf(errmsg, (gulong) errmsg_len,
1869 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
1870 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
1873 case WSAEINPROGRESS:
1874 g_snprintf(errmsg, (gulong) errmsg_len,
1875 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
1879 g_snprintf(errmsg, (gulong) errmsg_len,
1880 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
1884 g_snprintf(errmsg, (gulong) errmsg_len,
1885 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
1889 g_snprintf(errmsg, (gulong) errmsg_len,
1890 "Couldn't initialize Windows Sockets: error %d", err);
1893 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
1898 /* Open the network interface to capture from it.
1899 Some versions of libpcap may put warnings into the error buffer
1900 if they succeed; to tell if that's happened, we have to clear
1901 the error buffer, and check if it's still a null string. */
1902 open_err_str[0] = '\0';
1903 #ifdef HAVE_PCAP_OPEN
1905 * If we're opening a remote device, use pcap_open(); that's currently
1906 * the only open routine that supports remote devices.
1908 if (strncmp (capture_opts->iface, "rpcap://", 8) == 0) {
1909 auth.type = capture_opts->auth_type == CAPTURE_AUTH_PWD ?
1910 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
1911 auth.username = capture_opts->auth_username;
1912 auth.password = capture_opts->auth_password;
1914 ld->pcap_h = pcap_open(capture_opts->iface,
1915 capture_opts->has_snaplen ? capture_opts->snaplen :
1916 WTAP_MAX_PACKET_SIZE,
1918 (capture_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
1919 (capture_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
1920 (capture_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
1921 CAP_READ_TIMEOUT, &auth, open_err_str);
1923 #endif /* HAVE_PCAP_OPEN */
1926 * If we're not opening a remote device, use pcap_create() and
1927 * pcap_activate() if we have them, so that we can set the buffer
1928 * size, otherwise use pcap_open_live().
1930 #ifdef HAVE_PCAP_CREATE
1931 ld->pcap_h = pcap_create(capture_opts->iface, open_err_str);
1932 if (ld->pcap_h != NULL) {
1933 pcap_set_snaplen(ld->pcap_h, capture_opts->has_snaplen ? capture_opts->snaplen : WTAP_MAX_PACKET_SIZE);
1934 pcap_set_promisc(ld->pcap_h, capture_opts->promisc_mode);
1935 pcap_set_timeout(ld->pcap_h, CAP_READ_TIMEOUT);
1937 if (capture_opts->buffer_size > 1) {
1938 pcap_set_buffer_size(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024);
1940 if (capture_opts->monitor_mode)
1941 pcap_set_rfmon(ld->pcap_h, 1);
1942 err = pcap_activate(ld->pcap_h);
1944 /* Failed to activate, set to NULL */
1945 if (err == PCAP_ERROR)
1946 g_strlcpy(open_err_str, pcap_geterr(ld->pcap_h), sizeof open_err_str);
1948 g_strlcpy(open_err_str, pcap_statustostr(err), sizeof open_err_str);
1949 pcap_close(ld->pcap_h);
1954 ld->pcap_h = pcap_open_live(capture_opts->iface,
1955 capture_opts->has_snaplen ? capture_opts->snaplen :
1956 WTAP_MAX_PACKET_SIZE,
1957 capture_opts->promisc_mode, CAP_READ_TIMEOUT,
1962 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
1963 /* to remove any suid privileges. */
1964 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
1965 /* (euid/egid have already previously been set to ruid/rgid. */
1966 /* (See comment in main() for details) */
1968 relinquish_special_privs_perm();
1970 relinquish_all_capabilities();
1973 if (ld->pcap_h != NULL) {
1974 /* we've opened "iface" as a network device */
1976 /* try to set the capture buffer size */
1977 if (capture_opts->buffer_size > 1 &&
1978 pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
1979 sync_secondary_msg_str = g_strdup_printf(
1980 "The capture buffer size of %dMB seems to be too high for your machine,\n"
1981 "the default of 1MB will be used.\n"
1983 "Nonetheless, the capture is started.\n",
1984 capture_opts->buffer_size);
1985 report_capture_error("Couldn't set the capture buffer size!",
1986 sync_secondary_msg_str);
1987 g_free(sync_secondary_msg_str);
1991 #if defined(HAVE_PCAP_REMOTE) && defined(HAVE_PCAP_SETSAMPLING)
1992 if ((capture_opts->sampling_method != CAPTURE_SAMP_NONE) &&
1993 (strncmp (capture_opts->iface, "rpcap://", 8) == 0))
1995 struct pcap_samp *samp;
1997 if ((samp = pcap_setsampling(ld->pcap_h)) != NULL)
1999 switch (capture_opts->sampling_method)
2001 case CAPTURE_SAMP_BY_COUNT:
2002 samp->method = PCAP_SAMP_1_EVERY_N;
2005 case CAPTURE_SAMP_BY_TIMER:
2006 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2010 sync_msg_str = g_strdup_printf(
2011 "Unknown sampling method %d specified,\n"
2012 "continue without packet sampling",
2013 capture_opts->sampling_method);
2014 report_capture_error("Couldn't set the capture "
2015 "sampling", sync_msg_str);
2016 g_free(sync_msg_str);
2018 samp->value = capture_opts->sampling_param;
2022 report_capture_error("Couldn't set the capture sampling",
2023 "Cannot get packet sampling data structure");
2029 /* setting the data link type only works on real interfaces */
2030 if (capture_opts->linktype != -1) {
2031 set_linktype_err_str = set_pcap_linktype(ld->pcap_h, capture_opts->iface,
2032 capture_opts->linktype);
2033 if (set_linktype_err_str != NULL) {
2034 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
2035 set_linktype_err_str);
2036 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2040 ld->linktype = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
2042 /* We couldn't open "iface" as a network device. */
2043 /* Try to open it as a pipe */
2044 cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, (int) errmsg_len);
2047 if (ld->cap_pipe_fd == -1) {
2049 if (ld->cap_pipe_h == INVALID_HANDLE_VALUE) {
2052 if (ld->cap_pipe_err == PIPNEXIST) {
2053 /* Pipe doesn't exist, so output message for interface */
2055 /* If we got a "can't find PPA for X" message, warn the user (who
2056 is running (T)Wireshark on HP-UX) that they don't have a version
2057 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
2058 versions, which properly handle HP-UX, say "can't find /dev/dlpi
2059 PPA for X" rather than "can't find PPA for X"). */
2060 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
2063 "You are running (T)Wireshark with a version of the libpcap library\n"
2064 "that doesn't handle HP-UX network devices well; this means that\n"
2065 "(T)Wireshark may not be able to capture packets.\n"
2067 "To fix this, you should install libpcap 0.6.2, or a later version\n"
2068 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
2069 "packaged binary form from the Software Porting And Archive Centre\n"
2070 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
2071 "at the URL lists a number of mirror sites.";
2074 g_snprintf(errmsg, (gulong) errmsg_len,
2075 "The capture session could not be initiated (%s).", open_err_str);
2077 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
2078 "Please check to make sure you have sufficient permissions, and that you have "
2079 "the proper interface or pipe specified.%s", libpcap_warn);
2081 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
2083 "Please check that \"%s\" is the proper interface.\n"
2086 "Help can be found at:\n"
2088 " http://wiki.wireshark.org/WinPcap\n"
2089 " http://wiki.wireshark.org/CaptureSetup\n",
2090 capture_opts->iface);
2094 * Else pipe (or file) does exist and cap_pipe_open_live() has
2099 /* cap_pipe_open_live() succeeded; don't want
2100 error message from pcap_open_live() */
2101 open_err_str[0] = '\0';
2104 /* XXX - will this work for tshark? */
2105 #ifdef MUST_DO_SELECT
2106 if (!ld->from_cap_pipe) {
2107 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2108 ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
2110 ld->pcap_fd = pcap_fileno(ld->pcap_h);
2115 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2116 returned a warning; print it, but keep capturing. */
2117 if (open_err_str[0] != '\0') {
2118 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2119 report_capture_error(sync_msg_str, "");
2120 g_free(sync_msg_str);
2127 /* close the capture input file (pcap or capture pipe) */
2128 static void capture_loop_close_input(loop_data *ld) {
2130 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2132 /* if open, close the capture pipe "input file" */
2134 if (ld->cap_pipe_fd >= 0) {
2135 g_assert(ld->from_cap_pipe);
2136 ws_close(ld->cap_pipe_fd);
2137 ld->cap_pipe_fd = 0;
2140 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE) {
2141 CloseHandle(ld->cap_pipe_h);
2142 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
2146 /* if open, close the pcap "input file" */
2147 if(ld->pcap_h != NULL) {
2148 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)ld->pcap_h);
2149 g_assert(!ld->from_cap_pipe);
2150 pcap_close(ld->pcap_h);
2157 /* Shut down windows sockets */
2163 /* init the capture filter */
2164 static initfilter_status_t
2165 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe, gchar * iface, gchar * cfilter) {
2166 bpf_u_int32 netnum, netmask;
2167 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
2168 struct bpf_program fcode;
2171 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2173 /* capture filters only work on real interfaces */
2174 if (cfilter && !from_cap_pipe) {
2175 /* A capture filter was specified; set it up. */
2176 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
2178 * Well, we can't get the netmask for this interface; it's used
2179 * only for filters that check for broadcast IP addresses, so
2180 * we just punt and use 0. It might be nice to warn the user,
2181 * but that's a pain in a GUI application, as it'd involve popping
2182 * up a message box, and it's not clear how often this would make
2183 * a difference (only filters that check for IP broadcast addresses
2187 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
2190 if (pcap_compile(pcap_h, &fcode, cfilter, 1, netmask) < 0) {
2191 /* Treat this specially - our caller might try to compile this
2192 as a display filter and, if that succeeds, warn the user that
2193 the display and capture filter syntaxes are different. */
2194 return INITFILTER_BAD_FILTER;
2196 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2197 #ifdef HAVE_PCAP_FREECODE
2198 pcap_freecode(&fcode);
2200 return INITFILTER_OTHER_ERROR;
2202 #ifdef HAVE_PCAP_FREECODE
2203 pcap_freecode(&fcode);
2207 return INITFILTER_NO_ERROR;
2211 /* set up to write to the already-opened capture output file/files */
2213 capture_loop_init_output(capture_options *capture_opts, int save_file_fd, loop_data *ld, char *errmsg, int errmsg_len) {
2217 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2220 if (ld->from_cap_pipe) {
2221 ld->file_snaplen = ld->cap_pipe_hdr.snaplen;
2224 ld->file_snaplen = pcap_snapshot(ld->pcap_h);
2227 /* Set up to write to the capture file. */
2228 if (capture_opts->multi_files_on) {
2229 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2231 ld->pdh = libpcap_fdopen(save_file_fd, &err);
2234 gboolean successful;
2236 ld->bytes_written = 0;
2237 if (capture_opts->use_pcapng) {
2240 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2241 successful = libpcap_write_session_header_block(ld->pdh, appname, &ld->bytes_written, &err) &&
2242 libpcap_write_interface_description_block(ld->pdh, capture_opts->iface, capture_opts->cfilter, ld->linktype, ld->file_snaplen, &ld->bytes_written, &err);
2244 successful = libpcap_write_file_header(ld->pdh, ld->linktype, ld->file_snaplen,
2245 &ld->bytes_written, &err);
2253 if (ld->pdh == NULL) {
2254 /* We couldn't set up to write to the capture file. */
2255 /* XXX - use cf_open_error_message from tshark instead? */
2258 case WTAP_ERR_CANT_OPEN:
2259 g_snprintf(errmsg, errmsg_len, "The file to which the capture would be saved"
2260 " couldn't be created for some unknown reason.");
2263 case WTAP_ERR_SHORT_WRITE:
2264 g_snprintf(errmsg, errmsg_len, "A full header couldn't be written to the file"
2265 " to which the capture would be saved.");
2270 g_snprintf(errmsg, errmsg_len,
2271 "The file to which the capture would be"
2272 " saved (\"%s\") could not be opened: Error %d.",
2273 capture_opts->save_file, err);
2275 g_snprintf(errmsg, errmsg_len,
2276 "The file to which the capture would be"
2277 " saved (\"%s\") could not be opened: %s.",
2278 capture_opts->save_file, strerror(err));
2290 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
2292 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2294 if (capture_opts->multi_files_on) {
2295 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2297 if (capture_opts->use_pcapng) {
2298 libpcap_write_interface_statistics_block(ld->pdh, 0, ld->pcap_h, &ld->bytes_written, err_close);
2300 return libpcap_dump_close(ld->pdh, err_close);
2304 /* dispatch incoming packets (pcap or capture pipe)
2306 * Waits for incoming packets to be available, and calls pcap_dispatch()
2307 * to cause them to be processed.
2309 * Returns the number of packets which were processed.
2311 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2312 * packet-batching behaviour does not cause packets to get held back
2316 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
2317 char *errmsg, int errmsg_len)
2320 gint packet_count_before;
2321 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
2326 packet_count_before = ld->packet_count;
2327 if (ld->from_cap_pipe) {
2328 /* dispatch from capture pipe */
2329 #ifdef LOG_CAPTURE_VERBOSE
2330 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2333 sel_ret = cap_pipe_select(ld->cap_pipe_fd);
2336 if (sel_ret < 0 && errno != EINTR) {
2337 g_snprintf(errmsg, errmsg_len,
2338 "Unexpected error from select: %s", strerror(errno));
2339 report_capture_error(errmsg, please_report);
2344 * "select()" says we can read from the pipe without blocking
2346 #endif /* USE_THREADS */
2347 inpkts = cap_pipe_dispatch(ld, pcap_data, errmsg, errmsg_len);
2357 /* dispatch from pcap */
2358 #ifdef MUST_DO_SELECT
2360 * If we have "pcap_get_selectable_fd()", we use it to get the
2361 * descriptor on which to select; if that's -1, it means there
2362 * is no descriptor on which you can do a "select()" (perhaps
2363 * because you're capturing on a special device, and that device's
2364 * driver unfortunately doesn't support "select()", in which case
2365 * we don't do the select - which means it might not be possible
2366 * to stop a capture until a packet arrives. If that's unacceptable,
2367 * plead with whoever supplies the software for that device to add
2368 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2369 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2370 * later, so it can use pcap_breakloop().
2372 #ifdef LOG_CAPTURE_VERBOSE
2373 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2375 if (ld->pcap_fd != -1) {
2376 sel_ret = cap_pipe_select(ld->pcap_fd);
2379 * "select()" says we can read from it without blocking; go for
2382 * We don't have pcap_breakloop(), so we only process one packet
2383 * per pcap_dispatch() call, to allow a signal to stop the
2384 * processing immediately, rather than processing all packets
2385 * in a batch before quitting.
2387 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb,
2391 /* Error, rather than pcap_breakloop(). */
2392 ld->pcap_err = TRUE;
2394 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2397 if (sel_ret < 0 && errno != EINTR) {
2398 g_snprintf(errmsg, errmsg_len,
2399 "Unexpected error from select: %s", strerror(errno));
2400 report_capture_error(errmsg, please_report);
2406 #endif /* MUST_DO_SELECT */
2408 /* dispatch from pcap without select */
2410 #ifdef LOG_CAPTURE_VERBOSE
2411 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2415 * On Windows, we don't support asynchronously telling a process to
2416 * stop capturing; instead, we check for an indication on a pipe
2417 * after processing packets. We therefore process only one packet
2418 * at a time, so that we can check the pipe after every packet.
2420 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb, (u_char *) ld);
2422 inpkts = pcap_dispatch(ld->pcap_h, -1, capture_loop_packet_cb, (u_char *) ld);
2426 /* Error, rather than pcap_breakloop(). */
2427 ld->pcap_err = TRUE;
2429 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2431 #else /* pcap_next_ex */
2432 #ifdef LOG_CAPTURE_VERBOSE
2433 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2435 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2438 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2439 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
2440 * This should be fixed in the WinPcap 4.0 alpha release.
2442 * For reference, an example remote interface:
2443 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2446 /* emulate dispatch from pcap */
2449 struct pcap_pkthdr *pkt_header;
2454 (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1)
2455 capture_loop_packet_cb( (u_char *) ld, pkt_header, pkt_data);
2458 ld->pcap_err = TRUE;
2462 #endif /* pcap_next_ex */
2466 #ifdef LOG_CAPTURE_VERBOSE
2467 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2470 return ld->packet_count - packet_count_before;
2474 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2475 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2477 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2478 char *errmsg, int errmsg_len) {
2481 gchar *capfile_name;
2482 gboolean is_tempfile;
2487 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2488 (capture_opts->save_file) ? capture_opts->save_file : "");
2490 if (capture_opts->save_file != NULL) {
2491 /* We return to the caller while the capture is in progress.
2492 * Therefore we need to take a copy of save_file in
2493 * case the caller destroys it after we return.
2495 capfile_name = g_strdup(capture_opts->save_file);
2497 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2498 if (capture_opts->multi_files_on) {
2499 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2500 g_snprintf(errmsg, errmsg_len,
2501 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2502 g_free(capfile_name);
2505 if (strcmp(capfile_name, "-") == 0) {
2506 /* write to stdout */
2509 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
2510 _setmode(1, O_BINARY);
2513 } /* if (...output_to_pipe ... */
2516 if (capture_opts->multi_files_on) {
2517 /* ringbuffer is enabled */
2518 *save_file_fd = ringbuf_init(capfile_name,
2519 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
2521 /* we need the ringbuf name */
2522 if(*save_file_fd != -1) {
2523 g_free(capfile_name);
2524 capfile_name = g_strdup(ringbuf_current_filename());
2527 /* Try to open/create the specified file for use as a capture buffer. */
2528 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
2532 is_tempfile = FALSE;
2534 /* Choose a random name for the temporary capture buffer */
2535 *save_file_fd = create_tempfile(&tmpname, "wireshark");
2536 capfile_name = g_strdup(tmpname);
2540 /* did we fail to open the output file? */
2541 if (*save_file_fd == -1) {
2543 g_snprintf(errmsg, errmsg_len,
2544 "The temporary file to which the capture would be saved (\"%s\") "
2545 "could not be opened: %s.", capfile_name, strerror(errno));
2547 if (capture_opts->multi_files_on) {
2548 ringbuf_error_cleanup();
2551 g_snprintf(errmsg, errmsg_len,
2552 "The file to which the capture would be saved (\"%s\") "
2553 "could not be opened: %s.", capfile_name,
2556 g_free(capfile_name);
2560 if(capture_opts->save_file != NULL) {
2561 g_free(capture_opts->save_file);
2563 capture_opts->save_file = capfile_name;
2564 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2565 "g_free(capfile_name)". */
2567 ret = fchown(*save_file_fd, capture_opts->owner, capture_opts->group);
2575 #define TIME_GET() GetTickCount()
2577 #define TIME_GET() time(NULL)
2580 /* Do the low-level work of a capture.
2581 Returns TRUE if it succeeds, FALSE otherwise. */
2583 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
2585 time_t upd_time, cur_time;
2589 gint inpkts_to_sync_pipe = 0; /* packets not already send out to the sync_pipe */
2590 condition *cnd_file_duration = NULL;
2591 condition *cnd_autostop_files = NULL;
2592 condition *cnd_autostop_size = NULL;
2593 condition *cnd_autostop_duration = NULL;
2594 guint32 autostop_files = 0;
2597 gboolean cfilter_error = FALSE;
2598 #define MSG_MAX_LENGTH 4096
2599 char errmsg[MSG_MAX_LENGTH+1];
2600 char secondary_errmsg[MSG_MAX_LENGTH+1];
2601 int save_file_fd = -1;
2604 *secondary_errmsg = '\0';
2606 /* init the loop data */
2607 global_ld.go = TRUE;
2608 global_ld.packet_count = 0;
2609 if (capture_opts->has_autostop_packets)
2610 global_ld.packet_max = capture_opts->autostop_packets;
2612 global_ld.packet_max = 0; /* no limit */
2613 global_ld.err = 0; /* no error seen yet */
2614 global_ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
2615 global_ld.pcap_err = FALSE;
2616 global_ld.from_cap_pipe = FALSE;
2617 global_ld.pdh = NULL;
2619 global_ld.cap_pipe_fd = -1;
2621 global_ld.cap_pipe_h = INVALID_HANDLE_VALUE;
2623 #ifdef MUST_DO_SELECT
2624 global_ld.pcap_fd = 0;
2627 /* We haven't yet gotten the capture statistics. */
2628 *stats_known = FALSE;
2630 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
2631 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
2633 /* open the "input file" from network interface or capture pipe */
2634 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
2635 secondary_errmsg, sizeof(secondary_errmsg))) {
2639 /* init the input filter from the network interface (capture pipe will do nothing) */
2640 switch (capture_loop_init_filter(global_ld.pcap_h, global_ld.from_cap_pipe,
2641 capture_opts->iface,
2642 capture_opts->cfilter)) {
2644 case INITFILTER_NO_ERROR:
2647 case INITFILTER_BAD_FILTER:
2648 cfilter_error = TRUE;
2649 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(global_ld.pcap_h));
2652 case INITFILTER_OTHER_ERROR:
2653 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
2654 pcap_geterr(global_ld.pcap_h));
2655 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
2659 /* If we're supposed to write to a capture file, open it for output
2660 (temporary/specified name/ringbuffer) */
2661 if (capture_opts->saving_to_file) {
2662 if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
2666 /* set up to write to the already-opened capture output file/files */
2667 if (!capture_loop_init_output(capture_opts, save_file_fd, &global_ld,
2668 errmsg, sizeof(errmsg))) {
2672 /* XXX - capture SIGTERM and close the capture, in case we're on a
2673 Linux 2.0[.x] system and you have to explicitly close the capture
2674 stream in order to turn promiscuous mode off? We need to do that
2675 in other places as well - and I don't think that works all the
2676 time in any case, due to libpcap bugs. */
2678 /* Well, we should be able to start capturing.
2680 Sync out the capture file, so the header makes it to the file system,
2681 and send a "capture started successfully and capture file created"
2682 message to our parent so that they'll open the capture file and
2683 update its windows to indicate that we have a live capture in
2685 libpcap_dump_flush(global_ld.pdh, NULL);
2686 report_new_capture_file(capture_opts->save_file);
2689 /* initialize capture stop (and alike) conditions */
2690 init_capture_stop_conditions();
2691 /* create stop conditions */
2692 if (capture_opts->has_autostop_filesize)
2694 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
2695 if (capture_opts->has_autostop_duration)
2696 cnd_autostop_duration =
2697 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
2699 if (capture_opts->multi_files_on) {
2700 if (capture_opts->has_file_duration)
2702 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
2704 if (capture_opts->has_autostop_files)
2705 cnd_autostop_files =
2706 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
2709 /* init the time values */
2710 start_time = TIME_GET();
2711 upd_time = TIME_GET();
2713 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
2715 /* WOW, everything is prepared! */
2716 /* please fasten your seat belts, we will enter now the actual capture loop */
2717 while (global_ld.go) {
2718 /* dispatch incoming packets */
2719 inpkts = capture_loop_dispatch(capture_opts, &global_ld, errmsg,
2723 /* any news from our parent (signal pipe)? -> just stop the capture */
2724 if (!signal_pipe_check_running()) {
2725 global_ld.go = FALSE;
2730 inpkts_to_sync_pipe += inpkts;
2732 /* check capture size condition */
2733 if (cnd_autostop_size != NULL &&
2734 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)){
2735 /* Capture size limit reached, do we have another file? */
2736 if (capture_opts->multi_files_on) {
2737 if (cnd_autostop_files != NULL &&
2738 cnd_eval(cnd_autostop_files, ++autostop_files)) {
2739 /* no files left: stop here */
2740 global_ld.go = FALSE;
2744 /* Switch to the next ringbuffer file */
2745 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2746 &save_file_fd, &global_ld.err)) {
2747 gboolean successful;
2749 /* File switch succeeded: reset the conditions */
2750 global_ld.bytes_written = 0;
2751 if (capture_opts->use_pcapng) {
2754 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2755 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2756 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);
2758 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2759 &global_ld.bytes_written, &global_ld.err);
2762 fclose(global_ld.pdh);
2763 global_ld.pdh = NULL;
2764 global_ld.go = FALSE;
2767 cnd_reset(cnd_autostop_size);
2768 if (cnd_file_duration) {
2769 cnd_reset(cnd_file_duration);
2771 libpcap_dump_flush(global_ld.pdh, NULL);
2772 report_packet_count(inpkts_to_sync_pipe);
2773 inpkts_to_sync_pipe = 0;
2774 report_new_capture_file(capture_opts->save_file);
2776 /* File switch failed: stop here */
2777 global_ld.go = FALSE;
2781 /* single file, stop now */
2782 global_ld.go = FALSE;
2785 } /* cnd_autostop_size */
2786 if (capture_opts->output_to_pipe) {
2787 libpcap_dump_flush(global_ld.pdh, NULL);
2791 /* Only update once a second (Win32: 500ms) so as not to overload slow
2792 * displays. This also prevents too much context-switching between the
2793 * dumpcap and wireshark processes */
2794 cur_time = TIME_GET();
2796 if ( (cur_time - upd_time) > 500) {
2798 if (cur_time - upd_time > 0) {
2800 upd_time = cur_time;
2802 /*if (pcap_stats(pch, stats) >= 0) {
2803 *stats_known = TRUE;
2806 /* Let the parent process know. */
2807 if (inpkts_to_sync_pipe) {
2809 libpcap_dump_flush(global_ld.pdh, NULL);
2811 /* Send our parent a message saying we've written out "inpkts_to_sync_pipe"
2812 packets to the capture file. */
2813 report_packet_count(inpkts_to_sync_pipe);
2815 inpkts_to_sync_pipe = 0;
2818 /* check capture duration condition */
2819 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
2820 /* The maximum capture time has elapsed; stop the capture. */
2821 global_ld.go = FALSE;
2825 /* check capture file duration condition */
2826 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
2827 /* duration limit reached, do we have another file? */
2828 if (capture_opts->multi_files_on) {
2829 if (cnd_autostop_files != NULL &&
2830 cnd_eval(cnd_autostop_files, ++autostop_files)) {
2831 /* no files left: stop here */
2832 global_ld.go = FALSE;
2836 /* Switch to the next ringbuffer file */
2837 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2838 &save_file_fd, &global_ld.err)) {
2839 gboolean successful;
2841 /* file switch succeeded: reset the conditions */
2842 global_ld.bytes_written = 0;
2843 if (capture_opts->use_pcapng) {
2846 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2847 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2848 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);
2850 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2851 &global_ld.bytes_written, &global_ld.err);
2854 fclose(global_ld.pdh);
2855 global_ld.pdh = NULL;
2856 global_ld.go = FALSE;
2859 cnd_reset(cnd_file_duration);
2860 if(cnd_autostop_size)
2861 cnd_reset(cnd_autostop_size);
2862 libpcap_dump_flush(global_ld.pdh, NULL);
2863 report_packet_count(inpkts_to_sync_pipe);
2864 inpkts_to_sync_pipe = 0;
2865 report_new_capture_file(capture_opts->save_file);
2867 /* File switch failed: stop here */
2868 global_ld.go = FALSE;
2872 /* single file, stop now */
2873 global_ld.go = FALSE;
2876 } /* cnd_file_duration */
2879 } /* while (global_ld.go) */
2881 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
2883 /* delete stop conditions */
2884 if (cnd_file_duration != NULL)
2885 cnd_delete(cnd_file_duration);
2886 if (cnd_autostop_files != NULL)
2887 cnd_delete(cnd_autostop_files);
2888 if (cnd_autostop_size != NULL)
2889 cnd_delete(cnd_autostop_size);
2890 if (cnd_autostop_duration != NULL)
2891 cnd_delete(cnd_autostop_duration);
2893 /* did we had a pcap (input) error? */
2894 if (global_ld.pcap_err) {
2895 /* On Linux, if an interface goes down while you're capturing on it,
2896 you'll get a "recvfrom: Network is down" error (ENETDOWN).
2897 (At least you will if strerror() doesn't show a local translation
2900 On FreeBSD and OS X, if a network adapter disappears while
2901 you're capturing on it, you'll get a "read: Device not configured"
2902 error (ENXIO). (See previous parenthetical note.)
2904 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
2906 These should *not* be reported to the Wireshark developers. */
2909 cap_err_str = pcap_geterr(global_ld.pcap_h);
2910 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
2911 strcmp(cap_err_str, "read: Device not configured") == 0 ||
2912 strcmp(cap_err_str, "read: I/O error") == 0) {
2913 report_capture_error("The network adapter on which the capture was being done "
2914 "is no longer running; the capture has stopped.",
2917 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
2919 report_capture_error(errmsg, please_report);
2922 else if (global_ld.from_cap_pipe && global_ld.cap_pipe_err == PIPERR)
2923 report_capture_error(errmsg, "");
2925 /* did we had an error while capturing? */
2926 if (global_ld.err == 0) {
2929 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
2930 global_ld.err, FALSE);
2931 report_capture_error(errmsg, please_report);
2935 if (capture_opts->saving_to_file) {
2936 /* close the wiretap (output) file */
2937 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
2941 /* there might be packets not yet notified to the parent */
2942 /* (do this after closing the file, so all packets are already flushed) */
2943 if(inpkts_to_sync_pipe) {
2944 report_packet_count(inpkts_to_sync_pipe);
2945 inpkts_to_sync_pipe = 0;
2948 /* If we've displayed a message about a write error, there's no point
2949 in displaying another message about an error on close. */
2950 if (!close_ok && write_ok) {
2951 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
2953 report_capture_error(errmsg, "");
2957 * XXX We exhibit different behaviour between normal mode and sync mode
2958 * when the pipe is stdin and not already at EOF. If we're a child, the
2959 * parent's stdin isn't closed, so if the user starts another capture,
2960 * cap_pipe_open_live() will very likely not see the expected magic bytes and
2961 * will say "Unrecognized libpcap format". On the other hand, in normal
2962 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
2965 /* get packet drop statistics from pcap */
2966 if(global_ld.pcap_h != NULL) {
2967 g_assert(!global_ld.from_cap_pipe);
2968 /* Get the capture statistics, so we know how many packets were
2970 if (pcap_stats(global_ld.pcap_h, stats) >= 0) {
2971 *stats_known = TRUE;
2972 /* Let the parent process know. */
2973 report_packet_drops(stats->ps_drop);
2975 g_snprintf(errmsg, sizeof(errmsg),
2976 "Can't get packet-drop statistics: %s",
2977 pcap_geterr(global_ld.pcap_h));
2978 report_capture_error(errmsg, please_report);
2982 /* close the input file (pcap or capture pipe) */
2983 capture_loop_close_input(&global_ld);
2985 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
2987 /* ok, if the write and the close were successful. */
2988 return write_ok && close_ok;
2991 if (capture_opts->multi_files_on) {
2992 /* cleanup ringbuffer */
2993 ringbuf_error_cleanup();
2995 /* We can't use the save file, and we have no FILE * for the stream
2996 to close in order to close it, so close the FD directly. */
2997 if(save_file_fd != -1) {
2998 ws_close(save_file_fd);
3001 /* We couldn't even start the capture, so get rid of the capture
3003 if(capture_opts->save_file != NULL) {
3004 ws_unlink(capture_opts->save_file);
3005 g_free(capture_opts->save_file);
3008 capture_opts->save_file = NULL;
3010 report_cfilter_error(capture_opts->cfilter, errmsg);
3012 report_capture_error(errmsg, secondary_errmsg);
3014 /* close the input file (pcap or cap_pipe) */
3015 capture_loop_close_input(&global_ld);
3017 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3023 static void capture_loop_stop(void)
3025 #ifdef HAVE_PCAP_BREAKLOOP
3026 if(global_ld.pcap_h != NULL)
3027 pcap_breakloop(global_ld.pcap_h);
3029 global_ld.go = FALSE;
3034 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3035 int err, gboolean is_close)
3040 g_snprintf(errmsg, errmsglen,
3041 "Not all the packets could be written to the file"
3042 " to which the capture was being saved\n"
3043 "(\"%s\") because there is no space left on the file system\n"
3044 "on which that file resides.",
3050 g_snprintf(errmsg, errmsglen,
3051 "Not all the packets could be written to the file"
3052 " to which the capture was being saved\n"
3053 "(\"%s\") because you are too close to, or over,"
3054 " your disk quota\n"
3055 "on the file system on which that file resides.",
3060 case WTAP_ERR_CANT_CLOSE:
3061 g_snprintf(errmsg, errmsglen,
3062 "The file to which the capture was being saved"
3063 " couldn't be closed for some unknown reason.");
3066 case WTAP_ERR_SHORT_WRITE:
3067 g_snprintf(errmsg, errmsglen,
3068 "Not all the packets could be written to the file"
3069 " to which the capture was being saved\n"
3076 g_snprintf(errmsg, errmsglen,
3077 "The file to which the capture was being saved\n"
3078 "(\"%s\") could not be closed: %s.",
3079 fname, wtap_strerror(err));
3081 g_snprintf(errmsg, errmsglen,
3082 "An error occurred while writing to the file"
3083 " to which the capture was being saved\n"
3085 fname, wtap_strerror(err));
3092 /* one packet was captured, process it */
3094 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
3097 loop_data *ld = (loop_data *) (void *) user;
3100 /* We may be called multiple times from pcap_dispatch(); if we've set
3101 the "stop capturing" flag, ignore this packet, as we're not
3102 supposed to be saving any more packets. */
3107 gboolean successful;
3108 /* We're supposed to write the packet to a file; do so.
3109 If this fails, set "ld->go" to FALSE, to stop the capture, and set
3110 "ld->err" to the error. */
3111 if (global_capture_opts.use_pcapng) {
3112 successful = libpcap_write_enhanced_packet_block(ld->pdh, phdr, 0, pd, &ld->bytes_written, &err);
3114 successful = libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err);
3121 /* if the user told us to stop after x packets, do we already have enough? */
3122 if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
3131 /* And now our feature presentation... [ fade to music ] */
3133 main(int argc, char *argv[])
3136 gboolean arg_error = FALSE;
3141 struct sigaction action, oldaction;
3144 gboolean start_capture = TRUE;
3145 gboolean stats_known;
3146 struct pcap_stat stats;
3147 GLogLevelFlags log_flags;
3148 gboolean list_interfaces = FALSE;
3149 gboolean list_link_layer_types = FALSE;
3150 gboolean machine_readable = FALSE;
3151 gboolean print_statistics = FALSE;
3152 int status, run_once_args = 0;
3154 #if defined(__APPLE__) && defined(__LP64__)
3155 struct utsname osinfo;
3158 #ifdef HAVE_PCAP_REMOTE
3159 #define OPTSTRING_A "A:"
3160 #define OPTSTRING_r "r"
3161 #define OPTSTRING_u "u"
3163 #define OPTSTRING_A ""
3164 #define OPTSTRING_r ""
3165 #define OPTSTRING_u ""
3168 #ifdef HAVE_PCAP_SETSAMPLING
3169 #define OPTSTRING_m "m:"
3171 #define OPTSTRING_m ""
3174 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
3175 #define OPTSTRING_B "B:"
3177 #define OPTSTRING_B ""
3178 #endif /* _WIN32 or HAVE_PCAP_CREATE */
3180 #ifdef HAVE_PCAP_CREATE
3181 #define OPTSTRING_I "I"
3183 #define OPTSTRING_I ""
3186 #define OPTSTRING "a:" OPTSTRING_A "b:" OPTSTRING_B "c:Df:hi:" OPTSTRING_I "L" OPTSTRING_m "Mnp" OPTSTRING_r "Ss:" OPTSTRING_u "vw:y:Z:"
3188 #ifdef DEBUG_CHILD_DUMPCAP
3189 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
3190 fprintf (stderr, "Unable to open debug log file !\n");
3195 #if defined(__APPLE__) && defined(__LP64__)
3197 * Is this Mac OS X 10.6.x, other than 10.6.2? If so, we need a bug
3198 * workaround - timeouts less than 1 second don't work with libpcap
3199 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
3200 * and re-introduced in 10.6.3. We don't know whether it'll be fixed
3201 * again in a later 10.6.x release; we'll assume that it'll be fixed
3202 * in any future major releases.)
3204 if (uname(&osinfo) == 0) {
3206 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
3207 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
3208 * number of 10.0.0, not 10.1.0 - go figure).
3210 if (strncmp(osinfo.release, "10.", 3) == 0) {
3212 * OK, it's Snow Leopard - which version?
3214 if (strcmp(osinfo.release, "10.2.0") != 0) {
3216 need_timeout_workaround = TRUE;
3223 * Determine if dumpcap is being requested to run in a special
3224 * capture_child mode by going thru the command line args to see if
3225 * a -Z is present. (-Z is a hidden option).
3227 * The primary result of running in capture_child mode is that
3228 * all messages sent out on stderr are in a special type/len/string
3229 * format to allow message processing by type. These messages include
3230 * error messages if dumpcap fails to start the operation it was
3231 * requested to do, as well as various "status" messages which are sent
3232 * when an actual capture is in progress, and a "success" message sent
3233 * if dumpcap was requested to perform an operation other than a
3236 * Capture_child mode would normally be requested by a parent process
3237 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
3238 * to which dumpcap stderr has been redirected. It might also have
3239 * another pipe to obtain dumpcap stdout output; for operations other
3240 * than a capture, that information is formatted specially for easier
3241 * parsing by the parent process.
3243 * Capture_child mode needs to be determined immediately upon
3244 * startup so that any messages generated by dumpcap in this mode
3245 * (eg: during initialization) will be formatted properly.
3248 for (i=1; i<argc; i++) {
3249 if (strcmp("-Z", argv[i]) == 0) {
3250 capture_child = TRUE;
3251 machine_readable = TRUE; /* request machine-readable output */
3253 /* set output pipe to binary mode, to avoid ugly text conversions */
3254 _setmode(2, O_BINARY);
3259 /* The default_log_handler will use stdout, which makes trouble in */
3260 /* capture child mode, as it uses stdout for it's sync_pipe. */
3261 /* So: the filtering is done in the console_log_handler and not here.*/
3262 /* We set the log handlers right up front to make sure that any log */
3263 /* messages when running as child will be sent back to the parent */
3264 /* with the correct format. */
3268 G_LOG_LEVEL_CRITICAL|
3269 G_LOG_LEVEL_WARNING|
3270 G_LOG_LEVEL_MESSAGE|
3273 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
3275 g_log_set_handler(NULL,
3277 console_log_handler, NULL /* user_data */);
3278 g_log_set_handler(LOG_DOMAIN_MAIN,
3280 console_log_handler, NULL /* user_data */);
3281 g_log_set_handler(LOG_DOMAIN_CAPTURE,
3283 console_log_handler, NULL /* user_data */);
3284 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
3286 console_log_handler, NULL /* user_data */);
3289 /* Load wpcap if possible. Do this before collecting the run-time version information */
3292 /* ... and also load the packet.dll from wpcap */
3293 /* XXX - currently not required, may change later. */
3294 /*wpcap_packet_load();*/
3296 /* Start windows sockets */
3297 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
3299 /* Set handler for Ctrl+C key */
3300 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
3302 /* Prepare to read from a pipe */
3303 if (!g_thread_supported ())
3304 g_thread_init (NULL);
3305 cap_pipe_pending_q = g_async_queue_new();
3306 cap_pipe_done_q = g_async_queue_new();
3307 cap_pipe_read_mtx = g_mutex_new();
3310 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
3312 action.sa_handler = capture_cleanup_handler;
3314 * Arrange that system calls not get restarted, because when
3315 * our signal handler returns we don't want to restart
3316 * a call that was waiting for packets to arrive.
3318 action.sa_flags = 0;
3319 sigemptyset(&action.sa_mask);
3320 sigaction(SIGTERM, &action, NULL);
3321 sigaction(SIGINT, &action, NULL);
3322 sigaction(SIGPIPE, &action, NULL);
3323 sigaction(SIGHUP, NULL, &oldaction);
3324 if (oldaction.sa_handler == SIG_DFL)
3325 sigaction(SIGHUP, &action, NULL);
3328 /* ----------------------------------------------------------------- */
3329 /* Privilege and capability handling */
3331 /* 1. Running not as root or suid root; no special capabilities. */
3334 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
3337 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
3339 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
3340 /* capabilities; Drop all other capabilities; */
3341 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3342 /* else: after pcap_open_live() in capture_loop_open_input() */
3343 /* drop all capabilities (NET_RAW and NET_ADMIN); */
3344 /* (Note: this means that the process, although logged in */
3345 /* as root, does not have various permissions such as the */
3346 /* ability to bypass file access permissions). */
3347 /* XXX: Should we just leave capabilities alone in this case */
3348 /* so that user gets expected effect that root can do */
3351 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
3353 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3354 /* else: after pcap_open_live() in capture_loop_open_input() */
3355 /* drop suid root (set euid=ruid).(ie: keep suid until after */
3356 /* pcap_open_live). */
3358 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
3360 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
3361 /* capabilities; Drop all other capabilities; */
3362 /* Drop suid privileges (euid=ruid); */
3363 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3364 /* else: after pcap_open_live() in capture_loop_open_input() */
3365 /* drop all capabilities (NET_RAW and NET_ADMIN). */
3367 /* XXX: For some Linux versions/distros with capabilities */
3368 /* a 'normal' process with any capabilities cannot be */
3369 /* 'killed' (signaled) from another (same uid) non-privileged */
3371 /* For example: If (non-suid) Wireshark forks a */
3372 /* child suid dumpcap which acts as described here (case 5), */
3373 /* Wireshark will be unable to kill (signal) the child */
3374 /* dumpcap process until the capabilities have been dropped */
3375 /* (after pcap_open_live()). */
3376 /* This behaviour will apparently be changed in the kernel */
3377 /* to allow the kill (signal) in this case. */
3378 /* See the following for details: */
3379 /* http://www.mail-archive.com/ [wrapped] */
3380 /* linux-security-module@vger.kernel.org/msg02913.html */
3382 /* It is therefore conceivable that if dumpcap somehow hangs */
3383 /* in pcap_open_live or before that wireshark will not */
3384 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
3385 /* In this case, exiting wireshark will kill the child */
3386 /* dumpcap process. */
3388 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
3389 /* capabilities; Using libcap. Note: capset cmd (which see) */
3390 /* used to assign capabilities to file. */
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 all capabilities (NET_RAW and NET_ADMIN) */
3396 /* ToDo: -S (stats) should drop privileges/capabilities when no */
3397 /* longer required (similar to capture). */
3399 /* ----------------------------------------------------------------- */
3401 get_credential_info();
3404 /* If 'started with special privileges' (and using libcap) */
3405 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
3406 /* Set euid/egid = ruid/rgid to remove suid privileges */
3407 relinquish_privs_except_capture();
3410 /* Set the initial values in the capture options. This might be overwritten
3411 by the command line parameters. */
3412 capture_opts_init(&global_capture_opts, NULL);
3414 /* Default to capturing the entire packet. */
3415 global_capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
3417 /* We always save to a file - if no file was specified, we save to a
3419 global_capture_opts.saving_to_file = TRUE;
3420 global_capture_opts.has_ring_num_files = TRUE;
3422 /* Now get our args */
3423 while ((opt = getopt(argc, argv, OPTSTRING)) != -1) {
3425 case 'h': /* Print help and exit */
3429 case 'v': /* Show version and exit */
3431 GString *comp_info_str;
3432 GString *runtime_info_str;
3433 /* Assemble the compile-time version information string */
3434 comp_info_str = g_string_new("Compiled ");
3435 get_compiled_version_info(comp_info_str, NULL);
3437 /* Assemble the run-time version information string */
3438 runtime_info_str = g_string_new("Running ");
3439 get_runtime_version_info(runtime_info_str, NULL);
3440 show_version(comp_info_str, runtime_info_str);
3441 g_string_free(comp_info_str, TRUE);
3442 g_string_free(runtime_info_str, TRUE);
3446 /*** capture option specific ***/
3447 case 'a': /* autostop criteria */
3448 case 'b': /* Ringbuffer option */
3449 case 'c': /* Capture x packets */
3450 case 'f': /* capture filter */
3451 case 'i': /* Use interface x */
3452 case 'n': /* Use pcapng format */
3453 case 'p': /* Don't capture in promiscuous mode */
3454 case 's': /* Set the snapshot (capture) length */
3455 case 'w': /* Write to capture file x */
3456 case 'y': /* Set the pcap data link type */
3457 #ifdef HAVE_PCAP_REMOTE
3458 case 'u': /* Use UDP for data transfer */
3459 case 'r': /* Capture own RPCAP traffic too */
3460 case 'A': /* Authentication */
3462 #ifdef HAVE_PCAP_SETSAMPLING
3463 case 'm': /* Sampling */
3465 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
3466 case 'B': /* Buffer size */
3467 #endif /* _WIN32 or HAVE_PCAP_CREATE */
3468 #ifdef HAVE_PCAP_CREATE
3469 case 'I': /* Monitor mode */
3471 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
3476 /*** hidden option: Wireshark child mode (using binary output messages) ***/
3478 capture_child = TRUE;
3480 /* set output pipe to binary mode, to avoid ugly text conversions */
3481 _setmode(2, O_BINARY);
3483 * optarg = the control ID, aka the PPID, currently used for the
3486 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
3487 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
3488 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
3489 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
3491 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
3492 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3493 "Signal pipe: Unable to open %s. Dead parent?",
3501 /*** all non capture option specific ***/
3502 case 'D': /* Print a list of capture devices and exit */
3503 list_interfaces = TRUE;
3506 case 'L': /* Print list of link-layer types and exit */
3507 list_link_layer_types = TRUE;
3510 case 'S': /* Print interface statistics once a second */
3511 print_statistics = TRUE;
3514 case 'M': /* For -D, -L, and -S, print machine-readable output */
3515 machine_readable = TRUE;
3518 case '?': /* Bad flag - print usage message */
3519 cmdarg_err("Invalid Option: %s", argv[optind-1]);
3527 /* user specified file name as regular command-line argument */
3528 /* XXX - use it as the capture file name (or something else)? */
3535 * Extra command line arguments were specified; complain.
3536 * XXX - interpret as capture filter, as tcpdump and tshark do?
3538 cmdarg_err("Invalid argument: %s", argv[0]);
3547 if (run_once_args > 1) {
3548 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
3550 } else if (run_once_args == 1) {
3551 /* We're supposed to print some information, rather than
3552 to capture traffic; did they specify a ring buffer option? */
3553 if (global_capture_opts.multi_files_on) {
3554 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
3558 /* We're supposed to capture traffic; was the ring buffer option
3559 specified and, if so, does it make sense? */
3560 if (global_capture_opts.multi_files_on) {
3561 /* Ring buffer works only under certain conditions:
3562 a) ring buffer does not work with temporary files;
3563 b) it makes no sense to enable the ring buffer if the maximum
3564 file size is set to "infinite". */
3565 if (global_capture_opts.save_file == NULL) {
3566 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
3567 global_capture_opts.multi_files_on = FALSE;
3569 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
3570 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
3571 /* XXX - this must be redesigned as the conditions changed */
3572 /* global_capture_opts.multi_files_on = FALSE;*/
3578 * "-D" requires no interface to be selected; it's supposed to list
3581 if (list_interfaces) {
3582 /* Get the list of interfaces */
3587 if_list = capture_interface_list(&err, &err_str);
3588 if (if_list == NULL) {
3590 case CANT_GET_INTERFACE_LIST:
3591 cmdarg_err("%s", err_str);
3596 case NO_INTERFACES_FOUND:
3598 * If we're being run by another program, just give them
3599 * an empty list of interfaces, don't report this as
3600 * an error; that lets them decide whether to report
3601 * this as an error or not.
3603 if (!machine_readable) {
3604 cmdarg_err("There are no interfaces on which a capture can be done");
3611 if (machine_readable) /* tab-separated values to stdout */
3612 print_machine_readable_interfaces(if_list);
3614 capture_opts_print_interfaces(if_list);
3615 free_interface_list(if_list);
3620 * "-S" requires no interface to be selected; it gives statistics
3621 * for all interfaces.
3623 if (print_statistics) {
3624 status = print_statistics_loop(machine_readable);
3629 * "-L", and capturing, act on a particular interface, so we have to
3630 * have an interface; if none was specified, pick a default.
3632 if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
3633 /* cmdarg_err() already called .... */
3637 /* Let the user know what interface was chosen. */
3638 /* get_interface_descriptive_name() is not available! */
3639 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", global_capture_opts.iface);
3641 if (list_link_layer_types) {
3642 /* Get the list of link-layer types for the capture device. */
3643 if_capabilities_t *caps;
3646 caps = get_if_capabilities(global_capture_opts.iface,
3647 global_capture_opts.monitor_mode, &err_str);
3649 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
3650 "Please check to make sure you have sufficient permissions, and that\n"
3651 "you have the proper interface or pipe specified.", global_capture_opts.iface, err_str);
3655 if (caps->data_link_types == NULL) {
3656 cmdarg_err("The capture device \"%s\" has no data link types.", global_capture_opts.iface);
3659 if (machine_readable) /* tab-separated values to stdout */
3660 print_machine_readable_if_capabilities(caps);
3662 capture_opts_print_if_capabilities(caps,
3663 global_capture_opts.monitor_mode);
3664 free_if_capabilities(caps);
3668 /* We're supposed to do a capture. Process the remaining arguments. */
3669 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
3670 capture_opts_trim_ring_num_files(&global_capture_opts);
3672 /* Now start the capture. */
3674 if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
3678 /* capture failed */
3685 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
3686 const char *message, gpointer user_data _U_)
3693 /* ignore log message, if log_level isn't interesting */
3694 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3695 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
3700 /* create a "timestamp" */
3702 today = localtime(&curr);
3704 switch(log_level & G_LOG_LEVEL_MASK) {
3705 case G_LOG_LEVEL_ERROR:
3708 case G_LOG_LEVEL_CRITICAL:
3711 case G_LOG_LEVEL_WARNING:
3714 case G_LOG_LEVEL_MESSAGE:
3717 case G_LOG_LEVEL_INFO:
3720 case G_LOG_LEVEL_DEBUG:
3724 fprintf(stderr, "unknown log_level %u\n", log_level);
3726 g_assert_not_reached();
3729 /* Generate the output message */
3730 if(log_level & G_LOG_LEVEL_MESSAGE) {
3731 /* normal user messages without additional infos */
3732 msg = g_strdup_printf("%s\n", message);
3734 /* info/debug messages with additional infos */
3735 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
3736 today->tm_hour, today->tm_min, today->tm_sec,
3737 log_domain != NULL ? log_domain : "",
3741 /* DEBUG & INFO msgs (if we're debugging today) */
3742 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3743 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3744 #ifdef DEBUG_DUMPCAP
3745 fprintf(stderr, "%s", msg);
3748 #ifdef DEBUG_CHILD_DUMPCAP
3749 fprintf(debug_log, "%s", msg);
3757 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
3758 /* to parent especially formatted if dumpcap running as child. */
3759 if (capture_child) {
3760 sync_pipe_errmsg_to_parent(2, msg, "");
3762 fprintf(stderr, "%s", msg);
3769 /****************************************************************************************************************/
3770 /* indication report routines */
3774 report_packet_count(int packet_count)
3776 char tmp[SP_DECISIZE+1+1];
3777 static int count = 0;
3780 g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
3781 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
3782 pipe_write_block(2, SP_PACKET_COUNT, tmp);
3784 count += packet_count;
3785 fprintf(stderr, "\rPackets: %u ", count);
3786 /* stderr could be line buffered */
3792 report_new_capture_file(const char *filename)
3795 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
3796 pipe_write_block(2, SP_FILE, filename);
3798 fprintf(stderr, "File: %s\n", filename);
3799 /* stderr could be line buffered */
3805 report_cfilter_error(const char *cfilter, const char *errmsg)
3807 if (capture_child) {
3808 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
3809 pipe_write_block(2, SP_BAD_FILTER, errmsg);
3812 "Invalid capture filter: \"%s\"!\n"
3814 "That string isn't a valid capture filter (%s).\n"
3815 "See the User's Guide for a description of the capture filter syntax.\n",
3821 report_capture_error(const char *error_msg, const char *secondary_error_msg)
3824 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3825 "Primary Error: %s", error_msg);
3826 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3827 "Secondary Error: %s", secondary_error_msg);
3828 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
3830 fprintf(stderr, "%s\n%s\n", error_msg, secondary_error_msg);
3835 report_packet_drops(guint32 drops)
3837 char tmp[SP_DECISIZE+1+1];
3839 g_snprintf(tmp, sizeof(tmp), "%u", drops);
3842 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
3843 pipe_write_block(2, SP_DROPS, tmp);
3845 fprintf(stderr, "Packets dropped: %s\n", tmp);
3846 /* stderr could be line buffered */
3852 /****************************************************************************************************************/
3853 /* signal_pipe handling */
3858 signal_pipe_check_running(void)
3860 /* any news from our parent? -> just stop the capture */
3864 /* if we are running standalone, no check required */
3865 if(!capture_child) {
3869 if(!sig_pipe_name || !sig_pipe_handle) {
3870 /* This shouldn't happen */
3871 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3872 "Signal pipe: No name or handle");
3877 * XXX - We should have the process ID of the parent (from the "-Z" flag)
3878 * at this point. Should we check to see if the parent is still alive,
3879 * e.g. by using OpenProcess?
3882 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
3884 if(!result || avail > 0) {
3885 /* peek failed or some bytes really available */
3886 /* (if not piping from stdin this would fail) */
3887 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3888 "Signal pipe: Stop capture: %s", sig_pipe_name);
3889 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3890 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
3891 sig_pipe_handle, result, avail);
3894 /* pipe ok and no bytes available */
3901 * Editor modelines - http://www.wireshark.org/tools/modelines.html
3906 * indent-tabs-mode: nil
3909 * vi: set shiftwidth=4 tabstop=8 expandtab
3910 * :indentSize=4:tabSize=8:noTabs=true: