5 * Wireshark - Network traffic analyzer
6 * By Gerald Combs <gerald@wireshark.org>
7 * Copyright 1998 Gerald Combs
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 #include <stdlib.h> /* for exit() */
35 #ifdef HAVE_SYS_TYPES_H
36 # include <sys/types.h>
39 #ifdef HAVE_SYS_STAT_H
40 # include <sys/stat.h>
51 #ifdef HAVE_ARPA_INET_H
52 #include <arpa/inet.h>
55 #if defined(__APPLE__) && defined(__LP64__)
56 #include <sys/utsname.h>
73 # include <sys/prctl.h>
74 # include <sys/capability.h>
77 #include "ringbuffer.h"
78 #include "clopts_common.h"
79 #include "console_io.h"
80 #include "cmdarg_err.h"
81 #include "version_info.h"
83 #include "capture-pcap-util.h"
88 #include "capture-wpcap.h"
89 #include <wsutil/unicode-utils.h>
93 #include <sys/socket.h>
97 #ifdef NEED_INET_V6DEFS_H
98 # include "inet_v6defs.h"
101 #include <wsutil/privileges.h>
103 #include "sync_pipe.h"
105 #include "capture_opts.h"
106 #include "capture_ifinfo.h"
107 #include "capture_sync.h"
109 #include "conditions.h"
110 #include "capture_stop_conditions.h"
112 #include "tempfile.h"
114 #include "wsutil/file_util.h"
117 * Get information about libpcap format from "wiretap/libpcap.h".
118 * XXX - can we just use pcap_open_offline() to read the pipe?
120 #include "wiretap/libpcap.h"
122 /**#define DEBUG_DUMPCAP**/
123 /**#define DEBUG_CHILD_DUMPCAP**/
125 #ifdef DEBUG_CHILD_DUMPCAP
126 FILE *debug_log; /* for logging debug messages to */
127 /* a file if DEBUG_CHILD_DUMPCAP */
135 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
137 static gchar *sig_pipe_name = NULL;
138 static HANDLE sig_pipe_handle = NULL;
139 static gboolean signal_pipe_check_running(void);
143 static GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
144 static GMutex *cap_pipe_read_mtx;
147 /** Stop a low-level capture (stops the capture child). */
148 static void capture_loop_stop(void);
150 #if !defined (__linux__)
151 #ifndef HAVE_PCAP_BREAKLOOP
153 * We don't have pcap_breakloop(), which is the only way to ensure that
154 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
155 * won't, if the call to read the next packet or batch of packets is
156 * is interrupted by a signal on UN*X, just go back and try again to
159 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
160 * the signal handler, set a flag to stop capturing; however, without
161 * a guarantee of that sort, we can't guarantee that we'll stop capturing
162 * if the read will be retried and won't time out if no packets arrive.
164 * Therefore, on at least some platforms, we work around the lack of
165 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
166 * to wait for packets to arrive, so that we're probably going to be
167 * blocked in the select() when the signal arrives, and can just bail
168 * out of the loop at that point.
170 * However, we don't want to that on BSD (because "select()" doesn't work
171 * correctly on BPF devices on at least some releases of some flavors of
172 * BSD), and we don't want to do it on Windows (because "select()" is
173 * something for sockets, not for arbitrary handles). (Note that "Windows"
174 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
175 * using WinPcap, not a UNIX libpcap.)
177 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
178 * on BSD times out even if no packets have arrived, so we'll eventually
179 * exit pcap_dispatch() with an indication that no packets have arrived,
180 * and will break out of the capture loop at that point.
182 * On Windows, we can't send a SIGINT to stop capturing, so none of this
183 * applies in any case.
185 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
186 * want to include it if it's not present on this platform, however.
188 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
189 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
191 # define MUST_DO_SELECT
192 # endif /* avoid select */
193 #endif /* HAVE_PCAP_BREAKLOOP */
195 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
196 * in pcap_dispatch(); on the other hand, select() works just fine there.
197 * Hence we use a select for that come what may.
199 #define MUST_DO_SELECT
202 /** init the capture filter */
205 INITFILTER_BAD_FILTER,
206 INITFILTER_OTHER_ERROR
207 } initfilter_status_t;
209 typedef struct _loop_data {
211 gboolean go; /* TRUE as long as we're supposed to keep capturing */
212 int err; /* if non-zero, error seen while capturing */
213 gint packet_count; /* Number of packets we have already captured */
214 gint packet_max; /* Number of packets we're supposed to capture - 0 means infinite */
216 /* pcap "input file" */
217 pcap_t *pcap_h; /* pcap handle */
218 gboolean pcap_err; /* TRUE if error from pcap */
219 #ifdef MUST_DO_SELECT
220 int pcap_fd; /* pcap file descriptor */
223 /* capture pipe (unix only "input file") */
224 gboolean from_cap_pipe; /* TRUE if we are capturing data from a capture pipe */
225 struct pcap_hdr cap_pipe_hdr; /* Pcap header when capturing from a pipe */
226 struct pcaprec_modified_hdr cap_pipe_rechdr; /* Pcap record header when capturing from a pipe */
228 HANDLE cap_pipe_h; /* The handle of the capture pipe */
230 int cap_pipe_fd; /* the file descriptor of the capture pipe */
232 gboolean cap_pipe_modified; /* TRUE if data in the pipe uses modified pcap headers */
233 gboolean cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
235 char * cap_pipe_buf; /* Pointer to the data buffer we read into */
236 #endif /* USE_THREADS */
237 int cap_pipe_bytes_to_read;/* Used by cap_pipe_dispatch */
238 int cap_pipe_bytes_read; /* Used by cap_pipe_dispatch */
240 STATE_EXPECT_REC_HDR,
245 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
257 * Standard secondary message for unexpected errors.
259 static const char please_report[] =
260 "Please report this to the Wireshark developers.\n"
261 "(This is not a crash; please do not report it as such.)";
264 * This needs to be static, so that the SIGINT handler can clear the "go"
267 static loop_data global_ld;
271 * Timeout, in milliseconds, for reads from the stream of captured packets.
273 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
274 * 64-bit applications, with sub-second timeouts not to work. The bug is
277 #if defined(__APPLE__) && defined(__LP64__)
278 static gboolean need_timeout_workaround;
280 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
282 #define CAP_READ_TIMEOUT 250
286 * Timeout, in microseconds, for threaded reads from a pipe.
288 #define THREAD_READ_TIMEOUT 100
289 static const char *cap_pipe_err_str;
292 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
293 const char *message, gpointer user_data _U_);
295 /* capture related options */
296 static capture_options global_capture_opts;
298 static void capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
300 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
301 int err, gboolean is_close);
303 static void exit_main(int err) G_GNUC_NORETURN;
305 static void report_new_capture_file(const char *filename);
306 static void report_packet_count(int packet_count);
307 static void report_packet_drops(guint32 drops);
308 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
309 static void report_cfilter_error(const char *cfilter, const char *errmsg);
312 print_usage(gboolean print_ver) {
320 "Dumpcap " VERSION "%s\n"
321 "Capture network packets and dump them into a libpcap file.\n"
322 "See http://www.wireshark.org for more information.\n",
323 wireshark_svnversion);
327 fprintf(output, "\nUsage: dumpcap [options] ...\n");
328 fprintf(output, "\n");
329 fprintf(output, "Capture interface:\n");
330 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
331 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
332 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
333 fprintf(output, " -p don't capture in promiscuous mode\n");
334 #ifdef HAVE_PCAP_CREATE
335 fprintf(output, " -I capture in monitor mode, if available\n");
337 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
338 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
340 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
341 fprintf(output, " -D print list of interfaces and exit\n");
342 fprintf(output, " -L print list of link-layer types of iface and exit\n");
343 fprintf(output, " -S print statistics for each interface once every second\n");
344 fprintf(output, " -M for -D, -L, and -S produce machine-readable output\n");
345 fprintf(output, "\n");
346 #ifdef HAVE_PCAP_REMOTE
347 fprintf(output, "\nRPCAP options:\n");
348 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
349 fprintf(output, " -u use UDP for RPCAP data transfer\n");
350 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
351 #ifdef HAVE_PCAP_SETSAMPLING
352 fprintf(output, " -m <sampling type> use packet sampling\n");
353 fprintf(output, " count:NUM - capture one packet of every NUM\n");
354 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
357 fprintf(output, "Stop conditions:\n");
358 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
359 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
360 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
361 fprintf(output, " files:NUM - stop after NUM files\n");
362 /*fprintf(output, "\n");*/
363 fprintf(output, "Output (files):\n");
364 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
365 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
366 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
367 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
368 fprintf(output, " -n use pcapng format instead of pcap\n");
369 /*fprintf(output, "\n");*/
370 fprintf(output, "Miscellaneous:\n");
371 fprintf(output, " -v print version information and exit\n");
372 fprintf(output, " -h display this help and exit\n");
373 fprintf(output, "\n");
374 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcap\n");
375 fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcap\"\n");
376 fprintf(output, "\n");
377 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
381 show_version(GString *comp_info_str, GString *runtime_info_str)
385 "Dumpcap " VERSION "%s\n"
390 "See http://www.wireshark.org for more information.\n",
391 wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
395 * Print to the standard error. This is a command-line tool, so there's
396 * no need to pop up a console.
399 vfprintf_stderr(const char *fmt, va_list ap)
401 vfprintf(stderr, fmt, ap);
405 fprintf_stderr(const char *fmt, ...)
410 vfprintf_stderr(fmt, ap);
415 * Report an error in command-line arguments.
418 cmdarg_err(const char *fmt, ...)
424 /* Generate a 'special format' message back to parent */
426 msg = g_strdup_vprintf(fmt, ap);
427 sync_pipe_errmsg_to_parent(2, msg, "");
432 fprintf(stderr, "dumpcap: ");
433 vfprintf(stderr, fmt, ap);
434 fprintf(stderr, "\n");
440 * Report additional information for an error in command-line arguments.
443 cmdarg_err_cont(const char *fmt, ...)
450 msg = g_strdup_vprintf(fmt, ap);
451 sync_pipe_errmsg_to_parent(2, msg, "");
456 vfprintf(stderr, fmt, ap);
457 fprintf(stderr, "\n");
463 * capture_interface_list() is expected to do the right thing to get
464 * a list of interfaces.
466 * In most of the programs in the Wireshark suite, "the right thing"
467 * is to run dumpcap and ask it for the list, because dumpcap may
468 * be the only program in the suite with enough privileges to get
471 * In dumpcap itself, however, we obviously can't run dumpcap to
472 * ask for the list. Therefore, our capture_interface_list() should
473 * just call get_interface_list().
476 capture_interface_list(int *err, char **err_str)
478 return get_interface_list(err, err_str);
482 * Get the data-link types available for a libpcap device.
484 static data_link_info_t *
485 create_data_link_info(int dlt)
487 data_link_info_t *data_link_info;
490 data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
491 data_link_info->dlt = dlt;
492 text = pcap_datalink_val_to_name(dlt);
494 data_link_info->name = g_strdup(text);
496 data_link_info->name = g_strdup_printf("DLT %d", dlt);
497 text = pcap_datalink_val_to_description(dlt);
499 data_link_info->description = g_strdup(text);
501 data_link_info->description = NULL;
502 return data_link_info;
506 get_if_capabilities(const char *devname, gboolean monitor_mode
507 #ifndef HAVE_PCAP_CREATE
513 char errbuf[PCAP_ERRBUF_SIZE];
515 #ifdef HAVE_PCAP_CREATE
519 #ifdef HAVE_PCAP_LIST_DATALINKS
523 data_link_info_t *data_link_info;
526 * Allocate the interface capabilities structure.
528 caps = g_malloc(sizeof *caps);
530 #ifdef HAVE_PCAP_OPEN
531 pch = pcap_open(devname, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
532 caps->can_set_rfmon = FALSE;
535 *err_str = g_strdup(errbuf);
539 #elif defined(HAVE_PCAP_CREATE)
540 pch = pcap_create(devname, errbuf);
543 *err_str = g_strdup(errbuf);
547 status = pcap_can_set_rfmon(pch);
551 caps->can_set_rfmon = FALSE;
555 caps->can_set_rfmon = TRUE;
557 pcap_set_rfmon(pch, 1);
560 case PCAP_ERROR_NO_SUCH_DEVICE:
562 *err_str = g_strdup_printf("There is no capture device named \"%s\"", devname);
569 *err_str = g_strdup_printf("pcap_can_set_rfmon on \"%s\" failed: %s",
570 devname, pcap_geterr(pch));
577 *err_str = g_strdup_printf("pcap_can_set_rfmon on \"%s\" failed: %s",
578 devname, pcap_statustostr(status));
584 status = pcap_activate(pch);
586 /* Error. We ignore warnings (status > 0). */
587 if (err_str != NULL) {
588 if (status == PCAP_ERROR) {
589 *err_str = g_strdup_printf("pcap_activate on %s failed: %s",
590 devname, pcap_geterr(pch));
592 *err_str = g_strdup_printf("pcap_activate on %s failed: %s",
593 devname, pcap_statustostr(status));
601 pch = pcap_open_live(devname, MIN_PACKET_SIZE, 0, 0, errbuf);
602 caps->can_set_rfmon = FALSE;
605 *err_str = g_strdup(errbuf);
610 deflt = get_pcap_linktype(pch, devname);
611 #ifdef HAVE_PCAP_LIST_DATALINKS
612 nlt = pcap_list_datalinks(pch, &linktypes);
613 if (nlt == 0 || linktypes == NULL) {
616 *err_str = NULL; /* an empty list doesn't mean an error */
619 caps->data_link_types = NULL;
620 for (i = 0; i < nlt; i++) {
621 data_link_info = create_data_link_info(linktypes[i]);
624 * XXX - for 802.11, make the most detailed 802.11
625 * version the default, rather than the one the
626 * device has as the default?
628 if (linktypes[i] == deflt)
629 caps->data_link_types = g_list_prepend(caps->data_link_types,
632 caps->data_link_types = g_list_append(caps->data_link_types,
635 #ifdef HAVE_PCAP_FREE_DATALINKS
636 pcap_free_datalinks(linktypes);
639 * In Windows, there's no guarantee that if you have a library
640 * built with one version of the MSVC++ run-time library, and
641 * it returns a pointer to allocated data, you can free that
642 * data from a program linked with another version of the
643 * MSVC++ run-time library.
645 * This is not an issue on UN*X.
647 * See the mail threads starting at
649 * http://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
653 * http://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
656 #define xx_free free /* hack so checkAPIs doesn't complain */
659 #endif /* HAVE_PCAP_FREE_DATALINKS */
660 #else /* HAVE_PCAP_LIST_DATALINKS */
662 data_link_info = create_data_link_info(deflt);
663 caps->data_link_types = g_list_append(caps->data_link_types,
665 #endif /* HAVE_PCAP_LIST_DATALINKS */
674 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
676 print_machine_readable_interfaces(GList *if_list)
683 char addr_str[ADDRSTRLEN];
685 i = 1; /* Interface id number */
686 for (if_entry = g_list_first(if_list); if_entry != NULL;
687 if_entry = g_list_next(if_entry)) {
688 if_info = (if_info_t *)if_entry->data;
689 printf("%d. %s", i++, if_info->name);
692 * Print the contents of the if_entry struct in a parseable format.
693 * Each if_entry element is tab-separated. Addresses are comma-
696 /* XXX - Make sure our description doesn't contain a tab */
697 if (if_info->description != NULL)
698 printf("\t%s\t", if_info->description);
702 for(addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
703 addr = g_slist_next(addr)) {
704 if (addr != g_slist_nth(if_info->addrs, 0))
707 if_addr = (if_addr_t *)addr->data;
708 switch(if_addr->ifat_type) {
710 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
712 printf("%s", addr_str);
714 printf("<unknown IPv4>");
718 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
719 addr_str, ADDRSTRLEN)) {
720 printf("%s", addr_str);
722 printf("<unknown IPv6>");
726 printf("<type unknown %u>", if_addr->ifat_type);
730 if (if_info->loopback)
731 printf("\tloopback");
740 * If you change the machine-readable output format of this function,
741 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
744 print_machine_readable_if_capabilities(if_caps_t *caps)
747 data_link_info_t *data_link_info;
748 const gchar *desc_str;
750 if (caps->can_set_rfmon)
754 for (lt_entry = caps->data_link_types; lt_entry != NULL;
755 lt_entry = g_list_next(lt_entry)) {
756 data_link_info = (data_link_info_t *)lt_entry->data;
757 if (data_link_info->description != NULL)
758 desc_str = data_link_info->description;
760 desc_str = "(not supported)";
761 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
771 /* Print the number of packets captured for each interface until we're killed. */
773 print_statistics_loop(gboolean machine_readable)
775 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
781 char errbuf[PCAP_ERRBUF_SIZE];
784 if_list = get_interface_list(&err, &err_str);
785 if (if_list == NULL) {
787 case CANT_GET_INTERFACE_LIST:
788 cmdarg_err("%s", err_str);
792 case NO_INTERFACES_FOUND:
793 cmdarg_err("There are no interfaces on which a capture can be done");
799 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
800 if_info = (if_info_t *)if_entry->data;
801 #ifdef HAVE_PCAP_OPEN
802 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
804 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
808 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
809 if_stat->name = g_strdup(if_info->name);
811 stat_list = g_list_append(stat_list, if_stat);
816 cmdarg_err("There are no interfaces on which a capture can be done");
820 if (!machine_readable) {
821 printf("%-15s %10s %10s\n", "Interface", "Received",
826 while (global_ld.go) {
827 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
828 if_stat = (if_stat_t *)stat_entry->data;
829 pcap_stats(if_stat->pch, &ps);
831 if (!machine_readable) {
832 printf("%-15s %10u %10u\n", if_stat->name,
833 ps.ps_recv, ps.ps_drop);
835 printf("%s\t%u\t%u\n", if_stat->name,
836 ps.ps_recv, ps.ps_drop);
841 if (! global_ld.from_cap_pipe)
848 /* XXX - Not reached. Should we look for 'q' in stdin? */
849 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
850 if_stat = (if_stat_t *)stat_entry->data;
851 pcap_close(if_stat->pch);
852 g_free(if_stat->name);
855 g_list_free(stat_list);
856 free_interface_list(if_list);
864 capture_cleanup_handler(DWORD dwCtrlType)
866 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
867 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
868 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
869 like SIGTERM at least when the machine's shutting down.
871 For now, if we're running as a command rather than a capture child,
872 we handle all but CTRL_LOGOFF_EVENT as indications that we should
873 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
876 If we're not running as a capture child, we might be running as
877 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
878 user logs out. (XXX - can we explicitly check whether we're
879 running as a service?) */
881 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
882 "Console: Control signal");
883 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
884 "Console: Control signal, CtrlType: %u", dwCtrlType);
886 /* Keep capture running if we're a service and a user logs off */
887 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
896 capture_cleanup_handler(int signum _U_)
898 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
899 SIGTERM. We assume that if the user wanted it to keep running
900 after they logged out, they'd have nohupped it. */
902 /* Note: don't call g_log() in the signal handler: if we happened to be in
903 * g_log() in process context when the signal came in, g_log will detect
904 * the "recursion" and abort.
911 static void exit_main(int status)
914 /* Shutdown windows sockets */
917 /* can be helpful for debugging */
919 printf("Press any key\n");
930 * If we were linked with libcap (not libpcap), make sure we have
931 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
932 * (See comment in main() for details)
936 #if 0 /* Set to enable capability debugging */
937 /* see 'man cap_to_text()' for explanation of output */
938 /* '=' means 'all= ' ie: no capabilities */
939 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
941 print_caps(const char *pfx) {
942 cap_t caps = cap_get_proc();
943 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
944 "%s: EUID: %d Capabilities: %s", pfx,
945 geteuid(), cap_to_text(caps, NULL));
948 print_caps(const char *pfx _U_) {
953 relinquish_privs_except_capture(void)
955 /* If 'started_with_special_privs' (ie: suid) then enable for
956 * ourself the NET_ADMIN and NET_RAW capabilities and then
957 * drop our suid privileges.
959 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
960 * stuff we don't need (and shouldn't have).
961 * CAP_NET_RAW: Packet capture (raw sockets).
964 if (started_with_special_privs()) {
965 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
966 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
968 cap_t caps = cap_init(); /* all capabilities initialized to off */
970 print_caps("Pre drop, pre set");
972 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
973 cmdarg_err("prctl() fail return: %s", strerror(errno));
976 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
977 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
979 if (cap_set_proc(caps)) {
980 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
982 print_caps("Pre drop, post set");
984 relinquish_special_privs_perm();
986 print_caps("Post drop, pre set");
987 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
988 if (cap_set_proc(caps)) {
989 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
991 print_caps("Post drop, post set");
999 relinquish_all_capabilities(void)
1001 /* Drop any and all capabilities this process may have. */
1002 /* Allowed whether or not process has any privileges. */
1003 cap_t caps = cap_init(); /* all capabilities initialized to off */
1004 print_caps("Pre-clear");
1005 if (cap_set_proc(caps)) {
1006 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
1008 print_caps("Post-clear");
1012 #endif /* HAVE_LIBCAP */
1014 /* Set the data link type on a pcap. */
1016 set_pcap_linktype(pcap_t *pch, char *devname
1017 #ifdef HAVE_PCAP_SET_DATALINK
1022 #ifdef HAVE_PCAP_SET_DATALINK
1023 if (pcap_set_datalink(pch, dlt) == 0)
1024 return NULL; /* no error */
1025 return pcap_geterr(pch);
1027 /* Let them set it to the type it is; reject any other request. */
1028 if (get_pcap_linktype(pch, devname) == dlt)
1029 return NULL; /* no error */
1030 return "That DLT isn't one of the DLTs supported by this device";
1034 /* Take care of byte order in the libpcap headers read from pipes.
1035 * (function taken from wiretap/libpcap.c) */
1037 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1040 /* Byte-swap the record header fields. */
1041 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
1042 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
1043 rechdr->incl_len = BSWAP32(rechdr->incl_len);
1044 rechdr->orig_len = BSWAP32(rechdr->orig_len);
1047 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1048 swapped, in order to match the BPF header layout.
1050 Unfortunately, some files were, according to a comment in the "libpcap"
1051 source, written with version 2.3 in their headers but without the
1052 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1053 would make no sense - we assume that we need to swap them. */
1054 if (hdr->version_major == 2 &&
1055 (hdr->version_minor < 3 ||
1056 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1059 temp = rechdr->orig_len;
1060 rechdr->orig_len = rechdr->incl_len;
1061 rechdr->incl_len = temp;
1067 * Thread function that reads from a pipe and pushes the data
1068 * to the main application thread.
1071 * XXX Right now we use async queues for basic signaling. The main thread
1072 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1073 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1074 * Iff the read is successful cap_pipe_read pushes an item onto
1075 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1076 * the queues themselves (yet).
1078 * We might want to move some of the cap_pipe_dispatch logic here so that
1079 * we can let cap_pipe_read run independently, queuing up multiple reads
1080 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1082 static void *cap_pipe_read(void *ld_ptr) {
1083 loop_data *ld = (loop_data *)ld_ptr;
1092 while (ld->cap_pipe_err == PIPOK) {
1093 g_async_queue_pop(cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1094 g_mutex_lock(cap_pipe_read_mtx);
1096 while (bytes_read < (int) ld->cap_pipe_bytes_to_read) {
1098 /* If we try to use read() on a named pipe on Windows with partial
1099 * data it appears to return EOF.
1101 res = ReadFile(ld->cap_pipe_h, ld->cap_pipe_buf+bytes_read,
1102 ld->cap_pipe_bytes_to_read - bytes_read,
1107 last_err = GetLastError();
1108 if (last_err == ERROR_MORE_DATA) {
1110 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1111 ld->cap_pipe_err = PIPEOF;
1115 ld->cap_pipe_err = PIPERR;
1118 } else if (b == 0 && ld->cap_pipe_bytes_to_read > 0) {
1119 ld->cap_pipe_err = PIPEOF;
1124 b = read(ld->cap_pipe_fd, ld->cap_pipe_buf+bytes_read,
1125 ld->cap_pipe_bytes_to_read - bytes_read);
1128 ld->cap_pipe_err = PIPEOF;
1132 ld->cap_pipe_err = PIPERR;
1141 ld->cap_pipe_bytes_read = bytes_read;
1142 if (ld->cap_pipe_bytes_read >= ld->cap_pipe_bytes_to_read) {
1143 g_async_queue_push(cap_pipe_done_q, ld->cap_pipe_buf); /* Any non-NULL value will do */
1145 g_mutex_unlock(cap_pipe_read_mtx);
1149 #endif /* USE_THREADS */
1151 /* Provide select() functionality for a single file descriptor
1152 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1154 * Returns the same values as select. If an error is returned,
1155 * the string cap_pipe_err_str should be used instead of errno.
1158 cap_pipe_select(int pipe_fd) {
1160 struct timeval timeout, *pto;
1163 cap_pipe_err_str = "Unknown error";
1166 FD_SET(pipe_fd, &rfds);
1169 timeout.tv_usec = CAP_READ_TIMEOUT * 1000;
1172 sel_ret = select(pipe_fd+1, &rfds, NULL, NULL, pto);
1174 cap_pipe_err_str = strerror(errno);
1179 /* Mimic pcap_open_live() for pipe captures
1181 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1182 * open it, and read the header.
1184 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1185 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1187 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
1188 char *errmsg, int errmsgl)
1191 struct stat pipe_stat;
1192 struct sockaddr_un sa;
1195 unsigned int bytes_read;
1206 ld->cap_pipe_fd = -1;
1208 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
1210 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1213 * XXX - this blocks until a pcap per-file header has been written to
1214 * the pipe, so it could block indefinitely.
1216 if (strcmp(pipename, "-") == 0) {
1218 fd = 0; /* read from stdin */
1220 ld->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1224 if (ws_stat(pipename, &pipe_stat) < 0) {
1225 if (errno == ENOENT || errno == ENOTDIR)
1226 ld->cap_pipe_err = PIPNEXIST;
1228 g_snprintf(errmsg, errmsgl,
1229 "The capture session could not be initiated "
1230 "due to error getting information on pipe/socket: %s", strerror(errno));
1231 ld->cap_pipe_err = PIPERR;
1235 if (S_ISFIFO(pipe_stat.st_mode)) {
1236 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1238 g_snprintf(errmsg, errmsgl,
1239 "The capture session could not be initiated "
1240 "due to error on pipe open: %s", strerror(errno));
1241 ld->cap_pipe_err = PIPERR;
1244 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1245 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1247 g_snprintf(errmsg, errmsgl,
1248 "The capture session could not be initiated "
1249 "due to error on socket create: %s", strerror(errno));
1250 ld->cap_pipe_err = PIPERR;
1253 sa.sun_family = AF_UNIX;
1255 * The Single UNIX Specification says:
1257 * The size of sun_path has intentionally been left undefined.
1258 * This is because different implementations use different sizes.
1259 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1260 * of 104. Since most implementations originate from BSD versions,
1261 * the size is typically in the range 92 to 108.
1263 * Applications should not assume a particular length for sun_path
1264 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1268 * The <sys/un.h> header shall define the sockaddr_un structure,
1269 * which shall include at least the following members:
1271 * sa_family_t sun_family Address family.
1272 * char sun_path[] Socket pathname.
1274 * so we assume that it's an array, with a specified size,
1275 * and that the size reflects the maximum path length.
1277 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1278 /* Path name too long */
1279 g_snprintf(errmsg, errmsgl,
1280 "The capture session coud not be initiated "
1281 "due to error on socket connect: Path name too long");
1282 ld->cap_pipe_err = PIPERR;
1285 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1287 g_snprintf(errmsg, errmsgl,
1288 "The capture session coud not be initiated "
1289 "due to error on socket connect: %s", strerror(errno));
1290 ld->cap_pipe_err = PIPERR;
1294 if (S_ISCHR(pipe_stat.st_mode)) {
1296 * Assume the user specified an interface on a system where
1297 * interfaces are in /dev. Pretend we haven't seen it.
1299 ld->cap_pipe_err = PIPNEXIST;
1302 g_snprintf(errmsg, errmsgl,
1303 "The capture session could not be initiated because\n"
1304 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
1305 ld->cap_pipe_err = PIPERR;
1310 #define PIPE_STR "\\pipe\\"
1311 /* Under Windows, named pipes _must_ have the form
1312 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1314 pncopy = g_strdup(pipename);
1315 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1316 pos = strchr(pncopy + 3, '\\');
1317 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1324 g_snprintf(errmsg, errmsgl,
1325 "The capture session could not be initiated because\n"
1326 "\"%s\" is neither an interface nor a pipe", pipename);
1327 ld->cap_pipe_err = PIPNEXIST;
1331 /* Wait for the pipe to appear */
1333 ld->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1334 OPEN_EXISTING, 0, NULL);
1336 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE)
1339 if (GetLastError() != ERROR_PIPE_BUSY) {
1340 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1341 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1342 g_snprintf(errmsg, errmsgl,
1343 "The capture session on \"%s\" could not be started "
1344 "due to error on pipe open: %s (error %d)",
1345 pipename, utf_16to8(err_str), GetLastError());
1347 ld->cap_pipe_err = PIPERR;
1351 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1352 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1353 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1354 g_snprintf(errmsg, errmsgl,
1355 "The capture session on \"%s\" timed out during "
1356 "pipe open: %s (error %d)",
1357 pipename, utf_16to8(err_str), GetLastError());
1359 ld->cap_pipe_err = PIPERR;
1366 ld->from_cap_pipe = TRUE;
1369 /* read the pcap header */
1371 while (bytes_read < sizeof magic) {
1372 sel_ret = cap_pipe_select(fd);
1374 g_snprintf(errmsg, errmsgl,
1375 "Unexpected error from select: %s", strerror(errno));
1377 } else if (sel_ret > 0) {
1378 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
1381 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1383 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1390 #else /* USE_THREADS */
1391 g_thread_create(&cap_pipe_read, ld, FALSE, NULL);
1393 ld->cap_pipe_buf = (char *) &magic;
1394 ld->cap_pipe_bytes_read = 0;
1395 ld->cap_pipe_bytes_to_read = sizeof(magic);
1396 /* We don't have to worry about cap_pipe_read_mtx here */
1397 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1398 g_async_queue_pop(cap_pipe_done_q);
1399 if (ld->cap_pipe_bytes_read <= 0) {
1400 if (ld->cap_pipe_bytes_read == 0)
1401 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1403 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1408 #endif /* USE_THREADS */
1412 /* Host that wrote it has our byte order, and was running
1413 a program using either standard or ss990417 libpcap. */
1414 ld->cap_pipe_byte_swapped = FALSE;
1415 ld->cap_pipe_modified = FALSE;
1417 case PCAP_MODIFIED_MAGIC:
1418 /* Host that wrote it has our byte order, but was running
1419 a program using either ss990915 or ss991029 libpcap. */
1420 ld->cap_pipe_byte_swapped = FALSE;
1421 ld->cap_pipe_modified = TRUE;
1423 case PCAP_SWAPPED_MAGIC:
1424 /* Host that wrote it has a byte order opposite to ours,
1425 and was running a program using either standard or
1426 ss990417 libpcap. */
1427 ld->cap_pipe_byte_swapped = TRUE;
1428 ld->cap_pipe_modified = FALSE;
1430 case PCAP_SWAPPED_MODIFIED_MAGIC:
1431 /* Host that wrote it out has a byte order opposite to
1432 ours, and was running a program using either ss990915
1433 or ss991029 libpcap. */
1434 ld->cap_pipe_byte_swapped = TRUE;
1435 ld->cap_pipe_modified = TRUE;
1438 /* Not a "libpcap" type we know about. */
1439 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
1444 /* Read the rest of the header */
1446 while (bytes_read < sizeof(struct pcap_hdr)) {
1447 sel_ret = cap_pipe_select(fd);
1449 g_snprintf(errmsg, errmsgl,
1450 "Unexpected error from select: %s", strerror(errno));
1452 } else if (sel_ret > 0) {
1453 b = read(fd, ((char *)hdr)+bytes_read,
1454 sizeof(struct pcap_hdr) - bytes_read);
1457 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1459 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
1466 #else /* USE_THREADS */
1467 ld->cap_pipe_buf = (char *) hdr;
1468 ld->cap_pipe_bytes_read = 0;
1469 ld->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1470 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1471 g_async_queue_pop(cap_pipe_done_q);
1472 if (ld->cap_pipe_bytes_read <= 0) {
1473 if (ld->cap_pipe_bytes_read == 0)
1474 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1476 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
1480 #endif /* USE_THREADS */
1482 if (ld->cap_pipe_byte_swapped) {
1483 /* Byte-swap the header fields about which we care. */
1484 hdr->version_major = BSWAP16(hdr->version_major);
1485 hdr->version_minor = BSWAP16(hdr->version_minor);
1486 hdr->snaplen = BSWAP32(hdr->snaplen);
1487 hdr->network = BSWAP32(hdr->network);
1489 ld->linktype = hdr->network;
1491 if (hdr->version_major < 2) {
1492 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1496 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1497 ld->cap_pipe_err = PIPOK;
1499 ld->cap_pipe_fd = fd;
1504 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1505 ld->cap_pipe_err = PIPERR;
1508 ld->cap_pipe_fd = -1;
1515 /* We read one record from the pipe, take care of byte order in the record
1516 * header, write the record to the capture file, and update capture statistics. */
1518 cap_pipe_dispatch(loop_data *ld, guchar *data, char *errmsg, int errmsgl)
1520 struct pcap_pkthdr phdr;
1521 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1533 #ifdef LOG_CAPTURE_VERBOSE
1534 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1537 switch (ld->cap_pipe_state) {
1539 case STATE_EXPECT_REC_HDR:
1541 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1544 ld->cap_pipe_state = STATE_READ_REC_HDR;
1545 ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
1546 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1547 ld->cap_pipe_bytes_read = 0;
1550 ld->cap_pipe_buf = (char *) &ld->cap_pipe_rechdr;
1551 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1552 g_mutex_unlock(cap_pipe_read_mtx);
1557 case STATE_READ_REC_HDR:
1559 b = read(ld->cap_pipe_fd, ((char *)&ld->cap_pipe_rechdr)+ld->cap_pipe_bytes_read,
1560 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1563 result = PD_PIPE_EOF;
1565 result = PD_PIPE_ERR;
1568 ld->cap_pipe_bytes_read += b;
1569 #else /* USE_THREADS */
1570 g_get_current_time(&wait_time);
1571 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1572 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1573 if (ld->cap_pipe_err == PIPEOF) {
1574 result = PD_PIPE_EOF;
1576 } else if (ld->cap_pipe_err == PIPERR) {
1577 result = PD_PIPE_ERR;
1583 #endif /* USE_THREADS */
1584 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1586 result = PD_REC_HDR_READ;
1589 case STATE_EXPECT_DATA:
1591 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1594 ld->cap_pipe_state = STATE_READ_DATA;
1595 ld->cap_pipe_bytes_to_read = ld->cap_pipe_rechdr.hdr.incl_len;
1596 ld->cap_pipe_bytes_read = 0;
1599 ld->cap_pipe_buf = (char *) data;
1600 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1601 g_mutex_unlock(cap_pipe_read_mtx);
1606 case STATE_READ_DATA:
1608 b = read(ld->cap_pipe_fd, data+ld->cap_pipe_bytes_read,
1609 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1612 result = PD_PIPE_EOF;
1614 result = PD_PIPE_ERR;
1617 ld->cap_pipe_bytes_read += b;
1618 #else /* USE_THREADS */
1619 g_get_current_time(&wait_time);
1620 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1621 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1622 if (ld->cap_pipe_err == PIPEOF) {
1623 result = PD_PIPE_EOF;
1625 } else if (ld->cap_pipe_err == PIPERR) {
1626 result = PD_PIPE_ERR;
1632 #endif /* USE_THREADS */
1633 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1635 result = PD_DATA_READ;
1639 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
1642 } /* switch (ld->cap_pipe_state) */
1645 * We've now read as much data as we were expecting, so process it.
1649 case PD_REC_HDR_READ:
1650 /* We've read the header. Take care of byte order. */
1651 cap_pipe_adjust_header(ld->cap_pipe_byte_swapped, &ld->cap_pipe_hdr,
1652 &ld->cap_pipe_rechdr.hdr);
1653 if (ld->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1654 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
1655 ld->packet_count+1, ld->cap_pipe_rechdr.hdr.incl_len);
1658 ld->cap_pipe_state = STATE_EXPECT_DATA;
1662 /* Fill in a "struct pcap_pkthdr", and process the packet. */
1663 phdr.ts.tv_sec = ld->cap_pipe_rechdr.hdr.ts_sec;
1664 phdr.ts.tv_usec = ld->cap_pipe_rechdr.hdr.ts_usec;
1665 phdr.caplen = ld->cap_pipe_rechdr.hdr.incl_len;
1666 phdr.len = ld->cap_pipe_rechdr.hdr.orig_len;
1668 capture_loop_packet_cb((u_char *)ld, &phdr, data);
1670 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1674 ld->cap_pipe_err = PIPEOF;
1679 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1680 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1681 g_snprintf(errmsg, errmsgl,
1682 "Error reading from pipe: %s (error %d)",
1683 utf_16to8(err_str), GetLastError());
1686 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
1694 ld->cap_pipe_err = PIPERR;
1695 /* Return here rather than inside the switch to prevent GCC warning */
1700 /** Open the capture input file (pcap or capture pipe).
1701 * Returns TRUE if it succeeds, FALSE otherwise. */
1703 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
1704 char *errmsg, size_t errmsg_len,
1705 char *secondary_errmsg, size_t secondary_errmsg_len)
1707 gchar open_err_str[PCAP_ERRBUF_SIZE];
1708 gchar *sync_msg_str;
1709 static const char ppamsg[] = "can't find PPA for ";
1710 const char *set_linktype_err_str;
1711 const char *libpcap_warn;
1713 gchar *sync_secondary_msg_str;
1715 WORD wVersionRequested;
1718 #ifdef HAVE_PCAP_REMOTE
1719 struct pcap_rmtauth auth;
1723 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
1726 /* XXX - opening Winsock on tshark? */
1728 /* Initialize Windows Socket if we are in a WIN32 OS
1729 This needs to be done before querying the interface for network/netmask */
1731 /* XXX - do we really require 1.1 or earlier?
1732 Are there any versions that support only 2.0 or higher? */
1733 wVersionRequested = MAKEWORD(1, 1);
1734 err = WSAStartup(wVersionRequested, &wsaData);
1738 case WSASYSNOTREADY:
1739 g_snprintf(errmsg, (gulong) errmsg_len,
1740 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
1743 case WSAVERNOTSUPPORTED:
1744 g_snprintf(errmsg, (gulong) errmsg_len,
1745 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
1746 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
1749 case WSAEINPROGRESS:
1750 g_snprintf(errmsg, (gulong) errmsg_len,
1751 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
1755 g_snprintf(errmsg, (gulong) errmsg_len,
1756 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
1760 g_snprintf(errmsg, (gulong) errmsg_len,
1761 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
1765 g_snprintf(errmsg, (gulong) errmsg_len,
1766 "Couldn't initialize Windows Sockets: error %d", err);
1769 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
1774 /* Open the network interface to capture from it.
1775 Some versions of libpcap may put warnings into the error buffer
1776 if they succeed; to tell if that's happened, we have to clear
1777 the error buffer, and check if it's still a null string. */
1778 open_err_str[0] = '\0';
1779 #ifdef HAVE_PCAP_OPEN
1781 * If we're opening a remote device, use pcap_open(); that's currently
1782 * the only open routine that supports remote devices.
1784 if (strncmp (capture_opts->iface, "rpcap://", 8) == 0) {
1785 auth.type = capture_opts->auth_type == CAPTURE_AUTH_PWD ?
1786 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
1787 auth.username = capture_opts->auth_username;
1788 auth.password = capture_opts->auth_password;
1790 ld->pcap_h = pcap_open(capture_opts->iface,
1791 capture_opts->has_snaplen ? capture_opts->snaplen :
1792 WTAP_MAX_PACKET_SIZE,
1794 (capture_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
1795 (capture_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
1796 (capture_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
1797 CAP_READ_TIMEOUT, &auth, open_err_str);
1799 #endif /* HAVE_PCAP_OPEN */
1802 * If we're not opening a remote device, use pcap_create() and
1803 * pcap_activate() if we have them, so that we can set the buffer
1804 * size, otherwise use pcap_open_live().
1806 #ifdef HAVE_PCAP_CREATE
1807 ld->pcap_h = pcap_create(capture_opts->iface, open_err_str);
1808 if (ld->pcap_h != NULL) {
1809 pcap_set_snaplen(ld->pcap_h, capture_opts->has_snaplen ? capture_opts->snaplen : WTAP_MAX_PACKET_SIZE);
1810 pcap_set_promisc(ld->pcap_h, capture_opts->promisc_mode);
1811 pcap_set_timeout(ld->pcap_h, CAP_READ_TIMEOUT);
1813 if (capture_opts->buffer_size > 1) {
1814 pcap_set_buffer_size(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024);
1816 if (capture_opts->monitor_mode)
1817 pcap_set_rfmon(ld->pcap_h, 1);
1818 if (pcap_activate(ld->pcap_h) != 0) {
1819 /* Failed to activate, set to NULL */
1820 pcap_close(ld->pcap_h);
1825 ld->pcap_h = pcap_open_live(capture_opts->iface,
1826 capture_opts->has_snaplen ? capture_opts->snaplen :
1827 WTAP_MAX_PACKET_SIZE,
1828 capture_opts->promisc_mode, CAP_READ_TIMEOUT,
1833 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
1834 /* to remove any suid privileges. */
1835 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
1836 /* (euid/egid have already previously been set to ruid/rgid. */
1837 /* (See comment in main() for details) */
1839 relinquish_special_privs_perm();
1841 relinquish_all_capabilities();
1844 if (ld->pcap_h != NULL) {
1845 /* we've opened "iface" as a network device */
1847 /* try to set the capture buffer size */
1848 if (capture_opts->buffer_size > 1 &&
1849 pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
1850 sync_secondary_msg_str = g_strdup_printf(
1851 "The capture buffer size of %dMB seems to be too high for your machine,\n"
1852 "the default of 1MB will be used.\n"
1854 "Nonetheless, the capture is started.\n",
1855 capture_opts->buffer_size);
1856 report_capture_error("Couldn't set the capture buffer size!",
1857 sync_secondary_msg_str);
1858 g_free(sync_secondary_msg_str);
1862 #if defined(HAVE_PCAP_REMOTE) && defined(HAVE_PCAP_SETSAMPLING)
1863 if ((capture_opts->sampling_method != CAPTURE_SAMP_NONE) &&
1864 (strncmp (capture_opts->iface, "rpcap://", 8) == 0))
1866 struct pcap_samp *samp;
1868 if ((samp = pcap_setsampling(ld->pcap_h)) != NULL)
1870 switch (capture_opts->sampling_method)
1872 case CAPTURE_SAMP_BY_COUNT:
1873 samp->method = PCAP_SAMP_1_EVERY_N;
1876 case CAPTURE_SAMP_BY_TIMER:
1877 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
1881 sync_msg_str = g_strdup_printf(
1882 "Unknown sampling method %d specified,\n"
1883 "continue without packet sampling",
1884 capture_opts->sampling_method);
1885 report_capture_error("Couldn't set the capture "
1886 "sampling", sync_msg_str);
1887 g_free(sync_msg_str);
1889 samp->value = capture_opts->sampling_param;
1893 report_capture_error("Couldn't set the capture sampling",
1894 "Cannot get packet sampling data structure");
1900 /* setting the data link type only works on real interfaces */
1901 if (capture_opts->linktype != -1) {
1902 set_linktype_err_str = set_pcap_linktype(ld->pcap_h, capture_opts->iface,
1903 capture_opts->linktype);
1904 if (set_linktype_err_str != NULL) {
1905 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
1906 set_linktype_err_str);
1907 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
1911 ld->linktype = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
1913 /* We couldn't open "iface" as a network device. */
1914 /* Try to open it as a pipe */
1915 cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, (int) errmsg_len);
1918 if (ld->cap_pipe_fd == -1) {
1920 if (ld->cap_pipe_h == INVALID_HANDLE_VALUE) {
1923 if (ld->cap_pipe_err == PIPNEXIST) {
1924 /* Pipe doesn't exist, so output message for interface */
1926 /* If we got a "can't find PPA for X" message, warn the user (who
1927 is running (T)Wireshark on HP-UX) that they don't have a version
1928 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1929 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1930 PPA for X" rather than "can't find PPA for X"). */
1931 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1934 "You are running (T)Wireshark with a version of the libpcap library\n"
1935 "that doesn't handle HP-UX network devices well; this means that\n"
1936 "(T)Wireshark may not be able to capture packets.\n"
1938 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1939 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1940 "packaged binary form from the Software Porting And Archive Centre\n"
1941 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1942 "at the URL lists a number of mirror sites.";
1945 g_snprintf(errmsg, (gulong) errmsg_len,
1946 "The capture session could not be initiated (%s).", open_err_str);
1948 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
1949 "Please check to make sure you have sufficient permissions, and that you have "
1950 "the proper interface or pipe specified.%s", libpcap_warn);
1952 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
1954 "Please check that \"%s\" is the proper interface.\n"
1957 "Help can be found at:\n"
1959 " http://wiki.wireshark.org/WinPcap\n"
1960 " http://wiki.wireshark.org/CaptureSetup\n",
1961 capture_opts->iface);
1965 * Else pipe (or file) does exist and cap_pipe_open_live() has
1970 /* cap_pipe_open_live() succeeded; don't want
1971 error message from pcap_open_live() */
1972 open_err_str[0] = '\0';
1975 /* XXX - will this work for tshark? */
1976 #ifdef MUST_DO_SELECT
1977 if (!ld->from_cap_pipe) {
1978 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
1979 ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
1981 ld->pcap_fd = pcap_fileno(ld->pcap_h);
1986 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1987 returned a warning; print it, but keep capturing. */
1988 if (open_err_str[0] != '\0') {
1989 sync_msg_str = g_strdup_printf("%s.", open_err_str);
1990 report_capture_error(sync_msg_str, "");
1991 g_free(sync_msg_str);
1998 /* close the capture input file (pcap or capture pipe) */
1999 static void capture_loop_close_input(loop_data *ld) {
2001 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2003 /* if open, close the capture pipe "input file" */
2005 if (ld->cap_pipe_fd >= 0) {
2006 g_assert(ld->from_cap_pipe);
2007 ws_close(ld->cap_pipe_fd);
2008 ld->cap_pipe_fd = 0;
2011 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE) {
2012 CloseHandle(ld->cap_pipe_h);
2013 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
2017 /* if open, close the pcap "input file" */
2018 if(ld->pcap_h != NULL) {
2019 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)ld->pcap_h);
2020 g_assert(!ld->from_cap_pipe);
2021 pcap_close(ld->pcap_h);
2028 /* Shut down windows sockets */
2034 /* init the capture filter */
2035 static initfilter_status_t
2036 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe, gchar * iface, gchar * cfilter) {
2037 bpf_u_int32 netnum, netmask;
2038 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
2039 struct bpf_program fcode;
2042 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2044 /* capture filters only work on real interfaces */
2045 if (cfilter && !from_cap_pipe) {
2046 /* A capture filter was specified; set it up. */
2047 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
2049 * Well, we can't get the netmask for this interface; it's used
2050 * only for filters that check for broadcast IP addresses, so
2051 * we just punt and use 0. It might be nice to warn the user,
2052 * but that's a pain in a GUI application, as it'd involve popping
2053 * up a message box, and it's not clear how often this would make
2054 * a difference (only filters that check for IP broadcast addresses
2058 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
2061 if (pcap_compile(pcap_h, &fcode, cfilter, 1, netmask) < 0) {
2062 /* Treat this specially - our caller might try to compile this
2063 as a display filter and, if that succeeds, warn the user that
2064 the display and capture filter syntaxes are different. */
2065 return INITFILTER_BAD_FILTER;
2067 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2068 #ifdef HAVE_PCAP_FREECODE
2069 pcap_freecode(&fcode);
2071 return INITFILTER_OTHER_ERROR;
2073 #ifdef HAVE_PCAP_FREECODE
2074 pcap_freecode(&fcode);
2078 return INITFILTER_NO_ERROR;
2082 /* set up to write to the already-opened capture output file/files */
2084 capture_loop_init_output(capture_options *capture_opts, int save_file_fd, loop_data *ld, char *errmsg, int errmsg_len) {
2088 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2091 if (ld->from_cap_pipe) {
2092 ld->file_snaplen = ld->cap_pipe_hdr.snaplen;
2095 ld->file_snaplen = pcap_snapshot(ld->pcap_h);
2098 /* Set up to write to the capture file. */
2099 if (capture_opts->multi_files_on) {
2100 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2102 ld->pdh = libpcap_fdopen(save_file_fd, &err);
2105 gboolean successful;
2107 ld->bytes_written = 0;
2108 if (capture_opts->use_pcapng) {
2111 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2112 successful = libpcap_write_session_header_block(ld->pdh, appname, &ld->bytes_written, &err) &&
2113 libpcap_write_interface_description_block(ld->pdh, capture_opts->iface, capture_opts->cfilter, ld->linktype, ld->file_snaplen, &ld->bytes_written, &err);
2115 successful = libpcap_write_file_header(ld->pdh, ld->linktype, ld->file_snaplen,
2116 &ld->bytes_written, &err);
2124 if (ld->pdh == NULL) {
2125 /* We couldn't set up to write to the capture file. */
2126 /* XXX - use cf_open_error_message from tshark instead? */
2129 case WTAP_ERR_CANT_OPEN:
2130 g_snprintf(errmsg, errmsg_len, "The file to which the capture would be saved"
2131 " couldn't be created for some unknown reason.");
2134 case WTAP_ERR_SHORT_WRITE:
2135 g_snprintf(errmsg, errmsg_len, "A full header couldn't be written to the file"
2136 " to which the capture would be saved.");
2141 g_snprintf(errmsg, errmsg_len,
2142 "The file to which the capture would be"
2143 " saved (\"%s\") could not be opened: Error %d.",
2144 capture_opts->save_file, err);
2146 g_snprintf(errmsg, errmsg_len,
2147 "The file to which the capture would be"
2148 " saved (\"%s\") could not be opened: %s.",
2149 capture_opts->save_file, strerror(err));
2161 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
2163 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2165 if (capture_opts->multi_files_on) {
2166 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2168 if (capture_opts->use_pcapng) {
2169 libpcap_write_interface_statistics_block(ld->pdh, 0, ld->pcap_h, &ld->bytes_written, err_close);
2171 return libpcap_dump_close(ld->pdh, err_close);
2175 /* dispatch incoming packets (pcap or capture pipe)
2177 * Waits for incoming packets to be available, and calls pcap_dispatch()
2178 * to cause them to be processed.
2180 * Returns the number of packets which were processed.
2182 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2183 * packet-batching behaviour does not cause packets to get held back
2187 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
2188 char *errmsg, int errmsg_len)
2191 gint packet_count_before;
2192 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
2197 packet_count_before = ld->packet_count;
2198 if (ld->from_cap_pipe) {
2199 /* dispatch from capture pipe */
2200 #ifdef LOG_CAPTURE_VERBOSE
2201 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2204 sel_ret = cap_pipe_select(ld->cap_pipe_fd);
2207 if (sel_ret < 0 && errno != EINTR) {
2208 g_snprintf(errmsg, errmsg_len,
2209 "Unexpected error from select: %s", strerror(errno));
2210 report_capture_error(errmsg, please_report);
2215 * "select()" says we can read from the pipe without blocking
2217 #endif /* USE_THREADS */
2218 inpkts = cap_pipe_dispatch(ld, pcap_data, errmsg, errmsg_len);
2228 /* dispatch from pcap */
2229 #ifdef MUST_DO_SELECT
2231 * If we have "pcap_get_selectable_fd()", we use it to get the
2232 * descriptor on which to select; if that's -1, it means there
2233 * is no descriptor on which you can do a "select()" (perhaps
2234 * because you're capturing on a special device, and that device's
2235 * driver unfortunately doesn't support "select()", in which case
2236 * we don't do the select - which means it might not be possible
2237 * to stop a capture until a packet arrives. If that's unacceptable,
2238 * plead with whoever supplies the software for that device to add
2239 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2240 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2241 * later, so it can use pcap_breakloop().
2243 #ifdef LOG_CAPTURE_VERBOSE
2244 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2246 if (ld->pcap_fd != -1) {
2247 sel_ret = cap_pipe_select(ld->pcap_fd);
2250 * "select()" says we can read from it without blocking; go for
2253 * We don't have pcap_breakloop(), so we only process one packet
2254 * per pcap_dispatch() call, to allow a signal to stop the
2255 * processing immediately, rather than processing all packets
2256 * in a batch before quitting.
2258 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb,
2262 /* Error, rather than pcap_breakloop(). */
2263 ld->pcap_err = TRUE;
2265 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2268 if (sel_ret < 0 && errno != EINTR) {
2269 g_snprintf(errmsg, errmsg_len,
2270 "Unexpected error from select: %s", strerror(errno));
2271 report_capture_error(errmsg, please_report);
2277 #endif /* MUST_DO_SELECT */
2279 /* dispatch from pcap without select */
2281 #ifdef LOG_CAPTURE_VERBOSE
2282 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2286 * On Windows, we don't support asynchronously telling a process to
2287 * stop capturing; instead, we check for an indication on a pipe
2288 * after processing packets. We therefore process only one packet
2289 * at a time, so that we can check the pipe after every packet.
2291 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb, (u_char *) ld);
2293 inpkts = pcap_dispatch(ld->pcap_h, -1, capture_loop_packet_cb, (u_char *) ld);
2297 /* Error, rather than pcap_breakloop(). */
2298 ld->pcap_err = TRUE;
2300 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2302 #else /* pcap_next_ex */
2303 #ifdef LOG_CAPTURE_VERBOSE
2304 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2306 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2309 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2310 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
2311 * This should be fixed in the WinPcap 4.0 alpha release.
2313 * For reference, an example remote interface:
2314 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2317 /* emulate dispatch from pcap */
2320 struct pcap_pkthdr *pkt_header;
2325 (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1)
2326 capture_loop_packet_cb( (u_char *) ld, pkt_header, pkt_data);
2329 ld->pcap_err = TRUE;
2333 #endif /* pcap_next_ex */
2337 #ifdef LOG_CAPTURE_VERBOSE
2338 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2341 return ld->packet_count - packet_count_before;
2345 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2346 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2348 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2349 char *errmsg, int errmsg_len) {
2352 gchar *capfile_name;
2353 gboolean is_tempfile;
2358 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2359 (capture_opts->save_file) ? capture_opts->save_file : "");
2361 if (capture_opts->save_file != NULL) {
2362 /* We return to the caller while the capture is in progress.
2363 * Therefore we need to take a copy of save_file in
2364 * case the caller destroys it after we return.
2366 capfile_name = g_strdup(capture_opts->save_file);
2368 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2369 if (capture_opts->multi_files_on) {
2370 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2371 g_snprintf(errmsg, errmsg_len,
2372 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2373 g_free(capfile_name);
2376 if (strcmp(capfile_name, "-") == 0) {
2377 /* write to stdout */
2380 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
2381 _setmode(1, O_BINARY);
2384 } /* if (...output_to_pipe ... */
2387 if (capture_opts->multi_files_on) {
2388 /* ringbuffer is enabled */
2389 *save_file_fd = ringbuf_init(capfile_name,
2390 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
2392 /* we need the ringbuf name */
2393 if(*save_file_fd != -1) {
2394 g_free(capfile_name);
2395 capfile_name = g_strdup(ringbuf_current_filename());
2398 /* Try to open/create the specified file for use as a capture buffer. */
2399 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
2403 is_tempfile = FALSE;
2405 /* Choose a random name for the temporary capture buffer */
2406 *save_file_fd = create_tempfile(&tmpname, "wireshark");
2407 capfile_name = g_strdup(tmpname);
2411 /* did we fail to open the output file? */
2412 if (*save_file_fd == -1) {
2414 g_snprintf(errmsg, errmsg_len,
2415 "The temporary file to which the capture would be saved (\"%s\") "
2416 "could not be opened: %s.", capfile_name, strerror(errno));
2418 if (capture_opts->multi_files_on) {
2419 ringbuf_error_cleanup();
2422 g_snprintf(errmsg, errmsg_len,
2423 "The file to which the capture would be saved (\"%s\") "
2424 "could not be opened: %s.", capfile_name,
2427 g_free(capfile_name);
2431 if(capture_opts->save_file != NULL) {
2432 g_free(capture_opts->save_file);
2434 capture_opts->save_file = capfile_name;
2435 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2436 "g_free(capfile_name)". */
2438 ret = fchown(*save_file_fd, capture_opts->owner, capture_opts->group);
2446 #define TIME_GET() GetTickCount()
2448 #define TIME_GET() time(NULL)
2451 /* Do the low-level work of a capture.
2452 Returns TRUE if it succeeds, FALSE otherwise. */
2454 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
2456 time_t upd_time, cur_time;
2460 gint inpkts_to_sync_pipe = 0; /* packets not already send out to the sync_pipe */
2461 condition *cnd_file_duration = NULL;
2462 condition *cnd_autostop_files = NULL;
2463 condition *cnd_autostop_size = NULL;
2464 condition *cnd_autostop_duration = NULL;
2465 guint32 autostop_files = 0;
2468 gboolean cfilter_error = FALSE;
2469 #define MSG_MAX_LENGTH 4096
2470 char errmsg[MSG_MAX_LENGTH+1];
2471 char secondary_errmsg[MSG_MAX_LENGTH+1];
2472 int save_file_fd = -1;
2475 *secondary_errmsg = '\0';
2477 /* init the loop data */
2478 global_ld.go = TRUE;
2479 global_ld.packet_count = 0;
2480 if (capture_opts->has_autostop_packets)
2481 global_ld.packet_max = capture_opts->autostop_packets;
2483 global_ld.packet_max = 0; /* no limit */
2484 global_ld.err = 0; /* no error seen yet */
2485 global_ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
2486 global_ld.pcap_err = FALSE;
2487 global_ld.from_cap_pipe = FALSE;
2488 global_ld.pdh = NULL;
2490 global_ld.cap_pipe_fd = -1;
2492 global_ld.cap_pipe_h = INVALID_HANDLE_VALUE;
2494 #ifdef MUST_DO_SELECT
2495 global_ld.pcap_fd = 0;
2498 /* We haven't yet gotten the capture statistics. */
2499 *stats_known = FALSE;
2501 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
2502 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
2504 /* open the "input file" from network interface or capture pipe */
2505 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
2506 secondary_errmsg, sizeof(secondary_errmsg))) {
2510 /* init the input filter from the network interface (capture pipe will do nothing) */
2511 switch (capture_loop_init_filter(global_ld.pcap_h, global_ld.from_cap_pipe,
2512 capture_opts->iface,
2513 capture_opts->cfilter)) {
2515 case INITFILTER_NO_ERROR:
2518 case INITFILTER_BAD_FILTER:
2519 cfilter_error = TRUE;
2520 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(global_ld.pcap_h));
2523 case INITFILTER_OTHER_ERROR:
2524 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
2525 pcap_geterr(global_ld.pcap_h));
2526 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
2530 /* If we're supposed to write to a capture file, open it for output
2531 (temporary/specified name/ringbuffer) */
2532 if (capture_opts->saving_to_file) {
2533 if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
2537 /* set up to write to the already-opened capture output file/files */
2538 if (!capture_loop_init_output(capture_opts, save_file_fd, &global_ld,
2539 errmsg, sizeof(errmsg))) {
2543 /* XXX - capture SIGTERM and close the capture, in case we're on a
2544 Linux 2.0[.x] system and you have to explicitly close the capture
2545 stream in order to turn promiscuous mode off? We need to do that
2546 in other places as well - and I don't think that works all the
2547 time in any case, due to libpcap bugs. */
2549 /* Well, we should be able to start capturing.
2551 Sync out the capture file, so the header makes it to the file system,
2552 and send a "capture started successfully and capture file created"
2553 message to our parent so that they'll open the capture file and
2554 update its windows to indicate that we have a live capture in
2556 libpcap_dump_flush(global_ld.pdh, NULL);
2557 report_new_capture_file(capture_opts->save_file);
2560 /* initialize capture stop (and alike) conditions */
2561 init_capture_stop_conditions();
2562 /* create stop conditions */
2563 if (capture_opts->has_autostop_filesize)
2565 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
2566 if (capture_opts->has_autostop_duration)
2567 cnd_autostop_duration =
2568 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
2570 if (capture_opts->multi_files_on) {
2571 if (capture_opts->has_file_duration)
2573 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
2575 if (capture_opts->has_autostop_files)
2576 cnd_autostop_files =
2577 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
2580 /* init the time values */
2581 start_time = TIME_GET();
2582 upd_time = TIME_GET();
2584 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
2586 /* WOW, everything is prepared! */
2587 /* please fasten your seat belts, we will enter now the actual capture loop */
2588 while (global_ld.go) {
2589 /* dispatch incoming packets */
2590 inpkts = capture_loop_dispatch(capture_opts, &global_ld, errmsg,
2594 /* any news from our parent (signal pipe)? -> just stop the capture */
2595 if (!signal_pipe_check_running()) {
2596 global_ld.go = FALSE;
2601 inpkts_to_sync_pipe += inpkts;
2603 /* check capture size condition */
2604 if (cnd_autostop_size != NULL &&
2605 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)){
2606 /* Capture size limit reached, do we have another file? */
2607 if (capture_opts->multi_files_on) {
2608 if (cnd_autostop_files != NULL &&
2609 cnd_eval(cnd_autostop_files, ++autostop_files)) {
2610 /* no files left: stop here */
2611 global_ld.go = FALSE;
2615 /* Switch to the next ringbuffer file */
2616 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2617 &save_file_fd, &global_ld.err)) {
2618 gboolean successful;
2620 /* File switch succeeded: reset the conditions */
2621 global_ld.bytes_written = 0;
2622 if (capture_opts->use_pcapng) {
2625 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2626 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2627 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);
2629 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2630 &global_ld.bytes_written, &global_ld.err);
2633 fclose(global_ld.pdh);
2634 global_ld.pdh = NULL;
2635 global_ld.go = FALSE;
2638 cnd_reset(cnd_autostop_size);
2639 if (cnd_file_duration) {
2640 cnd_reset(cnd_file_duration);
2642 libpcap_dump_flush(global_ld.pdh, NULL);
2643 report_packet_count(inpkts_to_sync_pipe);
2644 inpkts_to_sync_pipe = 0;
2645 report_new_capture_file(capture_opts->save_file);
2647 /* File switch failed: stop here */
2648 global_ld.go = FALSE;
2652 /* single file, stop now */
2653 global_ld.go = FALSE;
2656 } /* cnd_autostop_size */
2657 if (capture_opts->output_to_pipe) {
2658 libpcap_dump_flush(global_ld.pdh, NULL);
2662 /* Only update once a second (Win32: 500ms) so as not to overload slow
2663 * displays. This also prevents too much context-switching between the
2664 * dumpcap and wireshark processes */
2665 cur_time = TIME_GET();
2667 if ( (cur_time - upd_time) > 500) {
2669 if (cur_time - upd_time > 0) {
2671 upd_time = cur_time;
2673 /*if (pcap_stats(pch, stats) >= 0) {
2674 *stats_known = TRUE;
2677 /* Let the parent process know. */
2678 if (inpkts_to_sync_pipe) {
2680 libpcap_dump_flush(global_ld.pdh, NULL);
2682 /* Send our parent a message saying we've written out "inpkts_to_sync_pipe"
2683 packets to the capture file. */
2684 report_packet_count(inpkts_to_sync_pipe);
2686 inpkts_to_sync_pipe = 0;
2689 /* check capture duration condition */
2690 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
2691 /* The maximum capture time has elapsed; stop the capture. */
2692 global_ld.go = FALSE;
2696 /* check capture file duration condition */
2697 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
2698 /* duration limit reached, do we have another file? */
2699 if (capture_opts->multi_files_on) {
2700 if (cnd_autostop_files != NULL &&
2701 cnd_eval(cnd_autostop_files, ++autostop_files)) {
2702 /* no files left: stop here */
2703 global_ld.go = FALSE;
2707 /* Switch to the next ringbuffer file */
2708 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2709 &save_file_fd, &global_ld.err)) {
2710 gboolean successful;
2712 /* file switch succeeded: reset the conditions */
2713 global_ld.bytes_written = 0;
2714 if (capture_opts->use_pcapng) {
2717 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2718 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2719 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);
2721 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2722 &global_ld.bytes_written, &global_ld.err);
2725 fclose(global_ld.pdh);
2726 global_ld.pdh = NULL;
2727 global_ld.go = FALSE;
2730 cnd_reset(cnd_file_duration);
2731 if(cnd_autostop_size)
2732 cnd_reset(cnd_autostop_size);
2733 libpcap_dump_flush(global_ld.pdh, NULL);
2734 report_packet_count(inpkts_to_sync_pipe);
2735 inpkts_to_sync_pipe = 0;
2736 report_new_capture_file(capture_opts->save_file);
2738 /* File switch failed: stop here */
2739 global_ld.go = FALSE;
2743 /* single file, stop now */
2744 global_ld.go = FALSE;
2747 } /* cnd_file_duration */
2750 } /* while (global_ld.go) */
2752 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
2754 /* delete stop conditions */
2755 if (cnd_file_duration != NULL)
2756 cnd_delete(cnd_file_duration);
2757 if (cnd_autostop_files != NULL)
2758 cnd_delete(cnd_autostop_files);
2759 if (cnd_autostop_size != NULL)
2760 cnd_delete(cnd_autostop_size);
2761 if (cnd_autostop_duration != NULL)
2762 cnd_delete(cnd_autostop_duration);
2764 /* did we had a pcap (input) error? */
2765 if (global_ld.pcap_err) {
2766 /* On Linux, if an interface goes down while you're capturing on it,
2767 you'll get a "recvfrom: Network is down" error (ENETDOWN).
2768 (At least you will if strerror() doesn't show a local translation
2771 On FreeBSD and OS X, if a network adapter disappears while
2772 you're capturing on it, you'll get a "read: Device not configured"
2773 error (ENXIO). (See previous parenthetical note.)
2775 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
2777 These should *not* be reported to the Wireshark developers. */
2780 cap_err_str = pcap_geterr(global_ld.pcap_h);
2781 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
2782 strcmp(cap_err_str, "read: Device not configured") == 0 ||
2783 strcmp(cap_err_str, "read: I/O error") == 0) {
2784 report_capture_error("The network adapter on which the capture was being done "
2785 "is no longer running; the capture has stopped.",
2788 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
2790 report_capture_error(errmsg, please_report);
2793 else if (global_ld.from_cap_pipe && global_ld.cap_pipe_err == PIPERR)
2794 report_capture_error(errmsg, "");
2796 /* did we had an error while capturing? */
2797 if (global_ld.err == 0) {
2800 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
2801 global_ld.err, FALSE);
2802 report_capture_error(errmsg, please_report);
2806 if (capture_opts->saving_to_file) {
2807 /* close the wiretap (output) file */
2808 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
2812 /* there might be packets not yet notified to the parent */
2813 /* (do this after closing the file, so all packets are already flushed) */
2814 if(inpkts_to_sync_pipe) {
2815 report_packet_count(inpkts_to_sync_pipe);
2816 inpkts_to_sync_pipe = 0;
2819 /* If we've displayed a message about a write error, there's no point
2820 in displaying another message about an error on close. */
2821 if (!close_ok && write_ok) {
2822 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
2824 report_capture_error(errmsg, "");
2828 * XXX We exhibit different behaviour between normal mode and sync mode
2829 * when the pipe is stdin and not already at EOF. If we're a child, the
2830 * parent's stdin isn't closed, so if the user starts another capture,
2831 * cap_pipe_open_live() will very likely not see the expected magic bytes and
2832 * will say "Unrecognized libpcap format". On the other hand, in normal
2833 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
2836 /* get packet drop statistics from pcap */
2837 if(global_ld.pcap_h != NULL) {
2838 g_assert(!global_ld.from_cap_pipe);
2839 /* Get the capture statistics, so we know how many packets were
2841 if (pcap_stats(global_ld.pcap_h, stats) >= 0) {
2842 *stats_known = TRUE;
2843 /* Let the parent process know. */
2844 report_packet_drops(stats->ps_drop);
2846 g_snprintf(errmsg, sizeof(errmsg),
2847 "Can't get packet-drop statistics: %s",
2848 pcap_geterr(global_ld.pcap_h));
2849 report_capture_error(errmsg, please_report);
2853 /* close the input file (pcap or capture pipe) */
2854 capture_loop_close_input(&global_ld);
2856 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
2858 /* ok, if the write and the close were successful. */
2859 return write_ok && close_ok;
2862 if (capture_opts->multi_files_on) {
2863 /* cleanup ringbuffer */
2864 ringbuf_error_cleanup();
2866 /* We can't use the save file, and we have no FILE * for the stream
2867 to close in order to close it, so close the FD directly. */
2868 if(save_file_fd != -1) {
2869 ws_close(save_file_fd);
2872 /* We couldn't even start the capture, so get rid of the capture
2874 if(capture_opts->save_file != NULL) {
2875 ws_unlink(capture_opts->save_file);
2876 g_free(capture_opts->save_file);
2879 capture_opts->save_file = NULL;
2881 report_cfilter_error(capture_opts->cfilter, errmsg);
2883 report_capture_error(errmsg, secondary_errmsg);
2885 /* close the input file (pcap or cap_pipe) */
2886 capture_loop_close_input(&global_ld);
2888 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
2894 static void capture_loop_stop(void)
2896 #ifdef HAVE_PCAP_BREAKLOOP
2897 if(global_ld.pcap_h != NULL)
2898 pcap_breakloop(global_ld.pcap_h);
2900 global_ld.go = FALSE;
2905 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
2906 int err, gboolean is_close)
2911 g_snprintf(errmsg, errmsglen,
2912 "Not all the packets could be written to the file"
2913 " to which the capture was being saved\n"
2914 "(\"%s\") because there is no space left on the file system\n"
2915 "on which that file resides.",
2921 g_snprintf(errmsg, errmsglen,
2922 "Not all the packets could be written to the file"
2923 " to which the capture was being saved\n"
2924 "(\"%s\") because you are too close to, or over,"
2925 " your disk quota\n"
2926 "on the file system on which that file resides.",
2931 case WTAP_ERR_CANT_CLOSE:
2932 g_snprintf(errmsg, errmsglen,
2933 "The file to which the capture was being saved"
2934 " couldn't be closed for some unknown reason.");
2937 case WTAP_ERR_SHORT_WRITE:
2938 g_snprintf(errmsg, errmsglen,
2939 "Not all the packets could be written to the file"
2940 " to which the capture was being saved\n"
2947 g_snprintf(errmsg, errmsglen,
2948 "The file to which the capture was being saved\n"
2949 "(\"%s\") could not be closed: %s.",
2950 fname, wtap_strerror(err));
2952 g_snprintf(errmsg, errmsglen,
2953 "An error occurred while writing to the file"
2954 " to which the capture was being saved\n"
2956 fname, wtap_strerror(err));
2963 /* one packet was captured, process it */
2965 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
2968 loop_data *ld = (loop_data *) (void *) user;
2971 /* We may be called multiple times from pcap_dispatch(); if we've set
2972 the "stop capturing" flag, ignore this packet, as we're not
2973 supposed to be saving any more packets. */
2978 gboolean successful;
2979 /* We're supposed to write the packet to a file; do so.
2980 If this fails, set "ld->go" to FALSE, to stop the capture, and set
2981 "ld->err" to the error. */
2982 if (global_capture_opts.use_pcapng) {
2983 successful = libpcap_write_enhanced_packet_block(ld->pdh, phdr, 0, pd, &ld->bytes_written, &err);
2985 successful = libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err);
2992 /* if the user told us to stop after x packets, do we already have enough? */
2993 if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
3002 /* And now our feature presentation... [ fade to music ] */
3004 main(int argc, char *argv[])
3007 gboolean arg_error = FALSE;
3012 struct sigaction action, oldaction;
3015 gboolean start_capture = TRUE;
3016 gboolean stats_known;
3017 struct pcap_stat stats;
3018 GLogLevelFlags log_flags;
3019 gboolean list_interfaces = FALSE;
3020 gboolean list_link_layer_types = FALSE;
3021 gboolean machine_readable = FALSE;
3022 gboolean print_statistics = FALSE;
3023 int status, run_once_args = 0;
3025 #if defined(__APPLE__) && defined(__LP64__)
3026 struct utsname osinfo;
3029 #ifdef HAVE_PCAP_REMOTE
3030 #define OPTSTRING_A "A:"
3031 #define OPTSTRING_r "r"
3032 #define OPTSTRING_u "u"
3034 #define OPTSTRING_A ""
3035 #define OPTSTRING_r ""
3036 #define OPTSTRING_u ""
3039 #ifdef HAVE_PCAP_SETSAMPLING
3040 #define OPTSTRING_m "m:"
3042 #define OPTSTRING_m ""
3045 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
3046 #define OPTSTRING_B "B:"
3048 #define OPTSTRING_B ""
3049 #endif /* _WIN32 or HAVE_PCAP_CREATE */
3051 #ifdef HAVE_PCAP_CREATE
3052 #define OPTSTRING_I "I"
3054 #define OPTSTRING_I ""
3057 #define OPTSTRING "a:" OPTSTRING_A "b:" OPTSTRING_B "c:Df:hi:" OPTSTRING_I "L" OPTSTRING_m "Mnp" OPTSTRING_r "Ss:" OPTSTRING_u "vw:y:Z:"
3059 #ifdef DEBUG_CHILD_DUMPCAP
3060 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
3061 fprintf (stderr, "Unable to open debug log file !\n");
3066 #if defined(__APPLE__) && defined(__LP64__)
3068 * Is this Mac OS X 10.6.x, other than 10.6.2? If so, we need a bug
3069 * workaround - timeouts less than 1 second don't work with libpcap
3070 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
3071 * and re-introduced in 10.6.3. We don't know whether it'll be fixed
3072 * again in a later 10.6.x release; we'll assume that it'll be fixed
3073 * in any future major releases.)
3075 if (uname(&osinfo) == 0) {
3077 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
3078 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
3079 * number of 10.0.0, not 10.1.0 - go figure).
3081 if (strncmp(osinfo.release, "10.", 3) == 0) {
3083 * OK, it's Snow Leopard - which version?
3085 if (strcmp(osinfo.release, "10.2.0") != 0) {
3087 need_timeout_workaround = TRUE;
3093 /* Determine if dumpcap is being requested to run in a special */
3094 /* capture_child mode by going thru the command line args to see if */
3095 /* a -Z is present. (-Z is a hidden option). */
3096 /* The primary result of running in capture_child mode is that */
3097 /* all messages sent out on stderr are in a special type/len/string */
3098 /* format to allow message processing by type. */
3099 /* These messages include various 'status' messages which are sent */
3100 /* when an actual capture is in progress. Capture_child mode */
3101 /* would normally be requested by a parent process which invokes */
3102 /* dumpcap and obtains dumpcap stderr output via a pipe to which */
3103 /* dumpcap stderr has been redirected. */
3104 /* Capture_child mode needs to be determined immediately upon */
3105 /* startup so that any messages generated by dumpcap in this mode */
3106 /* (eg: during initialization) will be formatted properly. */
3108 for (i=1; i<argc; i++) {
3109 if (strcmp("-Z", argv[i]) == 0) {
3110 capture_child = TRUE;
3112 /* set output pipe to binary mode, to avoid ugly text conversions */
3113 _setmode(2, O_BINARY);
3118 /* The default_log_handler will use stdout, which makes trouble in */
3119 /* capture child mode, as it uses stdout for it's sync_pipe. */
3120 /* So: the filtering is done in the console_log_handler and not here.*/
3121 /* We set the log handlers right up front to make sure that any log */
3122 /* messages when running as child will be sent back to the parent */
3123 /* with the correct format. */
3127 G_LOG_LEVEL_CRITICAL|
3128 G_LOG_LEVEL_WARNING|
3129 G_LOG_LEVEL_MESSAGE|
3132 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
3134 g_log_set_handler(NULL,
3136 console_log_handler, NULL /* user_data */);
3137 g_log_set_handler(LOG_DOMAIN_MAIN,
3139 console_log_handler, NULL /* user_data */);
3140 g_log_set_handler(LOG_DOMAIN_CAPTURE,
3142 console_log_handler, NULL /* user_data */);
3143 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
3145 console_log_handler, NULL /* user_data */);
3148 /* Load wpcap if possible. Do this before collecting the run-time version information */
3151 /* ... and also load the packet.dll from wpcap */
3152 /* XXX - currently not required, may change later. */
3153 /*wpcap_packet_load();*/
3155 /* Start windows sockets */
3156 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
3158 /* Set handler for Ctrl+C key */
3159 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
3161 /* Prepare to read from a pipe */
3162 if (!g_thread_supported ())
3163 g_thread_init (NULL);
3164 cap_pipe_pending_q = g_async_queue_new();
3165 cap_pipe_done_q = g_async_queue_new();
3166 cap_pipe_read_mtx = g_mutex_new();
3169 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
3171 action.sa_handler = capture_cleanup_handler;
3173 * Arrange that system calls not get restarted, because when
3174 * our signal handler returns we don't want to restart
3175 * a call that was waiting for packets to arrive.
3177 action.sa_flags = 0;
3178 sigemptyset(&action.sa_mask);
3179 sigaction(SIGTERM, &action, NULL);
3180 sigaction(SIGINT, &action, NULL);
3181 sigaction(SIGPIPE, &action, NULL);
3182 sigaction(SIGHUP, NULL, &oldaction);
3183 if (oldaction.sa_handler == SIG_DFL)
3184 sigaction(SIGHUP, &action, NULL);
3187 /* ----------------------------------------------------------------- */
3188 /* Privilege and capability handling */
3190 /* 1. Running not as root or suid root; no special capabilities. */
3193 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
3196 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
3198 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
3199 /* capabilities; Drop all other capabilities; */
3200 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3201 /* else: after pcap_open_live() in capture_loop_open_input() */
3202 /* drop all capabilities (NET_RAW and NET_ADMIN); */
3203 /* (Note: this means that the process, although logged in */
3204 /* as root, does not have various permissions such as the */
3205 /* ability to bypass file access permissions). */
3206 /* XXX: Should we just leave capabilities alone in this case */
3207 /* so that user gets expected effect that root can do */
3210 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
3212 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3213 /* else: after pcap_open_live() in capture_loop_open_input() */
3214 /* drop suid root (set euid=ruid).(ie: keep suid until after */
3215 /* pcap_open_live). */
3217 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
3219 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
3220 /* capabilities; Drop all other capabilities; */
3221 /* Drop suid privileges (euid=ruid); */
3222 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3223 /* else: after pcap_open_live() in capture_loop_open_input() */
3224 /* drop all capabilities (NET_RAW and NET_ADMIN). */
3226 /* XXX: For some Linux versions/distros with capabilities */
3227 /* a 'normal' process with any capabilities cannot be */
3228 /* 'killed' (signaled) from another (same uid) non-privileged */
3230 /* For example: If (non-suid) Wireshark forks a */
3231 /* child suid dumpcap which acts as described here (case 5), */
3232 /* Wireshark will be unable to kill (signal) the child */
3233 /* dumpcap process until the capabilities have been dropped */
3234 /* (after pcap_open_live()). */
3235 /* This behaviour will apparently be changed in the kernel */
3236 /* to allow the kill (signal) in this case. */
3237 /* See the following for details: */
3238 /* http://www.mail-archive.com/ [wrapped] */
3239 /* linux-security-module@vger.kernel.org/msg02913.html */
3241 /* It is therefore conceivable that if dumpcap somehow hangs */
3242 /* in pcap_open_live or before that wireshark will not */
3243 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
3244 /* In this case, exiting wireshark will kill the child */
3245 /* dumpcap process. */
3247 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
3248 /* capabilities; Using libcap. Note: capset cmd (which see) */
3249 /* used to assign capabilities to file. */
3251 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3252 /* else: after pcap_open_live() in capture_loop_open_input() */
3253 /* drop all capabilities (NET_RAW and NET_ADMIN) */
3255 /* ToDo: -S (stats) should drop privileges/capabilities when no */
3256 /* longer required (similar to capture). */
3258 /* ----------------------------------------------------------------- */
3260 get_credential_info();
3263 /* If 'started with special privileges' (and using libcap) */
3264 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
3265 /* Set euid/egid = ruid/rgid to remove suid privileges */
3266 relinquish_privs_except_capture();
3269 /* Set the initial values in the capture options. This might be overwritten
3270 by the command line parameters. */
3271 capture_opts_init(&global_capture_opts, NULL);
3273 /* Default to capturing the entire packet. */
3274 global_capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
3276 /* We always save to a file - if no file was specified, we save to a
3278 global_capture_opts.saving_to_file = TRUE;
3279 global_capture_opts.has_ring_num_files = TRUE;
3281 /* Now get our args */
3282 while ((opt = getopt(argc, argv, OPTSTRING)) != -1) {
3284 case 'h': /* Print help and exit */
3288 case 'v': /* Show version and exit */
3290 GString *comp_info_str;
3291 GString *runtime_info_str;
3292 /* Assemble the compile-time version information string */
3293 comp_info_str = g_string_new("Compiled ");
3294 get_compiled_version_info(comp_info_str, NULL);
3296 /* Assemble the run-time version information string */
3297 runtime_info_str = g_string_new("Running ");
3298 get_runtime_version_info(runtime_info_str, NULL);
3299 show_version(comp_info_str, runtime_info_str);
3300 g_string_free(comp_info_str, TRUE);
3301 g_string_free(runtime_info_str, TRUE);
3305 /*** capture option specific ***/
3306 case 'a': /* autostop criteria */
3307 case 'b': /* Ringbuffer option */
3308 case 'c': /* Capture x packets */
3309 case 'f': /* capture filter */
3310 case 'i': /* Use interface x */
3311 case 'n': /* Use pcapng format */
3312 case 'p': /* Don't capture in promiscuous mode */
3313 case 's': /* Set the snapshot (capture) length */
3314 case 'w': /* Write to capture file x */
3315 case 'y': /* Set the pcap data link type */
3316 #ifdef HAVE_PCAP_REMOTE
3317 case 'u': /* Use UDP for data transfer */
3318 case 'r': /* Capture own RPCAP traffic too */
3319 case 'A': /* Authentication */
3321 #ifdef HAVE_PCAP_SETSAMPLING
3322 case 'm': /* Sampling */
3324 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
3325 case 'B': /* Buffer size */
3326 #endif /* _WIN32 or HAVE_PCAP_CREATE */
3327 #ifdef HAVE_PCAP_CREATE
3328 case 'I': /* Monitor mode */
3330 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
3335 /*** hidden option: Wireshark child mode (using binary output messages) ***/
3337 capture_child = TRUE;
3339 /* set output pipe to binary mode, to avoid ugly text conversions */
3340 _setmode(2, O_BINARY);
3342 * optarg = the control ID, aka the PPID, currently used for the
3345 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
3346 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
3347 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
3348 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
3350 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
3351 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3352 "Signal pipe: Unable to open %s. Dead parent?",
3360 /*** all non capture option specific ***/
3361 case 'D': /* Print a list of capture devices and exit */
3362 list_interfaces = TRUE;
3365 case 'L': /* Print list of link-layer types and exit */
3366 list_link_layer_types = TRUE;
3369 case 'S': /* Print interface statistics once a second */
3370 print_statistics = TRUE;
3373 case 'M': /* For -D and -L, print machine-readable output */
3374 machine_readable = TRUE;
3377 case '?': /* Bad flag - print usage message */
3378 cmdarg_err("Invalid Option: %s", argv[optind-1]);
3386 /* user specified file name as regular command-line argument */
3387 /* XXX - use it as the capture file name (or something else)? */
3394 * Extra command line arguments were specified; complain.
3395 * XXX - interpret as capture filter, as tcpdump and tshark do?
3397 cmdarg_err("Invalid argument: %s", argv[0]);
3406 if (run_once_args > 1) {
3407 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
3409 } else if (list_link_layer_types) {
3410 /* We're supposed to list the link-layer types for an interface;
3411 did the user also specify a capture file to be read? */
3412 /* No - did they specify a ring buffer option? */
3413 if (global_capture_opts.multi_files_on) {
3414 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
3418 /* No - was the ring buffer option specified and, if so, does it make
3420 if (global_capture_opts.multi_files_on) {
3421 /* Ring buffer works only under certain conditions:
3422 a) ring buffer does not work with temporary files;
3423 b) it makes no sense to enable the ring buffer if the maximum
3424 file size is set to "infinite". */
3425 if (global_capture_opts.save_file == NULL) {
3426 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
3427 global_capture_opts.multi_files_on = FALSE;
3429 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
3430 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
3431 /* XXX - this must be redesigned as the conditions changed */
3432 /* global_capture_opts.multi_files_on = FALSE;*/
3437 if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
3438 /* cmdarg_err() already called .... */
3442 /* Let the user know what interface was chosen. */
3443 /* get_interface_descriptive_name() is not available! */
3444 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", global_capture_opts.iface);
3446 if (list_interfaces) {
3447 /* Get the list of interfaces */
3452 if_list = capture_interface_list(&err, &err_str);
3453 if (if_list == NULL) {
3455 case CANT_GET_INTERFACE_LIST:
3456 cmdarg_err("%s", err_str);
3460 case NO_INTERFACES_FOUND:
3461 cmdarg_err("There are no interfaces on which a capture can be done");
3467 if (machine_readable) /* tab-separated values to stdout */
3468 print_machine_readable_interfaces(if_list);
3470 capture_opts_print_interfaces(if_list);
3471 free_interface_list(if_list);
3473 } else if (list_link_layer_types) {
3474 /* Get the list of link-layer types for the capture device. */
3478 caps = get_if_capabilities(global_capture_opts.iface,
3479 global_capture_opts.monitor_mode, &err_str);
3481 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s)."
3482 "Please check to make sure you have sufficient permissions, and that\n"
3483 "you have the proper interface or pipe specified.\n", global_capture_opts.iface, err_str);
3487 if (caps->data_link_types == NULL) {
3488 cmdarg_err("The capture device \"%s\" has no data link types.", global_capture_opts.iface);
3491 if (machine_readable) /* tab-separated values to stdout */
3492 print_machine_readable_if_capabilities(caps);
3494 capture_opts_print_if_capabilities(caps,
3495 global_capture_opts.monitor_mode);
3496 free_if_capabilities(caps);
3498 } else if (print_statistics) {
3499 status = print_statistics_loop(machine_readable);
3503 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
3504 capture_opts_trim_ring_num_files(&global_capture_opts);
3506 /* Now start the capture. */
3508 if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
3512 /* capture failed */
3519 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
3520 const char *message, gpointer user_data _U_)
3527 /* ignore log message, if log_level isn't interesting */
3528 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3529 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
3534 /* create a "timestamp" */
3536 today = localtime(&curr);
3538 switch(log_level & G_LOG_LEVEL_MASK) {
3539 case G_LOG_LEVEL_ERROR:
3542 case G_LOG_LEVEL_CRITICAL:
3545 case G_LOG_LEVEL_WARNING:
3548 case G_LOG_LEVEL_MESSAGE:
3551 case G_LOG_LEVEL_INFO:
3554 case G_LOG_LEVEL_DEBUG:
3558 fprintf(stderr, "unknown log_level %u\n", log_level);
3560 g_assert_not_reached();
3563 /* Generate the output message */
3564 if(log_level & G_LOG_LEVEL_MESSAGE) {
3565 /* normal user messages without additional infos */
3566 msg = g_strdup_printf("%s\n", message);
3568 /* info/debug messages with additional infos */
3569 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
3570 today->tm_hour, today->tm_min, today->tm_sec,
3571 log_domain != NULL ? log_domain : "",
3575 /* DEBUG & INFO msgs (if we're debugging today) */
3576 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3577 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3578 #ifdef DEBUG_DUMPCAP
3579 fprintf(stderr, "%s", msg);
3582 #ifdef DEBUG_CHILD_DUMPCAP
3583 fprintf(debug_log, "%s", msg);
3591 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
3592 /* to parent especially formatted if dumpcap running as child. */
3593 if (capture_child) {
3594 sync_pipe_errmsg_to_parent(2, msg, "");
3596 fprintf(stderr, "%s", msg);
3603 /****************************************************************************************************************/
3604 /* indication report routines */
3608 report_packet_count(int packet_count)
3610 char tmp[SP_DECISIZE+1+1];
3611 static int count = 0;
3614 g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
3615 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
3616 pipe_write_block(2, SP_PACKET_COUNT, tmp);
3618 count += packet_count;
3619 fprintf(stderr, "\rPackets: %u ", count);
3620 /* stderr could be line buffered */
3626 report_new_capture_file(const char *filename)
3629 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
3630 pipe_write_block(2, SP_FILE, filename);
3632 fprintf(stderr, "File: %s\n", filename);
3633 /* stderr could be line buffered */
3639 report_cfilter_error(const char *cfilter, const char *errmsg)
3641 if (capture_child) {
3642 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
3643 pipe_write_block(2, SP_BAD_FILTER, errmsg);
3646 "Invalid capture filter: \"%s\"!\n"
3648 "That string isn't a valid capture filter (%s).\n"
3649 "See the User's Guide for a description of the capture filter syntax.\n",
3655 report_capture_error(const char *error_msg, const char *secondary_error_msg)
3658 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3659 "Primary Error: %s", error_msg);
3660 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3661 "Secondary Error: %s", secondary_error_msg);
3662 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
3664 fprintf(stderr, "%s\n%s\n", error_msg, secondary_error_msg);
3669 report_packet_drops(guint32 drops)
3671 char tmp[SP_DECISIZE+1+1];
3673 g_snprintf(tmp, sizeof(tmp), "%u", drops);
3676 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
3677 pipe_write_block(2, SP_DROPS, tmp);
3679 fprintf(stderr, "Packets dropped: %s\n", tmp);
3680 /* stderr could be line buffered */
3686 /****************************************************************************************************************/
3687 /* signal_pipe handling */
3692 signal_pipe_check_running(void)
3694 /* any news from our parent? -> just stop the capture */
3698 /* if we are running standalone, no check required */
3699 if(!capture_child) {
3703 if(!sig_pipe_name || !sig_pipe_handle) {
3704 /* This shouldn't happen */
3705 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3706 "Signal pipe: No name or handle");
3711 * XXX - We should have the process ID of the parent (from the "-Z" flag)
3712 * at this point. Should we check to see if the parent is still alive,
3713 * e.g. by using OpenProcess?
3716 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
3718 if(!result || avail > 0) {
3719 /* peek failed or some bytes really available */
3720 /* (if not piping from stdin this would fail) */
3721 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3722 "Signal pipe: Stop capture: %s", sig_pipe_name);
3723 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3724 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
3725 sig_pipe_handle, result, avail);
3728 /* pipe ok and no bytes available */
3735 * Editor modelines - http://www.wireshark.org/tools/modelines.html
3740 * indent-tabs-mode: nil
3743 * vi: set shiftwidth=4 tabstop=8 expandtab
3744 * :indentSize=4:tabSize=8:noTabs=true: