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 "epan/unicode-utils.h"
85 #include "epan/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"
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;
247 static capture_options *capture_opts = &global_capture_opts;
249 static void capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
251 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
252 int err, gboolean is_close);
256 static void exit_main(int err) __attribute__ ((noreturn));
258 static void exit_main(int err);
261 static void report_new_capture_file(const char *filename);
262 static void report_packet_count(int packet_count);
263 static void report_packet_drops(int drops);
264 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
265 static void report_cfilter_error(const char *cfilter, const char *errmsg);
268 static gboolean signal_pipe_check_running(void);
272 print_usage(gboolean print_ver) {
280 "Dumpcap " VERSION "%s\n"
281 "Capture network packets and dump them into a libpcap file.\n"
282 "See http://www.wireshark.org for more information.\n",
283 wireshark_svnversion);
287 fprintf(output, "\nUsage: dumpcap [options] ...\n");
288 fprintf(output, "\n");
289 fprintf(output, "Capture interface:\n");
290 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
291 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
292 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
293 fprintf(output, " -p don't capture in promiscuous mode\n");
295 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
297 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
298 fprintf(output, " -D print list of interfaces and exit\n");
299 fprintf(output, " -L print list of link-layer types of iface and exit\n");
300 fprintf(output, " -S print statistics for each interface once every second\n");
301 fprintf(output, " -M for -D, -L, and -S produce machine-readable output\n");
302 fprintf(output, "\n");
303 #ifdef HAVE_PCAP_REMOTE
304 fprintf(output, "\nRPCAP options:\n");
305 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
306 fprintf(output, " -u use UDP for RPCAP data transfer\n");
307 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
308 #ifdef HAVE_PCAP_SETSAMPLING
309 fprintf(output, " -m <sampling type> use packet sampling\n");
310 fprintf(output, " count:NUM - capture one packet of every NUM\n");
311 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
314 fprintf(output, "Stop conditions:\n");
315 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
316 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
317 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
318 fprintf(output, " files:NUM - stop after NUM files\n");
319 /*fprintf(output, "\n");*/
320 fprintf(output, "Output (files):\n");
321 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
322 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
323 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
324 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
325 /*fprintf(output, "\n");*/
326 fprintf(output, "Miscellaneous:\n");
327 fprintf(output, " -v print version information and exit\n");
328 fprintf(output, " -h display this help and exit\n");
329 fprintf(output, "\n");
330 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcap\n");
331 fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcap\"\n");
332 fprintf(output, "\n");
333 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
337 show_version(GString *comp_info_str, GString *runtime_info_str)
341 "Dumpcap " VERSION "%s\n"
346 "See http://www.wireshark.org for more information.\n",
347 wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
351 * Report an error in command-line arguments.
354 cmdarg_err(const char *fmt, ...)
360 /* Generate a 'special format' message back to parent */
362 msg = g_strdup_vprintf(fmt, ap);
363 sync_pipe_errmsg_to_parent(2, msg, "");
368 fprintf(stderr, "dumpcap: ");
369 vfprintf(stderr, fmt, ap);
370 fprintf(stderr, "\n");
376 * Report additional information for an error in command-line arguments.
379 cmdarg_err_cont(const char *fmt, ...)
386 msg = g_strdup_vprintf(fmt, ap);
387 sync_pipe_errmsg_to_parent(2, msg, "");
392 vfprintf(stderr, fmt, ap);
393 fprintf(stderr, "\n");
401 capture_cleanup(DWORD dwCtrlType)
403 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
404 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
405 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
406 like SIGTERM at least when the machine's shutting down.
408 For now, if we're running as a command rather than a capture child,
409 we handle all but CTRL_LOGOFF_EVENT as indications that we should
410 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
413 If we're not running as a capture child, we might be running as
414 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
415 user logs out. (XXX - can we explicitly check whether we're
416 running as a service?) */
418 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
419 "Console: Control signal");
420 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
421 "Console: Control signal, CtrlType: %u", dwCtrlType);
423 /* Keep capture running if we're a service and a user logs off */
424 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
433 capture_cleanup(int signum)
435 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
436 SIGTERM. We assume that if the user wanted it to keep running
437 after they logged out, they'd have nohupped it. */
439 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
441 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
442 "Console: Signal, signal value: %u", signum);
448 static void exit_main(int status)
451 /* Shutdown windows sockets */
454 /* can be helpful for debugging */
456 printf("Press any key\n");
467 * If we were linked with libcap (not libpcap), make sure we have
468 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
469 * (See comment in main() for details)
473 #if 0 /* Set to enable capability debugging */
474 /* see 'man cap_to_text()' for explanation of output */
475 /* '=' means 'all= ' ie: no capabilities */
476 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
478 print_caps(char *pfx) {
479 cap_t caps = cap_get_proc();
480 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
481 "%s: EUID: %d Capabilities: %s", pfx,
482 geteuid(), cap_to_text(caps, NULL));
485 print_caps(char *pfx _U_) {
490 relinquish_privs_except_capture(void)
492 /* If 'started_with_special_privs' (ie: suid) then enable for
493 * ourself the NET_ADMIN and NET_RAW capabilities and then
494 * drop our suid privileges.
496 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
497 * stuff we don't need (and shouldn't have).
498 * CAP_NET_RAW: Packet capture (raw sockets).
501 if (started_with_special_privs()) {
502 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
503 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
505 cap_t caps = cap_init(); /* all capabilities initialized to off */
507 print_caps("Pre drop, pre set");
509 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
510 cmdarg_err("prctl() fail return: %s", strerror(errno));
513 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
514 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
516 if (cap_set_proc(caps)) {
517 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
519 print_caps("Pre drop, post set");
521 relinquish_special_privs_perm();
523 print_caps("Post drop, pre set");
524 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
525 if (cap_set_proc(caps)) {
526 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
528 print_caps("Post drop, post set");
536 relinquish_all_capabilities()
538 /* Drop any and all capabilities this process may have. */
539 /* Allowed whether or not process has any privileges. */
540 cap_t caps = cap_init(); /* all capabilities initialized to off */
541 print_caps("Pre-clear");
542 if (cap_set_proc(caps)) {
543 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
545 print_caps("Post-clear");
549 #endif /* HAVE_LIBCAP */
551 /* Take care of byte order in the libpcap headers read from pipes.
552 * (function taken from wiretap/libpcap.c) */
554 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
557 /* Byte-swap the record header fields. */
558 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
559 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
560 rechdr->incl_len = BSWAP32(rechdr->incl_len);
561 rechdr->orig_len = BSWAP32(rechdr->orig_len);
564 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
565 swapped, in order to match the BPF header layout.
567 Unfortunately, some files were, according to a comment in the "libpcap"
568 source, written with version 2.3 in their headers but without the
569 interchanged fields, so if "incl_len" is greater than "orig_len" - which
570 would make no sense - we assume that we need to swap them. */
571 if (hdr->version_major == 2 &&
572 (hdr->version_minor < 3 ||
573 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
576 temp = rechdr->orig_len;
577 rechdr->orig_len = rechdr->incl_len;
578 rechdr->incl_len = temp;
582 /* Provide select() functionality for a single file descriptor
583 * on both UNIX/POSIX and Windows.
585 * The Windows version calls WaitForSingleObject instead of
588 * Returns the same values as select. If an error is returned,
589 * the string cap_pipe_err_str should be used instead of errno.
592 cap_pipe_select(int pipe_fd) {
595 struct timeval timeout, *pto;
598 cap_pipe_err_str = "Unknown error";
601 FD_SET(pipe_fd, &rfds);
604 timeout.tv_usec = CAP_READ_TIMEOUT * 1000;
607 sel_ret = select(pipe_fd+1, &rfds, NULL, NULL, pto);
609 cap_pipe_err_str = strerror(errno);
613 /* XXX - Should we just use file handles exclusively under Windows?
614 * Otherwise we have to convert between file handles and file descriptors
615 * here and when we open a named pipe.
617 HANDLE hPipe = (HANDLE) _get_osfhandle(pipe_fd);
621 if (hPipe == INVALID_HANDLE_VALUE) {
622 cap_pipe_err_str = "Could not open standard input";
626 cap_pipe_err_str = "Unknown error";
628 wait_ret = WaitForSingleObject(hPipe, CAP_READ_TIMEOUT);
630 /* XXX - This probably isn't correct */
639 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
640 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
641 cap_pipe_err_str = utf_16to8(err_str);
645 g_assert_not_reached();
652 /* Mimic pcap_open_live() for pipe captures
653 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
655 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
656 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
658 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
659 char *errmsg, int errmsgl)
662 struct stat pipe_stat;
674 unsigned int bytes_read;
676 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
679 * XXX (T)Wireshark blocks until we return
681 if (strcmp(pipename, "-") == 0) {
682 fd = 0; /* read from stdin */
685 * This is needed to set the stdin pipe into binary mode, otherwise
686 * CR/LF are mangled...
688 _setmode(0, _O_BINARY);
692 if (ws_stat(pipename, &pipe_stat) < 0) {
693 if (errno == ENOENT || errno == ENOTDIR)
694 ld->cap_pipe_err = PIPNEXIST;
696 g_snprintf(errmsg, errmsgl,
697 "The capture session could not be initiated "
698 "due to error on pipe: %s", strerror(errno));
699 ld->cap_pipe_err = PIPERR;
703 if (! S_ISFIFO(pipe_stat.st_mode)) {
704 if (S_ISCHR(pipe_stat.st_mode)) {
706 * Assume the user specified an interface on a system where
707 * interfaces are in /dev. Pretend we haven't seen it.
709 ld->cap_pipe_err = PIPNEXIST;
712 g_snprintf(errmsg, errmsgl,
713 "The capture session could not be initiated because\n"
714 "\"%s\" is neither an interface nor a pipe", pipename);
715 ld->cap_pipe_err = PIPERR;
719 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
721 g_snprintf(errmsg, errmsgl,
722 "The capture session could not be initiated "
723 "due to error on pipe open: %s", strerror(errno));
724 ld->cap_pipe_err = PIPERR;
728 #define PIPE_STR "\\pipe\\"
729 /* Under Windows, named pipes _must_ have the form
730 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
732 pncopy = g_strdup(pipename);
733 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
734 pos = strchr(pncopy + 3, '\\');
735 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
742 g_snprintf(errmsg, errmsgl,
743 "The capture session could not be initiated because\n"
744 "\"%s\" is neither an interface nor a pipe", pipename);
745 ld->cap_pipe_err = PIPNEXIST;
749 /* Wait for the pipe to appear */
751 hPipe = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
752 OPEN_EXISTING, 0, NULL);
754 if (hPipe != INVALID_HANDLE_VALUE)
757 if (GetLastError() != ERROR_PIPE_BUSY) {
758 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
759 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
760 g_snprintf(errmsg, errmsgl,
761 "The capture session on \"%s\" could not be initiated "
762 "due to error on pipe open: pipe busy: %s (error %d)",
763 pipename, utf_16to8(err_str), GetLastError());
765 ld->cap_pipe_err = PIPERR;
769 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
770 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
771 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
772 g_snprintf(errmsg, errmsgl,
773 "The capture session could not be initiated "
774 "due to error on named pipe open: %s (error %d)",
775 utf_16to8(err_str), GetLastError());
777 ld->cap_pipe_err = PIPERR;
782 fd = _open_osfhandle((long) hPipe, _O_RDONLY);
784 g_snprintf(errmsg, errmsgl,
785 "The capture session could not be initiated "
786 "due to error on pipe open: %s", strerror(errno));
787 ld->cap_pipe_err = PIPERR;
793 ld->from_cap_pipe = TRUE;
795 /* read the pcap header */
797 while (bytes_read < sizeof magic) {
798 sel_ret = cap_pipe_select(fd);
800 g_snprintf(errmsg, errmsgl,
801 "Unexpected error from select: %s", strerror(errno));
803 } else if (sel_ret > 0) {
804 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
807 g_snprintf(errmsg, errmsgl, "End of file on pipe during open");
809 g_snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
819 /* Host that wrote it has our byte order, and was running
820 a program using either standard or ss990417 libpcap. */
821 ld->cap_pipe_byte_swapped = FALSE;
822 ld->cap_pipe_modified = FALSE;
824 case PCAP_MODIFIED_MAGIC:
825 /* Host that wrote it has our byte order, but was running
826 a program using either ss990915 or ss991029 libpcap. */
827 ld->cap_pipe_byte_swapped = FALSE;
828 ld->cap_pipe_modified = TRUE;
830 case PCAP_SWAPPED_MAGIC:
831 /* Host that wrote it has a byte order opposite to ours,
832 and was running a program using either standard or
834 ld->cap_pipe_byte_swapped = TRUE;
835 ld->cap_pipe_modified = FALSE;
837 case PCAP_SWAPPED_MODIFIED_MAGIC:
838 /* Host that wrote it out has a byte order opposite to
839 ours, and was running a program using either ss990915
840 or ss991029 libpcap. */
841 ld->cap_pipe_byte_swapped = TRUE;
842 ld->cap_pipe_modified = TRUE;
845 /* Not a "libpcap" type we know about. */
846 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
850 /* Read the rest of the header */
852 while (bytes_read < sizeof(struct pcap_hdr)) {
853 sel_ret = cap_pipe_select(fd);
855 g_snprintf(errmsg, errmsgl,
856 "Unexpected error from select: %s", strerror(errno));
858 } else if (sel_ret > 0) {
859 b = read(fd, ((char *)hdr)+bytes_read,
860 sizeof(struct pcap_hdr) - bytes_read);
863 g_snprintf(errmsg, errmsgl, "End of file on pipe during open");
865 g_snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
873 if (ld->cap_pipe_byte_swapped) {
874 /* Byte-swap the header fields about which we care. */
875 hdr->version_major = BSWAP16(hdr->version_major);
876 hdr->version_minor = BSWAP16(hdr->version_minor);
877 hdr->snaplen = BSWAP32(hdr->snaplen);
878 hdr->network = BSWAP32(hdr->network);
880 ld->linktype = hdr->network;
882 if (hdr->version_major < 2) {
883 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
887 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
888 ld->cap_pipe_err = PIPOK;
892 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
893 ld->cap_pipe_err = PIPERR;
900 /* We read one record from the pipe, take care of byte order in the record
901 * header, write the record to the capture file, and update capture statistics. */
903 cap_pipe_dispatch(loop_data *ld, guchar *data, char *errmsg, int errmsgl)
905 struct pcap_pkthdr phdr;
907 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
911 #ifdef LOG_CAPTURE_VERBOSE
912 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
915 switch (ld->cap_pipe_state) {
917 case STATE_EXPECT_REC_HDR:
918 ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
919 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
920 ld->cap_pipe_bytes_read = 0;
921 ld->cap_pipe_state = STATE_READ_REC_HDR;
924 case STATE_READ_REC_HDR:
925 b = read(ld->cap_pipe_fd, ((char *)&ld->cap_pipe_rechdr)+ld->cap_pipe_bytes_read,
926 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
929 result = PD_PIPE_EOF;
931 result = PD_PIPE_ERR;
934 if ((ld->cap_pipe_bytes_read += b) < ld->cap_pipe_bytes_to_read)
936 result = PD_REC_HDR_READ;
939 case STATE_EXPECT_DATA:
940 ld->cap_pipe_bytes_read = 0;
941 ld->cap_pipe_state = STATE_READ_DATA;
944 case STATE_READ_DATA:
945 b = read(ld->cap_pipe_fd, data+ld->cap_pipe_bytes_read,
946 ld->cap_pipe_rechdr.hdr.incl_len - ld->cap_pipe_bytes_read);
949 result = PD_PIPE_EOF;
951 result = PD_PIPE_ERR;
954 if ((ld->cap_pipe_bytes_read += b) < ld->cap_pipe_rechdr.hdr.incl_len)
956 result = PD_DATA_READ;
960 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
963 } /* switch (ld->cap_pipe_state) */
966 * We've now read as much data as we were expecting, so process it.
970 case PD_REC_HDR_READ:
971 /* We've read the header. Take care of byte order. */
972 cap_pipe_adjust_header(ld->cap_pipe_byte_swapped, &ld->cap_pipe_hdr,
973 &ld->cap_pipe_rechdr.hdr);
974 if (ld->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
975 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
976 ld->packet_count+1, ld->cap_pipe_rechdr.hdr.incl_len);
979 ld->cap_pipe_state = STATE_EXPECT_DATA;
983 /* Fill in a "struct pcap_pkthdr", and process the packet. */
984 phdr.ts.tv_sec = ld->cap_pipe_rechdr.hdr.ts_sec;
985 phdr.ts.tv_usec = ld->cap_pipe_rechdr.hdr.ts_usec;
986 phdr.caplen = ld->cap_pipe_rechdr.hdr.incl_len;
987 phdr.len = ld->cap_pipe_rechdr.hdr.orig_len;
989 capture_loop_packet_cb((u_char *)ld, &phdr, data);
991 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
995 ld->cap_pipe_err = PIPEOF;
999 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
1006 ld->cap_pipe_err = PIPERR;
1007 /* Return here rather than inside the switch to prevent GCC warning */
1012 /** Open the capture input file (pcap or capture pipe).
1013 * Returns TRUE if it succeeds, FALSE otherwise. */
1015 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
1016 char *errmsg, size_t errmsg_len,
1017 char *secondary_errmsg, size_t secondary_errmsg_len)
1019 gchar open_err_str[PCAP_ERRBUF_SIZE];
1020 gchar *sync_msg_str;
1021 static const char ppamsg[] = "can't find PPA for ";
1022 const char *set_linktype_err_str;
1023 const char *libpcap_warn;
1025 gchar *sync_secondary_msg_str;
1027 WORD wVersionRequested;
1030 #ifdef HAVE_PCAP_REMOTE
1031 struct pcap_rmtauth auth;
1035 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
1038 /* XXX - opening Winsock on tshark? */
1040 /* Initialize Windows Socket if we are in a WIN32 OS
1041 This needs to be done before querying the interface for network/netmask */
1043 /* XXX - do we really require 1.1 or earlier?
1044 Are there any versions that support only 2.0 or higher? */
1045 wVersionRequested = MAKEWORD(1, 1);
1046 err = WSAStartup(wVersionRequested, &wsaData);
1050 case WSASYSNOTREADY:
1051 g_snprintf(errmsg, errmsg_len,
1052 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
1055 case WSAVERNOTSUPPORTED:
1056 g_snprintf(errmsg, errmsg_len,
1057 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
1058 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
1061 case WSAEINPROGRESS:
1062 g_snprintf(errmsg, errmsg_len,
1063 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
1067 g_snprintf(errmsg, errmsg_len,
1068 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
1072 g_snprintf(errmsg, errmsg_len,
1073 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
1077 g_snprintf(errmsg, errmsg_len,
1078 "Couldn't initialize Windows Sockets: error %d", err);
1081 g_snprintf(secondary_errmsg, secondary_errmsg_len, please_report);
1086 /* Open the network interface to capture from it.
1087 Some versions of libpcap may put warnings into the error buffer
1088 if they succeed; to tell if that's happened, we have to clear
1089 the error buffer, and check if it's still a null string. */
1090 open_err_str[0] = '\0';
1091 #ifdef HAVE_PCAP_OPEN
1092 auth.type = capture_opts->auth_type == CAPTURE_AUTH_PWD ?
1093 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
1094 auth.username = capture_opts->auth_username;
1095 auth.password = capture_opts->auth_password;
1097 ld->pcap_h = pcap_open(capture_opts->iface,
1098 capture_opts->has_snaplen ? capture_opts->snaplen :
1099 WTAP_MAX_PACKET_SIZE,
1101 (capture_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
1102 (capture_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
1103 (capture_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
1104 CAP_READ_TIMEOUT, &auth, open_err_str);
1106 ld->pcap_h = pcap_open_live(capture_opts->iface,
1107 capture_opts->has_snaplen ? capture_opts->snaplen :
1108 WTAP_MAX_PACKET_SIZE,
1109 capture_opts->promisc_mode, CAP_READ_TIMEOUT,
1113 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
1114 /* to remove any suid privileges. */
1115 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
1116 /* (euid/egid have already previously been set to ruid/rgid. */
1117 /* (See comment in main() for details) */
1119 relinquish_special_privs_perm();
1121 relinquish_all_capabilities();
1124 if (ld->pcap_h != NULL) {
1125 /* we've opened "iface" as a network device */
1127 /* try to set the capture buffer size */
1128 if (pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
1129 sync_secondary_msg_str = g_strdup_printf(
1130 "The capture buffer size of %luMB seems to be too high for your machine,\n"
1131 "the default of 1MB will be used.\n"
1133 "Nonetheless, the capture is started.\n",
1134 capture_opts->buffer_size);
1135 report_capture_error("Couldn't set the capture buffer size!",
1136 sync_secondary_msg_str);
1137 g_free(sync_secondary_msg_str);
1141 #if defined(HAVE_PCAP_REMOTE) && defined(HAVE_PCAP_SETSAMPLING)
1142 if (capture_opts->sampling_method != CAPTURE_SAMP_NONE)
1144 struct pcap_samp *samp;
1146 if ((samp = pcap_setsampling(ld->pcap_h)) != NULL)
1148 switch (capture_opts->sampling_method)
1150 case CAPTURE_SAMP_BY_COUNT:
1151 samp->method = PCAP_SAMP_1_EVERY_N;
1154 case CAPTURE_SAMP_BY_TIMER:
1155 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
1159 sync_msg_str = g_strdup_printf(
1160 "Unknown sampling method %d specified,\n"
1161 "continue without packet sampling",
1162 capture_opts->sampling_method);
1163 report_capture_error("Couldn't set the capture "
1164 "sampling", sync_msg_str);
1165 g_free(sync_msg_str);
1167 samp->value = capture_opts->sampling_param;
1171 report_capture_error("Couldn't set the capture sampling",
1172 "Cannot get packet sampling data structure");
1178 /* setting the data link type only works on real interfaces */
1179 if (capture_opts->linktype != -1) {
1180 set_linktype_err_str = set_pcap_linktype(ld->pcap_h, capture_opts->iface,
1181 capture_opts->linktype);
1182 if (set_linktype_err_str != NULL) {
1183 g_snprintf(errmsg, errmsg_len, "Unable to set data link type (%s).",
1184 set_linktype_err_str);
1185 g_snprintf(secondary_errmsg, secondary_errmsg_len, please_report);
1189 ld->linktype = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
1191 /* We couldn't open "iface" as a network device. */
1192 /* Try to open it as a pipe */
1193 ld->cap_pipe_fd = cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, errmsg_len);
1195 if (ld->cap_pipe_fd == -1) {
1197 if (ld->cap_pipe_err == PIPNEXIST) {
1198 /* Pipe doesn't exist, so output message for interface */
1200 /* If we got a "can't find PPA for X" message, warn the user (who
1201 is running (T)Wireshark on HP-UX) that they don't have a version
1202 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1203 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1204 PPA for X" rather than "can't find PPA for X"). */
1205 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1208 "You are running (T)Wireshark with a version of the libpcap library\n"
1209 "that doesn't handle HP-UX network devices well; this means that\n"
1210 "(T)Wireshark may not be able to capture packets.\n"
1212 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1213 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1214 "packaged binary form from the Software Porting And Archive Centre\n"
1215 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1216 "at the URL lists a number of mirror sites.";
1219 g_snprintf(errmsg, errmsg_len,
1220 "The capture session could not be initiated (%s).", open_err_str);
1222 g_snprintf(secondary_errmsg, secondary_errmsg_len,
1223 "Please check to make sure you have sufficient permissions, and that you have "
1224 "the proper interface or pipe specified.%s", libpcap_warn);
1226 g_snprintf(secondary_errmsg, secondary_errmsg_len,
1228 "Please check that \"%s\" is the proper interface.\n"
1231 "Help can be found at:\n"
1233 " http://wiki.wireshark.org/CaptureSetup\n"
1236 "WinPcap does not support 64-bit Windows; you will have to use some other\n"
1237 "tool to capture traffic, such as netcap.\n"
1238 "For netcap details see: http://support.microsoft.com/?id=310875\n"
1240 "Modem (PPP/WAN):\n"
1241 "Note that version 3.0 of WinPcap, and earlier versions of WinPcap, don't\n"
1242 "support capturing on PPP/WAN interfaces on Windows NT 4.0 / 2000 / XP /\n"
1244 "WinPcap 3.1 has support for it on Windows 2000 / XP / Server 2003, but has no\n"
1245 "support for it on Windows NT 4.0 or Windows Vista (Beta 1).",
1246 capture_opts->iface);
1250 * Else pipe (or file) does exist and cap_pipe_open_live() has
1255 /* cap_pipe_open_live() succeeded; don't want
1256 error message from pcap_open_live() */
1257 open_err_str[0] = '\0';
1260 /* XXX - will this work for tshark? */
1261 #ifdef MUST_DO_SELECT
1262 if (!ld->from_cap_pipe) {
1263 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
1264 ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
1266 ld->pcap_fd = pcap_fileno(ld->pcap_h);
1271 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1272 returned a warning; print it, but keep capturing. */
1273 if (open_err_str[0] != '\0') {
1274 sync_msg_str = g_strdup_printf("%s.", open_err_str);
1275 report_capture_error(sync_msg_str, "");
1276 g_free(sync_msg_str);
1283 /* close the capture input file (pcap or capture pipe) */
1284 static void capture_loop_close_input(loop_data *ld) {
1286 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
1288 /* if open, close the capture pipe "input file" */
1289 if (ld->cap_pipe_fd >= 0) {
1290 g_assert(ld->from_cap_pipe);
1291 ws_close(ld->cap_pipe_fd);
1292 ld->cap_pipe_fd = 0;
1295 /* if open, close the pcap "input file" */
1296 if(ld->pcap_h != NULL) {
1297 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", ld->pcap_h);
1298 g_assert(!ld->from_cap_pipe);
1299 pcap_close(ld->pcap_h);
1306 /* Shut down windows sockets */
1312 /* init the capture filter */
1313 static initfilter_status_t
1314 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe, gchar * iface, gchar * cfilter) {
1315 bpf_u_int32 netnum, netmask;
1316 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
1317 struct bpf_program fcode;
1320 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
1322 /* capture filters only work on real interfaces */
1323 if (cfilter && !from_cap_pipe) {
1324 /* A capture filter was specified; set it up. */
1325 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1327 * Well, we can't get the netmask for this interface; it's used
1328 * only for filters that check for broadcast IP addresses, so
1329 * we just punt and use 0. It might be nice to warn the user,
1330 * but that's a pain in a GUI application, as it'd involve popping
1331 * up a message box, and it's not clear how often this would make
1332 * a difference (only filters that check for IP broadcast addresses
1336 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
1339 if (pcap_compile(pcap_h, &fcode, cfilter, 1, netmask) < 0) {
1340 /* Treat this specially - our caller might try to compile this
1341 as a display filter and, if that succeeds, warn the user that
1342 the display and capture filter syntaxes are different. */
1343 return INITFILTER_BAD_FILTER;
1345 if (pcap_setfilter(pcap_h, &fcode) < 0) {
1346 #ifdef HAVE_PCAP_FREECODE
1347 pcap_freecode(&fcode);
1349 return INITFILTER_OTHER_ERROR;
1351 #ifdef HAVE_PCAP_FREECODE
1352 pcap_freecode(&fcode);
1356 return INITFILTER_NO_ERROR;
1360 /* set up to write to the already-opened capture output file/files */
1362 capture_loop_init_output(capture_options *capture_opts, int save_file_fd, loop_data *ld, char *errmsg, int errmsg_len) {
1367 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
1370 if (ld->from_cap_pipe) {
1371 file_snaplen = ld->cap_pipe_hdr.snaplen;
1374 file_snaplen = pcap_snapshot(ld->pcap_h);
1377 /* Set up to write to the capture file. */
1378 if (capture_opts->multi_files_on) {
1379 ld->pdh = ringbuf_init_libpcap_fdopen(ld->linktype, file_snaplen,
1380 &ld->bytes_written, &err);
1382 ld->pdh = libpcap_fdopen(save_file_fd, ld->linktype, file_snaplen,
1383 &ld->bytes_written, &err);
1386 if (ld->pdh == NULL) {
1387 /* We couldn't set up to write to the capture file. */
1388 /* XXX - use cf_open_error_message from tshark instead? */
1391 case WTAP_ERR_CANT_OPEN:
1392 g_snprintf(errmsg, errmsg_len, "The file to which the capture would be saved"
1393 " couldn't be created for some unknown reason.");
1396 case WTAP_ERR_SHORT_WRITE:
1397 g_snprintf(errmsg, errmsg_len, "A full header couldn't be written to the file"
1398 " to which the capture would be saved.");
1403 g_snprintf(errmsg, errmsg_len,
1404 "The file to which the capture would be"
1405 " saved (\"%s\") could not be opened: Error %d.",
1406 capture_opts->save_file, err);
1408 g_snprintf(errmsg, errmsg_len,
1409 "The file to which the capture would be"
1410 " saved (\"%s\") could not be opened: %s.",
1411 capture_opts->save_file, strerror(err));
1423 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
1425 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
1427 if (capture_opts->multi_files_on) {
1428 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
1430 return libpcap_dump_close(ld->pdh, err_close);
1434 /* dispatch incoming packets (pcap or capture pipe)
1436 * Waits for incoming packets to be available, and calls pcap_dispatch()
1437 * to cause them to be processed.
1439 * Returns the number of packets which were processed.
1441 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
1442 * packet-batching behaviour does not cause packets to get held back
1446 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
1447 char *errmsg, int errmsg_len)
1451 gint packet_count_before;
1452 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1454 packet_count_before = ld->packet_count;
1455 if (ld->from_cap_pipe) {
1456 /* dispatch from capture pipe */
1457 #ifdef LOG_CAPTURE_VERBOSE
1458 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
1460 sel_ret = cap_pipe_select(ld->cap_pipe_fd);
1463 if (sel_ret < 0 && errno != EINTR) {
1464 g_snprintf(errmsg, errmsg_len,
1465 "Unexpected error from select: %s", strerror(errno));
1466 report_capture_error(errmsg, please_report);
1471 * "select()" says we can read from the pipe without blocking
1473 inpkts = cap_pipe_dispatch(ld, pcap_data, errmsg, errmsg_len);
1481 /* dispatch from pcap */
1482 #ifdef MUST_DO_SELECT
1484 * If we have "pcap_get_selectable_fd()", we use it to get the
1485 * descriptor on which to select; if that's -1, it means there
1486 * is no descriptor on which you can do a "select()" (perhaps
1487 * because you're capturing on a special device, and that device's
1488 * driver unfortunately doesn't support "select()", in which case
1489 * we don't do the select - which means it might not be possible
1490 * to stop a capture until a packet arrives. If that's unacceptable,
1491 * plead with whoever supplies the software for that device to add
1492 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
1493 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
1494 * later, so it can use pcap_breakloop().
1496 #ifdef LOG_CAPTURE_VERBOSE
1497 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
1499 if (ld->pcap_fd != -1) {
1500 sel_ret = cap_pipe_select(ld->pcap_fd);
1503 * "select()" says we can read from it without blocking; go for
1506 * We don't have pcap_breakloop(), so we only process one packet
1507 * per pcap_dispatch() call, to allow a signal to stop the
1508 * processing immediately, rather than processing all packets
1509 * in a batch before quitting.
1511 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb,
1514 ld->pcap_err = TRUE;
1515 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1518 if (sel_ret < 0 && errno != EINTR) {
1519 g_snprintf(errmsg, errmsg_len,
1520 "Unexpected error from select: %s", strerror(errno));
1521 report_capture_error(errmsg, please_report);
1527 #endif /* MUST_DO_SELECT */
1529 /* dispatch from pcap without select */
1531 #ifdef LOG_CAPTURE_VERBOSE
1532 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
1536 * On Windows, we don't support asynchronously telling a process to
1537 * stop capturing; instead, we check for an indication on a pipe
1538 * after processing packets. We therefore process only one packet
1539 * at a time, so that we can check the pipe after every packet.
1541 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb, (u_char *) ld);
1543 inpkts = pcap_dispatch(ld->pcap_h, -1, capture_loop_packet_cb, (u_char *) ld);
1547 /* Error, rather than pcap_breakloop(). */
1548 ld->pcap_err = TRUE;
1550 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1552 #else /* pcap_next_ex */
1553 #ifdef LOG_CAPTURE_VERBOSE
1554 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
1556 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
1559 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
1560 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
1561 * This should be fixed in the WinPcap 4.0 alpha release.
1563 * For reference, an example remote interface:
1564 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
1567 /* emulate dispatch from pcap */
1570 struct pcap_pkthdr *pkt_header;
1575 (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1)
1576 capture_loop_packet_cb( (u_char *) ld, pkt_header, pkt_data);
1579 ld->pcap_err = TRUE;
1583 #endif /* pcap_next_ex */
1587 #ifdef LOG_CAPTURE_VERBOSE
1588 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
1591 return ld->packet_count - packet_count_before;
1595 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
1596 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
1598 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
1599 char *errmsg, int errmsg_len) {
1601 char tmpname[128+1];
1602 gchar *capfile_name;
1603 gboolean is_tempfile;
1606 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
1607 (capture_opts->save_file) ? capture_opts->save_file : "");
1609 if (capture_opts->save_file != NULL) {
1610 /* We return to the caller while the capture is in progress.
1611 * Therefore we need to take a copy of save_file in
1612 * case the caller destroys it after we return.
1614 capfile_name = g_strdup(capture_opts->save_file);
1616 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
1617 if (capture_opts->multi_files_on) {
1618 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
1619 g_snprintf(errmsg, errmsg_len,
1620 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
1621 g_free(capfile_name);
1624 if (strcmp(capfile_name, "-") == 0) {
1625 /* write to stdout */
1628 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
1629 _setmode(1, O_BINARY);
1632 } /* if (...output_to_pipe ... */
1635 if (capture_opts->multi_files_on) {
1636 /* ringbuffer is enabled */
1637 *save_file_fd = ringbuf_init(capfile_name,
1638 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
1640 /* we need the ringbuf name */
1641 if(*save_file_fd != -1) {
1642 g_free(capfile_name);
1643 capfile_name = g_strdup(ringbuf_current_filename());
1646 /* Try to open/create the specified file for use as a capture buffer. */
1647 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
1651 is_tempfile = FALSE;
1653 /* Choose a random name for the temporary capture buffer */
1654 *save_file_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
1655 capfile_name = g_strdup(tmpname);
1659 /* did we fail to open the output file? */
1660 if (*save_file_fd == -1) {
1662 g_snprintf(errmsg, errmsg_len,
1663 "The temporary file to which the capture would be saved (\"%s\") "
1664 "could not be opened: %s.", capfile_name, strerror(errno));
1666 if (capture_opts->multi_files_on) {
1667 ringbuf_error_cleanup();
1670 g_snprintf(errmsg, errmsg_len,
1671 "The file to which the capture would be saved (\"%s\") "
1672 "could not be opened: %s.", capfile_name,
1675 g_free(capfile_name);
1679 if(capture_opts->save_file != NULL) {
1680 g_free(capture_opts->save_file);
1682 capture_opts->save_file = capfile_name;
1683 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
1684 "g_free(capfile_name)". */
1686 fchown(*save_file_fd, capture_opts->owner, capture_opts->group);
1694 capture_loop_stop_signal_handler(int signo _U_)
1696 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Signal: Stop capture");
1697 capture_loop_stop();
1701 #define TIME_GET() GetTickCount()
1703 #define TIME_GET() time(NULL)
1706 /* Do the low-level work of a capture.
1707 Returns TRUE if it succeeds, FALSE otherwise. */
1709 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
1712 struct sigaction act;
1714 time_t upd_time, cur_time;
1718 gint inpkts_to_sync_pipe = 0; /* packets not already send out to the sync_pipe */
1719 condition *cnd_file_duration = NULL;
1720 condition *cnd_autostop_files = NULL;
1721 condition *cnd_autostop_size = NULL;
1722 condition *cnd_autostop_duration = NULL;
1723 guint32 autostop_files = 0;
1726 gboolean cfilter_error = FALSE;
1727 #define MSG_MAX_LENGTH 4096
1728 char errmsg[MSG_MAX_LENGTH+1];
1729 char secondary_errmsg[MSG_MAX_LENGTH+1];
1730 int save_file_fd = -1;
1733 *secondary_errmsg = '\0';
1735 /* init the loop data */
1737 ld.packet_count = 0;
1738 if (capture_opts->has_autostop_packets)
1739 ld.packet_max = capture_opts->autostop_packets;
1741 ld.packet_max = 0; /* no limit */
1742 ld.err = 0; /* no error seen yet */
1743 ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
1744 ld.pcap_err = FALSE;
1745 ld.from_cap_pipe = FALSE;
1747 ld.cap_pipe_fd = -1;
1748 #ifdef MUST_DO_SELECT
1752 /* We haven't yet gotten the capture statistics. */
1753 *stats_known = FALSE;
1757 * Catch SIGUSR1, so that we exit cleanly if the parent process
1758 * kills us with it due to the user selecting "Capture->Stop".
1760 act.sa_handler = capture_loop_stop_signal_handler;
1762 * Arrange that system calls not get restarted, because when
1763 * our signal handler returns we don't want to restart
1764 * a call that was waiting for packets to arrive.
1767 sigemptyset(&act.sa_mask);
1768 sigaction(SIGUSR1, &act, NULL);
1771 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
1772 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
1774 /* open the "input file" from network interface or capture pipe */
1775 if (!capture_loop_open_input(capture_opts, &ld, errmsg, sizeof(errmsg),
1776 secondary_errmsg, sizeof(secondary_errmsg))) {
1780 /* init the input filter from the network interface (capture pipe will do nothing) */
1781 switch (capture_loop_init_filter(ld.pcap_h, ld.from_cap_pipe, capture_opts->iface, capture_opts->cfilter)) {
1783 case INITFILTER_NO_ERROR:
1786 case INITFILTER_BAD_FILTER:
1787 cfilter_error = TRUE;
1788 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(ld.pcap_h));
1791 case INITFILTER_OTHER_ERROR:
1792 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
1793 pcap_geterr(ld.pcap_h));
1794 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
1798 /* If we're supposed to write to a capture file, open it for output
1799 (temporary/specified name/ringbuffer) */
1800 if (capture_opts->saving_to_file) {
1801 if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
1805 /* set up to write to the already-opened capture output file/files */
1806 if (!capture_loop_init_output(capture_opts, save_file_fd, &ld, errmsg, sizeof(errmsg))) {
1810 /* XXX - capture SIGTERM and close the capture, in case we're on a
1811 Linux 2.0[.x] system and you have to explicitly close the capture
1812 stream in order to turn promiscuous mode off? We need to do that
1813 in other places as well - and I don't think that works all the
1814 time in any case, due to libpcap bugs. */
1816 /* Well, we should be able to start capturing.
1818 Sync out the capture file, so the header makes it to the file system,
1819 and send a "capture started successfully and capture file created"
1820 message to our parent so that they'll open the capture file and
1821 update its windows to indicate that we have a live capture in
1823 libpcap_dump_flush(ld.pdh, NULL);
1824 report_new_capture_file(capture_opts->save_file);
1827 /* initialize capture stop (and alike) conditions */
1828 init_capture_stop_conditions();
1829 /* create stop conditions */
1830 if (capture_opts->has_autostop_filesize)
1832 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
1833 if (capture_opts->has_autostop_duration)
1834 cnd_autostop_duration =
1835 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
1837 if (capture_opts->multi_files_on) {
1838 if (capture_opts->has_file_duration)
1840 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
1842 if (capture_opts->has_autostop_files)
1843 cnd_autostop_files =
1844 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
1847 /* init the time values */
1848 start_time = TIME_GET();
1849 upd_time = TIME_GET();
1851 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
1853 /* WOW, everything is prepared! */
1854 /* please fasten your seat belts, we will enter now the actual capture loop */
1856 /* dispatch incoming packets */
1857 inpkts = capture_loop_dispatch(capture_opts, &ld, errmsg, sizeof(errmsg));
1860 /* any news from our parent (signal pipe)? -> just stop the capture */
1861 if (!signal_pipe_check_running()) {
1867 inpkts_to_sync_pipe += inpkts;
1869 /* check capture size condition */
1870 if (cnd_autostop_size != NULL &&
1871 cnd_eval(cnd_autostop_size, (guint32)ld.bytes_written)){
1872 /* Capture size limit reached, do we have another file? */
1873 if (capture_opts->multi_files_on) {
1874 if (cnd_autostop_files != NULL &&
1875 cnd_eval(cnd_autostop_files, ++autostop_files)) {
1876 /* no files left: stop here */
1881 /* Switch to the next ringbuffer file */
1882 if (ringbuf_switch_file(&ld.pdh, &capture_opts->save_file,
1883 &save_file_fd, &ld.bytes_written, &ld.err)) {
1884 /* File switch succeeded: reset the conditions */
1885 cnd_reset(cnd_autostop_size);
1886 if (cnd_file_duration) {
1887 cnd_reset(cnd_file_duration);
1889 libpcap_dump_flush(ld.pdh, NULL);
1890 report_packet_count(inpkts_to_sync_pipe);
1891 inpkts_to_sync_pipe = 0;
1892 report_new_capture_file(capture_opts->save_file);
1894 /* File switch failed: stop here */
1899 /* single file, stop now */
1903 } /* cnd_autostop_size */
1904 if (capture_opts->output_to_pipe) {
1905 libpcap_dump_flush(ld.pdh, NULL);
1909 /* Only update once a second (Win32: 500ms) so as not to overload slow
1910 * displays. This also prevents too much context-switching between the
1911 * dumpcap and wireshark processes */
1912 cur_time = TIME_GET();
1914 if ( (cur_time - upd_time) > 500) {
1916 if (cur_time - upd_time > 0) {
1918 upd_time = cur_time;
1920 /*if (pcap_stats(pch, stats) >= 0) {
1921 *stats_known = TRUE;
1924 /* Let the parent process know. */
1925 if (inpkts_to_sync_pipe) {
1927 libpcap_dump_flush(ld.pdh, NULL);
1929 /* Send our parent a message saying we've written out "inpkts_to_sync_pipe"
1930 packets to the capture file. */
1931 report_packet_count(inpkts_to_sync_pipe);
1933 inpkts_to_sync_pipe = 0;
1936 /* check capture duration condition */
1937 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
1938 /* The maximum capture time has elapsed; stop the capture. */
1943 /* check capture file duration condition */
1944 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
1945 /* duration limit reached, do we have another file? */
1946 if (capture_opts->multi_files_on) {
1947 if (cnd_autostop_files != NULL &&
1948 cnd_eval(cnd_autostop_files, ++autostop_files)) {
1949 /* no files left: stop here */
1954 /* Switch to the next ringbuffer file */
1955 if (ringbuf_switch_file(&ld.pdh, &capture_opts->save_file,
1956 &save_file_fd, &ld.bytes_written, &ld.err)) {
1957 /* file switch succeeded: reset the conditions */
1958 cnd_reset(cnd_file_duration);
1959 if(cnd_autostop_size)
1960 cnd_reset(cnd_autostop_size);
1961 libpcap_dump_flush(ld.pdh, NULL);
1962 report_packet_count(inpkts_to_sync_pipe);
1963 inpkts_to_sync_pipe = 0;
1964 report_new_capture_file(capture_opts->save_file);
1966 /* File switch failed: stop here */
1971 /* single file, stop now */
1975 } /* cnd_file_duration */
1978 } /* while (ld.go) */
1980 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
1982 /* delete stop conditions */
1983 if (cnd_file_duration != NULL)
1984 cnd_delete(cnd_file_duration);
1985 if (cnd_autostop_files != NULL)
1986 cnd_delete(cnd_autostop_files);
1987 if (cnd_autostop_size != NULL)
1988 cnd_delete(cnd_autostop_size);
1989 if (cnd_autostop_duration != NULL)
1990 cnd_delete(cnd_autostop_duration);
1992 /* did we had a pcap (input) error? */
1994 /* On Linux, if an interface goes down while you're capturing on it,
1995 you'll get a "recvfrom: Network is down" error (ENETDOWN).
1996 (At least you will if strerror() doesn't show a local translation
1999 On FreeBSD and OS X, if a network adapter disappears while
2000 you're capturing on it, you'll get a "read: Device not configured"
2001 error (ENXIO). (See previous parenthetical note.)
2003 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
2005 These should *not* be reported to the Wireshark developers. */
2008 cap_err_str = pcap_geterr(ld.pcap_h);
2009 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
2010 strcmp(cap_err_str, "read: Device not configured") == 0 ||
2011 strcmp(cap_err_str, "read: I/O error") == 0) {
2012 report_capture_error("The network adapter on which the capture was being done "
2013 "is no longer running; the capture has stopped.",
2016 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
2018 report_capture_error(errmsg, please_report);
2021 else if (ld.from_cap_pipe && ld.cap_pipe_err == PIPERR)
2022 report_capture_error(errmsg, "");
2024 /* did we had an error while capturing? */
2028 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, ld.err,
2030 report_capture_error(errmsg, please_report);
2034 if (capture_opts->saving_to_file) {
2035 /* close the wiretap (output) file */
2036 close_ok = capture_loop_close_output(capture_opts, &ld, &err_close);
2040 /* there might be packets not yet notified to the parent */
2041 /* (do this after closing the file, so all packets are already flushed) */
2042 if(inpkts_to_sync_pipe) {
2043 report_packet_count(inpkts_to_sync_pipe);
2044 inpkts_to_sync_pipe = 0;
2047 /* If we've displayed a message about a write error, there's no point
2048 in displaying another message about an error on close. */
2049 if (!close_ok && write_ok) {
2050 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
2052 report_capture_error(errmsg, "");
2056 * XXX We exhibit different behaviour between normal mode and sync mode
2057 * when the pipe is stdin and not already at EOF. If we're a child, the
2058 * parent's stdin isn't closed, so if the user starts another capture,
2059 * cap_pipe_open_live() will very likely not see the expected magic bytes and
2060 * will say "Unrecognized libpcap format". On the other hand, in normal
2061 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
2064 /* get packet drop statistics from pcap */
2065 if(ld.pcap_h != NULL) {
2066 g_assert(!ld.from_cap_pipe);
2067 /* Get the capture statistics, so we know how many packets were
2069 if (pcap_stats(ld.pcap_h, stats) >= 0) {
2070 *stats_known = TRUE;
2071 /* Let the parent process know. */
2072 report_packet_drops(stats->ps_drop);
2074 g_snprintf(errmsg, sizeof(errmsg),
2075 "Can't get packet-drop statistics: %s",
2076 pcap_geterr(ld.pcap_h));
2077 report_capture_error(errmsg, please_report);
2081 /* close the input file (pcap or capture pipe) */
2082 capture_loop_close_input(&ld);
2084 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
2086 /* ok, if the write and the close were successful. */
2087 return write_ok && close_ok;
2090 if (capture_opts->multi_files_on) {
2091 /* cleanup ringbuffer */
2092 ringbuf_error_cleanup();
2094 /* We can't use the save file, and we have no FILE * for the stream
2095 to close in order to close it, so close the FD directly. */
2096 if(save_file_fd != -1) {
2097 ws_close(save_file_fd);
2100 /* We couldn't even start the capture, so get rid of the capture
2102 if(capture_opts->save_file != NULL) {
2103 ws_unlink(capture_opts->save_file);
2104 g_free(capture_opts->save_file);
2107 capture_opts->save_file = NULL;
2109 report_cfilter_error(capture_opts->cfilter, errmsg);
2111 report_capture_error(errmsg, secondary_errmsg);
2113 /* close the input file (pcap or cap_pipe) */
2114 capture_loop_close_input(&ld);
2116 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
2122 static void capture_loop_stop(void)
2124 #ifdef HAVE_PCAP_BREAKLOOP
2125 if(ld.pcap_h != NULL)
2126 pcap_breakloop(ld.pcap_h);
2133 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
2134 int err, gboolean is_close)
2139 g_snprintf(errmsg, errmsglen,
2140 "Not all the packets could be written to the file"
2141 " to which the capture was being saved\n"
2142 "(\"%s\") because there is no space left on the file system\n"
2143 "on which that file resides.",
2149 g_snprintf(errmsg, errmsglen,
2150 "Not all the packets could be written to the file"
2151 " to which the capture was being saved\n"
2152 "(\"%s\") because you are too close to, or over,"
2153 " your disk quota\n"
2154 "on the file system on which that file resides.",
2159 case WTAP_ERR_CANT_CLOSE:
2160 g_snprintf(errmsg, errmsglen,
2161 "The file to which the capture was being saved"
2162 " couldn't be closed for some unknown reason.");
2165 case WTAP_ERR_SHORT_WRITE:
2166 g_snprintf(errmsg, errmsglen,
2167 "Not all the packets could be written to the file"
2168 " to which the capture was being saved\n"
2175 g_snprintf(errmsg, errmsglen,
2176 "The file to which the capture was being saved\n"
2177 "(\"%s\") could not be closed: %s.",
2178 fname, wtap_strerror(err));
2180 g_snprintf(errmsg, errmsglen,
2181 "An error occurred while writing to the file"
2182 " to which the capture was being saved\n"
2184 fname, wtap_strerror(err));
2191 /* one packet was captured, process it */
2193 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
2196 loop_data *ld = (void *) user;
2199 /* if the user told us to stop after x packets, do we already have enough? */
2200 if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
2206 /* We may be called multiple times from pcap_dispatch(); if we've set
2207 the "stop capturing" flag, ignore this packet, as we're not
2208 supposed to be saving any more packets. */
2213 /* We're supposed to write the packet to a file; do so.
2214 If this fails, set "ld->go" to FALSE, to stop the capture, and set
2215 "ld->err" to the error. */
2216 if (!libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err)) {
2225 /* And now our feature presentation... [ fade to music ] */
2227 main(int argc, char *argv[])
2230 extern char *optarg;
2231 gboolean arg_error = FALSE;
2237 struct sigaction action, oldaction;
2240 gboolean start_capture = TRUE;
2241 gboolean stats_known;
2242 struct pcap_stat stats;
2243 GLogLevelFlags log_flags;
2244 gboolean list_interfaces = FALSE;
2245 gboolean list_link_layer_types = FALSE;
2246 gboolean machine_readable = FALSE;
2247 gboolean print_statistics = FALSE;
2248 int status, run_once_args = 0;
2251 #ifdef HAVE_PCAP_REMOTE
2252 #define OPTSTRING_INIT "a:A:b:c:Df:hi:Lm:MprSs:uvw:y:Z:"
2254 #define OPTSTRING_INIT "a:b:c:Df:hi:LMpSs:vw:y:Z:"
2258 #define OPTSTRING_WIN32 "B:"
2260 #define OPTSTRING_WIN32 ""
2263 char optstring[sizeof(OPTSTRING_INIT) + sizeof(OPTSTRING_WIN32) - 1] =
2264 OPTSTRING_INIT OPTSTRING_WIN32;
2266 #ifdef DEBUG_CHILD_DUMPCAP
2267 if ((debug_log = fopen("dumpcap_debug_log.tmp","w")) == NULL) {
2268 fprintf (stderr, "Unable to open debug log file !\n");
2273 /* Determine if dumpcap is being requested to run in a special */
2274 /* capture_child mode by going thru the command line args to see if */
2275 /* a -Z is present. (-Z is a hidden option). */
2276 /* The primary result of running in capture_child mode is that */
2277 /* all messages sent out on stderr are in a special type/len/string */
2278 /* format to allow message processing by type. */
2279 /* These messages include various 'status' messages which are sent */
2280 /* when an actual capture is in progress. Capture_child mode */
2281 /* would normally be requested by a parent process which invokes */
2282 /* dumpcap and obtains dumpcap stderr output via a pipe to which */
2283 /* dumpcap stderr has been redirected. */
2284 /* Capture_child mode needs to be determined immediately upon */
2285 /* startup so that any messages generated by dumpcap in this mode */
2286 /* (eg: during initialization) will be formatted properly. */
2288 for (i=1; i<argc; i++) {
2289 if (strcmp("-Z", argv[i]) == 0) {
2290 capture_child = TRUE;
2292 /* set output pipe to binary mode, to avoid ugly text conversions */
2293 _setmode(2, O_BINARY);
2298 /* The default_log_handler will use stdout, which makes trouble in */
2299 /* capture child mode, as it uses stdout for it's sync_pipe. */
2300 /* So: the filtering is done in the console_log_handler and not here.*/
2301 /* We set the log handlers right up front to make sure that any log */
2302 /* messages when running as child will be sent back to the parent */
2303 /* with the correct format. */
2307 G_LOG_LEVEL_CRITICAL|
2308 G_LOG_LEVEL_WARNING|
2309 G_LOG_LEVEL_MESSAGE|
2312 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
2314 g_log_set_handler(NULL,
2316 console_log_handler, NULL /* user_data */);
2317 g_log_set_handler(LOG_DOMAIN_MAIN,
2319 console_log_handler, NULL /* user_data */);
2320 g_log_set_handler(LOG_DOMAIN_CAPTURE,
2322 console_log_handler, NULL /* user_data */);
2323 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
2325 console_log_handler, NULL /* user_data */);
2328 /* Load wpcap if possible. Do this before collecting the run-time version information */
2331 /* ... and also load the packet.dll from wpcap */
2332 /* XXX - currently not required, may change later. */
2333 /*wpcap_packet_load();*/
2335 /* Start windows sockets */
2336 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
2338 /* Set handler for Ctrl+C key */
2339 SetConsoleCtrlHandler(capture_cleanup, TRUE);
2341 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
2343 action.sa_handler = capture_cleanup;
2344 action.sa_flags = 0;
2345 sigemptyset(&action.sa_mask);
2346 sigaction(SIGTERM, &action, NULL);
2347 sigaction(SIGINT, &action, NULL);
2348 sigaction(SIGHUP, NULL, &oldaction);
2349 if (oldaction.sa_handler == SIG_DFL)
2350 sigaction(SIGHUP, &action, NULL);
2353 /* ----------------------------------------------------------------- */
2354 /* Privilege and capability handling */
2356 /* 1. Running not as root or suid root; no special capabilities. */
2359 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
2362 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
2364 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
2365 /* capabilities; Drop all other capabilities; */
2366 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2367 /* else: after pcap_open_live() in capture_loop_open_input() */
2368 /* drop all capabilities (NET_RAW and NET_ADMIN); */
2369 /* (Note: this means that the process, although logged in */
2370 /* as root, does not have various permissions such as the */
2371 /* ability to bypass file access permissions). */
2372 /* XXX: Should we just leave capabilities alone in this case */
2373 /* so that user gets expected effect that root can do */
2376 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
2378 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2379 /* else: after pcap_open_live() in capture_loop_open_input() */
2380 /* drop suid root (set euid=ruid).(ie: keep suid until after */
2381 /* pcap_open_live). */
2383 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
2385 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
2386 /* capabilities; Drop all other capabilities; */
2387 /* Drop suid privileges (euid=ruid); */
2388 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2389 /* else: after pcap_open_live() in capture_loop_open_input() */
2390 /* drop all capabilities (NET_RAW and NET_ADMIN). */
2392 /* XXX: For some Linux versions/distros with capabilities */
2393 /* a 'normal' process with any capabilities cannot be */
2394 /* 'killed' (signaled) from another (same uid) non-privileged */
2396 /* For example: If (non-suid) Wireshark forks a */
2397 /* child suid dumpcap which acts as described here (case 5), */
2398 /* Wireshark will be unable to kill (signal) the child */
2399 /* dumpcap process until the capabilities have been dropped */
2400 /* (after pcap_open_live()). */
2401 /* This behaviour will apparently be changed in the kernel */
2402 /* to allow the kill (signal) in this case. */
2403 /* See the following for details: */
2404 /* http://www.mail-archive.com/ [wrapped] */
2405 /* linux-security-module@vger.kernel.org/msg02913.html */
2407 /* It is therefore conceivable that if dumpcap somehow hangs */
2408 /* in pcap_open_live or before that wireshark will not */
2409 /* be able to stop dumpcap using a signal (USR1, TERM, etc). */
2410 /* In this case, exiting wireshark will kill the child */
2411 /* dumpcap process. */
2413 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
2414 /* capabilities; Using libcap. Note: capset cmd (which see) */
2415 /* used to assign capabilities to file. */
2417 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2418 /* else: after pcap_open_live() in capture_loop_open_input() */
2419 /* drop all capabilities (NET_RAW and NET_ADMIN) */
2421 /* ToDo: -S (stats) should drop privileges/capabilities when no */
2422 /* longer required (similar to capture). */
2424 /* ----------------------------------------------------------------- */
2426 get_credential_info();
2429 /* If 'started with special privileges' (and using libcap) */
2430 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
2431 /* Set euid/egid = ruid/rgid to remove suid privileges */
2432 relinquish_privs_except_capture();
2435 /* Set the initial values in the capture_opts. This might be overwritten
2436 by the command line parameters. */
2437 capture_opts_init(capture_opts, NULL);
2439 /* Default to capturing the entire packet. */
2440 capture_opts->snaplen = WTAP_MAX_PACKET_SIZE;
2442 /* We always save to a file - if no file was specified, we save to a
2444 capture_opts->saving_to_file = TRUE;
2445 capture_opts->has_ring_num_files = TRUE;
2447 /* Now get our args */
2448 while ((opt = getopt(argc, argv, optstring)) != -1) {
2450 case 'h': /* Print help and exit */
2454 case 'v': /* Show version and exit */
2456 GString *comp_info_str;
2457 GString *runtime_info_str;
2458 /* Assemble the compile-time version information string */
2459 comp_info_str = g_string_new("Compiled ");
2460 get_compiled_version_info(comp_info_str, NULL);
2462 /* Assemble the run-time version information string */
2463 runtime_info_str = g_string_new("Running ");
2464 get_runtime_version_info(runtime_info_str, NULL);
2465 show_version(comp_info_str, runtime_info_str);
2466 g_string_free(comp_info_str, TRUE);
2467 g_string_free(runtime_info_str, TRUE);
2471 /*** capture option specific ***/
2472 case 'a': /* autostop criteria */
2473 case 'b': /* Ringbuffer option */
2474 case 'c': /* Capture x packets */
2475 case 'f': /* capture filter */
2476 case 'i': /* Use interface x */
2477 case 'p': /* Don't capture in promiscuous mode */
2478 case 's': /* Set the snapshot (capture) length */
2479 case 'w': /* Write to capture file x */
2480 case 'y': /* Set the pcap data link type */
2481 #ifdef HAVE_PCAP_REMOTE
2482 case 'u': /* Use UDP for data transfer */
2483 case 'r': /* Capture own RPCAP traffic too */
2484 case 'A': /* Authentication */
2486 #ifdef HAVE_PCAP_SETSAMPLING
2487 case 'm': /* Sampling */
2490 case 'B': /* Buffer size */
2492 status = capture_opts_add_opt(capture_opts, opt, optarg, &start_capture);
2497 /*** hidden option: Wireshark child mode (using binary output messages) ***/
2499 capture_child = TRUE;
2501 /* set output pipe to binary mode, to avoid ugly text conversions */
2502 _setmode(2, O_BINARY);
2504 * optarg = the control ID, aka the PPID, currently used for the
2507 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
2508 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
2509 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
2510 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
2512 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
2513 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2514 "Signal pipe: Unable to open %s. Dead parent?",
2522 /*** all non capture option specific ***/
2523 case 'D': /* Print a list of capture devices and exit */
2524 list_interfaces = TRUE;
2527 case 'L': /* Print list of link-layer types and exit */
2528 list_link_layer_types = TRUE;
2531 case 'S': /* Print interface statistics once a second */
2532 print_statistics = TRUE;
2535 case 'M': /* For -D and -L, print machine-readable output */
2536 machine_readable = TRUE;
2539 case '?': /* Bad flag - print usage message */
2540 cmdarg_err("Invalid Option: %s", argv[optind-1]);
2548 /* user specified file name as regular command-line argument */
2549 /* XXX - use it as the capture file name (or something else)? */
2556 * Extra command line arguments were specified; complain.
2557 * XXX - interpret as capture filter, as tcpdump and tshark do?
2559 cmdarg_err("Invalid argument: %s", argv[0]);
2568 if (run_once_args > 1) {
2569 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
2571 } else if (list_link_layer_types) {
2572 /* We're supposed to list the link-layer types for an interface;
2573 did the user also specify a capture file to be read? */
2574 /* No - did they specify a ring buffer option? */
2575 if (capture_opts->multi_files_on) {
2576 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
2580 /* No - was the ring buffer option specified and, if so, does it make
2582 if (capture_opts->multi_files_on) {
2583 /* Ring buffer works only under certain conditions:
2584 a) ring buffer does not work with temporary files;
2585 b) it makes no sense to enable the ring buffer if the maximum
2586 file size is set to "infinite". */
2587 if (capture_opts->save_file == NULL) {
2588 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
2589 capture_opts->multi_files_on = FALSE;
2591 if (!capture_opts->has_autostop_filesize && !capture_opts->has_file_duration) {
2592 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
2593 /* XXX - this must be redesigned as the conditions changed */
2594 /* capture_opts->multi_files_on = FALSE;*/
2599 if (capture_opts_trim_iface(capture_opts, NULL) == FALSE) {
2600 /* cmdarg_err() already called .... */
2604 /* Let the user know what interface was chosen. */
2605 /* get_interface_descriptive_name() is not available! */
2606 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", capture_opts->iface);
2608 if (list_interfaces) {
2609 status = capture_opts_list_interfaces(machine_readable);
2611 } else if (list_link_layer_types) {
2612 status = capture_opts_list_link_layer_types(capture_opts, machine_readable);
2614 } else if (print_statistics) {
2615 status = capture_opts_print_statistics(machine_readable);
2619 capture_opts_trim_snaplen(capture_opts, MIN_PACKET_SIZE);
2620 capture_opts_trim_ring_num_files(capture_opts);
2622 /* Now start the capture. */
2624 if(capture_loop_start(capture_opts, &stats_known, &stats) == TRUE) {
2628 /* capture failed */
2635 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
2636 const char *message, gpointer user_data _U_)
2643 /* ignore log message, if log_level isn't interesting */
2644 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
2645 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
2650 /* create a "timestamp" */
2652 today = localtime(&curr);
2654 switch(log_level & G_LOG_LEVEL_MASK) {
2655 case G_LOG_LEVEL_ERROR:
2658 case G_LOG_LEVEL_CRITICAL:
2661 case G_LOG_LEVEL_WARNING:
2664 case G_LOG_LEVEL_MESSAGE:
2667 case G_LOG_LEVEL_INFO:
2670 case G_LOG_LEVEL_DEBUG:
2674 fprintf(stderr, "unknown log_level %u\n", log_level);
2676 g_assert_not_reached();
2679 /* Generate the output message */
2680 if(log_level & G_LOG_LEVEL_MESSAGE) {
2681 /* normal user messages without additional infos */
2682 msg = g_strdup_printf("%s\n", message);
2684 /* info/debug messages with additional infos */
2685 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
2686 today->tm_hour, today->tm_min, today->tm_sec,
2687 log_domain != NULL ? log_domain : "",
2691 /* DEBUG & INFO msgs (if we're debugging today) */
2692 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
2693 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
2694 #ifdef DEBUG_DUMPCAP
2695 fprintf(stderr, "%s", msg);
2698 #ifdef DEBUG_CHILD_DUMPCAP
2699 fprintf(debug_log, "%s", msg);
2707 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
2708 /* to parent especially formatted if dumpcap running as child. */
2709 if (capture_child) {
2710 sync_pipe_errmsg_to_parent(2, msg, "");
2712 fprintf(stderr, "%s", msg);
2719 /****************************************************************************************************************/
2720 /* indication report routines */
2724 report_packet_count(int packet_count)
2726 char tmp[SP_DECISIZE+1+1];
2727 static int count = 0;
2730 g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
2731 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
2732 pipe_write_block(2, SP_PACKET_COUNT, tmp);
2734 count += packet_count;
2735 fprintf(stderr, "\rPackets: %u ", count);
2736 /* stderr could be line buffered */
2742 report_new_capture_file(const char *filename)
2745 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
2746 pipe_write_block(2, SP_FILE, filename);
2748 fprintf(stderr, "File: %s\n", filename);
2749 /* stderr could be line buffered */
2755 report_cfilter_error(const char *cfilter, const char *errmsg)
2757 if (capture_child) {
2758 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
2759 pipe_write_block(2, SP_BAD_FILTER, errmsg);
2762 "Invalid capture filter: \"%s\"!\n"
2764 "That string isn't a valid capture filter (%s).\n"
2765 "See the User's Guide for a description of the capture filter syntax.\n",
2771 report_capture_error(const char *error_msg, const char *secondary_error_msg)
2774 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
2775 "Primary Error: %s", error_msg);
2776 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
2777 "Secondary Error: %s", secondary_error_msg);
2778 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
2780 fprintf(stderr, "%s\n%s\n", error_msg, secondary_error_msg);
2785 report_packet_drops(int drops)
2787 char tmp[SP_DECISIZE+1+1];
2789 g_snprintf(tmp, sizeof(tmp), "%d", drops);
2792 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
2793 pipe_write_block(2, SP_DROPS, tmp);
2795 fprintf(stderr, "Packets dropped: %s\n", tmp);
2796 /* stderr could be line buffered */
2802 /****************************************************************************************************************/
2803 /* signal_pipe handling */
2808 signal_pipe_check_running(void)
2810 /* any news from our parent? -> just stop the capture */
2814 /* if we are running standalone, no check required */
2815 if(!capture_child) {
2819 if(!sig_pipe_name || !sig_pipe_handle) {
2820 /* This shouldn't happen */
2821 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2822 "Signal pipe: No name or handle");
2827 * XXX - We should have the process ID of the parent (from the "-Z" flag)
2828 * at this point. Should we check to see if the parent is still alive,
2829 * e.g. by using OpenProcess?
2832 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
2834 if(!result || avail > 0) {
2835 /* peek failed or some bytes really available */
2836 /* (if not piping from stdin this would fail) */
2837 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2838 "Signal pipe: Stop capture: %s", sig_pipe_name);
2839 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
2840 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
2841 sig_pipe_handle, result, avail);
2844 /* pipe ok and no bytes available */