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;
148 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
149 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
152 /** Stop a low-level capture (stops the capture child). */
153 static void capture_loop_stop(void);
155 #if !defined (__linux__)
156 #ifndef HAVE_PCAP_BREAKLOOP
158 * We don't have pcap_breakloop(), which is the only way to ensure that
159 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
160 * won't, if the call to read the next packet or batch of packets is
161 * is interrupted by a signal on UN*X, just go back and try again to
164 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
165 * the signal handler, set a flag to stop capturing; however, without
166 * a guarantee of that sort, we can't guarantee that we'll stop capturing
167 * if the read will be retried and won't time out if no packets arrive.
169 * Therefore, on at least some platforms, we work around the lack of
170 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
171 * to wait for packets to arrive, so that we're probably going to be
172 * blocked in the select() when the signal arrives, and can just bail
173 * out of the loop at that point.
175 * However, we don't want to that on BSD (because "select()" doesn't work
176 * correctly on BPF devices on at least some releases of some flavors of
177 * BSD), and we don't want to do it on Windows (because "select()" is
178 * something for sockets, not for arbitrary handles). (Note that "Windows"
179 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
180 * using WinPcap, not a UNIX libpcap.)
182 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
183 * on BSD times out even if no packets have arrived, so we'll eventually
184 * exit pcap_dispatch() with an indication that no packets have arrived,
185 * and will break out of the capture loop at that point.
187 * On Windows, we can't send a SIGINT to stop capturing, so none of this
188 * applies in any case.
190 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
191 * want to include it if it's not present on this platform, however.
193 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
194 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
196 # define MUST_DO_SELECT
197 # endif /* avoid select */
198 #endif /* HAVE_PCAP_BREAKLOOP */
200 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
201 * in pcap_dispatch(); on the other hand, select() works just fine there.
202 * Hence we use a select for that come what may.
204 #define MUST_DO_SELECT
207 /** init the capture filter */
210 INITFILTER_BAD_FILTER,
211 INITFILTER_OTHER_ERROR
212 } initfilter_status_t;
214 typedef struct _loop_data {
216 gboolean go; /* TRUE as long as we're supposed to keep capturing */
217 int err; /* if non-zero, error seen while capturing */
218 gint packet_count; /* Number of packets we have already captured */
219 gint packet_max; /* Number of packets we're supposed to capture - 0 means infinite */
220 gint inpkts_to_sync_pipe; /* Packets not already send out to the sync_pipe */
222 gboolean report_packet_count; /* Set by SIGINFO handler; print packet count */
225 /* pcap "input file" */
226 pcap_t *pcap_h; /* pcap handle */
227 gboolean pcap_err; /* TRUE if error from pcap */
228 #ifdef MUST_DO_SELECT
229 int pcap_fd; /* pcap file descriptor */
232 /* capture pipe (unix only "input file") */
233 gboolean from_cap_pipe; /* TRUE if we are capturing data from a capture pipe */
234 struct pcap_hdr cap_pipe_hdr; /* Pcap header when capturing from a pipe */
235 struct pcaprec_modified_hdr cap_pipe_rechdr; /* Pcap record header when capturing from a pipe */
237 HANDLE cap_pipe_h; /* The handle of the capture pipe */
239 int cap_pipe_fd; /* the file descriptor of the capture pipe */
241 gboolean cap_pipe_modified; /* TRUE if data in the pipe uses modified pcap headers */
242 gboolean cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
244 char * cap_pipe_buf; /* Pointer to the data buffer we read into */
245 #endif /* USE_THREADS */
246 int cap_pipe_bytes_to_read;/* Used by cap_pipe_dispatch */
247 int cap_pipe_bytes_read; /* Used by cap_pipe_dispatch */
249 STATE_EXPECT_REC_HDR,
254 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
263 guint32 autostop_files;
267 * Standard secondary message for unexpected errors.
269 static const char please_report[] =
270 "Please report this to the Wireshark developers.\n"
271 "(This is not a crash; please do not report it as such.)";
274 * This needs to be static, so that the SIGINT handler can clear the "go"
277 static loop_data global_ld;
281 * Timeout, in milliseconds, for reads from the stream of captured packets.
283 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
284 * 64-bit applications, with sub-second timeouts not to work. The bug is
287 #if defined(__APPLE__) && defined(__LP64__)
288 static gboolean need_timeout_workaround;
290 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
292 #define CAP_READ_TIMEOUT 250
296 * Timeout, in microseconds, for threaded reads from a pipe.
298 #define THREAD_READ_TIMEOUT 100
299 static const char *cap_pipe_err_str;
302 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
303 const char *message, gpointer user_data _U_);
305 /* capture related options */
306 static capture_options global_capture_opts;
308 static void capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
310 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
311 int err, gboolean is_close);
313 static void exit_main(int err) G_GNUC_NORETURN;
315 static void report_new_capture_file(const char *filename);
316 static void report_packet_count(int packet_count);
317 static void report_packet_drops(guint32 drops);
318 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
319 static void report_cfilter_error(const char *cfilter, const char *errmsg);
322 print_usage(gboolean print_ver) {
330 "Dumpcap " VERSION "%s\n"
331 "Capture network packets and dump them into a libpcap file.\n"
332 "See http://www.wireshark.org for more information.\n",
333 wireshark_svnversion);
337 fprintf(output, "\nUsage: dumpcap [options] ...\n");
338 fprintf(output, "\n");
339 fprintf(output, "Capture interface:\n");
340 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
341 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
342 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
343 fprintf(output, " -p don't capture in promiscuous mode\n");
344 #ifdef HAVE_PCAP_CREATE
345 fprintf(output, " -I capture in monitor mode, if available\n");
347 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
348 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
350 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
351 fprintf(output, " -D print list of interfaces and exit\n");
352 fprintf(output, " -L print list of link-layer types of iface and exit\n");
353 fprintf(output, " -S print statistics for each interface once every second\n");
354 fprintf(output, " -M for -D, -L, and -S produce machine-readable output\n");
355 fprintf(output, "\n");
356 #ifdef HAVE_PCAP_REMOTE
357 fprintf(output, "\nRPCAP options:\n");
358 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
359 fprintf(output, " -u use UDP for RPCAP data transfer\n");
360 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
361 #ifdef HAVE_PCAP_SETSAMPLING
362 fprintf(output, " -m <sampling type> use packet sampling\n");
363 fprintf(output, " count:NUM - capture one packet of every NUM\n");
364 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
367 fprintf(output, "Stop conditions:\n");
368 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
369 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
370 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
371 fprintf(output, " files:NUM - stop after NUM files\n");
372 /*fprintf(output, "\n");*/
373 fprintf(output, "Output (files):\n");
374 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
375 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
376 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
377 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
378 fprintf(output, " -n use pcapng format instead of pcap\n");
379 /*fprintf(output, "\n");*/
380 fprintf(output, "Miscellaneous:\n");
381 fprintf(output, " -q don't report packet capture counts\n");
382 fprintf(output, " -v print version information and exit\n");
383 fprintf(output, " -h display this help and exit\n");
384 fprintf(output, "\n");
385 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcap\n");
386 fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcap\"\n");
387 fprintf(output, "\n");
388 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
392 show_version(GString *comp_info_str, GString *runtime_info_str)
396 "Dumpcap " VERSION "%s\n"
401 "See http://www.wireshark.org for more information.\n",
402 wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
406 * Print to the standard error. This is a command-line tool, so there's
407 * no need to pop up a console.
410 vfprintf_stderr(const char *fmt, va_list ap)
412 vfprintf(stderr, fmt, ap);
416 fprintf_stderr(const char *fmt, ...)
421 vfprintf_stderr(fmt, ap);
426 * Report an error in command-line arguments.
429 cmdarg_err(const char *fmt, ...)
435 /* Generate a 'special format' message back to parent */
437 msg = g_strdup_vprintf(fmt, ap);
438 sync_pipe_errmsg_to_parent(2, msg, "");
443 fprintf(stderr, "dumpcap: ");
444 vfprintf(stderr, fmt, ap);
445 fprintf(stderr, "\n");
451 * Report additional information for an error in command-line arguments.
454 cmdarg_err_cont(const char *fmt, ...)
461 msg = g_strdup_vprintf(fmt, ap);
462 sync_pipe_errmsg_to_parent(2, msg, "");
467 vfprintf(stderr, fmt, ap);
468 fprintf(stderr, "\n");
474 * capture_interface_list() is expected to do the right thing to get
475 * a list of interfaces.
477 * In most of the programs in the Wireshark suite, "the right thing"
478 * is to run dumpcap and ask it for the list, because dumpcap may
479 * be the only program in the suite with enough privileges to get
482 * In dumpcap itself, however, we obviously can't run dumpcap to
483 * ask for the list. Therefore, our capture_interface_list() should
484 * just call get_interface_list().
487 capture_interface_list(int *err, char **err_str)
489 return get_interface_list(err, err_str);
493 * Get the data-link type for a libpcap device.
494 * This works around AIX 5.x's non-standard and incompatible-with-the-
495 * rest-of-the-universe libpcap.
498 get_pcap_linktype(pcap_t *pch, const char *devname
506 const char *ifacename;
509 linktype = pcap_datalink(pch);
513 * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
514 * rather than DLT_ values for link-layer types; the ifType values
515 * for LAN devices are:
522 * and the ifType value for a loopback device is 24.
524 * The AIX names for LAN devices begin with:
531 * and the AIX names for loopback devices begin with "lo".
533 * (The difference between "Ethernet" and "802.3" is presumably
534 * whether packets have an Ethernet header, with a packet type,
535 * or an 802.3 header, with a packet length, followed by an 802.2
536 * header and possibly a SNAP header.)
538 * If the device name matches "linktype" interpreted as an ifType
539 * value, rather than as a DLT_ value, we will assume this is AIX's
540 * non-standard, incompatible libpcap, rather than a standard libpcap,
541 * and will map the link-layer type to the standard DLT_ value for
542 * that link-layer type, as that's what the rest of Wireshark expects.
544 * (This means the capture files won't be readable by a tcpdump
545 * linked with AIX's non-standard libpcap, but so it goes. They
546 * *will* be readable by standard versions of tcpdump, Wireshark,
549 * XXX - if we conclude we're using AIX libpcap, should we also
550 * set a flag to cause us to assume the time stamps are in
551 * seconds-and-nanoseconds form, and to convert them to
552 * seconds-and-microseconds form before processing them and
557 * Find the last component of the device name, which is the
560 ifacename = strchr(devname, '/');
561 if (ifacename == NULL)
564 /* See if it matches any of the LAN device names. */
565 if (strncmp(ifacename, "en", 2) == 0) {
568 * That's the RFC 1573 value for Ethernet; map it to DLT_EN10MB.
572 } else if (strncmp(ifacename, "et", 2) == 0) {
575 * That's the RFC 1573 value for 802.3; map it to DLT_EN10MB.
576 * (libpcap, tcpdump, Wireshark, etc. don't care if it's Ethernet
581 } else if (strncmp(ifacename, "tr", 2) == 0) {
584 * That's the RFC 1573 value for 802.5 (Token Ring); map it to
585 * DLT_IEEE802, which is what's used for Token Ring.
589 } else if (strncmp(ifacename, "fi", 2) == 0) {
590 if (linktype == 15) {
592 * That's the RFC 1573 value for FDDI; map it to DLT_FDDI.
596 } else if (strncmp(ifacename, "lo", 2) == 0) {
597 if (linktype == 24) {
599 * That's the RFC 1573 value for "software loopback" devices; map it
600 * to DLT_NULL, which is what's used for loopback devices on BSD.
610 static data_link_info_t *
611 create_data_link_info(int dlt)
613 data_link_info_t *data_link_info;
616 data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
617 data_link_info->dlt = dlt;
618 text = pcap_datalink_val_to_name(dlt);
620 data_link_info->name = g_strdup(text);
622 data_link_info->name = g_strdup_printf("DLT %d", dlt);
623 text = pcap_datalink_val_to_description(dlt);
625 data_link_info->description = g_strdup(text);
627 data_link_info->description = NULL;
628 return data_link_info;
632 * Get the capabilities of a network device.
634 static if_capabilities_t *
635 get_if_capabilities(const char *devname, gboolean monitor_mode
636 #ifndef HAVE_PCAP_CREATE
641 if_capabilities_t *caps;
642 char errbuf[PCAP_ERRBUF_SIZE];
644 #ifdef HAVE_PCAP_CREATE
648 #ifdef HAVE_PCAP_LIST_DATALINKS
652 data_link_info_t *data_link_info;
655 * Allocate the interface capabilities structure.
657 caps = g_malloc(sizeof *caps);
659 #ifdef HAVE_PCAP_OPEN
660 pch = pcap_open(devname, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
661 caps->can_set_rfmon = FALSE;
664 *err_str = g_strdup(errbuf);
668 #elif defined(HAVE_PCAP_CREATE)
669 pch = pcap_create(devname, errbuf);
672 *err_str = g_strdup(errbuf);
676 status = pcap_can_set_rfmon(pch);
679 if (status == PCAP_ERROR)
680 *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
683 *err_str = g_strdup(pcap_statustostr(status));
689 caps->can_set_rfmon = FALSE;
690 else if (status == 1) {
691 caps->can_set_rfmon = TRUE;
693 pcap_set_rfmon(pch, 1);
695 if (err_str != NULL) {
696 *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
704 status = pcap_activate(pch);
706 /* Error. We ignore warnings (status > 0). */
707 if (err_str != NULL) {
708 if (status == PCAP_ERROR)
709 *err_str = g_strdup_printf("pcap_activate() failed: %s",
712 *err_str = g_strdup(pcap_statustostr(status));
719 pch = pcap_open_live(devname, MIN_PACKET_SIZE, 0, 0, errbuf);
720 caps->can_set_rfmon = FALSE;
723 *err_str = g_strdup(errbuf);
728 deflt = get_pcap_linktype(pch, devname);
729 #ifdef HAVE_PCAP_LIST_DATALINKS
730 nlt = pcap_list_datalinks(pch, &linktypes);
731 if (nlt == 0 || linktypes == NULL) {
734 *err_str = NULL; /* an empty list doesn't mean an error */
737 caps->data_link_types = NULL;
738 for (i = 0; i < nlt; i++) {
739 data_link_info = create_data_link_info(linktypes[i]);
742 * XXX - for 802.11, make the most detailed 802.11
743 * version the default, rather than the one the
744 * device has as the default?
746 if (linktypes[i] == deflt)
747 caps->data_link_types = g_list_prepend(caps->data_link_types,
750 caps->data_link_types = g_list_append(caps->data_link_types,
753 #ifdef HAVE_PCAP_FREE_DATALINKS
754 pcap_free_datalinks(linktypes);
757 * In Windows, there's no guarantee that if you have a library
758 * built with one version of the MSVC++ run-time library, and
759 * it returns a pointer to allocated data, you can free that
760 * data from a program linked with another version of the
761 * MSVC++ run-time library.
763 * This is not an issue on UN*X.
765 * See the mail threads starting at
767 * http://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
771 * http://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
774 #define xx_free free /* hack so checkAPIs doesn't complain */
777 #endif /* HAVE_PCAP_FREE_DATALINKS */
778 #else /* HAVE_PCAP_LIST_DATALINKS */
780 data_link_info = create_data_link_info(deflt);
781 caps->data_link_types = g_list_append(caps->data_link_types,
783 #endif /* HAVE_PCAP_LIST_DATALINKS */
792 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
794 print_machine_readable_interfaces(GList *if_list)
801 char addr_str[ADDRSTRLEN];
804 /* Let our parent know we succeeded. */
805 pipe_write_block(2, SP_SUCCESS, NULL);
808 i = 1; /* Interface id number */
809 for (if_entry = g_list_first(if_list); if_entry != NULL;
810 if_entry = g_list_next(if_entry)) {
811 if_info = (if_info_t *)if_entry->data;
812 printf("%d. %s", i++, if_info->name);
815 * Print the contents of the if_entry struct in a parseable format.
816 * Each if_entry element is tab-separated. Addresses are comma-
819 /* XXX - Make sure our description doesn't contain a tab */
820 if (if_info->description != NULL)
821 printf("\t%s\t", if_info->description);
825 for(addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
826 addr = g_slist_next(addr)) {
827 if (addr != g_slist_nth(if_info->addrs, 0))
830 if_addr = (if_addr_t *)addr->data;
831 switch(if_addr->ifat_type) {
833 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
835 printf("%s", addr_str);
837 printf("<unknown IPv4>");
841 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
842 addr_str, ADDRSTRLEN)) {
843 printf("%s", addr_str);
845 printf("<unknown IPv6>");
849 printf("<type unknown %u>", if_addr->ifat_type);
853 if (if_info->loopback)
854 printf("\tloopback");
863 * If you change the machine-readable output format of this function,
864 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
867 print_machine_readable_if_capabilities(if_capabilities_t *caps)
870 data_link_info_t *data_link_info;
871 const gchar *desc_str;
874 /* Let our parent know we succeeded. */
875 pipe_write_block(2, SP_SUCCESS, NULL);
878 if (caps->can_set_rfmon)
882 for (lt_entry = caps->data_link_types; lt_entry != NULL;
883 lt_entry = g_list_next(lt_entry)) {
884 data_link_info = (data_link_info_t *)lt_entry->data;
885 if (data_link_info->description != NULL)
886 desc_str = data_link_info->description;
888 desc_str = "(not supported)";
889 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
899 /* Print the number of packets captured for each interface until we're killed. */
901 print_statistics_loop(gboolean machine_readable)
903 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
909 char errbuf[PCAP_ERRBUF_SIZE];
912 if_list = get_interface_list(&err, &err_str);
913 if (if_list == NULL) {
915 case CANT_GET_INTERFACE_LIST:
916 cmdarg_err("%s", err_str);
920 case NO_INTERFACES_FOUND:
921 cmdarg_err("There are no interfaces on which a capture can be done");
927 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
928 if_info = (if_info_t *)if_entry->data;
929 #ifdef HAVE_PCAP_OPEN
930 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
932 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
936 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
937 if_stat->name = g_strdup(if_info->name);
939 stat_list = g_list_append(stat_list, if_stat);
944 cmdarg_err("There are no interfaces on which a capture can be done");
949 /* Let our parent know we succeeded. */
950 pipe_write_block(2, SP_SUCCESS, NULL);
953 if (!machine_readable) {
954 printf("%-15s %10s %10s\n", "Interface", "Received",
959 while (global_ld.go) {
960 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
961 if_stat = (if_stat_t *)stat_entry->data;
962 pcap_stats(if_stat->pch, &ps);
964 if (!machine_readable) {
965 printf("%-15s %10u %10u\n", if_stat->name,
966 ps.ps_recv, ps.ps_drop);
968 printf("%s\t%u\t%u\n", if_stat->name,
969 ps.ps_recv, ps.ps_drop);
974 if (! global_ld.from_cap_pipe)
981 /* XXX - Not reached. Should we look for 'q' in stdin? */
982 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
983 if_stat = (if_stat_t *)stat_entry->data;
984 pcap_close(if_stat->pch);
985 g_free(if_stat->name);
988 g_list_free(stat_list);
989 free_interface_list(if_list);
997 capture_cleanup_handler(DWORD dwCtrlType)
999 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1000 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1001 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1002 like SIGTERM at least when the machine's shutting down.
1004 For now, if we're running as a command rather than a capture child,
1005 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1006 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1007 in that way on UN*X.
1009 If we're not running as a capture child, we might be running as
1010 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1011 user logs out. (XXX - can we explicitly check whether we're
1012 running as a service?) */
1014 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1015 "Console: Control signal");
1016 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1017 "Console: Control signal, CtrlType: %u", dwCtrlType);
1019 /* Keep capture running if we're a service and a user logs off */
1020 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1021 capture_loop_stop();
1029 capture_cleanup_handler(int signum _U_)
1031 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1032 SIGTERM. We assume that if the user wanted it to keep running
1033 after they logged out, they'd have nohupped it. */
1035 /* Note: don't call g_log() in the signal handler: if we happened to be in
1036 * g_log() in process context when the signal came in, g_log will detect
1037 * the "recursion" and abort.
1040 capture_loop_stop();
1049 if (global_capture_opts.quiet) {
1050 /* Report the count only if we aren't printing a packet count
1051 as packets arrive. */
1052 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
1053 plurality(global_ld.packet_count, "", "s"));
1055 infoprint = FALSE; /* we just reported it */
1059 report_counts_siginfo(int signum _U_)
1061 int sav_errno = errno;
1062 /* If we've been told to delay printing, just set a flag asking
1063 that we print counts (if we're supposed to), otherwise print
1064 the count of packets captured (if we're supposed to). */
1071 #endif /* SIGINFO */
1073 static void exit_main(int status)
1076 /* Shutdown windows sockets */
1079 /* can be helpful for debugging */
1080 #ifdef DEBUG_DUMPCAP
1081 printf("Press any key\n");
1092 * If we were linked with libcap (not libpcap), make sure we have
1093 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1094 * (See comment in main() for details)
1098 #if 0 /* Set to enable capability debugging */
1099 /* see 'man cap_to_text()' for explanation of output */
1100 /* '=' means 'all= ' ie: no capabilities */
1101 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
1103 print_caps(const char *pfx) {
1104 cap_t caps = cap_get_proc();
1105 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1106 "%s: EUID: %d Capabilities: %s", pfx,
1107 geteuid(), cap_to_text(caps, NULL));
1110 print_caps(const char *pfx _U_) {
1115 relinquish_privs_except_capture(void)
1117 /* If 'started_with_special_privs' (ie: suid) then enable for
1118 * ourself the NET_ADMIN and NET_RAW capabilities and then
1119 * drop our suid privileges.
1121 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1122 * stuff we don't need (and shouldn't have).
1123 * CAP_NET_RAW: Packet capture (raw sockets).
1126 if (started_with_special_privs()) {
1127 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1128 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1130 cap_t caps = cap_init(); /* all capabilities initialized to off */
1132 print_caps("Pre drop, pre set");
1134 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1135 cmdarg_err("prctl() fail return: %s", strerror(errno));
1138 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1139 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1141 if (cap_set_proc(caps)) {
1142 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
1144 print_caps("Pre drop, post set");
1146 relinquish_special_privs_perm();
1148 print_caps("Post drop, pre set");
1149 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1150 if (cap_set_proc(caps)) {
1151 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
1153 print_caps("Post drop, post set");
1161 relinquish_all_capabilities(void)
1163 /* Drop any and all capabilities this process may have. */
1164 /* Allowed whether or not process has any privileges. */
1165 cap_t caps = cap_init(); /* all capabilities initialized to off */
1166 print_caps("Pre-clear");
1167 if (cap_set_proc(caps)) {
1168 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
1170 print_caps("Post-clear");
1174 #endif /* HAVE_LIBCAP */
1176 /* Set the data link type on a pcap. */
1178 set_pcap_linktype(pcap_t *pch, char *devname
1179 #ifdef HAVE_PCAP_SET_DATALINK
1184 #ifdef HAVE_PCAP_SET_DATALINK
1185 if (pcap_set_datalink(pch, dlt) == 0)
1186 return NULL; /* no error */
1187 return pcap_geterr(pch);
1189 /* Let them set it to the type it is; reject any other request. */
1190 if (get_pcap_linktype(pch, devname) == dlt)
1191 return NULL; /* no error */
1192 return "That DLT isn't one of the DLTs supported by this device";
1196 /* Take care of byte order in the libpcap headers read from pipes.
1197 * (function taken from wiretap/libpcap.c) */
1199 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1202 /* Byte-swap the record header fields. */
1203 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
1204 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
1205 rechdr->incl_len = BSWAP32(rechdr->incl_len);
1206 rechdr->orig_len = BSWAP32(rechdr->orig_len);
1209 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1210 swapped, in order to match the BPF header layout.
1212 Unfortunately, some files were, according to a comment in the "libpcap"
1213 source, written with version 2.3 in their headers but without the
1214 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1215 would make no sense - we assume that we need to swap them. */
1216 if (hdr->version_major == 2 &&
1217 (hdr->version_minor < 3 ||
1218 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1221 temp = rechdr->orig_len;
1222 rechdr->orig_len = rechdr->incl_len;
1223 rechdr->incl_len = temp;
1229 * Thread function that reads from a pipe and pushes the data
1230 * to the main application thread.
1233 * XXX Right now we use async queues for basic signaling. The main thread
1234 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1235 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1236 * Iff the read is successful cap_pipe_read pushes an item onto
1237 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1238 * the queues themselves (yet).
1240 * We might want to move some of the cap_pipe_dispatch logic here so that
1241 * we can let cap_pipe_read run independently, queuing up multiple reads
1242 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1244 static void *cap_pipe_read(void *ld_ptr) {
1245 loop_data *ld = (loop_data *)ld_ptr;
1254 while (ld->cap_pipe_err == PIPOK) {
1255 g_async_queue_pop(cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1256 g_mutex_lock(cap_pipe_read_mtx);
1258 while (bytes_read < (int) ld->cap_pipe_bytes_to_read) {
1260 /* If we try to use read() on a named pipe on Windows with partial
1261 * data it appears to return EOF.
1263 res = ReadFile(ld->cap_pipe_h, ld->cap_pipe_buf+bytes_read,
1264 ld->cap_pipe_bytes_to_read - bytes_read,
1269 last_err = GetLastError();
1270 if (last_err == ERROR_MORE_DATA) {
1272 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1273 ld->cap_pipe_err = PIPEOF;
1277 ld->cap_pipe_err = PIPERR;
1280 } else if (b == 0 && ld->cap_pipe_bytes_to_read > 0) {
1281 ld->cap_pipe_err = PIPEOF;
1286 b = read(ld->cap_pipe_fd, ld->cap_pipe_buf+bytes_read,
1287 ld->cap_pipe_bytes_to_read - bytes_read);
1290 ld->cap_pipe_err = PIPEOF;
1294 ld->cap_pipe_err = PIPERR;
1303 ld->cap_pipe_bytes_read = bytes_read;
1304 if (ld->cap_pipe_bytes_read >= ld->cap_pipe_bytes_to_read) {
1305 g_async_queue_push(cap_pipe_done_q, ld->cap_pipe_buf); /* Any non-NULL value will do */
1307 g_mutex_unlock(cap_pipe_read_mtx);
1311 #endif /* USE_THREADS */
1313 /* Provide select() functionality for a single file descriptor
1314 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1316 * Returns the same values as select. If an error is returned,
1317 * the string cap_pipe_err_str should be used instead of errno.
1320 cap_pipe_select(int pipe_fd) {
1322 struct timeval timeout, *pto;
1325 cap_pipe_err_str = "Unknown error";
1328 FD_SET(pipe_fd, &rfds);
1331 timeout.tv_usec = CAP_READ_TIMEOUT * 1000;
1334 sel_ret = select(pipe_fd+1, &rfds, NULL, NULL, pto);
1336 cap_pipe_err_str = strerror(errno);
1341 /* Mimic pcap_open_live() for pipe captures
1343 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1344 * open it, and read the header.
1346 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1347 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1349 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
1350 char *errmsg, int errmsgl)
1353 struct stat pipe_stat;
1354 struct sockaddr_un sa;
1357 unsigned int bytes_read;
1368 ld->cap_pipe_fd = -1;
1370 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
1372 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1375 * XXX - this blocks until a pcap per-file header has been written to
1376 * the pipe, so it could block indefinitely.
1378 if (strcmp(pipename, "-") == 0) {
1380 fd = 0; /* read from stdin */
1382 ld->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1386 if (ws_stat(pipename, &pipe_stat) < 0) {
1387 if (errno == ENOENT || errno == ENOTDIR)
1388 ld->cap_pipe_err = PIPNEXIST;
1390 g_snprintf(errmsg, errmsgl,
1391 "The capture session could not be initiated "
1392 "due to error getting information on pipe/socket: %s", strerror(errno));
1393 ld->cap_pipe_err = PIPERR;
1397 if (S_ISFIFO(pipe_stat.st_mode)) {
1398 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1400 g_snprintf(errmsg, errmsgl,
1401 "The capture session could not be initiated "
1402 "due to error on pipe open: %s", strerror(errno));
1403 ld->cap_pipe_err = PIPERR;
1406 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1407 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1409 g_snprintf(errmsg, errmsgl,
1410 "The capture session could not be initiated "
1411 "due to error on socket create: %s", strerror(errno));
1412 ld->cap_pipe_err = PIPERR;
1415 sa.sun_family = AF_UNIX;
1417 * The Single UNIX Specification says:
1419 * The size of sun_path has intentionally been left undefined.
1420 * This is because different implementations use different sizes.
1421 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1422 * of 104. Since most implementations originate from BSD versions,
1423 * the size is typically in the range 92 to 108.
1425 * Applications should not assume a particular length for sun_path
1426 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1430 * The <sys/un.h> header shall define the sockaddr_un structure,
1431 * which shall include at least the following members:
1433 * sa_family_t sun_family Address family.
1434 * char sun_path[] Socket pathname.
1436 * so we assume that it's an array, with a specified size,
1437 * and that the size reflects the maximum path length.
1439 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1440 /* Path name too long */
1441 g_snprintf(errmsg, errmsgl,
1442 "The capture session coud not be initiated "
1443 "due to error on socket connect: Path name too long");
1444 ld->cap_pipe_err = PIPERR;
1447 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1449 g_snprintf(errmsg, errmsgl,
1450 "The capture session coud not be initiated "
1451 "due to error on socket connect: %s", strerror(errno));
1452 ld->cap_pipe_err = PIPERR;
1456 if (S_ISCHR(pipe_stat.st_mode)) {
1458 * Assume the user specified an interface on a system where
1459 * interfaces are in /dev. Pretend we haven't seen it.
1461 ld->cap_pipe_err = PIPNEXIST;
1464 g_snprintf(errmsg, errmsgl,
1465 "The capture session could not be initiated because\n"
1466 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
1467 ld->cap_pipe_err = PIPERR;
1472 #define PIPE_STR "\\pipe\\"
1473 /* Under Windows, named pipes _must_ have the form
1474 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1476 pncopy = g_strdup(pipename);
1477 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1478 pos = strchr(pncopy + 3, '\\');
1479 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1486 g_snprintf(errmsg, errmsgl,
1487 "The capture session could not be initiated because\n"
1488 "\"%s\" is neither an interface nor a pipe", pipename);
1489 ld->cap_pipe_err = PIPNEXIST;
1493 /* Wait for the pipe to appear */
1495 ld->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1496 OPEN_EXISTING, 0, NULL);
1498 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE)
1501 if (GetLastError() != ERROR_PIPE_BUSY) {
1502 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1503 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1504 g_snprintf(errmsg, errmsgl,
1505 "The capture session on \"%s\" could not be started "
1506 "due to error on pipe open: %s (error %d)",
1507 pipename, utf_16to8(err_str), GetLastError());
1509 ld->cap_pipe_err = PIPERR;
1513 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1514 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1515 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1516 g_snprintf(errmsg, errmsgl,
1517 "The capture session on \"%s\" timed out during "
1518 "pipe open: %s (error %d)",
1519 pipename, utf_16to8(err_str), GetLastError());
1521 ld->cap_pipe_err = PIPERR;
1528 ld->from_cap_pipe = TRUE;
1531 /* read the pcap header */
1533 while (bytes_read < sizeof magic) {
1534 sel_ret = cap_pipe_select(fd);
1536 g_snprintf(errmsg, errmsgl,
1537 "Unexpected error from select: %s", strerror(errno));
1539 } else if (sel_ret > 0) {
1540 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
1543 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1545 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1552 #else /* USE_THREADS */
1553 g_thread_create(&cap_pipe_read, ld, FALSE, NULL);
1555 ld->cap_pipe_buf = (char *) &magic;
1556 ld->cap_pipe_bytes_read = 0;
1557 ld->cap_pipe_bytes_to_read = sizeof(magic);
1558 /* We don't have to worry about cap_pipe_read_mtx here */
1559 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1560 g_async_queue_pop(cap_pipe_done_q);
1561 if (ld->cap_pipe_bytes_read <= 0) {
1562 if (ld->cap_pipe_bytes_read == 0)
1563 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1565 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1570 #endif /* USE_THREADS */
1574 /* Host that wrote it has our byte order, and was running
1575 a program using either standard or ss990417 libpcap. */
1576 ld->cap_pipe_byte_swapped = FALSE;
1577 ld->cap_pipe_modified = FALSE;
1579 case PCAP_MODIFIED_MAGIC:
1580 /* Host that wrote it has our byte order, but was running
1581 a program using either ss990915 or ss991029 libpcap. */
1582 ld->cap_pipe_byte_swapped = FALSE;
1583 ld->cap_pipe_modified = TRUE;
1585 case PCAP_SWAPPED_MAGIC:
1586 /* Host that wrote it has a byte order opposite to ours,
1587 and was running a program using either standard or
1588 ss990417 libpcap. */
1589 ld->cap_pipe_byte_swapped = TRUE;
1590 ld->cap_pipe_modified = FALSE;
1592 case PCAP_SWAPPED_MODIFIED_MAGIC:
1593 /* Host that wrote it out has a byte order opposite to
1594 ours, and was running a program using either ss990915
1595 or ss991029 libpcap. */
1596 ld->cap_pipe_byte_swapped = TRUE;
1597 ld->cap_pipe_modified = TRUE;
1600 /* Not a "libpcap" type we know about. */
1601 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
1606 /* Read the rest of the header */
1608 while (bytes_read < sizeof(struct pcap_hdr)) {
1609 sel_ret = cap_pipe_select(fd);
1611 g_snprintf(errmsg, errmsgl,
1612 "Unexpected error from select: %s", strerror(errno));
1614 } else if (sel_ret > 0) {
1615 b = read(fd, ((char *)hdr)+bytes_read,
1616 sizeof(struct pcap_hdr) - bytes_read);
1619 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1621 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
1628 #else /* USE_THREADS */
1629 ld->cap_pipe_buf = (char *) hdr;
1630 ld->cap_pipe_bytes_read = 0;
1631 ld->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1632 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1633 g_async_queue_pop(cap_pipe_done_q);
1634 if (ld->cap_pipe_bytes_read <= 0) {
1635 if (ld->cap_pipe_bytes_read == 0)
1636 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1638 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
1642 #endif /* USE_THREADS */
1644 if (ld->cap_pipe_byte_swapped) {
1645 /* Byte-swap the header fields about which we care. */
1646 hdr->version_major = BSWAP16(hdr->version_major);
1647 hdr->version_minor = BSWAP16(hdr->version_minor);
1648 hdr->snaplen = BSWAP32(hdr->snaplen);
1649 hdr->network = BSWAP32(hdr->network);
1651 ld->linktype = hdr->network;
1653 if (hdr->version_major < 2) {
1654 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1658 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1659 ld->cap_pipe_err = PIPOK;
1661 ld->cap_pipe_fd = fd;
1666 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1667 ld->cap_pipe_err = PIPERR;
1670 ld->cap_pipe_fd = -1;
1677 /* We read one record from the pipe, take care of byte order in the record
1678 * header, write the record to the capture file, and update capture statistics. */
1680 cap_pipe_dispatch(loop_data *ld, guchar *data, char *errmsg, int errmsgl)
1682 struct pcap_pkthdr phdr;
1683 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1695 #ifdef LOG_CAPTURE_VERBOSE
1696 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1699 switch (ld->cap_pipe_state) {
1701 case STATE_EXPECT_REC_HDR:
1703 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1706 ld->cap_pipe_state = STATE_READ_REC_HDR;
1707 ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
1708 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1709 ld->cap_pipe_bytes_read = 0;
1712 ld->cap_pipe_buf = (char *) &ld->cap_pipe_rechdr;
1713 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1714 g_mutex_unlock(cap_pipe_read_mtx);
1719 case STATE_READ_REC_HDR:
1721 b = read(ld->cap_pipe_fd, ((char *)&ld->cap_pipe_rechdr)+ld->cap_pipe_bytes_read,
1722 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1725 result = PD_PIPE_EOF;
1727 result = PD_PIPE_ERR;
1730 ld->cap_pipe_bytes_read += b;
1731 #else /* USE_THREADS */
1732 g_get_current_time(&wait_time);
1733 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1734 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1735 if (ld->cap_pipe_err == PIPEOF) {
1736 result = PD_PIPE_EOF;
1738 } else if (ld->cap_pipe_err == PIPERR) {
1739 result = PD_PIPE_ERR;
1745 #endif /* USE_THREADS */
1746 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1748 result = PD_REC_HDR_READ;
1751 case STATE_EXPECT_DATA:
1753 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1756 ld->cap_pipe_state = STATE_READ_DATA;
1757 ld->cap_pipe_bytes_to_read = ld->cap_pipe_rechdr.hdr.incl_len;
1758 ld->cap_pipe_bytes_read = 0;
1761 ld->cap_pipe_buf = (char *) data;
1762 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1763 g_mutex_unlock(cap_pipe_read_mtx);
1768 case STATE_READ_DATA:
1770 b = read(ld->cap_pipe_fd, data+ld->cap_pipe_bytes_read,
1771 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1774 result = PD_PIPE_EOF;
1776 result = PD_PIPE_ERR;
1779 ld->cap_pipe_bytes_read += b;
1780 #else /* USE_THREADS */
1781 g_get_current_time(&wait_time);
1782 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1783 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1784 if (ld->cap_pipe_err == PIPEOF) {
1785 result = PD_PIPE_EOF;
1787 } else if (ld->cap_pipe_err == PIPERR) {
1788 result = PD_PIPE_ERR;
1794 #endif /* USE_THREADS */
1795 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1797 result = PD_DATA_READ;
1801 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
1804 } /* switch (ld->cap_pipe_state) */
1807 * We've now read as much data as we were expecting, so process it.
1811 case PD_REC_HDR_READ:
1812 /* We've read the header. Take care of byte order. */
1813 cap_pipe_adjust_header(ld->cap_pipe_byte_swapped, &ld->cap_pipe_hdr,
1814 &ld->cap_pipe_rechdr.hdr);
1815 if (ld->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1816 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
1817 ld->packet_count+1, ld->cap_pipe_rechdr.hdr.incl_len);
1820 ld->cap_pipe_state = STATE_EXPECT_DATA;
1824 /* Fill in a "struct pcap_pkthdr", and process the packet. */
1825 phdr.ts.tv_sec = ld->cap_pipe_rechdr.hdr.ts_sec;
1826 phdr.ts.tv_usec = ld->cap_pipe_rechdr.hdr.ts_usec;
1827 phdr.caplen = ld->cap_pipe_rechdr.hdr.incl_len;
1828 phdr.len = ld->cap_pipe_rechdr.hdr.orig_len;
1830 capture_loop_packet_cb((u_char *)ld, &phdr, data);
1832 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1836 ld->cap_pipe_err = PIPEOF;
1841 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1842 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1843 g_snprintf(errmsg, errmsgl,
1844 "Error reading from pipe: %s (error %d)",
1845 utf_16to8(err_str), GetLastError());
1848 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
1856 ld->cap_pipe_err = PIPERR;
1857 /* Return here rather than inside the switch to prevent GCC warning */
1862 /** Open the capture input file (pcap or capture pipe).
1863 * Returns TRUE if it succeeds, FALSE otherwise. */
1865 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
1866 char *errmsg, size_t errmsg_len,
1867 char *secondary_errmsg, size_t secondary_errmsg_len)
1869 gchar open_err_str[PCAP_ERRBUF_SIZE];
1870 gchar *sync_msg_str;
1871 static const char ppamsg[] = "can't find PPA for ";
1872 const char *set_linktype_err_str;
1873 const char *libpcap_warn;
1874 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
1878 gchar *sync_secondary_msg_str;
1879 WORD wVersionRequested;
1882 #ifdef HAVE_PCAP_REMOTE
1883 struct pcap_rmtauth auth;
1887 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
1890 /* XXX - opening Winsock on tshark? */
1892 /* Initialize Windows Socket if we are in a WIN32 OS
1893 This needs to be done before querying the interface for network/netmask */
1895 /* XXX - do we really require 1.1 or earlier?
1896 Are there any versions that support only 2.0 or higher? */
1897 wVersionRequested = MAKEWORD(1, 1);
1898 err = WSAStartup(wVersionRequested, &wsaData);
1902 case WSASYSNOTREADY:
1903 g_snprintf(errmsg, (gulong) errmsg_len,
1904 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
1907 case WSAVERNOTSUPPORTED:
1908 g_snprintf(errmsg, (gulong) errmsg_len,
1909 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
1910 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
1913 case WSAEINPROGRESS:
1914 g_snprintf(errmsg, (gulong) errmsg_len,
1915 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
1919 g_snprintf(errmsg, (gulong) errmsg_len,
1920 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
1924 g_snprintf(errmsg, (gulong) errmsg_len,
1925 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
1929 g_snprintf(errmsg, (gulong) errmsg_len,
1930 "Couldn't initialize Windows Sockets: error %d", err);
1933 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
1938 /* Open the network interface to capture from it.
1939 Some versions of libpcap may put warnings into the error buffer
1940 if they succeed; to tell if that's happened, we have to clear
1941 the error buffer, and check if it's still a null string. */
1942 open_err_str[0] = '\0';
1943 #ifdef HAVE_PCAP_OPEN
1945 * If we're opening a remote device, use pcap_open(); that's currently
1946 * the only open routine that supports remote devices.
1948 if (strncmp (capture_opts->iface, "rpcap://", 8) == 0) {
1949 auth.type = capture_opts->auth_type == CAPTURE_AUTH_PWD ?
1950 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
1951 auth.username = capture_opts->auth_username;
1952 auth.password = capture_opts->auth_password;
1954 ld->pcap_h = pcap_open(capture_opts->iface,
1955 capture_opts->has_snaplen ? capture_opts->snaplen :
1956 WTAP_MAX_PACKET_SIZE,
1958 (capture_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
1959 (capture_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
1960 (capture_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
1961 CAP_READ_TIMEOUT, &auth, open_err_str);
1963 #endif /* HAVE_PCAP_OPEN */
1966 * If we're not opening a remote device, use pcap_create() and
1967 * pcap_activate() if we have them, so that we can set the buffer
1968 * size, otherwise use pcap_open_live().
1970 #ifdef HAVE_PCAP_CREATE
1971 ld->pcap_h = pcap_create(capture_opts->iface, open_err_str);
1972 if (ld->pcap_h != NULL) {
1973 pcap_set_snaplen(ld->pcap_h, capture_opts->has_snaplen ? capture_opts->snaplen : WTAP_MAX_PACKET_SIZE);
1974 pcap_set_promisc(ld->pcap_h, capture_opts->promisc_mode);
1975 pcap_set_timeout(ld->pcap_h, CAP_READ_TIMEOUT);
1977 if (capture_opts->buffer_size > 1) {
1978 pcap_set_buffer_size(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024);
1980 if (capture_opts->monitor_mode)
1981 pcap_set_rfmon(ld->pcap_h, 1);
1982 err = pcap_activate(ld->pcap_h);
1984 /* Failed to activate, set to NULL */
1985 if (err == PCAP_ERROR)
1986 g_strlcpy(open_err_str, pcap_geterr(ld->pcap_h), sizeof open_err_str);
1988 g_strlcpy(open_err_str, pcap_statustostr(err), sizeof open_err_str);
1989 pcap_close(ld->pcap_h);
1994 ld->pcap_h = pcap_open_live(capture_opts->iface,
1995 capture_opts->has_snaplen ? capture_opts->snaplen :
1996 WTAP_MAX_PACKET_SIZE,
1997 capture_opts->promisc_mode, CAP_READ_TIMEOUT,
2002 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2003 /* to remove any suid privileges. */
2004 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2005 /* (euid/egid have already previously been set to ruid/rgid. */
2006 /* (See comment in main() for details) */
2008 relinquish_special_privs_perm();
2010 relinquish_all_capabilities();
2013 if (ld->pcap_h != NULL) {
2014 /* we've opened "iface" as a network device */
2016 /* try to set the capture buffer size */
2017 if (capture_opts->buffer_size > 1 &&
2018 pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
2019 sync_secondary_msg_str = g_strdup_printf(
2020 "The capture buffer size of %dMB seems to be too high for your machine,\n"
2021 "the default of 1MB will be used.\n"
2023 "Nonetheless, the capture is started.\n",
2024 capture_opts->buffer_size);
2025 report_capture_error("Couldn't set the capture buffer size!",
2026 sync_secondary_msg_str);
2027 g_free(sync_secondary_msg_str);
2031 #if defined(HAVE_PCAP_REMOTE) && defined(HAVE_PCAP_SETSAMPLING)
2032 if ((capture_opts->sampling_method != CAPTURE_SAMP_NONE) &&
2033 (strncmp (capture_opts->iface, "rpcap://", 8) == 0))
2035 struct pcap_samp *samp;
2037 if ((samp = pcap_setsampling(ld->pcap_h)) != NULL)
2039 switch (capture_opts->sampling_method)
2041 case CAPTURE_SAMP_BY_COUNT:
2042 samp->method = PCAP_SAMP_1_EVERY_N;
2045 case CAPTURE_SAMP_BY_TIMER:
2046 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2050 sync_msg_str = g_strdup_printf(
2051 "Unknown sampling method %d specified,\n"
2052 "continue without packet sampling",
2053 capture_opts->sampling_method);
2054 report_capture_error("Couldn't set the capture "
2055 "sampling", sync_msg_str);
2056 g_free(sync_msg_str);
2058 samp->value = capture_opts->sampling_param;
2062 report_capture_error("Couldn't set the capture sampling",
2063 "Cannot get packet sampling data structure");
2069 /* setting the data link type only works on real interfaces */
2070 if (capture_opts->linktype != -1) {
2071 set_linktype_err_str = set_pcap_linktype(ld->pcap_h, capture_opts->iface,
2072 capture_opts->linktype);
2073 if (set_linktype_err_str != NULL) {
2074 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
2075 set_linktype_err_str);
2076 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2080 ld->linktype = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
2082 /* We couldn't open "iface" as a network device. */
2083 /* Try to open it as a pipe */
2084 cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, (int) errmsg_len);
2087 if (ld->cap_pipe_fd == -1) {
2089 if (ld->cap_pipe_h == INVALID_HANDLE_VALUE) {
2092 if (ld->cap_pipe_err == PIPNEXIST) {
2093 /* Pipe doesn't exist, so output message for interface */
2095 /* If we got a "can't find PPA for X" message, warn the user (who
2096 is running (T)Wireshark on HP-UX) that they don't have a version
2097 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
2098 versions, which properly handle HP-UX, say "can't find /dev/dlpi
2099 PPA for X" rather than "can't find PPA for X"). */
2100 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
2103 "You are running (T)Wireshark with a version of the libpcap library\n"
2104 "that doesn't handle HP-UX network devices well; this means that\n"
2105 "(T)Wireshark may not be able to capture packets.\n"
2107 "To fix this, you should install libpcap 0.6.2, or a later version\n"
2108 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
2109 "packaged binary form from the Software Porting And Archive Centre\n"
2110 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
2111 "at the URL lists a number of mirror sites.";
2114 g_snprintf(errmsg, (gulong) errmsg_len,
2115 "The capture session could not be initiated (%s).", open_err_str);
2117 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
2118 "Please check to make sure you have sufficient permissions, and that you have "
2119 "the proper interface or pipe specified.%s", libpcap_warn);
2121 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
2123 "Please check that \"%s\" is the proper interface.\n"
2126 "Help can be found at:\n"
2128 " http://wiki.wireshark.org/WinPcap\n"
2129 " http://wiki.wireshark.org/CaptureSetup\n",
2130 capture_opts->iface);
2134 * Else pipe (or file) does exist and cap_pipe_open_live() has
2139 /* cap_pipe_open_live() succeeded; don't want
2140 error message from pcap_open_live() */
2141 open_err_str[0] = '\0';
2144 /* XXX - will this work for tshark? */
2145 #ifdef MUST_DO_SELECT
2146 if (!ld->from_cap_pipe) {
2147 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2148 ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
2150 ld->pcap_fd = pcap_fileno(ld->pcap_h);
2155 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2156 returned a warning; print it, but keep capturing. */
2157 if (open_err_str[0] != '\0') {
2158 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2159 report_capture_error(sync_msg_str, "");
2160 g_free(sync_msg_str);
2167 /* close the capture input file (pcap or capture pipe) */
2168 static void capture_loop_close_input(loop_data *ld) {
2170 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2172 /* if open, close the capture pipe "input file" */
2174 if (ld->cap_pipe_fd >= 0) {
2175 g_assert(ld->from_cap_pipe);
2176 ws_close(ld->cap_pipe_fd);
2177 ld->cap_pipe_fd = 0;
2180 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE) {
2181 CloseHandle(ld->cap_pipe_h);
2182 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
2186 /* if open, close the pcap "input file" */
2187 if(ld->pcap_h != NULL) {
2188 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)ld->pcap_h);
2189 g_assert(!ld->from_cap_pipe);
2190 pcap_close(ld->pcap_h);
2197 /* Shut down windows sockets */
2203 /* init the capture filter */
2204 static initfilter_status_t
2205 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe, gchar * iface, gchar * cfilter) {
2206 bpf_u_int32 netnum, netmask;
2207 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
2208 struct bpf_program fcode;
2211 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2213 /* capture filters only work on real interfaces */
2214 if (cfilter && !from_cap_pipe) {
2215 /* A capture filter was specified; set it up. */
2216 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
2218 * Well, we can't get the netmask for this interface; it's used
2219 * only for filters that check for broadcast IP addresses, so
2220 * we just punt and use 0. It might be nice to warn the user,
2221 * but that's a pain in a GUI application, as it'd involve popping
2222 * up a message box, and it's not clear how often this would make
2223 * a difference (only filters that check for IP broadcast addresses
2227 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
2230 if (pcap_compile(pcap_h, &fcode, cfilter, 1, netmask) < 0) {
2231 /* Treat this specially - our caller might try to compile this
2232 as a display filter and, if that succeeds, warn the user that
2233 the display and capture filter syntaxes are different. */
2234 return INITFILTER_BAD_FILTER;
2236 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2237 #ifdef HAVE_PCAP_FREECODE
2238 pcap_freecode(&fcode);
2240 return INITFILTER_OTHER_ERROR;
2242 #ifdef HAVE_PCAP_FREECODE
2243 pcap_freecode(&fcode);
2247 return INITFILTER_NO_ERROR;
2251 /* set up to write to the already-opened capture output file/files */
2253 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len) {
2257 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2260 if (ld->from_cap_pipe) {
2261 ld->file_snaplen = ld->cap_pipe_hdr.snaplen;
2264 ld->file_snaplen = pcap_snapshot(ld->pcap_h);
2267 /* Set up to write to the capture file. */
2268 if (capture_opts->multi_files_on) {
2269 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2271 ld->pdh = libpcap_fdopen(ld->save_file_fd, &err);
2274 gboolean successful;
2276 ld->bytes_written = 0;
2277 if (capture_opts->use_pcapng) {
2280 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2281 successful = libpcap_write_session_header_block(ld->pdh, appname, &ld->bytes_written, &err) &&
2282 libpcap_write_interface_description_block(ld->pdh, capture_opts->iface, capture_opts->cfilter, ld->linktype, ld->file_snaplen, &ld->bytes_written, &err);
2284 successful = libpcap_write_file_header(ld->pdh, ld->linktype, ld->file_snaplen,
2285 &ld->bytes_written, &err);
2293 if (ld->pdh == NULL) {
2294 /* We couldn't set up to write to the capture file. */
2295 /* XXX - use cf_open_error_message from tshark instead? */
2298 case WTAP_ERR_CANT_OPEN:
2299 g_snprintf(errmsg, errmsg_len, "The file to which the capture would be saved"
2300 " couldn't be created for some unknown reason.");
2303 case WTAP_ERR_SHORT_WRITE:
2304 g_snprintf(errmsg, errmsg_len, "A full header couldn't be written to the file"
2305 " to which the capture would be saved.");
2310 g_snprintf(errmsg, errmsg_len,
2311 "The file to which the capture would be"
2312 " saved (\"%s\") could not be opened: Error %d.",
2313 capture_opts->save_file, err);
2315 g_snprintf(errmsg, errmsg_len,
2316 "The file to which the capture would be"
2317 " saved (\"%s\") could not be opened: %s.",
2318 capture_opts->save_file, strerror(err));
2330 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
2332 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2334 if (capture_opts->multi_files_on) {
2335 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2337 if (capture_opts->use_pcapng) {
2338 libpcap_write_interface_statistics_block(ld->pdh, 0, ld->pcap_h, &ld->bytes_written, err_close);
2340 return libpcap_dump_close(ld->pdh, err_close);
2344 /* dispatch incoming packets (pcap or capture pipe)
2346 * Waits for incoming packets to be available, and calls pcap_dispatch()
2347 * to cause them to be processed.
2349 * Returns the number of packets which were processed.
2351 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2352 * packet-batching behaviour does not cause packets to get held back
2356 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
2357 char *errmsg, int errmsg_len)
2360 gint packet_count_before;
2361 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
2366 packet_count_before = ld->packet_count;
2367 if (ld->from_cap_pipe) {
2368 /* dispatch from capture pipe */
2369 #ifdef LOG_CAPTURE_VERBOSE
2370 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2373 sel_ret = cap_pipe_select(ld->cap_pipe_fd);
2376 if (sel_ret < 0 && errno != EINTR) {
2377 g_snprintf(errmsg, errmsg_len,
2378 "Unexpected error from select: %s", strerror(errno));
2379 report_capture_error(errmsg, please_report);
2384 * "select()" says we can read from the pipe without blocking
2386 #endif /* USE_THREADS */
2387 inpkts = cap_pipe_dispatch(ld, pcap_data, errmsg, errmsg_len);
2397 /* dispatch from pcap */
2398 #ifdef MUST_DO_SELECT
2400 * If we have "pcap_get_selectable_fd()", we use it to get the
2401 * descriptor on which to select; if that's -1, it means there
2402 * is no descriptor on which you can do a "select()" (perhaps
2403 * because you're capturing on a special device, and that device's
2404 * driver unfortunately doesn't support "select()", in which case
2405 * we don't do the select - which means it might not be possible
2406 * to stop a capture until a packet arrives. If that's unacceptable,
2407 * plead with whoever supplies the software for that device to add
2408 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2409 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2410 * later, so it can use pcap_breakloop().
2412 #ifdef LOG_CAPTURE_VERBOSE
2413 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2415 if (ld->pcap_fd != -1) {
2416 sel_ret = cap_pipe_select(ld->pcap_fd);
2419 * "select()" says we can read from it without blocking; go for
2422 * We don't have pcap_breakloop(), so we only process one packet
2423 * per pcap_dispatch() call, to allow a signal to stop the
2424 * processing immediately, rather than processing all packets
2425 * in a batch before quitting.
2427 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb,
2431 /* Error, rather than pcap_breakloop(). */
2432 ld->pcap_err = TRUE;
2434 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2437 if (sel_ret < 0 && errno != EINTR) {
2438 g_snprintf(errmsg, errmsg_len,
2439 "Unexpected error from select: %s", strerror(errno));
2440 report_capture_error(errmsg, please_report);
2446 #endif /* MUST_DO_SELECT */
2448 /* dispatch from pcap without select */
2450 #ifdef LOG_CAPTURE_VERBOSE
2451 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2455 * On Windows, we don't support asynchronously telling a process to
2456 * stop capturing; instead, we check for an indication on a pipe
2457 * after processing packets. We therefore process only one packet
2458 * at a time, so that we can check the pipe after every packet.
2460 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb, (u_char *) ld);
2462 inpkts = pcap_dispatch(ld->pcap_h, -1, capture_loop_packet_cb, (u_char *) ld);
2466 /* Error, rather than pcap_breakloop(). */
2467 ld->pcap_err = TRUE;
2469 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2471 #else /* pcap_next_ex */
2472 #ifdef LOG_CAPTURE_VERBOSE
2473 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2475 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2478 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2479 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
2480 * This should be fixed in the WinPcap 4.0 alpha release.
2482 * For reference, an example remote interface:
2483 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2486 /* emulate dispatch from pcap */
2489 struct pcap_pkthdr *pkt_header;
2494 (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1)
2495 capture_loop_packet_cb( (u_char *) ld, pkt_header, pkt_data);
2498 ld->pcap_err = TRUE;
2502 #endif /* pcap_next_ex */
2506 #ifdef LOG_CAPTURE_VERBOSE
2507 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2510 return ld->packet_count - packet_count_before;
2514 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2515 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2517 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2518 char *errmsg, int errmsg_len) {
2521 gchar *capfile_name;
2522 gboolean is_tempfile;
2527 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2528 (capture_opts->save_file) ? capture_opts->save_file : "");
2530 if (capture_opts->save_file != NULL) {
2531 /* We return to the caller while the capture is in progress.
2532 * Therefore we need to take a copy of save_file in
2533 * case the caller destroys it after we return.
2535 capfile_name = g_strdup(capture_opts->save_file);
2537 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2538 if (capture_opts->multi_files_on) {
2539 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2540 g_snprintf(errmsg, errmsg_len,
2541 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2542 g_free(capfile_name);
2545 if (strcmp(capfile_name, "-") == 0) {
2546 /* write to stdout */
2549 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
2550 _setmode(1, O_BINARY);
2553 } /* if (...output_to_pipe ... */
2556 if (capture_opts->multi_files_on) {
2557 /* ringbuffer is enabled */
2558 *save_file_fd = ringbuf_init(capfile_name,
2559 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
2561 /* we need the ringbuf name */
2562 if(*save_file_fd != -1) {
2563 g_free(capfile_name);
2564 capfile_name = g_strdup(ringbuf_current_filename());
2567 /* Try to open/create the specified file for use as a capture buffer. */
2568 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
2572 is_tempfile = FALSE;
2574 /* Choose a random name for the temporary capture buffer */
2575 *save_file_fd = create_tempfile(&tmpname, "wireshark");
2576 capfile_name = g_strdup(tmpname);
2580 /* did we fail to open the output file? */
2581 if (*save_file_fd == -1) {
2583 g_snprintf(errmsg, errmsg_len,
2584 "The temporary file to which the capture would be saved (\"%s\") "
2585 "could not be opened: %s.", capfile_name, strerror(errno));
2587 if (capture_opts->multi_files_on) {
2588 ringbuf_error_cleanup();
2591 g_snprintf(errmsg, errmsg_len,
2592 "The file to which the capture would be saved (\"%s\") "
2593 "could not be opened: %s.", capfile_name,
2596 g_free(capfile_name);
2600 if(capture_opts->save_file != NULL) {
2601 g_free(capture_opts->save_file);
2603 capture_opts->save_file = capfile_name;
2604 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2605 "g_free(capfile_name)". */
2607 ret = fchown(*save_file_fd, capture_opts->owner, capture_opts->group);
2615 #define TIME_GET() GetTickCount()
2617 #define TIME_GET() time(NULL)
2620 /* Do the work of handling either the file size or file duration capture
2621 conditions being reached, and switching files or stopping. */
2623 do_file_switch_or_stop(capture_options *capture_opts,
2624 condition *cnd_autostop_files,
2625 condition *cnd_autostop_size,
2626 condition *cnd_file_duration)
2628 if (capture_opts->multi_files_on) {
2629 if (cnd_autostop_files != NULL &&
2630 cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
2631 /* no files left: stop here */
2632 global_ld.go = FALSE;
2636 /* Switch to the next ringbuffer file */
2637 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2638 &global_ld.save_file_fd, &global_ld.err)) {
2639 gboolean successful;
2641 /* File switch succeeded: reset the conditions */
2642 global_ld.bytes_written = 0;
2643 if (capture_opts->use_pcapng) {
2646 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2647 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2648 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);
2650 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2651 &global_ld.bytes_written, &global_ld.err);
2654 fclose(global_ld.pdh);
2655 global_ld.pdh = NULL;
2656 global_ld.go = FALSE;
2659 if(cnd_autostop_size)
2660 cnd_reset(cnd_autostop_size);
2661 if(cnd_file_duration)
2662 cnd_reset(cnd_file_duration);
2663 libpcap_dump_flush(global_ld.pdh, NULL);
2664 if (!capture_opts->quiet)
2665 report_packet_count(global_ld.inpkts_to_sync_pipe);
2666 global_ld.inpkts_to_sync_pipe = 0;
2667 report_new_capture_file(capture_opts->save_file);
2669 /* File switch failed: stop here */
2670 global_ld.go = FALSE;
2674 /* single file, stop now */
2675 global_ld.go = FALSE;
2681 /* Do the low-level work of a capture.
2682 Returns TRUE if it succeeds, FALSE otherwise. */
2684 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
2686 time_t upd_time, cur_time;
2690 condition *cnd_file_duration = NULL;
2691 condition *cnd_autostop_files = NULL;
2692 condition *cnd_autostop_size = NULL;
2693 condition *cnd_autostop_duration = NULL;
2696 gboolean cfilter_error = FALSE;
2697 #define MSG_MAX_LENGTH 4096
2698 char errmsg[MSG_MAX_LENGTH+1];
2699 char secondary_errmsg[MSG_MAX_LENGTH+1];
2702 *secondary_errmsg = '\0';
2704 /* init the loop data */
2705 global_ld.go = TRUE;
2706 global_ld.packet_count = 0;
2708 global_ld.report_packet_count = FALSE;
2710 if (capture_opts->has_autostop_packets)
2711 global_ld.packet_max = capture_opts->autostop_packets;
2713 global_ld.packet_max = 0; /* no limit */
2714 global_ld.inpkts_to_sync_pipe = 0;
2715 global_ld.err = 0; /* no error seen yet */
2716 global_ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
2717 global_ld.pcap_err = FALSE;
2718 global_ld.from_cap_pipe = FALSE;
2719 global_ld.pdh = NULL;
2721 global_ld.cap_pipe_fd = -1;
2723 global_ld.cap_pipe_h = INVALID_HANDLE_VALUE;
2725 #ifdef MUST_DO_SELECT
2726 global_ld.pcap_fd = 0;
2728 global_ld.autostop_files = 0;
2729 global_ld.save_file_fd = -1;
2731 /* We haven't yet gotten the capture statistics. */
2732 *stats_known = FALSE;
2734 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
2735 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
2737 /* open the "input file" from network interface or capture pipe */
2738 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
2739 secondary_errmsg, sizeof(secondary_errmsg))) {
2743 /* init the input filter from the network interface (capture pipe will do nothing) */
2744 switch (capture_loop_init_filter(global_ld.pcap_h, global_ld.from_cap_pipe,
2745 capture_opts->iface,
2746 capture_opts->cfilter)) {
2748 case INITFILTER_NO_ERROR:
2751 case INITFILTER_BAD_FILTER:
2752 cfilter_error = TRUE;
2753 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(global_ld.pcap_h));
2756 case INITFILTER_OTHER_ERROR:
2757 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
2758 pcap_geterr(global_ld.pcap_h));
2759 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
2763 /* If we're supposed to write to a capture file, open it for output
2764 (temporary/specified name/ringbuffer) */
2765 if (capture_opts->saving_to_file) {
2766 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
2767 errmsg, sizeof(errmsg))) {
2771 /* set up to write to the already-opened capture output file/files */
2772 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
2777 /* XXX - capture SIGTERM and close the capture, in case we're on a
2778 Linux 2.0[.x] system and you have to explicitly close the capture
2779 stream in order to turn promiscuous mode off? We need to do that
2780 in other places as well - and I don't think that works all the
2781 time in any case, due to libpcap bugs. */
2783 /* Well, we should be able to start capturing.
2785 Sync out the capture file, so the header makes it to the file system,
2786 and send a "capture started successfully and capture file created"
2787 message to our parent so that they'll open the capture file and
2788 update its windows to indicate that we have a live capture in
2790 libpcap_dump_flush(global_ld.pdh, NULL);
2791 report_new_capture_file(capture_opts->save_file);
2794 /* initialize capture stop (and alike) conditions */
2795 init_capture_stop_conditions();
2796 /* create stop conditions */
2797 if (capture_opts->has_autostop_filesize)
2799 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
2800 if (capture_opts->has_autostop_duration)
2801 cnd_autostop_duration =
2802 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
2804 if (capture_opts->multi_files_on) {
2805 if (capture_opts->has_file_duration)
2807 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
2809 if (capture_opts->has_autostop_files)
2810 cnd_autostop_files =
2811 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
2814 /* init the time values */
2815 start_time = TIME_GET();
2816 upd_time = TIME_GET();
2818 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
2820 /* WOW, everything is prepared! */
2821 /* please fasten your seat belts, we will enter now the actual capture loop */
2822 while (global_ld.go) {
2823 /* dispatch incoming packets */
2824 inpkts = capture_loop_dispatch(capture_opts, &global_ld, errmsg,
2828 /* Were we asked to print packet counts by the SIGINFO handler? */
2829 if (global_ld.report_packet_count) {
2830 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
2831 plurality(global_ld.packet_count, "", "s"));
2832 global_ld.report_packet_count = FALSE;
2837 /* any news from our parent (signal pipe)? -> just stop the capture */
2838 if (!signal_pipe_check_running()) {
2839 global_ld.go = FALSE;
2844 global_ld.inpkts_to_sync_pipe += inpkts;
2846 /* check capture size condition */
2847 if (cnd_autostop_size != NULL &&
2848 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)) {
2849 /* Capture size limit reached, do we have another file? */
2850 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
2851 cnd_autostop_size, cnd_file_duration))
2853 } /* cnd_autostop_size */
2854 if (capture_opts->output_to_pipe) {
2855 libpcap_dump_flush(global_ld.pdh, NULL);
2859 /* Only update once a second (Win32: 500ms) so as not to overload slow
2860 * displays. This also prevents too much context-switching between the
2861 * dumpcap and wireshark processes */
2862 cur_time = TIME_GET();
2864 if ( (cur_time - upd_time) > 500) {
2866 if (cur_time - upd_time > 0) {
2868 upd_time = cur_time;
2870 /*if (pcap_stats(pch, stats) >= 0) {
2871 *stats_known = TRUE;
2874 /* Let the parent process know. */
2875 if (global_ld.inpkts_to_sync_pipe) {
2877 libpcap_dump_flush(global_ld.pdh, NULL);
2879 /* Send our parent a message saying we've written out
2880 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
2881 if (!capture_opts->quiet)
2882 report_packet_count(global_ld.inpkts_to_sync_pipe);
2884 global_ld.inpkts_to_sync_pipe = 0;
2887 /* check capture duration condition */
2888 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
2889 /* The maximum capture time has elapsed; stop the capture. */
2890 global_ld.go = FALSE;
2894 /* check capture file duration condition */
2895 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
2896 /* duration limit reached, do we have another file? */
2897 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
2898 cnd_autostop_size, cnd_file_duration))
2900 } /* cnd_file_duration */
2903 } /* while (global_ld.go) */
2905 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
2907 /* delete stop conditions */
2908 if (cnd_file_duration != NULL)
2909 cnd_delete(cnd_file_duration);
2910 if (cnd_autostop_files != NULL)
2911 cnd_delete(cnd_autostop_files);
2912 if (cnd_autostop_size != NULL)
2913 cnd_delete(cnd_autostop_size);
2914 if (cnd_autostop_duration != NULL)
2915 cnd_delete(cnd_autostop_duration);
2917 /* did we had a pcap (input) error? */
2918 if (global_ld.pcap_err) {
2919 /* On Linux, if an interface goes down while you're capturing on it,
2920 you'll get a "recvfrom: Network is down" error (ENETDOWN).
2921 (At least you will if strerror() doesn't show a local translation
2924 On FreeBSD and OS X, if a network adapter disappears while
2925 you're capturing on it, you'll get a "read: Device not configured"
2926 error (ENXIO). (See previous parenthetical note.)
2928 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
2930 These should *not* be reported to the Wireshark developers. */
2933 cap_err_str = pcap_geterr(global_ld.pcap_h);
2934 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
2935 strcmp(cap_err_str, "read: Device not configured") == 0 ||
2936 strcmp(cap_err_str, "read: I/O error") == 0) {
2937 report_capture_error("The network adapter on which the capture was being done "
2938 "is no longer running; the capture has stopped.",
2941 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
2943 report_capture_error(errmsg, please_report);
2946 else if (global_ld.from_cap_pipe && global_ld.cap_pipe_err == PIPERR)
2947 report_capture_error(errmsg, "");
2949 /* did we had an error while capturing? */
2950 if (global_ld.err == 0) {
2953 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
2954 global_ld.err, FALSE);
2955 report_capture_error(errmsg, please_report);
2959 if (capture_opts->saving_to_file) {
2960 /* close the wiretap (output) file */
2961 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
2965 /* there might be packets not yet notified to the parent */
2966 /* (do this after closing the file, so all packets are already flushed) */
2967 if(global_ld.inpkts_to_sync_pipe) {
2968 if (!capture_opts->quiet)
2969 report_packet_count(global_ld.inpkts_to_sync_pipe);
2970 global_ld.inpkts_to_sync_pipe = 0;
2973 /* If we've displayed a message about a write error, there's no point
2974 in displaying another message about an error on close. */
2975 if (!close_ok && write_ok) {
2976 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
2978 report_capture_error(errmsg, "");
2982 * XXX We exhibit different behaviour between normal mode and sync mode
2983 * when the pipe is stdin and not already at EOF. If we're a child, the
2984 * parent's stdin isn't closed, so if the user starts another capture,
2985 * cap_pipe_open_live() will very likely not see the expected magic bytes and
2986 * will say "Unrecognized libpcap format". On the other hand, in normal
2987 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
2990 /* get packet drop statistics from pcap */
2991 if(global_ld.pcap_h != NULL) {
2992 g_assert(!global_ld.from_cap_pipe);
2993 /* Get the capture statistics, so we know how many packets were
2995 if (pcap_stats(global_ld.pcap_h, stats) >= 0) {
2996 *stats_known = TRUE;
2997 /* Let the parent process know. */
2998 report_packet_drops(stats->ps_drop);
3000 g_snprintf(errmsg, sizeof(errmsg),
3001 "Can't get packet-drop statistics: %s",
3002 pcap_geterr(global_ld.pcap_h));
3003 report_capture_error(errmsg, please_report);
3007 /* close the input file (pcap or capture pipe) */
3008 capture_loop_close_input(&global_ld);
3010 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
3012 /* ok, if the write and the close were successful. */
3013 return write_ok && close_ok;
3016 if (capture_opts->multi_files_on) {
3017 /* cleanup ringbuffer */
3018 ringbuf_error_cleanup();
3020 /* We can't use the save file, and we have no FILE * for the stream
3021 to close in order to close it, so close the FD directly. */
3022 if(global_ld.save_file_fd != -1) {
3023 ws_close(global_ld.save_file_fd);
3026 /* We couldn't even start the capture, so get rid of the capture
3028 if(capture_opts->save_file != NULL) {
3029 ws_unlink(capture_opts->save_file);
3030 g_free(capture_opts->save_file);
3033 capture_opts->save_file = NULL;
3035 report_cfilter_error(capture_opts->cfilter, errmsg);
3037 report_capture_error(errmsg, secondary_errmsg);
3039 /* close the input file (pcap or cap_pipe) */
3040 capture_loop_close_input(&global_ld);
3042 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3048 static void capture_loop_stop(void)
3050 #ifdef HAVE_PCAP_BREAKLOOP
3051 if(global_ld.pcap_h != NULL)
3052 pcap_breakloop(global_ld.pcap_h);
3054 global_ld.go = FALSE;
3059 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3060 int err, gboolean is_close)
3065 g_snprintf(errmsg, errmsglen,
3066 "Not all the packets could be written to the file"
3067 " to which the capture was being saved\n"
3068 "(\"%s\") because there is no space left on the file system\n"
3069 "on which that file resides.",
3075 g_snprintf(errmsg, errmsglen,
3076 "Not all the packets could be written to the file"
3077 " to which the capture was being saved\n"
3078 "(\"%s\") because you are too close to, or over,"
3079 " your disk quota\n"
3080 "on the file system on which that file resides.",
3085 case WTAP_ERR_CANT_CLOSE:
3086 g_snprintf(errmsg, errmsglen,
3087 "The file to which the capture was being saved"
3088 " couldn't be closed for some unknown reason.");
3091 case WTAP_ERR_SHORT_WRITE:
3092 g_snprintf(errmsg, errmsglen,
3093 "Not all the packets could be written to the file"
3094 " to which the capture was being saved\n"
3101 g_snprintf(errmsg, errmsglen,
3102 "The file to which the capture was being saved\n"
3103 "(\"%s\") could not be closed: %s.",
3104 fname, wtap_strerror(err));
3106 g_snprintf(errmsg, errmsglen,
3107 "An error occurred while writing to the file"
3108 " to which the capture was being saved\n"
3110 fname, wtap_strerror(err));
3117 /* one packet was captured, process it */
3119 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
3122 loop_data *ld = (loop_data *) (void *) user;
3125 /* We may be called multiple times from pcap_dispatch(); if we've set
3126 the "stop capturing" flag, ignore this packet, as we're not
3127 supposed to be saving any more packets. */
3132 gboolean successful;
3133 /* We're supposed to write the packet to a file; do so.
3134 If this fails, set "ld->go" to FALSE, to stop the capture, and set
3135 "ld->err" to the error. */
3136 if (global_capture_opts.use_pcapng) {
3137 successful = libpcap_write_enhanced_packet_block(ld->pdh, phdr, 0, pd, &ld->bytes_written, &err);
3139 successful = libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err);
3146 /* if the user told us to stop after x packets, do we already have enough? */
3147 if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
3156 /* And now our feature presentation... [ fade to music ] */
3158 main(int argc, char *argv[])
3161 gboolean arg_error = FALSE;
3166 struct sigaction action, oldaction;
3169 gboolean start_capture = TRUE;
3170 gboolean stats_known;
3171 struct pcap_stat stats;
3172 GLogLevelFlags log_flags;
3173 gboolean list_interfaces = FALSE;
3174 gboolean list_link_layer_types = FALSE;
3175 gboolean machine_readable = FALSE;
3176 gboolean print_statistics = FALSE;
3177 int status, run_once_args = 0;
3179 #if defined(__APPLE__) && defined(__LP64__)
3180 struct utsname osinfo;
3183 #ifdef HAVE_PCAP_REMOTE
3184 #define OPTSTRING_A "A:"
3185 #define OPTSTRING_r "r"
3186 #define OPTSTRING_u "u"
3188 #define OPTSTRING_A ""
3189 #define OPTSTRING_r ""
3190 #define OPTSTRING_u ""
3193 #ifdef HAVE_PCAP_SETSAMPLING
3194 #define OPTSTRING_m "m:"
3196 #define OPTSTRING_m ""
3199 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
3200 #define OPTSTRING_B "B:"
3202 #define OPTSTRING_B ""
3203 #endif /* _WIN32 or HAVE_PCAP_CREATE */
3205 #ifdef HAVE_PCAP_CREATE
3206 #define OPTSTRING_I "I"
3208 #define OPTSTRING_I ""
3211 #define OPTSTRING "a:" OPTSTRING_A "b:" OPTSTRING_B "c:Df:hi:" OPTSTRING_I "L" OPTSTRING_m "Mnpq" OPTSTRING_r "Ss:" OPTSTRING_u "vw:y:Z:"
3213 #ifdef DEBUG_CHILD_DUMPCAP
3214 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
3215 fprintf (stderr, "Unable to open debug log file !\n");
3220 #if defined(__APPLE__) && defined(__LP64__)
3222 * Is this Mac OS X 10.6.x, other than 10.6.2? If so, we need a bug
3223 * workaround - timeouts less than 1 second don't work with libpcap
3224 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
3225 * and re-introduced in 10.6.3. We don't know whether it'll be fixed
3226 * again in a later 10.6.x release; we'll assume that it'll be fixed
3227 * in any future major releases.)
3229 if (uname(&osinfo) == 0) {
3231 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
3232 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
3233 * number of 10.0.0, not 10.1.0 - go figure).
3235 if (strncmp(osinfo.release, "10.", 3) == 0) {
3237 * OK, it's Snow Leopard - which version?
3239 if (strcmp(osinfo.release, "10.2.0") != 0) {
3241 need_timeout_workaround = TRUE;
3248 * Determine if dumpcap is being requested to run in a special
3249 * capture_child mode by going thru the command line args to see if
3250 * a -Z is present. (-Z is a hidden option).
3252 * The primary result of running in capture_child mode is that
3253 * all messages sent out on stderr are in a special type/len/string
3254 * format to allow message processing by type. These messages include
3255 * error messages if dumpcap fails to start the operation it was
3256 * requested to do, as well as various "status" messages which are sent
3257 * when an actual capture is in progress, and a "success" message sent
3258 * if dumpcap was requested to perform an operation other than a
3261 * Capture_child mode would normally be requested by a parent process
3262 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
3263 * to which dumpcap stderr has been redirected. It might also have
3264 * another pipe to obtain dumpcap stdout output; for operations other
3265 * than a capture, that information is formatted specially for easier
3266 * parsing by the parent process.
3268 * Capture_child mode needs to be determined immediately upon
3269 * startup so that any messages generated by dumpcap in this mode
3270 * (eg: during initialization) will be formatted properly.
3273 for (i=1; i<argc; i++) {
3274 if (strcmp("-Z", argv[i]) == 0) {
3275 capture_child = TRUE;
3276 machine_readable = TRUE; /* request machine-readable output */
3278 /* set output pipe to binary mode, to avoid ugly text conversions */
3279 _setmode(2, O_BINARY);
3284 /* The default_log_handler will use stdout, which makes trouble in */
3285 /* capture child mode, as it uses stdout for it's sync_pipe. */
3286 /* So: the filtering is done in the console_log_handler and not here.*/
3287 /* We set the log handlers right up front to make sure that any log */
3288 /* messages when running as child will be sent back to the parent */
3289 /* with the correct format. */
3293 G_LOG_LEVEL_CRITICAL|
3294 G_LOG_LEVEL_WARNING|
3295 G_LOG_LEVEL_MESSAGE|
3298 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
3300 g_log_set_handler(NULL,
3302 console_log_handler, NULL /* user_data */);
3303 g_log_set_handler(LOG_DOMAIN_MAIN,
3305 console_log_handler, NULL /* user_data */);
3306 g_log_set_handler(LOG_DOMAIN_CAPTURE,
3308 console_log_handler, NULL /* user_data */);
3309 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
3311 console_log_handler, NULL /* user_data */);
3314 /* Load wpcap if possible. Do this before collecting the run-time version information */
3317 /* ... and also load the packet.dll from wpcap */
3318 /* XXX - currently not required, may change later. */
3319 /*wpcap_packet_load();*/
3321 /* Start windows sockets */
3322 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
3324 /* Set handler for Ctrl+C key */
3325 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
3327 /* Prepare to read from a pipe */
3328 if (!g_thread_supported ())
3329 g_thread_init (NULL);
3330 cap_pipe_pending_q = g_async_queue_new();
3331 cap_pipe_done_q = g_async_queue_new();
3332 cap_pipe_read_mtx = g_mutex_new();
3335 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
3337 action.sa_handler = capture_cleanup_handler;
3339 * Arrange that system calls not get restarted, because when
3340 * our signal handler returns we don't want to restart
3341 * a call that was waiting for packets to arrive.
3343 action.sa_flags = 0;
3344 sigemptyset(&action.sa_mask);
3345 sigaction(SIGTERM, &action, NULL);
3346 sigaction(SIGINT, &action, NULL);
3347 sigaction(SIGPIPE, &action, NULL);
3348 sigaction(SIGHUP, NULL, &oldaction);
3349 if (oldaction.sa_handler == SIG_DFL)
3350 sigaction(SIGHUP, &action, NULL);
3353 /* Catch SIGINFO and, if we get it and we're capturing in
3354 quiet mode, report the number of packets we've captured. */
3355 action.sa_handler = report_counts_siginfo;
3356 action.sa_flags = 0;
3357 sigemptyset(&action.sa_mask);
3358 sigaction(SIGINFO, &action, NULL);
3359 #endif /* SIGINFO */
3362 /* ----------------------------------------------------------------- */
3363 /* Privilege and capability handling */
3365 /* 1. Running not as root or suid root; no special capabilities. */
3368 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
3371 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
3373 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
3374 /* capabilities; Drop all other capabilities; */
3375 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3376 /* else: after pcap_open_live() in capture_loop_open_input() */
3377 /* drop all capabilities (NET_RAW and NET_ADMIN); */
3378 /* (Note: this means that the process, although logged in */
3379 /* as root, does not have various permissions such as the */
3380 /* ability to bypass file access permissions). */
3381 /* XXX: Should we just leave capabilities alone in this case */
3382 /* so that user gets expected effect that root can do */
3385 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
3387 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3388 /* else: after pcap_open_live() in capture_loop_open_input() */
3389 /* drop suid root (set euid=ruid).(ie: keep suid until after */
3390 /* pcap_open_live). */
3392 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
3394 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
3395 /* capabilities; Drop all other capabilities; */
3396 /* Drop suid privileges (euid=ruid); */
3397 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3398 /* else: after pcap_open_live() in capture_loop_open_input() */
3399 /* drop all capabilities (NET_RAW and NET_ADMIN). */
3401 /* XXX: For some Linux versions/distros with capabilities */
3402 /* a 'normal' process with any capabilities cannot be */
3403 /* 'killed' (signaled) from another (same uid) non-privileged */
3405 /* For example: If (non-suid) Wireshark forks a */
3406 /* child suid dumpcap which acts as described here (case 5), */
3407 /* Wireshark will be unable to kill (signal) the child */
3408 /* dumpcap process until the capabilities have been dropped */
3409 /* (after pcap_open_live()). */
3410 /* This behaviour will apparently be changed in the kernel */
3411 /* to allow the kill (signal) in this case. */
3412 /* See the following for details: */
3413 /* http://www.mail-archive.com/ [wrapped] */
3414 /* linux-security-module@vger.kernel.org/msg02913.html */
3416 /* It is therefore conceivable that if dumpcap somehow hangs */
3417 /* in pcap_open_live or before that wireshark will not */
3418 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
3419 /* In this case, exiting wireshark will kill the child */
3420 /* dumpcap process. */
3422 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
3423 /* capabilities; Using libcap. Note: capset cmd (which see) */
3424 /* used to assign capabilities to file. */
3426 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3427 /* else: after pcap_open_live() in capture_loop_open_input() */
3428 /* drop all capabilities (NET_RAW and NET_ADMIN) */
3430 /* ToDo: -S (stats) should drop privileges/capabilities when no */
3431 /* longer required (similar to capture). */
3433 /* ----------------------------------------------------------------- */
3435 get_credential_info();
3438 /* If 'started with special privileges' (and using libcap) */
3439 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
3440 /* Set euid/egid = ruid/rgid to remove suid privileges */
3441 relinquish_privs_except_capture();
3444 /* Set the initial values in the capture options. This might be overwritten
3445 by the command line parameters. */
3446 capture_opts_init(&global_capture_opts, NULL);
3448 /* Default to capturing the entire packet. */
3449 global_capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
3451 /* We always save to a file - if no file was specified, we save to a
3453 global_capture_opts.saving_to_file = TRUE;
3454 global_capture_opts.has_ring_num_files = TRUE;
3456 /* Now get our args */
3457 while ((opt = getopt(argc, argv, OPTSTRING)) != -1) {
3459 case 'h': /* Print help and exit */
3463 case 'v': /* Show version and exit */
3465 GString *comp_info_str;
3466 GString *runtime_info_str;
3467 /* Assemble the compile-time version information string */
3468 comp_info_str = g_string_new("Compiled ");
3469 get_compiled_version_info(comp_info_str, NULL);
3471 /* Assemble the run-time version information string */
3472 runtime_info_str = g_string_new("Running ");
3473 get_runtime_version_info(runtime_info_str, NULL);
3474 show_version(comp_info_str, runtime_info_str);
3475 g_string_free(comp_info_str, TRUE);
3476 g_string_free(runtime_info_str, TRUE);
3480 /*** capture option specific ***/
3481 case 'a': /* autostop criteria */
3482 case 'b': /* Ringbuffer option */
3483 case 'c': /* Capture x packets */
3484 case 'f': /* capture filter */
3485 case 'i': /* Use interface x */
3486 case 'n': /* Use pcapng format */
3487 case 'p': /* Don't capture in promiscuous mode */
3488 case 'q': /* Don't print (or report) packet counts */
3489 case 's': /* Set the snapshot (capture) length */
3490 case 'w': /* Write to capture file x */
3491 case 'y': /* Set the pcap data link type */
3492 #ifdef HAVE_PCAP_REMOTE
3493 case 'u': /* Use UDP for data transfer */
3494 case 'r': /* Capture own RPCAP traffic too */
3495 case 'A': /* Authentication */
3497 #ifdef HAVE_PCAP_SETSAMPLING
3498 case 'm': /* Sampling */
3500 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
3501 case 'B': /* Buffer size */
3502 #endif /* _WIN32 or HAVE_PCAP_CREATE */
3503 #ifdef HAVE_PCAP_CREATE
3504 case 'I': /* Monitor mode */
3506 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
3511 /*** hidden option: Wireshark child mode (using binary output messages) ***/
3513 capture_child = TRUE;
3515 /* set output pipe to binary mode, to avoid ugly text conversions */
3516 _setmode(2, O_BINARY);
3518 * optarg = the control ID, aka the PPID, currently used for the
3521 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
3522 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
3523 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
3524 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
3526 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
3527 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3528 "Signal pipe: Unable to open %s. Dead parent?",
3536 /*** all non capture option specific ***/
3537 case 'D': /* Print a list of capture devices and exit */
3538 list_interfaces = TRUE;
3541 case 'L': /* Print list of link-layer types and exit */
3542 list_link_layer_types = TRUE;
3545 case 'S': /* Print interface statistics once a second */
3546 print_statistics = TRUE;
3549 case 'M': /* For -D, -L, and -S, print machine-readable output */
3550 machine_readable = TRUE;
3553 case '?': /* Bad flag - print usage message */
3554 cmdarg_err("Invalid Option: %s", argv[optind-1]);
3562 /* user specified file name as regular command-line argument */
3563 /* XXX - use it as the capture file name (or something else)? */
3570 * Extra command line arguments were specified; complain.
3571 * XXX - interpret as capture filter, as tcpdump and tshark do?
3573 cmdarg_err("Invalid argument: %s", argv[0]);
3582 if (run_once_args > 1) {
3583 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
3585 } else if (run_once_args == 1) {
3586 /* We're supposed to print some information, rather than
3587 to capture traffic; did they specify a ring buffer option? */
3588 if (global_capture_opts.multi_files_on) {
3589 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
3593 /* We're supposed to capture traffic; was the ring buffer option
3594 specified and, if so, does it make sense? */
3595 if (global_capture_opts.multi_files_on) {
3596 /* Ring buffer works only under certain conditions:
3597 a) ring buffer does not work with temporary files;
3598 b) it makes no sense to enable the ring buffer if the maximum
3599 file size is set to "infinite". */
3600 if (global_capture_opts.save_file == NULL) {
3601 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
3602 global_capture_opts.multi_files_on = FALSE;
3604 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
3605 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
3606 /* XXX - this must be redesigned as the conditions changed */
3607 /* global_capture_opts.multi_files_on = FALSE;*/
3613 * "-D" requires no interface to be selected; it's supposed to list
3616 if (list_interfaces) {
3617 /* Get the list of interfaces */
3622 if_list = capture_interface_list(&err, &err_str);
3623 if (if_list == NULL) {
3625 case CANT_GET_INTERFACE_LIST:
3626 cmdarg_err("%s", err_str);
3631 case NO_INTERFACES_FOUND:
3633 * If we're being run by another program, just give them
3634 * an empty list of interfaces, don't report this as
3635 * an error; that lets them decide whether to report
3636 * this as an error or not.
3638 if (!machine_readable) {
3639 cmdarg_err("There are no interfaces on which a capture can be done");
3646 if (machine_readable) /* tab-separated values to stdout */
3647 print_machine_readable_interfaces(if_list);
3649 capture_opts_print_interfaces(if_list);
3650 free_interface_list(if_list);
3655 * "-S" requires no interface to be selected; it gives statistics
3656 * for all interfaces.
3658 if (print_statistics) {
3659 status = print_statistics_loop(machine_readable);
3664 * "-L", and capturing, act on a particular interface, so we have to
3665 * have an interface; if none was specified, pick a default.
3667 if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
3668 /* cmdarg_err() already called .... */
3672 /* Let the user know what interface was chosen. */
3673 /* get_interface_descriptive_name() is not available! */
3674 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", global_capture_opts.iface);
3676 if (list_link_layer_types) {
3677 /* Get the list of link-layer types for the capture device. */
3678 if_capabilities_t *caps;
3681 caps = get_if_capabilities(global_capture_opts.iface,
3682 global_capture_opts.monitor_mode, &err_str);
3684 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
3685 "Please check to make sure you have sufficient permissions, and that\n"
3686 "you have the proper interface or pipe specified.", global_capture_opts.iface, err_str);
3690 if (caps->data_link_types == NULL) {
3691 cmdarg_err("The capture device \"%s\" has no data link types.", global_capture_opts.iface);
3694 if (machine_readable) /* tab-separated values to stdout */
3695 print_machine_readable_if_capabilities(caps);
3697 capture_opts_print_if_capabilities(caps,
3698 global_capture_opts.monitor_mode);
3699 free_if_capabilities(caps);
3703 /* We're supposed to do a capture. Process the remaining arguments. */
3704 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
3705 capture_opts_trim_ring_num_files(&global_capture_opts);
3707 /* Now start the capture. */
3709 if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
3713 /* capture failed */
3720 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
3721 const char *message, gpointer user_data _U_)
3728 /* ignore log message, if log_level isn't interesting */
3729 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3730 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
3735 /* create a "timestamp" */
3737 today = localtime(&curr);
3739 switch(log_level & G_LOG_LEVEL_MASK) {
3740 case G_LOG_LEVEL_ERROR:
3743 case G_LOG_LEVEL_CRITICAL:
3746 case G_LOG_LEVEL_WARNING:
3749 case G_LOG_LEVEL_MESSAGE:
3752 case G_LOG_LEVEL_INFO:
3755 case G_LOG_LEVEL_DEBUG:
3759 fprintf(stderr, "unknown log_level %u\n", log_level);
3761 g_assert_not_reached();
3764 /* Generate the output message */
3765 if(log_level & G_LOG_LEVEL_MESSAGE) {
3766 /* normal user messages without additional infos */
3767 msg = g_strdup_printf("%s\n", message);
3769 /* info/debug messages with additional infos */
3770 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
3771 today->tm_hour, today->tm_min, today->tm_sec,
3772 log_domain != NULL ? log_domain : "",
3776 /* DEBUG & INFO msgs (if we're debugging today) */
3777 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3778 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3779 #ifdef DEBUG_DUMPCAP
3780 fprintf(stderr, "%s", msg);
3783 #ifdef DEBUG_CHILD_DUMPCAP
3784 fprintf(debug_log, "%s", msg);
3792 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
3793 /* to parent especially formatted if dumpcap running as child. */
3794 if (capture_child) {
3795 sync_pipe_errmsg_to_parent(2, msg, "");
3797 fprintf(stderr, "%s", msg);
3804 /****************************************************************************************************************/
3805 /* indication report routines */
3809 report_packet_count(int packet_count)
3811 char tmp[SP_DECISIZE+1+1];
3812 static int count = 0;
3815 g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
3816 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
3817 pipe_write_block(2, SP_PACKET_COUNT, tmp);
3819 count += packet_count;
3820 fprintf(stderr, "\rPackets: %u ", count);
3821 /* stderr could be line buffered */
3827 report_new_capture_file(const char *filename)
3830 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
3831 pipe_write_block(2, SP_FILE, filename);
3835 * Prevent a SIGINFO handler from writing to the standard error
3836 * while we're doing so; instead, have it just set a flag telling
3837 * us to print that information when we're done.
3840 #endif /* SIGINFO */
3841 fprintf(stderr, "File: %s\n", filename);
3842 /* stderr could be line buffered */
3847 * Allow SIGINFO handlers to write.
3852 * If a SIGINFO handler asked us to write out capture counts, do so.
3856 #endif /* SIGINFO */
3861 report_cfilter_error(const char *cfilter, const char *errmsg)
3863 if (capture_child) {
3864 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
3865 pipe_write_block(2, SP_BAD_FILTER, errmsg);
3868 "Invalid capture filter: \"%s\"!\n"
3870 "That string isn't a valid capture filter (%s).\n"
3871 "See the User's Guide for a description of the capture filter syntax.\n",
3877 report_capture_error(const char *error_msg, const char *secondary_error_msg)
3880 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3881 "Primary Error: %s", error_msg);
3882 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3883 "Secondary Error: %s", secondary_error_msg);
3884 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
3886 fprintf(stderr, "%s\n%s\n", error_msg, secondary_error_msg);
3891 report_packet_drops(guint32 drops)
3893 char tmp[SP_DECISIZE+1+1];
3895 g_snprintf(tmp, sizeof(tmp), "%u", drops);
3898 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
3899 pipe_write_block(2, SP_DROPS, tmp);
3901 fprintf(stderr, "Packets dropped: %s\n", tmp);
3902 /* stderr could be line buffered */
3908 /****************************************************************************************************************/
3909 /* signal_pipe handling */
3914 signal_pipe_check_running(void)
3916 /* any news from our parent? -> just stop the capture */
3920 /* if we are running standalone, no check required */
3921 if(!capture_child) {
3925 if(!sig_pipe_name || !sig_pipe_handle) {
3926 /* This shouldn't happen */
3927 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3928 "Signal pipe: No name or handle");
3933 * XXX - We should have the process ID of the parent (from the "-Z" flag)
3934 * at this point. Should we check to see if the parent is still alive,
3935 * e.g. by using OpenProcess?
3938 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
3940 if(!result || avail > 0) {
3941 /* peek failed or some bytes really available */
3942 /* (if not piping from stdin this would fail) */
3943 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3944 "Signal pipe: Stop capture: %s", sig_pipe_name);
3945 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3946 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
3947 sig_pipe_handle, result, avail);
3950 /* pipe ok and no bytes available */
3957 * Editor modelines - http://www.wireshark.org/tools/modelines.html
3962 * indent-tabs-mode: nil
3965 * vi: set shiftwidth=4 tabstop=8 expandtab
3966 * :indentSize=4:tabSize=8:noTabs=true: