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.
28 #include <stdlib.h> /* for exit() */
34 #ifdef HAVE_SYS_TYPES_H
35 # include <sys/types.h>
38 #ifdef HAVE_SYS_STAT_H
39 # include <sys/stat.h>
62 # include <sys/prctl.h>
63 # include <sys/capability.h>
67 #include "ringbuffer.h"
68 #include "clopts_common.h"
69 #include "cmdarg_err.h"
70 #include "version_info.h"
75 #include "capture-pcap-util.h"
78 #include "capture-wpcap.h"
82 #include <wsutil/unicode-utils.h>
85 #include <wsutil/privileges.h>
87 #include "sync_pipe.h"
89 #include "capture_opts.h"
90 #include "capture_sync.h"
92 #include "conditions.h"
93 #include "capture_stop_conditions.h"
97 #include "wsutil/file_util.h"
100 * Get information about libpcap format from "wiretap/libpcap.h".
101 * XXX - can we just use pcap_open_offline() to read the pipe?
103 #include "wiretap/libpcap.h"
105 /**#define DEBUG_DUMPCAP**/
106 /**#define DEBUG_CHILD_DUMPCAP**/
108 #ifdef DEBUG_CHILD_DUMPCAP
109 FILE *debug_log; /* for logging debug messages to */
110 /* a file if DEBUG_CHILD_DUMPCAP */
114 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
116 static gchar *sig_pipe_name = NULL;
117 static HANDLE sig_pipe_handle = NULL;
120 /** Stop a low-level capture (stops the capture child). */
121 static void capture_loop_stop(void);
123 #if !defined (__linux__)
124 #ifndef HAVE_PCAP_BREAKLOOP
126 * We don't have pcap_breakloop(), which is the only way to ensure that
127 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
128 * won't, if the call to read the next packet or batch of packets is
129 * is interrupted by a signal on UN*X, just go back and try again to
132 * On UN*X, we catch SIGUSR1 as a "stop capturing" signal, and, in
133 * the signal handler, set a flag to stop capturing; however, without
134 * a guarantee of that sort, we can't guarantee that we'll stop capturing
135 * if the read will be retried and won't time out if no packets arrive.
137 * Therefore, on at least some platforms, we work around the lack of
138 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
139 * to wait for packets to arrive, so that we're probably going to be
140 * blocked in the select() when the signal arrives, and can just bail
141 * out of the loop at that point.
143 * However, we don't want to that on BSD (because "select()" doesn't work
144 * correctly on BPF devices on at least some releases of some flavors of
145 * BSD), and we don't want to do it on Windows (because "select()" is
146 * something for sockets, not for arbitrary handles). (Note that "Windows"
147 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
148 * using WinPcap, not a UNIX libpcap.)
150 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
151 * on BSD times out even if no packets have arrived, so we'll eventually
152 * exit pcap_dispatch() with an indication that no packets have arrived,
153 * and will break out of the capture loop at that point.
155 * On Windows, we can't send a SIGUSR1 to stop capturing, so none of this
156 * applies in any case.
158 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
159 * want to include it if it's not present on this platform, however.
161 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
162 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
164 # define MUST_DO_SELECT
165 # endif /* avoid select */
166 #endif /* HAVE_PCAP_BREAKLOOP */
168 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
169 * in pcap_dispatch(); on the other hand, select() works just fine there.
170 * Hence we use a select for that come what may.
172 #define MUST_DO_SELECT
175 /** init the capture filter */
178 INITFILTER_BAD_FILTER,
179 INITFILTER_OTHER_ERROR
180 } initfilter_status_t;
182 typedef struct _loop_data {
184 gboolean go; /* TRUE as long as we're supposed to keep capturing */
185 int err; /* if non-zero, error seen while capturing */
186 gint packet_count; /* Number of packets we have already captured */
187 gint packet_max; /* Number of packets we're supposed to capture - 0 means infinite */
189 /* pcap "input file" */
190 pcap_t *pcap_h; /* pcap handle */
191 gboolean pcap_err; /* TRUE if error from pcap */
192 #ifdef MUST_DO_SELECT
193 int pcap_fd; /* pcap file descriptor */
196 /* capture pipe (unix only "input file") */
197 gboolean from_cap_pipe; /* TRUE if we are capturing data from a capture pipe */
198 struct pcap_hdr cap_pipe_hdr; /* Pcap header when capturing from a pipe */
199 struct pcaprec_modified_hdr cap_pipe_rechdr; /* Pcap record header when capturing from a pipe */
200 int cap_pipe_fd; /* the file descriptor of the capture pipe */
201 gboolean cap_pipe_modified; /* TRUE if data in the pipe uses modified pcap headers */
202 gboolean cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
203 unsigned int cap_pipe_bytes_to_read;/* Used by cap_pipe_dispatch */
204 unsigned int cap_pipe_bytes_read; /* Used by cap_pipe_dispatch */
206 STATE_EXPECT_REC_HDR,
211 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
222 * Standard secondary message for unexpected errors.
224 static const char please_report[] =
225 "Please report this to the Wireshark developers.\n"
226 "(This is not a crash; please do not report it as such.)";
229 * This needs to be static, so that the SIGUSR1 handler can clear the "go"
232 static loop_data global_ld;
236 * Timeout, in milliseconds, for reads from the stream of captured packets.
238 #define CAP_READ_TIMEOUT 250
239 static char *cap_pipe_err_str;
242 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
243 const char *message, gpointer user_data _U_);
245 /* capture related options */
246 static capture_options global_capture_opts;
248 static void capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
250 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
251 int err, gboolean is_close);
255 static void exit_main(int err) __attribute__ ((noreturn));
257 static void exit_main(int err);
260 static void report_new_capture_file(const char *filename);
261 static void report_packet_count(int packet_count);
262 static void report_packet_drops(guint32 drops);
263 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
264 static void report_cfilter_error(const char *cfilter, const char *errmsg);
267 static gboolean signal_pipe_check_running(void);
271 print_usage(gboolean print_ver) {
279 "Dumpcap " VERSION "%s\n"
280 "Capture network packets and dump them into a libpcap file.\n"
281 "See http://www.wireshark.org for more information.\n",
282 wireshark_svnversion);
286 fprintf(output, "\nUsage: dumpcap [options] ...\n");
287 fprintf(output, "\n");
288 fprintf(output, "Capture interface:\n");
289 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
290 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
291 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
292 fprintf(output, " -p don't capture in promiscuous mode\n");
294 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
296 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
297 fprintf(output, " -D print list of interfaces and exit\n");
298 fprintf(output, " -L print list of link-layer types of iface and exit\n");
299 fprintf(output, " -S print statistics for each interface once every second\n");
300 fprintf(output, " -M for -D, -L, and -S produce machine-readable output\n");
301 fprintf(output, "\n");
302 #ifdef HAVE_PCAP_REMOTE
303 fprintf(output, "\nRPCAP options:\n");
304 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
305 fprintf(output, " -u use UDP for RPCAP data transfer\n");
306 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
307 #ifdef HAVE_PCAP_SETSAMPLING
308 fprintf(output, " -m <sampling type> use packet sampling\n");
309 fprintf(output, " count:NUM - capture one packet of every NUM\n");
310 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
313 fprintf(output, "Stop conditions:\n");
314 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
315 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
316 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
317 fprintf(output, " files:NUM - stop after NUM files\n");
318 /*fprintf(output, "\n");*/
319 fprintf(output, "Output (files):\n");
320 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
321 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
322 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
323 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
324 /*fprintf(output, "\n");*/
325 fprintf(output, "Miscellaneous:\n");
326 fprintf(output, " -v print version information and exit\n");
327 fprintf(output, " -h display this help and exit\n");
328 fprintf(output, "\n");
329 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcap\n");
330 fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcap\"\n");
331 fprintf(output, "\n");
332 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
336 show_version(GString *comp_info_str, GString *runtime_info_str)
340 "Dumpcap " VERSION "%s\n"
345 "See http://www.wireshark.org for more information.\n",
346 wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
350 * Report an error in command-line arguments.
353 cmdarg_err(const char *fmt, ...)
359 /* Generate a 'special format' message back to parent */
361 msg = g_strdup_vprintf(fmt, ap);
362 sync_pipe_errmsg_to_parent(2, msg, "");
367 fprintf(stderr, "dumpcap: ");
368 vfprintf(stderr, fmt, ap);
369 fprintf(stderr, "\n");
375 * Report additional information for an error in command-line arguments.
378 cmdarg_err_cont(const char *fmt, ...)
385 msg = g_strdup_vprintf(fmt, ap);
386 sync_pipe_errmsg_to_parent(2, msg, "");
391 vfprintf(stderr, fmt, ap);
392 fprintf(stderr, "\n");
402 /* Print the number of packets captured for each interface until we're killed. */
404 print_statistics_loop(gboolean machine_readable)
406 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
412 char errbuf[PCAP_ERRBUF_SIZE];
415 if_list = get_interface_list(&err, &err_str);
416 if (if_list == NULL) {
418 case CANT_GET_INTERFACE_LIST:
419 cmdarg_err("%s", err_str);
423 case NO_INTERFACES_FOUND:
424 cmdarg_err("There are no interfaces on which a capture can be done");
430 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
431 if_info = if_entry->data;
432 #ifdef HAVE_PCAP_OPEN
433 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
435 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
439 if_stat = g_malloc(sizeof(if_stat_t));
440 if_stat->name = g_strdup(if_info->name);
442 stat_list = g_list_append(stat_list, if_stat);
447 cmdarg_err("There are no interfaces on which a capture can be done");
451 if (!machine_readable) {
452 printf("%-15s %10s %10s\n", "Interface", "Received",
457 while (global_ld.go) {
458 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
459 if_stat = stat_entry->data;
460 pcap_stats(if_stat->pch, &ps);
462 if (!machine_readable) {
463 printf("%-15s %10u %10u\n", if_stat->name,
464 ps.ps_recv, ps.ps_drop);
466 printf("%s\t%u\t%u\n", if_stat->name,
467 ps.ps_recv, ps.ps_drop);
478 /* XXX - Not reached. Should we look for 'q' in stdin? */
479 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
480 if_stat = stat_entry->data;
481 pcap_close(if_stat->pch);
482 g_free(if_stat->name);
485 g_list_free(stat_list);
486 free_interface_list(if_list);
494 capture_cleanup(DWORD dwCtrlType)
496 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
497 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
498 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
499 like SIGTERM at least when the machine's shutting down.
501 For now, if we're running as a command rather than a capture child,
502 we handle all but CTRL_LOGOFF_EVENT as indications that we should
503 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
506 If we're not running as a capture child, we might be running as
507 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
508 user logs out. (XXX - can we explicitly check whether we're
509 running as a service?) */
511 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
512 "Console: Control signal");
513 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
514 "Console: Control signal, CtrlType: %u", dwCtrlType);
516 /* Keep capture running if we're a service and a user logs off */
517 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
526 capture_cleanup(int signum)
528 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
529 SIGTERM. We assume that if the user wanted it to keep running
530 after they logged out, they'd have nohupped it. */
532 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
534 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
535 "Console: Signal, signal value: %u", signum);
541 static void exit_main(int status)
544 /* Shutdown windows sockets */
547 /* can be helpful for debugging */
549 printf("Press any key\n");
560 * If we were linked with libcap (not libpcap), make sure we have
561 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
562 * (See comment in main() for details)
566 #if 0 /* Set to enable capability debugging */
567 /* see 'man cap_to_text()' for explanation of output */
568 /* '=' means 'all= ' ie: no capabilities */
569 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
571 print_caps(char *pfx) {
572 cap_t caps = cap_get_proc();
573 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
574 "%s: EUID: %d Capabilities: %s", pfx,
575 geteuid(), cap_to_text(caps, NULL));
578 print_caps(char *pfx _U_) {
583 relinquish_privs_except_capture(void)
585 /* If 'started_with_special_privs' (ie: suid) then enable for
586 * ourself the NET_ADMIN and NET_RAW capabilities and then
587 * drop our suid privileges.
589 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
590 * stuff we don't need (and shouldn't have).
591 * CAP_NET_RAW: Packet capture (raw sockets).
594 if (started_with_special_privs()) {
595 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
596 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
598 cap_t caps = cap_init(); /* all capabilities initialized to off */
600 print_caps("Pre drop, pre set");
602 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
603 cmdarg_err("prctl() fail return: %s", strerror(errno));
606 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
607 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
609 if (cap_set_proc(caps)) {
610 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
612 print_caps("Pre drop, post set");
614 relinquish_special_privs_perm();
616 print_caps("Post drop, pre set");
617 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
618 if (cap_set_proc(caps)) {
619 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
621 print_caps("Post drop, post set");
629 relinquish_all_capabilities()
631 /* Drop any and all capabilities this process may have. */
632 /* Allowed whether or not process has any privileges. */
633 cap_t caps = cap_init(); /* all capabilities initialized to off */
634 print_caps("Pre-clear");
635 if (cap_set_proc(caps)) {
636 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
638 print_caps("Post-clear");
642 #endif /* HAVE_LIBCAP */
644 /* Take care of byte order in the libpcap headers read from pipes.
645 * (function taken from wiretap/libpcap.c) */
647 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
650 /* Byte-swap the record header fields. */
651 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
652 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
653 rechdr->incl_len = BSWAP32(rechdr->incl_len);
654 rechdr->orig_len = BSWAP32(rechdr->orig_len);
657 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
658 swapped, in order to match the BPF header layout.
660 Unfortunately, some files were, according to a comment in the "libpcap"
661 source, written with version 2.3 in their headers but without the
662 interchanged fields, so if "incl_len" is greater than "orig_len" - which
663 would make no sense - we assume that we need to swap them. */
664 if (hdr->version_major == 2 &&
665 (hdr->version_minor < 3 ||
666 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
669 temp = rechdr->orig_len;
670 rechdr->orig_len = rechdr->incl_len;
671 rechdr->incl_len = temp;
675 /* Provide select() functionality for a single file descriptor
676 * on both UNIX/POSIX and Windows.
678 * The Windows version calls WaitForSingleObject instead of
681 * Returns the same values as select. If an error is returned,
682 * the string cap_pipe_err_str should be used instead of errno.
685 cap_pipe_select(int pipe_fd) {
688 struct timeval timeout, *pto;
691 cap_pipe_err_str = "Unknown error";
694 FD_SET(pipe_fd, &rfds);
697 timeout.tv_usec = CAP_READ_TIMEOUT * 1000;
700 sel_ret = select(pipe_fd+1, &rfds, NULL, NULL, pto);
702 cap_pipe_err_str = strerror(errno);
706 /* XXX - Should we just use file handles exclusively under Windows?
707 * Otherwise we have to convert between file handles and file descriptors
708 * here and when we open a named pipe.
710 HANDLE hPipe = (HANDLE) _get_osfhandle(pipe_fd);
714 if (hPipe == INVALID_HANDLE_VALUE) {
715 cap_pipe_err_str = "Could not open standard input";
719 cap_pipe_err_str = "Unknown error";
721 wait_ret = WaitForSingleObject(hPipe, CAP_READ_TIMEOUT);
723 /* XXX - This probably isn't correct */
732 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
733 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
734 cap_pipe_err_str = utf_16to8(err_str);
738 g_assert_not_reached();
745 /* Mimic pcap_open_live() for pipe captures
746 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
748 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
749 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
751 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
752 char *errmsg, int errmsgl)
755 struct stat pipe_stat;
767 unsigned int bytes_read;
769 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
772 * XXX (T)Wireshark blocks until we return
774 if (strcmp(pipename, "-") == 0) {
775 fd = 0; /* read from stdin */
778 * This is needed to set the stdin pipe into binary mode, otherwise
779 * CR/LF are mangled...
781 _setmode(0, _O_BINARY);
785 if (ws_stat(pipename, &pipe_stat) < 0) {
786 if (errno == ENOENT || errno == ENOTDIR)
787 ld->cap_pipe_err = PIPNEXIST;
789 g_snprintf(errmsg, errmsgl,
790 "The capture session could not be initiated "
791 "due to error on pipe: %s", strerror(errno));
792 ld->cap_pipe_err = PIPERR;
796 if (! S_ISFIFO(pipe_stat.st_mode)) {
797 if (S_ISCHR(pipe_stat.st_mode)) {
799 * Assume the user specified an interface on a system where
800 * interfaces are in /dev. Pretend we haven't seen it.
802 ld->cap_pipe_err = PIPNEXIST;
805 g_snprintf(errmsg, errmsgl,
806 "The capture session could not be initiated because\n"
807 "\"%s\" is neither an interface nor a pipe", pipename);
808 ld->cap_pipe_err = PIPERR;
812 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
814 g_snprintf(errmsg, errmsgl,
815 "The capture session could not be initiated "
816 "due to error on pipe open: %s", strerror(errno));
817 ld->cap_pipe_err = PIPERR;
821 #define PIPE_STR "\\pipe\\"
822 /* Under Windows, named pipes _must_ have the form
823 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
825 pncopy = g_strdup(pipename);
826 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
827 pos = strchr(pncopy + 3, '\\');
828 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
835 g_snprintf(errmsg, errmsgl,
836 "The capture session could not be initiated because\n"
837 "\"%s\" is neither an interface nor a pipe", pipename);
838 ld->cap_pipe_err = PIPNEXIST;
842 /* Wait for the pipe to appear */
844 hPipe = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
845 OPEN_EXISTING, 0, NULL);
847 if (hPipe != INVALID_HANDLE_VALUE)
850 if (GetLastError() != ERROR_PIPE_BUSY) {
851 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
852 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
853 g_snprintf(errmsg, errmsgl,
854 "The capture session on \"%s\" could not be initiated "
855 "due to error on pipe open: pipe busy: %s (error %d)",
856 pipename, utf_16to8(err_str), GetLastError());
858 ld->cap_pipe_err = PIPERR;
862 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
863 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
864 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
865 g_snprintf(errmsg, errmsgl,
866 "The capture session could not be initiated "
867 "due to error on named pipe open: %s (error %d)",
868 utf_16to8(err_str), GetLastError());
870 ld->cap_pipe_err = PIPERR;
875 fd = _open_osfhandle((long) hPipe, _O_RDONLY);
877 g_snprintf(errmsg, errmsgl,
878 "The capture session could not be initiated "
879 "due to error on pipe open: %s", strerror(errno));
880 ld->cap_pipe_err = PIPERR;
886 ld->from_cap_pipe = TRUE;
888 /* read the pcap header */
890 while (bytes_read < sizeof magic) {
891 sel_ret = cap_pipe_select(fd);
893 g_snprintf(errmsg, errmsgl,
894 "Unexpected error from select: %s", strerror(errno));
896 } else if (sel_ret > 0) {
897 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
900 g_snprintf(errmsg, errmsgl, "End of file on pipe during open");
902 g_snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
912 /* Host that wrote it has our byte order, and was running
913 a program using either standard or ss990417 libpcap. */
914 ld->cap_pipe_byte_swapped = FALSE;
915 ld->cap_pipe_modified = FALSE;
917 case PCAP_MODIFIED_MAGIC:
918 /* Host that wrote it has our byte order, but was running
919 a program using either ss990915 or ss991029 libpcap. */
920 ld->cap_pipe_byte_swapped = FALSE;
921 ld->cap_pipe_modified = TRUE;
923 case PCAP_SWAPPED_MAGIC:
924 /* Host that wrote it has a byte order opposite to ours,
925 and was running a program using either standard or
927 ld->cap_pipe_byte_swapped = TRUE;
928 ld->cap_pipe_modified = FALSE;
930 case PCAP_SWAPPED_MODIFIED_MAGIC:
931 /* Host that wrote it out has a byte order opposite to
932 ours, and was running a program using either ss990915
933 or ss991029 libpcap. */
934 ld->cap_pipe_byte_swapped = TRUE;
935 ld->cap_pipe_modified = TRUE;
938 /* Not a "libpcap" type we know about. */
939 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
943 /* Read the rest of the header */
945 while (bytes_read < sizeof(struct pcap_hdr)) {
946 sel_ret = cap_pipe_select(fd);
948 g_snprintf(errmsg, errmsgl,
949 "Unexpected error from select: %s", strerror(errno));
951 } else if (sel_ret > 0) {
952 b = read(fd, ((char *)hdr)+bytes_read,
953 sizeof(struct pcap_hdr) - bytes_read);
956 g_snprintf(errmsg, errmsgl, "End of file on pipe during open");
958 g_snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
966 if (ld->cap_pipe_byte_swapped) {
967 /* Byte-swap the header fields about which we care. */
968 hdr->version_major = BSWAP16(hdr->version_major);
969 hdr->version_minor = BSWAP16(hdr->version_minor);
970 hdr->snaplen = BSWAP32(hdr->snaplen);
971 hdr->network = BSWAP32(hdr->network);
973 ld->linktype = hdr->network;
975 if (hdr->version_major < 2) {
976 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
980 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
981 ld->cap_pipe_err = PIPOK;
985 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
986 ld->cap_pipe_err = PIPERR;
993 /* We read one record from the pipe, take care of byte order in the record
994 * header, write the record to the capture file, and update capture statistics. */
996 cap_pipe_dispatch(loop_data *ld, guchar *data, char *errmsg, int errmsgl)
998 struct pcap_pkthdr phdr;
1000 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1004 #ifdef LOG_CAPTURE_VERBOSE
1005 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1008 switch (ld->cap_pipe_state) {
1010 case STATE_EXPECT_REC_HDR:
1011 ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
1012 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1013 ld->cap_pipe_bytes_read = 0;
1014 ld->cap_pipe_state = STATE_READ_REC_HDR;
1017 case STATE_READ_REC_HDR:
1018 b = read(ld->cap_pipe_fd, ((char *)&ld->cap_pipe_rechdr)+ld->cap_pipe_bytes_read,
1019 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1022 result = PD_PIPE_EOF;
1024 result = PD_PIPE_ERR;
1027 if ((ld->cap_pipe_bytes_read += b) < ld->cap_pipe_bytes_to_read)
1029 result = PD_REC_HDR_READ;
1032 case STATE_EXPECT_DATA:
1033 ld->cap_pipe_bytes_read = 0;
1034 ld->cap_pipe_state = STATE_READ_DATA;
1037 case STATE_READ_DATA:
1038 b = read(ld->cap_pipe_fd, data+ld->cap_pipe_bytes_read,
1039 ld->cap_pipe_rechdr.hdr.incl_len - ld->cap_pipe_bytes_read);
1042 result = PD_PIPE_EOF;
1044 result = PD_PIPE_ERR;
1047 if ((ld->cap_pipe_bytes_read += b) < ld->cap_pipe_rechdr.hdr.incl_len)
1049 result = PD_DATA_READ;
1053 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
1056 } /* switch (ld->cap_pipe_state) */
1059 * We've now read as much data as we were expecting, so process it.
1063 case PD_REC_HDR_READ:
1064 /* We've read the header. Take care of byte order. */
1065 cap_pipe_adjust_header(ld->cap_pipe_byte_swapped, &ld->cap_pipe_hdr,
1066 &ld->cap_pipe_rechdr.hdr);
1067 if (ld->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1068 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
1069 ld->packet_count+1, ld->cap_pipe_rechdr.hdr.incl_len);
1072 ld->cap_pipe_state = STATE_EXPECT_DATA;
1076 /* Fill in a "struct pcap_pkthdr", and process the packet. */
1077 phdr.ts.tv_sec = ld->cap_pipe_rechdr.hdr.ts_sec;
1078 phdr.ts.tv_usec = ld->cap_pipe_rechdr.hdr.ts_usec;
1079 phdr.caplen = ld->cap_pipe_rechdr.hdr.incl_len;
1080 phdr.len = ld->cap_pipe_rechdr.hdr.orig_len;
1082 capture_loop_packet_cb((u_char *)ld, &phdr, data);
1084 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1088 ld->cap_pipe_err = PIPEOF;
1092 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
1099 ld->cap_pipe_err = PIPERR;
1100 /* Return here rather than inside the switch to prevent GCC warning */
1105 /** Open the capture input file (pcap or capture pipe).
1106 * Returns TRUE if it succeeds, FALSE otherwise. */
1108 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
1109 char *errmsg, size_t errmsg_len,
1110 char *secondary_errmsg, size_t secondary_errmsg_len)
1112 gchar open_err_str[PCAP_ERRBUF_SIZE];
1113 gchar *sync_msg_str;
1114 static const char ppamsg[] = "can't find PPA for ";
1115 const char *set_linktype_err_str;
1116 const char *libpcap_warn;
1118 gchar *sync_secondary_msg_str;
1120 WORD wVersionRequested;
1123 #ifdef HAVE_PCAP_REMOTE
1124 struct pcap_rmtauth auth;
1128 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
1131 /* XXX - opening Winsock on tshark? */
1133 /* Initialize Windows Socket if we are in a WIN32 OS
1134 This needs to be done before querying the interface for network/netmask */
1136 /* XXX - do we really require 1.1 or earlier?
1137 Are there any versions that support only 2.0 or higher? */
1138 wVersionRequested = MAKEWORD(1, 1);
1139 err = WSAStartup(wVersionRequested, &wsaData);
1143 case WSASYSNOTREADY:
1144 g_snprintf(errmsg, errmsg_len,
1145 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
1148 case WSAVERNOTSUPPORTED:
1149 g_snprintf(errmsg, errmsg_len,
1150 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
1151 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
1154 case WSAEINPROGRESS:
1155 g_snprintf(errmsg, errmsg_len,
1156 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
1160 g_snprintf(errmsg, errmsg_len,
1161 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
1165 g_snprintf(errmsg, errmsg_len,
1166 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
1170 g_snprintf(errmsg, errmsg_len,
1171 "Couldn't initialize Windows Sockets: error %d", err);
1174 g_snprintf(secondary_errmsg, secondary_errmsg_len, please_report);
1179 /* Open the network interface to capture from it.
1180 Some versions of libpcap may put warnings into the error buffer
1181 if they succeed; to tell if that's happened, we have to clear
1182 the error buffer, and check if it's still a null string. */
1183 open_err_str[0] = '\0';
1184 #ifdef HAVE_PCAP_OPEN
1185 auth.type = capture_opts->auth_type == CAPTURE_AUTH_PWD ?
1186 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
1187 auth.username = capture_opts->auth_username;
1188 auth.password = capture_opts->auth_password;
1190 ld->pcap_h = pcap_open(capture_opts->iface,
1191 capture_opts->has_snaplen ? capture_opts->snaplen :
1192 WTAP_MAX_PACKET_SIZE,
1194 (capture_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
1195 (capture_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
1196 (capture_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
1197 CAP_READ_TIMEOUT, &auth, open_err_str);
1199 ld->pcap_h = pcap_open_live(capture_opts->iface,
1200 capture_opts->has_snaplen ? capture_opts->snaplen :
1201 WTAP_MAX_PACKET_SIZE,
1202 capture_opts->promisc_mode, CAP_READ_TIMEOUT,
1206 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
1207 /* to remove any suid privileges. */
1208 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
1209 /* (euid/egid have already previously been set to ruid/rgid. */
1210 /* (See comment in main() for details) */
1212 relinquish_special_privs_perm();
1214 relinquish_all_capabilities();
1217 if (ld->pcap_h != NULL) {
1218 /* we've opened "iface" as a network device */
1220 /* try to set the capture buffer size */
1221 if (pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
1222 sync_secondary_msg_str = g_strdup_printf(
1223 "The capture buffer size of %luMB seems to be too high for your machine,\n"
1224 "the default of 1MB will be used.\n"
1226 "Nonetheless, the capture is started.\n",
1227 capture_opts->buffer_size);
1228 report_capture_error("Couldn't set the capture buffer size!",
1229 sync_secondary_msg_str);
1230 g_free(sync_secondary_msg_str);
1234 #if defined(HAVE_PCAP_REMOTE) && defined(HAVE_PCAP_SETSAMPLING)
1235 if (capture_opts->sampling_method != CAPTURE_SAMP_NONE)
1237 struct pcap_samp *samp;
1239 if ((samp = pcap_setsampling(ld->pcap_h)) != NULL)
1241 switch (capture_opts->sampling_method)
1243 case CAPTURE_SAMP_BY_COUNT:
1244 samp->method = PCAP_SAMP_1_EVERY_N;
1247 case CAPTURE_SAMP_BY_TIMER:
1248 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
1252 sync_msg_str = g_strdup_printf(
1253 "Unknown sampling method %d specified,\n"
1254 "continue without packet sampling",
1255 capture_opts->sampling_method);
1256 report_capture_error("Couldn't set the capture "
1257 "sampling", sync_msg_str);
1258 g_free(sync_msg_str);
1260 samp->value = capture_opts->sampling_param;
1264 report_capture_error("Couldn't set the capture sampling",
1265 "Cannot get packet sampling data structure");
1271 /* setting the data link type only works on real interfaces */
1272 if (capture_opts->linktype != -1) {
1273 set_linktype_err_str = set_pcap_linktype(ld->pcap_h, capture_opts->iface,
1274 capture_opts->linktype);
1275 if (set_linktype_err_str != NULL) {
1276 g_snprintf(errmsg, errmsg_len, "Unable to set data link type (%s).",
1277 set_linktype_err_str);
1278 g_snprintf(secondary_errmsg, secondary_errmsg_len, please_report);
1282 ld->linktype = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
1284 /* We couldn't open "iface" as a network device. */
1285 /* Try to open it as a pipe */
1286 ld->cap_pipe_fd = cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, errmsg_len);
1288 if (ld->cap_pipe_fd == -1) {
1290 if (ld->cap_pipe_err == PIPNEXIST) {
1291 /* Pipe doesn't exist, so output message for interface */
1293 /* If we got a "can't find PPA for X" message, warn the user (who
1294 is running (T)Wireshark on HP-UX) that they don't have a version
1295 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1296 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1297 PPA for X" rather than "can't find PPA for X"). */
1298 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1301 "You are running (T)Wireshark with a version of the libpcap library\n"
1302 "that doesn't handle HP-UX network devices well; this means that\n"
1303 "(T)Wireshark may not be able to capture packets.\n"
1305 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1306 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1307 "packaged binary form from the Software Porting And Archive Centre\n"
1308 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1309 "at the URL lists a number of mirror sites.";
1312 g_snprintf(errmsg, errmsg_len,
1313 "The capture session could not be initiated (%s).", open_err_str);
1315 g_snprintf(secondary_errmsg, secondary_errmsg_len,
1316 "Please check to make sure you have sufficient permissions, and that you have "
1317 "the proper interface or pipe specified.%s", libpcap_warn);
1319 g_snprintf(secondary_errmsg, secondary_errmsg_len,
1321 "Please check that \"%s\" is the proper interface.\n"
1324 "Help can be found at:\n"
1326 " http://wiki.wireshark.org/WinPcap\n"
1327 " http://wiki.wireshark.org/CaptureSetup\n",
1328 capture_opts->iface);
1332 * Else pipe (or file) does exist and cap_pipe_open_live() has
1337 /* cap_pipe_open_live() succeeded; don't want
1338 error message from pcap_open_live() */
1339 open_err_str[0] = '\0';
1342 /* XXX - will this work for tshark? */
1343 #ifdef MUST_DO_SELECT
1344 if (!ld->from_cap_pipe) {
1345 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
1346 ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
1348 ld->pcap_fd = pcap_fileno(ld->pcap_h);
1353 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1354 returned a warning; print it, but keep capturing. */
1355 if (open_err_str[0] != '\0') {
1356 sync_msg_str = g_strdup_printf("%s.", open_err_str);
1357 report_capture_error(sync_msg_str, "");
1358 g_free(sync_msg_str);
1365 /* close the capture input file (pcap or capture pipe) */
1366 static void capture_loop_close_input(loop_data *ld) {
1368 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
1370 /* if open, close the capture pipe "input file" */
1371 if (ld->cap_pipe_fd >= 0) {
1372 g_assert(ld->from_cap_pipe);
1373 ws_close(ld->cap_pipe_fd);
1374 ld->cap_pipe_fd = 0;
1377 /* if open, close the pcap "input file" */
1378 if(ld->pcap_h != NULL) {
1379 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", ld->pcap_h);
1380 g_assert(!ld->from_cap_pipe);
1381 pcap_close(ld->pcap_h);
1388 /* Shut down windows sockets */
1394 /* init the capture filter */
1395 static initfilter_status_t
1396 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe, gchar * iface, gchar * cfilter) {
1397 bpf_u_int32 netnum, netmask;
1398 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
1399 struct bpf_program fcode;
1402 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
1404 /* capture filters only work on real interfaces */
1405 if (cfilter && !from_cap_pipe) {
1406 /* A capture filter was specified; set it up. */
1407 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1409 * Well, we can't get the netmask for this interface; it's used
1410 * only for filters that check for broadcast IP addresses, so
1411 * we just punt and use 0. It might be nice to warn the user,
1412 * but that's a pain in a GUI application, as it'd involve popping
1413 * up a message box, and it's not clear how often this would make
1414 * a difference (only filters that check for IP broadcast addresses
1418 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
1421 if (pcap_compile(pcap_h, &fcode, cfilter, 1, netmask) < 0) {
1422 /* Treat this specially - our caller might try to compile this
1423 as a display filter and, if that succeeds, warn the user that
1424 the display and capture filter syntaxes are different. */
1425 return INITFILTER_BAD_FILTER;
1427 if (pcap_setfilter(pcap_h, &fcode) < 0) {
1428 #ifdef HAVE_PCAP_FREECODE
1429 pcap_freecode(&fcode);
1431 return INITFILTER_OTHER_ERROR;
1433 #ifdef HAVE_PCAP_FREECODE
1434 pcap_freecode(&fcode);
1438 return INITFILTER_NO_ERROR;
1442 /* set up to write to the already-opened capture output file/files */
1444 capture_loop_init_output(capture_options *capture_opts, int save_file_fd, loop_data *ld, char *errmsg, int errmsg_len) {
1449 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
1452 if (ld->from_cap_pipe) {
1453 file_snaplen = ld->cap_pipe_hdr.snaplen;
1456 file_snaplen = pcap_snapshot(ld->pcap_h);
1459 /* Set up to write to the capture file. */
1460 if (capture_opts->multi_files_on) {
1461 ld->pdh = ringbuf_init_libpcap_fdopen(ld->linktype, file_snaplen,
1462 &ld->bytes_written, &err);
1464 ld->pdh = libpcap_fdopen(save_file_fd, ld->linktype, file_snaplen,
1465 &ld->bytes_written, &err);
1468 if (ld->pdh == NULL) {
1469 /* We couldn't set up to write to the capture file. */
1470 /* XXX - use cf_open_error_message from tshark instead? */
1473 case WTAP_ERR_CANT_OPEN:
1474 g_snprintf(errmsg, errmsg_len, "The file to which the capture would be saved"
1475 " couldn't be created for some unknown reason.");
1478 case WTAP_ERR_SHORT_WRITE:
1479 g_snprintf(errmsg, errmsg_len, "A full header couldn't be written to the file"
1480 " to which the capture would be saved.");
1485 g_snprintf(errmsg, errmsg_len,
1486 "The file to which the capture would be"
1487 " saved (\"%s\") could not be opened: Error %d.",
1488 capture_opts->save_file, err);
1490 g_snprintf(errmsg, errmsg_len,
1491 "The file to which the capture would be"
1492 " saved (\"%s\") could not be opened: %s.",
1493 capture_opts->save_file, strerror(err));
1505 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
1507 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
1509 if (capture_opts->multi_files_on) {
1510 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
1512 return libpcap_dump_close(ld->pdh, err_close);
1516 /* dispatch incoming packets (pcap or capture pipe)
1518 * Waits for incoming packets to be available, and calls pcap_dispatch()
1519 * to cause them to be processed.
1521 * Returns the number of packets which were processed.
1523 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
1524 * packet-batching behaviour does not cause packets to get held back
1528 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
1529 char *errmsg, int errmsg_len)
1533 gint packet_count_before;
1534 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1536 packet_count_before = ld->packet_count;
1537 if (ld->from_cap_pipe) {
1538 /* dispatch from capture pipe */
1539 #ifdef LOG_CAPTURE_VERBOSE
1540 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
1542 sel_ret = cap_pipe_select(ld->cap_pipe_fd);
1545 if (sel_ret < 0 && errno != EINTR) {
1546 g_snprintf(errmsg, errmsg_len,
1547 "Unexpected error from select: %s", strerror(errno));
1548 report_capture_error(errmsg, please_report);
1553 * "select()" says we can read from the pipe without blocking
1555 inpkts = cap_pipe_dispatch(ld, pcap_data, errmsg, errmsg_len);
1563 /* dispatch from pcap */
1564 #ifdef MUST_DO_SELECT
1566 * If we have "pcap_get_selectable_fd()", we use it to get the
1567 * descriptor on which to select; if that's -1, it means there
1568 * is no descriptor on which you can do a "select()" (perhaps
1569 * because you're capturing on a special device, and that device's
1570 * driver unfortunately doesn't support "select()", in which case
1571 * we don't do the select - which means it might not be possible
1572 * to stop a capture until a packet arrives. If that's unacceptable,
1573 * plead with whoever supplies the software for that device to add
1574 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
1575 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
1576 * later, so it can use pcap_breakloop().
1578 #ifdef LOG_CAPTURE_VERBOSE
1579 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
1581 if (ld->pcap_fd != -1) {
1582 sel_ret = cap_pipe_select(ld->pcap_fd);
1585 * "select()" says we can read from it without blocking; go for
1588 * We don't have pcap_breakloop(), so we only process one packet
1589 * per pcap_dispatch() call, to allow a signal to stop the
1590 * processing immediately, rather than processing all packets
1591 * in a batch before quitting.
1593 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb,
1596 ld->pcap_err = TRUE;
1597 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1600 if (sel_ret < 0 && errno != EINTR) {
1601 g_snprintf(errmsg, errmsg_len,
1602 "Unexpected error from select: %s", strerror(errno));
1603 report_capture_error(errmsg, please_report);
1609 #endif /* MUST_DO_SELECT */
1611 /* dispatch from pcap without select */
1613 #ifdef LOG_CAPTURE_VERBOSE
1614 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
1618 * On Windows, we don't support asynchronously telling a process to
1619 * stop capturing; instead, we check for an indication on a pipe
1620 * after processing packets. We therefore process only one packet
1621 * at a time, so that we can check the pipe after every packet.
1623 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb, (u_char *) ld);
1625 inpkts = pcap_dispatch(ld->pcap_h, -1, capture_loop_packet_cb, (u_char *) ld);
1629 /* Error, rather than pcap_breakloop(). */
1630 ld->pcap_err = TRUE;
1632 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1634 #else /* pcap_next_ex */
1635 #ifdef LOG_CAPTURE_VERBOSE
1636 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
1638 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
1641 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
1642 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
1643 * This should be fixed in the WinPcap 4.0 alpha release.
1645 * For reference, an example remote interface:
1646 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
1649 /* emulate dispatch from pcap */
1652 struct pcap_pkthdr *pkt_header;
1657 (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1)
1658 capture_loop_packet_cb( (u_char *) ld, pkt_header, pkt_data);
1661 ld->pcap_err = TRUE;
1665 #endif /* pcap_next_ex */
1669 #ifdef LOG_CAPTURE_VERBOSE
1670 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
1673 return ld->packet_count - packet_count_before;
1677 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
1678 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
1680 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
1681 char *errmsg, int errmsg_len) {
1683 char tmpname[128+1];
1684 gchar *capfile_name;
1685 gboolean is_tempfile;
1688 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
1689 (capture_opts->save_file) ? capture_opts->save_file : "");
1691 if (capture_opts->save_file != NULL) {
1692 /* We return to the caller while the capture is in progress.
1693 * Therefore we need to take a copy of save_file in
1694 * case the caller destroys it after we return.
1696 capfile_name = g_strdup(capture_opts->save_file);
1698 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
1699 if (capture_opts->multi_files_on) {
1700 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
1701 g_snprintf(errmsg, errmsg_len,
1702 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
1703 g_free(capfile_name);
1706 if (strcmp(capfile_name, "-") == 0) {
1707 /* write to stdout */
1710 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
1711 _setmode(1, O_BINARY);
1714 } /* if (...output_to_pipe ... */
1717 if (capture_opts->multi_files_on) {
1718 /* ringbuffer is enabled */
1719 *save_file_fd = ringbuf_init(capfile_name,
1720 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
1722 /* we need the ringbuf name */
1723 if(*save_file_fd != -1) {
1724 g_free(capfile_name);
1725 capfile_name = g_strdup(ringbuf_current_filename());
1728 /* Try to open/create the specified file for use as a capture buffer. */
1729 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
1733 is_tempfile = FALSE;
1735 /* Choose a random name for the temporary capture buffer */
1736 *save_file_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
1737 capfile_name = g_strdup(tmpname);
1741 /* did we fail to open the output file? */
1742 if (*save_file_fd == -1) {
1744 g_snprintf(errmsg, errmsg_len,
1745 "The temporary file to which the capture would be saved (\"%s\") "
1746 "could not be opened: %s.", capfile_name, strerror(errno));
1748 if (capture_opts->multi_files_on) {
1749 ringbuf_error_cleanup();
1752 g_snprintf(errmsg, errmsg_len,
1753 "The file to which the capture would be saved (\"%s\") "
1754 "could not be opened: %s.", capfile_name,
1757 g_free(capfile_name);
1761 if(capture_opts->save_file != NULL) {
1762 g_free(capture_opts->save_file);
1764 capture_opts->save_file = capfile_name;
1765 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
1766 "g_free(capfile_name)". */
1768 fchown(*save_file_fd, capture_opts->owner, capture_opts->group);
1776 capture_loop_stop_signal_handler(int signo _U_)
1778 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Signal: Stop capture");
1779 capture_loop_stop();
1783 #define TIME_GET() GetTickCount()
1785 #define TIME_GET() time(NULL)
1788 /* Do the low-level work of a capture.
1789 Returns TRUE if it succeeds, FALSE otherwise. */
1791 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
1794 struct sigaction act;
1796 time_t upd_time, cur_time;
1800 gint inpkts_to_sync_pipe = 0; /* packets not already send out to the sync_pipe */
1801 condition *cnd_file_duration = NULL;
1802 condition *cnd_autostop_files = NULL;
1803 condition *cnd_autostop_size = NULL;
1804 condition *cnd_autostop_duration = NULL;
1805 guint32 autostop_files = 0;
1808 gboolean cfilter_error = FALSE;
1809 #define MSG_MAX_LENGTH 4096
1810 char errmsg[MSG_MAX_LENGTH+1];
1811 char secondary_errmsg[MSG_MAX_LENGTH+1];
1812 int save_file_fd = -1;
1815 *secondary_errmsg = '\0';
1817 /* init the loop data */
1818 global_ld.go = TRUE;
1819 global_ld.packet_count = 0;
1820 if (capture_opts->has_autostop_packets)
1821 global_ld.packet_max = capture_opts->autostop_packets;
1823 global_ld.packet_max = 0; /* no limit */
1824 global_ld.err = 0; /* no error seen yet */
1825 global_ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
1826 global_ld.pcap_err = FALSE;
1827 global_ld.from_cap_pipe = FALSE;
1828 global_ld.pdh = NULL;
1829 global_ld.cap_pipe_fd = -1;
1830 #ifdef MUST_DO_SELECT
1831 global_ld.pcap_fd = 0;
1834 /* We haven't yet gotten the capture statistics. */
1835 *stats_known = FALSE;
1839 * Catch SIGUSR1, so that we exit cleanly if the parent process
1840 * kills us with it due to the user selecting "Capture->Stop".
1842 act.sa_handler = capture_loop_stop_signal_handler;
1844 * Arrange that system calls not get restarted, because when
1845 * our signal handler returns we don't want to restart
1846 * a call that was waiting for packets to arrive.
1849 sigemptyset(&act.sa_mask);
1850 sigaction(SIGUSR1, &act, NULL);
1853 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
1854 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
1856 /* open the "input file" from network interface or capture pipe */
1857 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
1858 secondary_errmsg, sizeof(secondary_errmsg))) {
1862 /* init the input filter from the network interface (capture pipe will do nothing) */
1863 switch (capture_loop_init_filter(global_ld.pcap_h, global_ld.from_cap_pipe,
1864 capture_opts->iface,
1865 capture_opts->cfilter)) {
1867 case INITFILTER_NO_ERROR:
1870 case INITFILTER_BAD_FILTER:
1871 cfilter_error = TRUE;
1872 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(global_ld.pcap_h));
1875 case INITFILTER_OTHER_ERROR:
1876 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
1877 pcap_geterr(global_ld.pcap_h));
1878 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
1882 /* If we're supposed to write to a capture file, open it for output
1883 (temporary/specified name/ringbuffer) */
1884 if (capture_opts->saving_to_file) {
1885 if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
1889 /* set up to write to the already-opened capture output file/files */
1890 if (!capture_loop_init_output(capture_opts, save_file_fd, &global_ld,
1891 errmsg, sizeof(errmsg))) {
1895 /* XXX - capture SIGTERM and close the capture, in case we're on a
1896 Linux 2.0[.x] system and you have to explicitly close the capture
1897 stream in order to turn promiscuous mode off? We need to do that
1898 in other places as well - and I don't think that works all the
1899 time in any case, due to libpcap bugs. */
1901 /* Well, we should be able to start capturing.
1903 Sync out the capture file, so the header makes it to the file system,
1904 and send a "capture started successfully and capture file created"
1905 message to our parent so that they'll open the capture file and
1906 update its windows to indicate that we have a live capture in
1908 libpcap_dump_flush(global_ld.pdh, NULL);
1909 report_new_capture_file(capture_opts->save_file);
1912 /* initialize capture stop (and alike) conditions */
1913 init_capture_stop_conditions();
1914 /* create stop conditions */
1915 if (capture_opts->has_autostop_filesize)
1917 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
1918 if (capture_opts->has_autostop_duration)
1919 cnd_autostop_duration =
1920 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
1922 if (capture_opts->multi_files_on) {
1923 if (capture_opts->has_file_duration)
1925 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
1927 if (capture_opts->has_autostop_files)
1928 cnd_autostop_files =
1929 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
1932 /* init the time values */
1933 start_time = TIME_GET();
1934 upd_time = TIME_GET();
1936 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
1938 /* WOW, everything is prepared! */
1939 /* please fasten your seat belts, we will enter now the actual capture loop */
1940 while (global_ld.go) {
1941 /* dispatch incoming packets */
1942 inpkts = capture_loop_dispatch(capture_opts, &global_ld, errmsg,
1946 /* any news from our parent (signal pipe)? -> just stop the capture */
1947 if (!signal_pipe_check_running()) {
1948 global_ld.go = FALSE;
1953 inpkts_to_sync_pipe += inpkts;
1955 /* check capture size condition */
1956 if (cnd_autostop_size != NULL &&
1957 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)){
1958 /* Capture size limit reached, do we have another file? */
1959 if (capture_opts->multi_files_on) {
1960 if (cnd_autostop_files != NULL &&
1961 cnd_eval(cnd_autostop_files, ++autostop_files)) {
1962 /* no files left: stop here */
1963 global_ld.go = FALSE;
1967 /* Switch to the next ringbuffer file */
1968 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
1969 &save_file_fd, &global_ld.bytes_written, &global_ld.err)) {
1970 /* File switch succeeded: reset the conditions */
1971 cnd_reset(cnd_autostop_size);
1972 if (cnd_file_duration) {
1973 cnd_reset(cnd_file_duration);
1975 libpcap_dump_flush(global_ld.pdh, NULL);
1976 report_packet_count(inpkts_to_sync_pipe);
1977 inpkts_to_sync_pipe = 0;
1978 report_new_capture_file(capture_opts->save_file);
1980 /* File switch failed: stop here */
1981 global_ld.go = FALSE;
1985 /* single file, stop now */
1986 global_ld.go = FALSE;
1989 } /* cnd_autostop_size */
1990 if (capture_opts->output_to_pipe) {
1991 libpcap_dump_flush(global_ld.pdh, NULL);
1995 /* Only update once a second (Win32: 500ms) so as not to overload slow
1996 * displays. This also prevents too much context-switching between the
1997 * dumpcap and wireshark processes */
1998 cur_time = TIME_GET();
2000 if ( (cur_time - upd_time) > 500) {
2002 if (cur_time - upd_time > 0) {
2004 upd_time = cur_time;
2006 /*if (pcap_stats(pch, stats) >= 0) {
2007 *stats_known = TRUE;
2010 /* Let the parent process know. */
2011 if (inpkts_to_sync_pipe) {
2013 libpcap_dump_flush(global_ld.pdh, NULL);
2015 /* Send our parent a message saying we've written out "inpkts_to_sync_pipe"
2016 packets to the capture file. */
2017 report_packet_count(inpkts_to_sync_pipe);
2019 inpkts_to_sync_pipe = 0;
2022 /* check capture duration condition */
2023 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
2024 /* The maximum capture time has elapsed; stop the capture. */
2025 global_ld.go = FALSE;
2029 /* check capture file duration condition */
2030 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
2031 /* duration limit reached, do we have another file? */
2032 if (capture_opts->multi_files_on) {
2033 if (cnd_autostop_files != NULL &&
2034 cnd_eval(cnd_autostop_files, ++autostop_files)) {
2035 /* no files left: stop here */
2036 global_ld.go = FALSE;
2040 /* Switch to the next ringbuffer file */
2041 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2042 &save_file_fd, &global_ld.bytes_written,
2044 /* file switch succeeded: reset the conditions */
2045 cnd_reset(cnd_file_duration);
2046 if(cnd_autostop_size)
2047 cnd_reset(cnd_autostop_size);
2048 libpcap_dump_flush(global_ld.pdh, NULL);
2049 report_packet_count(inpkts_to_sync_pipe);
2050 inpkts_to_sync_pipe = 0;
2051 report_new_capture_file(capture_opts->save_file);
2053 /* File switch failed: stop here */
2054 global_ld.go = FALSE;
2058 /* single file, stop now */
2059 global_ld.go = FALSE;
2062 } /* cnd_file_duration */
2065 } /* while (global_ld.go) */
2067 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
2069 /* delete stop conditions */
2070 if (cnd_file_duration != NULL)
2071 cnd_delete(cnd_file_duration);
2072 if (cnd_autostop_files != NULL)
2073 cnd_delete(cnd_autostop_files);
2074 if (cnd_autostop_size != NULL)
2075 cnd_delete(cnd_autostop_size);
2076 if (cnd_autostop_duration != NULL)
2077 cnd_delete(cnd_autostop_duration);
2079 /* did we had a pcap (input) error? */
2080 if (global_ld.pcap_err) {
2081 /* On Linux, if an interface goes down while you're capturing on it,
2082 you'll get a "recvfrom: Network is down" error (ENETDOWN).
2083 (At least you will if strerror() doesn't show a local translation
2086 On FreeBSD and OS X, if a network adapter disappears while
2087 you're capturing on it, you'll get a "read: Device not configured"
2088 error (ENXIO). (See previous parenthetical note.)
2090 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
2092 These should *not* be reported to the Wireshark developers. */
2095 cap_err_str = pcap_geterr(global_ld.pcap_h);
2096 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
2097 strcmp(cap_err_str, "read: Device not configured") == 0 ||
2098 strcmp(cap_err_str, "read: I/O error") == 0) {
2099 report_capture_error("The network adapter on which the capture was being done "
2100 "is no longer running; the capture has stopped.",
2103 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
2105 report_capture_error(errmsg, please_report);
2108 else if (global_ld.from_cap_pipe && global_ld.cap_pipe_err == PIPERR)
2109 report_capture_error(errmsg, "");
2111 /* did we had an error while capturing? */
2112 if (global_ld.err == 0) {
2115 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
2116 global_ld.err, FALSE);
2117 report_capture_error(errmsg, please_report);
2121 if (capture_opts->saving_to_file) {
2122 /* close the wiretap (output) file */
2123 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
2127 /* there might be packets not yet notified to the parent */
2128 /* (do this after closing the file, so all packets are already flushed) */
2129 if(inpkts_to_sync_pipe) {
2130 report_packet_count(inpkts_to_sync_pipe);
2131 inpkts_to_sync_pipe = 0;
2134 /* If we've displayed a message about a write error, there's no point
2135 in displaying another message about an error on close. */
2136 if (!close_ok && write_ok) {
2137 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
2139 report_capture_error(errmsg, "");
2143 * XXX We exhibit different behaviour between normal mode and sync mode
2144 * when the pipe is stdin and not already at EOF. If we're a child, the
2145 * parent's stdin isn't closed, so if the user starts another capture,
2146 * cap_pipe_open_live() will very likely not see the expected magic bytes and
2147 * will say "Unrecognized libpcap format". On the other hand, in normal
2148 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
2151 /* get packet drop statistics from pcap */
2152 if(global_ld.pcap_h != NULL) {
2153 g_assert(!global_ld.from_cap_pipe);
2154 /* Get the capture statistics, so we know how many packets were
2156 if (pcap_stats(global_ld.pcap_h, stats) >= 0) {
2157 *stats_known = TRUE;
2158 /* Let the parent process know. */
2159 report_packet_drops(stats->ps_drop);
2161 g_snprintf(errmsg, sizeof(errmsg),
2162 "Can't get packet-drop statistics: %s",
2163 pcap_geterr(global_ld.pcap_h));
2164 report_capture_error(errmsg, please_report);
2168 /* close the input file (pcap or capture pipe) */
2169 capture_loop_close_input(&global_ld);
2171 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
2173 /* ok, if the write and the close were successful. */
2174 return write_ok && close_ok;
2177 if (capture_opts->multi_files_on) {
2178 /* cleanup ringbuffer */
2179 ringbuf_error_cleanup();
2181 /* We can't use the save file, and we have no FILE * for the stream
2182 to close in order to close it, so close the FD directly. */
2183 if(save_file_fd != -1) {
2184 ws_close(save_file_fd);
2187 /* We couldn't even start the capture, so get rid of the capture
2189 if(capture_opts->save_file != NULL) {
2190 ws_unlink(capture_opts->save_file);
2191 g_free(capture_opts->save_file);
2194 capture_opts->save_file = NULL;
2196 report_cfilter_error(capture_opts->cfilter, errmsg);
2198 report_capture_error(errmsg, secondary_errmsg);
2200 /* close the input file (pcap or cap_pipe) */
2201 capture_loop_close_input(&global_ld);
2203 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
2209 static void capture_loop_stop(void)
2211 #ifdef HAVE_PCAP_BREAKLOOP
2212 if(global_ld.pcap_h != NULL)
2213 pcap_breakloop(global_ld.pcap_h);
2215 global_ld.go = FALSE;
2220 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
2221 int err, gboolean is_close)
2226 g_snprintf(errmsg, errmsglen,
2227 "Not all the packets could be written to the file"
2228 " to which the capture was being saved\n"
2229 "(\"%s\") because there is no space left on the file system\n"
2230 "on which that file resides.",
2236 g_snprintf(errmsg, errmsglen,
2237 "Not all the packets could be written to the file"
2238 " to which the capture was being saved\n"
2239 "(\"%s\") because you are too close to, or over,"
2240 " your disk quota\n"
2241 "on the file system on which that file resides.",
2246 case WTAP_ERR_CANT_CLOSE:
2247 g_snprintf(errmsg, errmsglen,
2248 "The file to which the capture was being saved"
2249 " couldn't be closed for some unknown reason.");
2252 case WTAP_ERR_SHORT_WRITE:
2253 g_snprintf(errmsg, errmsglen,
2254 "Not all the packets could be written to the file"
2255 " to which the capture was being saved\n"
2262 g_snprintf(errmsg, errmsglen,
2263 "The file to which the capture was being saved\n"
2264 "(\"%s\") could not be closed: %s.",
2265 fname, wtap_strerror(err));
2267 g_snprintf(errmsg, errmsglen,
2268 "An error occurred while writing to the file"
2269 " to which the capture was being saved\n"
2271 fname, wtap_strerror(err));
2278 /* one packet was captured, process it */
2280 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
2283 loop_data *ld = (void *) user;
2286 /* if the user told us to stop after x packets, do we already have enough? */
2287 if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
2293 /* We may be called multiple times from pcap_dispatch(); if we've set
2294 the "stop capturing" flag, ignore this packet, as we're not
2295 supposed to be saving any more packets. */
2300 /* We're supposed to write the packet to a file; do so.
2301 If this fails, set "ld->go" to FALSE, to stop the capture, and set
2302 "ld->err" to the error. */
2303 if (!libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err)) {
2312 /* And now our feature presentation... [ fade to music ] */
2314 main(int argc, char *argv[])
2317 extern char *optarg;
2318 gboolean arg_error = FALSE;
2324 struct sigaction action, oldaction;
2327 gboolean start_capture = TRUE;
2328 gboolean stats_known;
2329 struct pcap_stat stats;
2330 GLogLevelFlags log_flags;
2331 gboolean list_interfaces = FALSE;
2332 gboolean list_link_layer_types = FALSE;
2333 gboolean machine_readable = FALSE;
2334 gboolean print_statistics = FALSE;
2335 int status, run_once_args = 0;
2338 #ifdef HAVE_PCAP_REMOTE
2339 #define OPTSTRING_INIT "a:A:b:c:Df:hi:Lm:MprSs:uvw:y:Z:"
2341 #define OPTSTRING_INIT "a:b:c:Df:hi:LMpSs:vw:y:Z:"
2345 #define OPTSTRING_WIN32 "B:"
2347 #define OPTSTRING_WIN32 ""
2350 char optstring[sizeof(OPTSTRING_INIT) + sizeof(OPTSTRING_WIN32) - 1] =
2351 OPTSTRING_INIT OPTSTRING_WIN32;
2353 #ifdef DEBUG_CHILD_DUMPCAP
2354 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
2355 fprintf (stderr, "Unable to open debug log file !\n");
2360 /* Determine if dumpcap is being requested to run in a special */
2361 /* capture_child mode by going thru the command line args to see if */
2362 /* a -Z is present. (-Z is a hidden option). */
2363 /* The primary result of running in capture_child mode is that */
2364 /* all messages sent out on stderr are in a special type/len/string */
2365 /* format to allow message processing by type. */
2366 /* These messages include various 'status' messages which are sent */
2367 /* when an actual capture is in progress. Capture_child mode */
2368 /* would normally be requested by a parent process which invokes */
2369 /* dumpcap and obtains dumpcap stderr output via a pipe to which */
2370 /* dumpcap stderr has been redirected. */
2371 /* Capture_child mode needs to be determined immediately upon */
2372 /* startup so that any messages generated by dumpcap in this mode */
2373 /* (eg: during initialization) will be formatted properly. */
2375 for (i=1; i<argc; i++) {
2376 if (strcmp("-Z", argv[i]) == 0) {
2377 capture_child = TRUE;
2379 /* set output pipe to binary mode, to avoid ugly text conversions */
2380 _setmode(2, O_BINARY);
2385 /* The default_log_handler will use stdout, which makes trouble in */
2386 /* capture child mode, as it uses stdout for it's sync_pipe. */
2387 /* So: the filtering is done in the console_log_handler and not here.*/
2388 /* We set the log handlers right up front to make sure that any log */
2389 /* messages when running as child will be sent back to the parent */
2390 /* with the correct format. */
2394 G_LOG_LEVEL_CRITICAL|
2395 G_LOG_LEVEL_WARNING|
2396 G_LOG_LEVEL_MESSAGE|
2399 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
2401 g_log_set_handler(NULL,
2403 console_log_handler, NULL /* user_data */);
2404 g_log_set_handler(LOG_DOMAIN_MAIN,
2406 console_log_handler, NULL /* user_data */);
2407 g_log_set_handler(LOG_DOMAIN_CAPTURE,
2409 console_log_handler, NULL /* user_data */);
2410 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
2412 console_log_handler, NULL /* user_data */);
2415 /* Load wpcap if possible. Do this before collecting the run-time version information */
2418 /* ... and also load the packet.dll from wpcap */
2419 /* XXX - currently not required, may change later. */
2420 /*wpcap_packet_load();*/
2422 /* Start windows sockets */
2423 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
2425 /* Set handler for Ctrl+C key */
2426 SetConsoleCtrlHandler(capture_cleanup, TRUE);
2428 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
2430 action.sa_handler = capture_cleanup;
2431 action.sa_flags = 0;
2432 sigemptyset(&action.sa_mask);
2433 sigaction(SIGTERM, &action, NULL);
2434 sigaction(SIGINT, &action, NULL);
2435 sigaction(SIGHUP, NULL, &oldaction);
2436 if (oldaction.sa_handler == SIG_DFL)
2437 sigaction(SIGHUP, &action, NULL);
2440 /* ----------------------------------------------------------------- */
2441 /* Privilege and capability handling */
2443 /* 1. Running not as root or suid root; no special capabilities. */
2446 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
2449 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
2451 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
2452 /* capabilities; Drop all other capabilities; */
2453 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2454 /* else: after pcap_open_live() in capture_loop_open_input() */
2455 /* drop all capabilities (NET_RAW and NET_ADMIN); */
2456 /* (Note: this means that the process, although logged in */
2457 /* as root, does not have various permissions such as the */
2458 /* ability to bypass file access permissions). */
2459 /* XXX: Should we just leave capabilities alone in this case */
2460 /* so that user gets expected effect that root can do */
2463 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
2465 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2466 /* else: after pcap_open_live() in capture_loop_open_input() */
2467 /* drop suid root (set euid=ruid).(ie: keep suid until after */
2468 /* pcap_open_live). */
2470 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
2472 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
2473 /* capabilities; Drop all other capabilities; */
2474 /* Drop suid privileges (euid=ruid); */
2475 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2476 /* else: after pcap_open_live() in capture_loop_open_input() */
2477 /* drop all capabilities (NET_RAW and NET_ADMIN). */
2479 /* XXX: For some Linux versions/distros with capabilities */
2480 /* a 'normal' process with any capabilities cannot be */
2481 /* 'killed' (signaled) from another (same uid) non-privileged */
2483 /* For example: If (non-suid) Wireshark forks a */
2484 /* child suid dumpcap which acts as described here (case 5), */
2485 /* Wireshark will be unable to kill (signal) the child */
2486 /* dumpcap process until the capabilities have been dropped */
2487 /* (after pcap_open_live()). */
2488 /* This behaviour will apparently be changed in the kernel */
2489 /* to allow the kill (signal) in this case. */
2490 /* See the following for details: */
2491 /* http://www.mail-archive.com/ [wrapped] */
2492 /* linux-security-module@vger.kernel.org/msg02913.html */
2494 /* It is therefore conceivable that if dumpcap somehow hangs */
2495 /* in pcap_open_live or before that wireshark will not */
2496 /* be able to stop dumpcap using a signal (USR1, TERM, etc). */
2497 /* In this case, exiting wireshark will kill the child */
2498 /* dumpcap process. */
2500 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
2501 /* capabilities; Using libcap. Note: capset cmd (which see) */
2502 /* used to assign capabilities to file. */
2504 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2505 /* else: after pcap_open_live() in capture_loop_open_input() */
2506 /* drop all capabilities (NET_RAW and NET_ADMIN) */
2508 /* ToDo: -S (stats) should drop privileges/capabilities when no */
2509 /* longer required (similar to capture). */
2511 /* ----------------------------------------------------------------- */
2513 get_credential_info();
2516 /* If 'started with special privileges' (and using libcap) */
2517 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
2518 /* Set euid/egid = ruid/rgid to remove suid privileges */
2519 relinquish_privs_except_capture();
2522 /* Set the initial values in the capture options. This might be overwritten
2523 by the command line parameters. */
2524 capture_opts_init(&global_capture_opts, NULL);
2526 /* Default to capturing the entire packet. */
2527 global_capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
2529 /* We always save to a file - if no file was specified, we save to a
2531 global_capture_opts.saving_to_file = TRUE;
2532 global_capture_opts.has_ring_num_files = TRUE;
2534 /* Now get our args */
2535 while ((opt = getopt(argc, argv, optstring)) != -1) {
2537 case 'h': /* Print help and exit */
2541 case 'v': /* Show version and exit */
2543 GString *comp_info_str;
2544 GString *runtime_info_str;
2545 /* Assemble the compile-time version information string */
2546 comp_info_str = g_string_new("Compiled ");
2547 get_compiled_version_info(comp_info_str, NULL);
2549 /* Assemble the run-time version information string */
2550 runtime_info_str = g_string_new("Running ");
2551 get_runtime_version_info(runtime_info_str, NULL);
2552 show_version(comp_info_str, runtime_info_str);
2553 g_string_free(comp_info_str, TRUE);
2554 g_string_free(runtime_info_str, TRUE);
2558 /*** capture option specific ***/
2559 case 'a': /* autostop criteria */
2560 case 'b': /* Ringbuffer option */
2561 case 'c': /* Capture x packets */
2562 case 'f': /* capture filter */
2563 case 'i': /* Use interface x */
2564 case 'p': /* Don't capture in promiscuous mode */
2565 case 's': /* Set the snapshot (capture) length */
2566 case 'w': /* Write to capture file x */
2567 case 'y': /* Set the pcap data link type */
2568 #ifdef HAVE_PCAP_REMOTE
2569 case 'u': /* Use UDP for data transfer */
2570 case 'r': /* Capture own RPCAP traffic too */
2571 case 'A': /* Authentication */
2573 #ifdef HAVE_PCAP_SETSAMPLING
2574 case 'm': /* Sampling */
2577 case 'B': /* Buffer size */
2579 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
2584 /*** hidden option: Wireshark child mode (using binary output messages) ***/
2586 capture_child = TRUE;
2588 /* set output pipe to binary mode, to avoid ugly text conversions */
2589 _setmode(2, O_BINARY);
2591 * optarg = the control ID, aka the PPID, currently used for the
2594 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
2595 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
2596 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
2597 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
2599 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
2600 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2601 "Signal pipe: Unable to open %s. Dead parent?",
2609 /*** all non capture option specific ***/
2610 case 'D': /* Print a list of capture devices and exit */
2611 list_interfaces = TRUE;
2614 case 'L': /* Print list of link-layer types and exit */
2615 list_link_layer_types = TRUE;
2618 case 'S': /* Print interface statistics once a second */
2619 print_statistics = TRUE;
2622 case 'M': /* For -D and -L, print machine-readable output */
2623 machine_readable = TRUE;
2626 case '?': /* Bad flag - print usage message */
2627 cmdarg_err("Invalid Option: %s", argv[optind-1]);
2635 /* user specified file name as regular command-line argument */
2636 /* XXX - use it as the capture file name (or something else)? */
2643 * Extra command line arguments were specified; complain.
2644 * XXX - interpret as capture filter, as tcpdump and tshark do?
2646 cmdarg_err("Invalid argument: %s", argv[0]);
2655 if (run_once_args > 1) {
2656 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
2658 } else if (list_link_layer_types) {
2659 /* We're supposed to list the link-layer types for an interface;
2660 did the user also specify a capture file to be read? */
2661 /* No - did they specify a ring buffer option? */
2662 if (global_capture_opts.multi_files_on) {
2663 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
2667 /* No - was the ring buffer option specified and, if so, does it make
2669 if (global_capture_opts.multi_files_on) {
2670 /* Ring buffer works only under certain conditions:
2671 a) ring buffer does not work with temporary files;
2672 b) it makes no sense to enable the ring buffer if the maximum
2673 file size is set to "infinite". */
2674 if (global_capture_opts.save_file == NULL) {
2675 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
2676 global_capture_opts.multi_files_on = FALSE;
2678 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
2679 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
2680 /* XXX - this must be redesigned as the conditions changed */
2681 /* global_capture_opts.multi_files_on = FALSE;*/
2686 if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
2687 /* cmdarg_err() already called .... */
2691 /* Let the user know what interface was chosen. */
2692 /* get_interface_descriptive_name() is not available! */
2693 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", global_capture_opts.iface);
2695 if (list_interfaces) {
2696 status = capture_opts_list_interfaces(machine_readable);
2698 } else if (list_link_layer_types) {
2699 status = capture_opts_list_link_layer_types(&global_capture_opts, machine_readable);
2701 } else if (print_statistics) {
2702 status = print_statistics_loop(machine_readable);
2706 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
2707 capture_opts_trim_ring_num_files(&global_capture_opts);
2709 /* Now start the capture. */
2711 if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
2715 /* capture failed */
2722 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
2723 const char *message, gpointer user_data _U_)
2730 /* ignore log message, if log_level isn't interesting */
2731 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
2732 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
2737 /* create a "timestamp" */
2739 today = localtime(&curr);
2741 switch(log_level & G_LOG_LEVEL_MASK) {
2742 case G_LOG_LEVEL_ERROR:
2745 case G_LOG_LEVEL_CRITICAL:
2748 case G_LOG_LEVEL_WARNING:
2751 case G_LOG_LEVEL_MESSAGE:
2754 case G_LOG_LEVEL_INFO:
2757 case G_LOG_LEVEL_DEBUG:
2761 fprintf(stderr, "unknown log_level %u\n", log_level);
2763 g_assert_not_reached();
2766 /* Generate the output message */
2767 if(log_level & G_LOG_LEVEL_MESSAGE) {
2768 /* normal user messages without additional infos */
2769 msg = g_strdup_printf("%s\n", message);
2771 /* info/debug messages with additional infos */
2772 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
2773 today->tm_hour, today->tm_min, today->tm_sec,
2774 log_domain != NULL ? log_domain : "",
2778 /* DEBUG & INFO msgs (if we're debugging today) */
2779 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
2780 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
2781 #ifdef DEBUG_DUMPCAP
2782 fprintf(stderr, "%s", msg);
2785 #ifdef DEBUG_CHILD_DUMPCAP
2786 fprintf(debug_log, "%s", msg);
2794 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
2795 /* to parent especially formatted if dumpcap running as child. */
2796 if (capture_child) {
2797 sync_pipe_errmsg_to_parent(2, msg, "");
2799 fprintf(stderr, "%s", msg);
2806 /****************************************************************************************************************/
2807 /* indication report routines */
2811 report_packet_count(int packet_count)
2813 char tmp[SP_DECISIZE+1+1];
2814 static int count = 0;
2817 g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
2818 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
2819 pipe_write_block(2, SP_PACKET_COUNT, tmp);
2821 count += packet_count;
2822 fprintf(stderr, "\rPackets: %u ", count);
2823 /* stderr could be line buffered */
2829 report_new_capture_file(const char *filename)
2832 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
2833 pipe_write_block(2, SP_FILE, filename);
2835 fprintf(stderr, "File: %s\n", filename);
2836 /* stderr could be line buffered */
2842 report_cfilter_error(const char *cfilter, const char *errmsg)
2844 if (capture_child) {
2845 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
2846 pipe_write_block(2, SP_BAD_FILTER, errmsg);
2849 "Invalid capture filter: \"%s\"!\n"
2851 "That string isn't a valid capture filter (%s).\n"
2852 "See the User's Guide for a description of the capture filter syntax.\n",
2858 report_capture_error(const char *error_msg, const char *secondary_error_msg)
2861 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
2862 "Primary Error: %s", error_msg);
2863 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
2864 "Secondary Error: %s", secondary_error_msg);
2865 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
2867 fprintf(stderr, "%s\n%s\n", error_msg, secondary_error_msg);
2872 report_packet_drops(guint32 drops)
2874 char tmp[SP_DECISIZE+1+1];
2876 g_snprintf(tmp, sizeof(tmp), "%u", drops);
2879 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
2880 pipe_write_block(2, SP_DROPS, tmp);
2882 fprintf(stderr, "Packets dropped: %s\n", tmp);
2883 /* stderr could be line buffered */
2889 /****************************************************************************************************************/
2890 /* signal_pipe handling */
2895 signal_pipe_check_running(void)
2897 /* any news from our parent? -> just stop the capture */
2901 /* if we are running standalone, no check required */
2902 if(!capture_child) {
2906 if(!sig_pipe_name || !sig_pipe_handle) {
2907 /* This shouldn't happen */
2908 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2909 "Signal pipe: No name or handle");
2914 * XXX - We should have the process ID of the parent (from the "-Z" flag)
2915 * at this point. Should we check to see if the parent is still alive,
2916 * e.g. by using OpenProcess?
2919 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
2921 if(!result || avail > 0) {
2922 /* peek failed or some bytes really available */
2923 /* (if not piping from stdin this would fail) */
2924 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2925 "Signal pipe: Stop capture: %s", sig_pipe_name);
2926 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
2927 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
2928 sig_pipe_handle, result, avail);
2931 /* pipe ok and no bytes available */