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"
86 #include "epan/privileges.h"
89 #include "sync_pipe.h"
92 #include "capture_sync.h"
94 #include "conditions.h"
95 #include "capture_stop_conditions.h"
99 #include "file_util.h"
101 #include "epan/unicode-utils.h"
103 #ifdef NEED_G_ASCII_STRCASECMP_H
104 #include "epan/g_ascii_strcasecmp.h"
108 * Get information about libpcap format from "wiretap/libpcap.h".
109 * XXX - can we just use pcap_open_offline() to read the pipe?
111 #include "wiretap/libpcap.h"
113 /*#define DEBUG_DUMPCAP*/
115 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
117 static gchar *sig_pipe_name = NULL;
118 static HANDLE sig_pipe_handle = NULL;
121 /** Stop a low-level capture (stops the capture child). */
122 static void capture_loop_stop(void);
124 #if !defined (__linux__)
125 #ifndef HAVE_PCAP_BREAKLOOP
127 * We don't have pcap_breakloop(), which is the only way to ensure that
128 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
129 * won't, if the call to read the next packet or batch of packets is
130 * is interrupted by a signal on UN*X, just go back and try again to
133 * On UN*X, we catch SIGUSR1 as a "stop capturing" signal, and, in
134 * the signal handler, set a flag to stop capturing; however, without
135 * a guarantee of that sort, we can't guarantee that we'll stop capturing
136 * if the read will be retried and won't time out if no packets arrive.
138 * Therefore, on at least some platforms, we work around the lack of
139 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
140 * to wait for packets to arrive, so that we're probably going to be
141 * blocked in the select() when the signal arrives, and can just bail
142 * out of the loop at that point.
144 * However, we don't want to that on BSD (because "select()" doesn't work
145 * correctly on BPF devices on at least some releases of some flavors of
146 * BSD), and we don't want to do it on Windows (because "select()" is
147 * something for sockets, not for arbitrary handles). (Note that "Windows"
148 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
149 * using WinPcap, not a UNIX libpcap.)
151 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
152 * on BSD times out even if no packets have arrived, so we'll eventually
153 * exit pcap_dispatch() with an indication that no packets have arrived,
154 * and will break out of the capture loop at that point.
156 * On Windows, we can't send a SIGUSR1 to stop capturing, so none of this
157 * applies in any case.
159 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
160 * want to include it if it's not present on this platform, however.
162 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
163 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
165 # define MUST_DO_SELECT
166 # endif /* avoid select */
167 #endif /* HAVE_PCAP_BREAKLOOP */
169 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
170 * in pcap_dispatch(); on the other hand, select() works just fine there.
171 * Hence we use a select for that come what may.
173 #define MUST_DO_SELECT
176 typedef void (*capture_packet_cb_fct)(u_char *, const struct pcap_pkthdr *, const u_char *);
178 /** init the capture filter */
181 INITFILTER_BAD_FILTER,
182 INITFILTER_OTHER_ERROR
183 } initfilter_status_t;
185 typedef struct _loop_data {
187 gboolean go; /* TRUE as long as we're supposed to keep capturing */
188 int err; /* if non-zero, error seen while capturing */
189 gint packet_count; /* Number of packets we have already captured */
190 gint packet_max; /* Number of packets we're supposed to capture - 0 means infinite */
192 capture_packet_cb_fct packet_cb; /* callback for a single captured packet */
194 /* pcap "input file" */
195 pcap_t *pcap_h; /* pcap handle */
196 gboolean pcap_err; /* TRUE if error from pcap */
197 #ifdef MUST_DO_SELECT
198 int pcap_fd; /* pcap file descriptor */
201 /* capture pipe (unix only "input file") */
202 gboolean from_cap_pipe; /* TRUE if we are capturing data from a capture pipe */
203 struct pcap_hdr cap_pipe_hdr; /* Pcap header when capturing from a pipe */
204 struct pcaprec_modified_hdr cap_pipe_rechdr; /* Pcap record header when capturing from a pipe */
205 int cap_pipe_fd; /* the file descriptor of the capture pipe */
206 gboolean cap_pipe_modified; /* TRUE if data in the pipe uses modified pcap headers */
207 gboolean cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
208 unsigned int cap_pipe_bytes_to_read;/* Used by cap_pipe_dispatch */
209 unsigned int cap_pipe_bytes_read; /* Used by cap_pipe_dispatch */
211 STATE_EXPECT_REC_HDR,
216 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
227 * Standard secondary message for unexpected errors.
229 static const char please_report[] =
230 "Please report this to the Wireshark developers.\n"
231 "(This is not a crash; please do not report it as such.)";
234 * This needs to be static, so that the SIGUSR1 handler can clear the "go"
241 * Timeout, in milliseconds, for reads from the stream of captured packets.
243 #define CAP_READ_TIMEOUT 250
244 static char *cap_pipe_err_str;
247 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
248 const char *message, gpointer user_data _U_);
250 /* capture related options */
251 static capture_options global_capture_opts;
252 static capture_options *capture_opts = &global_capture_opts;
254 static void capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
256 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
257 int err, gboolean is_close);
261 static void exit_main(int err) __attribute__ ((noreturn));
263 static void exit_main(int err);
266 static void report_new_capture_file(const char *filename);
267 static void report_packet_count(int packet_count);
268 static void report_packet_drops(int drops);
269 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
270 static void report_cfilter_error(const char *cfilter, const char *errmsg);
273 static gboolean signal_pipe_check_running(void);
277 print_usage(gboolean print_ver) {
285 "Dumpcap " VERSION "%s\n"
286 "Capture network packets and dump them into a libpcap file.\n"
287 "See http://www.wireshark.org for more information.\n",
288 wireshark_svnversion);
292 fprintf(output, "\nUsage: dumpcap [options] ...\n");
293 fprintf(output, "\n");
294 fprintf(output, "Capture interface:\n");
295 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
296 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
297 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
298 fprintf(output, " -p don't capture in promiscuous mode\n");
300 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
302 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
303 fprintf(output, " -D print list of interfaces and exit\n");
304 fprintf(output, " -L print list of link-layer types of iface and exit\n");
305 fprintf(output, " -S print statistics for each interface once every second\n");
306 fprintf(output, " -M for -D, -L, and -S produce machine-readable output\n");
307 fprintf(output, "\n");
308 #ifdef HAVE_PCAP_REMOTE
309 fprintf(output, "\nRPCAP options:\n");
310 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
311 fprintf(output, " -u use UDP for RPCAP data transfer\n");
312 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
313 #ifdef HAVE_PCAP_SETSAMPLING
314 fprintf(output, " -m <sampling type> use packet sampling\n");
315 fprintf(output, " count:NUM - capture one packet of every NUM\n");
316 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
319 fprintf(output, "Stop conditions:\n");
320 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
321 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
322 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
323 fprintf(output, " files:NUM - stop after NUM files\n");
324 /*fprintf(output, "\n");*/
325 fprintf(output, "Output (files):\n");
326 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
327 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
328 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
329 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
330 /*fprintf(output, "\n");*/
331 fprintf(output, "Miscellaneous:\n");
332 fprintf(output, " -v print version information and exit\n");
333 fprintf(output, " -h display this help and exit\n");
334 fprintf(output, "\n");
335 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcap\n");
336 fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcap\"\n");
337 fprintf(output, "\n");
338 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
342 show_version(GString *comp_info_str, GString *runtime_info_str)
346 "Dumpcap " VERSION "%s\n"
351 "See http://www.wireshark.org for more information.\n",
352 wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
356 * Report an error in command-line arguments.
359 cmdarg_err(const char *fmt, ...)
364 /* Print a bare error */
366 vfprintf(stderr, fmt, ap);
370 fprintf(stderr, "dumpcap: ");
371 vfprintf(stderr, fmt, ap);
372 fprintf(stderr, "\n");
378 * Report additional information for an error in command-line arguments.
381 cmdarg_err_cont(const char *fmt, ...)
386 /* XXX - convert to g_log */
389 vfprintf(stderr, fmt, ap);
390 fprintf(stderr, "\n");
398 capture_cleanup(DWORD dwCtrlType)
400 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
401 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
402 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
403 like SIGTERM at least when the machine's shutting down.
405 For now, if we're running as a command rather than a capture child,
406 we handle all but CTRL_LOGOFF_EVENT as indications that we should
407 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
410 If we're not running as a capture child, we might be running as
411 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
412 user logs out. (XXX - can we explicitly check whether we're
413 running as a service?) */
415 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
416 "Console: Control signal");
417 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
418 "Console: Control signal, CtrlType: %u", dwCtrlType);
420 /* Keep capture running if we're a service and a user logs off */
421 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
430 capture_cleanup(int signum)
432 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
433 SIGTERM. We assume that if the user wanted it to keep running
434 after they logged out, they'd have nohupped it. */
436 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
438 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
439 "Console: Signal, signal value: %u", signum);
445 static void exit_main(int status)
448 /* Shutdown windows sockets */
451 /* can be helpful for debugging */
453 printf("Press any key\n");
464 * If we were linked with libcap (not libpcap), make sure we have
465 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
469 #if 0 /* Set to enable capability debugging */
470 print_caps(char *pfx) {
471 cap_t caps = cap_get_proc();
472 fprintf(stderr, "%s: EUID: %d Capabilities: %s\n", pfx,
473 geteuid(), cap_to_text(caps, NULL));
476 print_caps(char *pfx _U_) {
481 relinquish_privs_except_capture(void)
483 /* CAP_NET_ADMIN: Promiscuous mode and a truckload of other
484 * stuff we don't need (and shouldn't have).
485 * CAP_NET_RAW: Packet capture (raw sockets).
487 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
488 cap_t caps = cap_init();
489 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
491 if (started_with_special_privs()) {
492 print_caps("Pre drop, pre set");
493 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
497 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
498 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
500 if (cap_set_proc(caps)) {
503 print_caps("Pre drop, post set");
506 relinquish_special_privs_perm();
508 print_caps("Post drop, pre set");
509 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
510 if (cap_set_proc(caps)) {
513 print_caps("Post drop, post set");
516 #endif /* HAVE_LIBCAP */
518 /* Take care of byte order in the libpcap headers read from pipes.
519 * (function taken from wiretap/libpcap.c) */
521 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
524 /* Byte-swap the record header fields. */
525 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
526 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
527 rechdr->incl_len = BSWAP32(rechdr->incl_len);
528 rechdr->orig_len = BSWAP32(rechdr->orig_len);
531 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
532 swapped, in order to match the BPF header layout.
534 Unfortunately, some files were, according to a comment in the "libpcap"
535 source, written with version 2.3 in their headers but without the
536 interchanged fields, so if "incl_len" is greater than "orig_len" - which
537 would make no sense - we assume that we need to swap them. */
538 if (hdr->version_major == 2 &&
539 (hdr->version_minor < 3 ||
540 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
543 temp = rechdr->orig_len;
544 rechdr->orig_len = rechdr->incl_len;
545 rechdr->incl_len = temp;
549 /* Provide select() functionality for a single file descriptor
550 * on both UNIX/POSIX and Windows.
552 * The Windows version calls WaitForSingleObject instead of
555 * Returns the same values as select. If an error is returned,
556 * the string cap_pipe_err_str should be used instead of errno.
559 cap_pipe_select(int pipe_fd) {
562 struct timeval timeout, *pto;
565 cap_pipe_err_str = "Unknown error";
568 FD_SET(pipe_fd, &rfds);
571 timeout.tv_usec = CAP_READ_TIMEOUT * 1000;
574 sel_ret = select(pipe_fd+1, &rfds, NULL, NULL, pto);
576 cap_pipe_err_str = strerror(errno);
580 /* XXX - Should we just use file handles exclusively under Windows?
581 * Otherwise we have to convert between file handles and file descriptors
582 * here and when we open a named pipe.
584 HANDLE hPipe = (HANDLE) _get_osfhandle(pipe_fd);
588 if (hPipe == INVALID_HANDLE_VALUE) {
589 cap_pipe_err_str = "Could not open standard input";
593 cap_pipe_err_str = "Unknown error";
595 wait_ret = WaitForSingleObject(hPipe, CAP_READ_TIMEOUT);
597 /* XXX - This probably isn't correct */
606 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
607 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
608 cap_pipe_err_str = utf_16to8(err_str);
612 g_assert_not_reached();
619 /* Mimic pcap_open_live() for pipe captures
620 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
622 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
623 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
625 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
626 char *errmsg, int errmsgl)
629 struct stat pipe_stat;
641 unsigned int bytes_read;
643 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
646 * XXX (T)Wireshark blocks until we return
648 if (strcmp(pipename, "-") == 0) {
649 fd = 0; /* read from stdin */
652 * This is needed to set the stdin pipe into binary mode, otherwise
653 * CR/LF are mangled...
655 _setmode(0, _O_BINARY);
659 if (eth_stat(pipename, &pipe_stat) < 0) {
660 if (errno == ENOENT || errno == ENOTDIR)
661 ld->cap_pipe_err = PIPNEXIST;
663 g_snprintf(errmsg, errmsgl,
664 "The capture session could not be initiated "
665 "due to error on pipe: %s", strerror(errno));
666 ld->cap_pipe_err = PIPERR;
670 if (! S_ISFIFO(pipe_stat.st_mode)) {
671 if (S_ISCHR(pipe_stat.st_mode)) {
673 * Assume the user specified an interface on a system where
674 * interfaces are in /dev. Pretend we haven't seen it.
676 ld->cap_pipe_err = PIPNEXIST;
679 g_snprintf(errmsg, errmsgl,
680 "The capture session could not be initiated because\n"
681 "\"%s\" is neither an interface nor a pipe", pipename);
682 ld->cap_pipe_err = PIPERR;
686 fd = eth_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
688 g_snprintf(errmsg, errmsgl,
689 "The capture session could not be initiated "
690 "due to error on pipe open: %s", strerror(errno));
691 ld->cap_pipe_err = PIPERR;
695 #define PIPE_STR "\\pipe\\"
696 /* Under Windows, named pipes _must_ have the form
697 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
699 pncopy = g_strdup(pipename);
700 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
701 pos = strchr(pncopy + 3, '\\');
702 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
709 g_snprintf(errmsg, errmsgl,
710 "The capture session could not be initiated because\n"
711 "\"%s\" is neither an interface nor a pipe", pipename);
712 ld->cap_pipe_err = PIPNEXIST;
716 /* Wait for the pipe to appear */
718 hPipe = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
719 OPEN_EXISTING, 0, NULL);
721 if (hPipe != INVALID_HANDLE_VALUE)
724 if (GetLastError() != ERROR_PIPE_BUSY) {
725 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
726 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
727 g_snprintf(errmsg, errmsgl,
728 "The capture session on \"%s\" could not be initiated "
729 "due to error on pipe open: pipe busy: %s (error %d)",
730 pipename, utf_16to8(err_str), GetLastError());
732 ld->cap_pipe_err = PIPERR;
736 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
737 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
738 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
739 g_snprintf(errmsg, errmsgl,
740 "The capture session could not be initiated "
741 "due to error on named pipe open: %s (error %d)",
742 utf_16to8(err_str), GetLastError());
744 ld->cap_pipe_err = PIPERR;
749 fd = _open_osfhandle((long) hPipe, _O_RDONLY);
751 g_snprintf(errmsg, errmsgl,
752 "The capture session could not be initiated "
753 "due to error on pipe open: %s", strerror(errno));
754 ld->cap_pipe_err = PIPERR;
760 ld->from_cap_pipe = TRUE;
762 /* read the pcap header */
764 while (bytes_read < sizeof magic) {
765 sel_ret = cap_pipe_select(fd);
767 g_snprintf(errmsg, errmsgl,
768 "Unexpected error from select: %s", strerror(errno));
770 } else if (sel_ret > 0) {
771 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
774 g_snprintf(errmsg, errmsgl, "End of file on pipe during open");
776 g_snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
786 /* Host that wrote it has our byte order, and was running
787 a program using either standard or ss990417 libpcap. */
788 ld->cap_pipe_byte_swapped = FALSE;
789 ld->cap_pipe_modified = FALSE;
791 case PCAP_MODIFIED_MAGIC:
792 /* Host that wrote it has our byte order, but was running
793 a program using either ss990915 or ss991029 libpcap. */
794 ld->cap_pipe_byte_swapped = FALSE;
795 ld->cap_pipe_modified = TRUE;
797 case PCAP_SWAPPED_MAGIC:
798 /* Host that wrote it has a byte order opposite to ours,
799 and was running a program using either standard or
801 ld->cap_pipe_byte_swapped = TRUE;
802 ld->cap_pipe_modified = FALSE;
804 case PCAP_SWAPPED_MODIFIED_MAGIC:
805 /* Host that wrote it out has a byte order opposite to
806 ours, and was running a program using either ss990915
807 or ss991029 libpcap. */
808 ld->cap_pipe_byte_swapped = TRUE;
809 ld->cap_pipe_modified = TRUE;
812 /* Not a "libpcap" type we know about. */
813 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
817 /* Read the rest of the header */
819 while (bytes_read < sizeof(struct pcap_hdr)) {
820 sel_ret = cap_pipe_select(fd);
822 g_snprintf(errmsg, errmsgl,
823 "Unexpected error from select: %s", strerror(errno));
825 } else if (sel_ret > 0) {
826 b = read(fd, ((char *)hdr)+bytes_read,
827 sizeof(struct pcap_hdr) - bytes_read);
830 g_snprintf(errmsg, errmsgl, "End of file on pipe during open");
832 g_snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
840 if (ld->cap_pipe_byte_swapped) {
841 /* Byte-swap the header fields about which we care. */
842 hdr->version_major = BSWAP16(hdr->version_major);
843 hdr->version_minor = BSWAP16(hdr->version_minor);
844 hdr->snaplen = BSWAP32(hdr->snaplen);
845 hdr->network = BSWAP32(hdr->network);
847 ld->linktype = hdr->network;
849 if (hdr->version_major < 2) {
850 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
854 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
855 ld->cap_pipe_err = PIPOK;
859 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
860 ld->cap_pipe_err = PIPERR;
867 /* We read one record from the pipe, take care of byte order in the record
868 * header, write the record to the capture file, and update capture statistics. */
870 cap_pipe_dispatch(loop_data *ld, guchar *data, char *errmsg, int errmsgl)
872 struct pcap_pkthdr phdr;
874 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
878 #ifdef LOG_CAPTURE_VERBOSE
879 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
882 switch (ld->cap_pipe_state) {
884 case STATE_EXPECT_REC_HDR:
885 ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
886 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
887 ld->cap_pipe_bytes_read = 0;
888 ld->cap_pipe_state = STATE_READ_REC_HDR;
891 case STATE_READ_REC_HDR:
892 b = read(ld->cap_pipe_fd, ((char *)&ld->cap_pipe_rechdr)+ld->cap_pipe_bytes_read,
893 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
896 result = PD_PIPE_EOF;
898 result = PD_PIPE_ERR;
901 if ((ld->cap_pipe_bytes_read += b) < ld->cap_pipe_bytes_to_read)
903 result = PD_REC_HDR_READ;
906 case STATE_EXPECT_DATA:
907 ld->cap_pipe_bytes_read = 0;
908 ld->cap_pipe_state = STATE_READ_DATA;
911 case STATE_READ_DATA:
912 b = read(ld->cap_pipe_fd, data+ld->cap_pipe_bytes_read,
913 ld->cap_pipe_rechdr.hdr.incl_len - ld->cap_pipe_bytes_read);
916 result = PD_PIPE_EOF;
918 result = PD_PIPE_ERR;
921 if ((ld->cap_pipe_bytes_read += b) < ld->cap_pipe_rechdr.hdr.incl_len)
923 result = PD_DATA_READ;
927 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
930 } /* switch (ld->cap_pipe_state) */
933 * We've now read as much data as we were expecting, so process it.
937 case PD_REC_HDR_READ:
938 /* We've read the header. Take care of byte order. */
939 cap_pipe_adjust_header(ld->cap_pipe_byte_swapped, &ld->cap_pipe_hdr,
940 &ld->cap_pipe_rechdr.hdr);
941 if (ld->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
942 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
943 ld->packet_count+1, ld->cap_pipe_rechdr.hdr.incl_len);
946 ld->cap_pipe_state = STATE_EXPECT_DATA;
950 /* Fill in a "struct pcap_pkthdr", and process the packet. */
951 phdr.ts.tv_sec = ld->cap_pipe_rechdr.hdr.ts_sec;
952 phdr.ts.tv_usec = ld->cap_pipe_rechdr.hdr.ts_usec;
953 phdr.caplen = ld->cap_pipe_rechdr.hdr.incl_len;
954 phdr.len = ld->cap_pipe_rechdr.hdr.orig_len;
956 ld->packet_cb((u_char *)ld, &phdr, data);
958 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
962 ld->cap_pipe_err = PIPEOF;
966 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
973 ld->cap_pipe_err = PIPERR;
974 /* Return here rather than inside the switch to prevent GCC warning */
979 /** Open the capture input file (pcap or capture pipe).
980 * Returns TRUE if it succeeds, FALSE otherwise. */
982 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
983 char *errmsg, size_t errmsg_len,
984 char *secondary_errmsg, size_t secondary_errmsg_len)
986 gchar open_err_str[PCAP_ERRBUF_SIZE];
988 static const char ppamsg[] = "can't find PPA for ";
989 const char *set_linktype_err_str;
990 const char *libpcap_warn;
992 gchar *sync_secondary_msg_str;
994 WORD wVersionRequested;
997 #ifdef HAVE_PCAP_REMOTE
998 struct pcap_rmtauth auth;
1002 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
1005 /* XXX - opening Winsock on tshark? */
1007 /* Initialize Windows Socket if we are in a WIN32 OS
1008 This needs to be done before querying the interface for network/netmask */
1010 /* XXX - do we really require 1.1 or earlier?
1011 Are there any versions that support only 2.0 or higher? */
1012 wVersionRequested = MAKEWORD(1, 1);
1013 err = WSAStartup(wVersionRequested, &wsaData);
1017 case WSASYSNOTREADY:
1018 g_snprintf(errmsg, errmsg_len,
1019 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
1022 case WSAVERNOTSUPPORTED:
1023 g_snprintf(errmsg, errmsg_len,
1024 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
1025 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
1028 case WSAEINPROGRESS:
1029 g_snprintf(errmsg, errmsg_len,
1030 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
1034 g_snprintf(errmsg, errmsg_len,
1035 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
1039 g_snprintf(errmsg, errmsg_len,
1040 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
1044 g_snprintf(errmsg, errmsg_len,
1045 "Couldn't initialize Windows Sockets: error %d", err);
1048 g_snprintf(secondary_errmsg, secondary_errmsg_len, please_report);
1053 /* Open the network interface to capture from it.
1054 Some versions of libpcap may put warnings into the error buffer
1055 if they succeed; to tell if that's happened, we have to clear
1056 the error buffer, and check if it's still a null string. */
1057 open_err_str[0] = '\0';
1058 #ifdef HAVE_PCAP_OPEN
1059 auth.type = capture_opts->auth_type == CAPTURE_AUTH_PWD ?
1060 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
1061 auth.username = capture_opts->auth_username;
1062 auth.password = capture_opts->auth_password;
1064 ld->pcap_h = pcap_open(capture_opts->iface,
1065 capture_opts->has_snaplen ? capture_opts->snaplen :
1066 WTAP_MAX_PACKET_SIZE,
1068 (capture_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
1069 (capture_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
1070 (capture_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
1071 CAP_READ_TIMEOUT, &auth, open_err_str);
1073 ld->pcap_h = pcap_open_live(capture_opts->iface,
1074 capture_opts->has_snaplen ? capture_opts->snaplen :
1075 WTAP_MAX_PACKET_SIZE,
1076 capture_opts->promisc_mode, CAP_READ_TIMEOUT,
1080 if (ld->pcap_h != NULL) {
1081 /* we've opened "iface" as a network device */
1083 /* try to set the capture buffer size */
1084 if (pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
1085 sync_secondary_msg_str = g_strdup_printf(
1086 "The capture buffer size of %luMB seems to be too high for your machine,\n"
1087 "the default of 1MB will be used.\n"
1089 "Nonetheless, the capture is started.\n",
1090 capture_opts->buffer_size);
1091 report_capture_error("Couldn't set the capture buffer size!",
1092 sync_secondary_msg_str);
1093 g_free(sync_secondary_msg_str);
1097 #if defined(HAVE_PCAP_REMOTE) && defined(HAVE_PCAP_SETSAMPLING)
1098 if (capture_opts->sampling_method != CAPTURE_SAMP_NONE)
1100 struct pcap_samp *samp;
1102 if ((samp = pcap_setsampling(ld->pcap_h)) != NULL)
1104 switch (capture_opts->sampling_method)
1106 case CAPTURE_SAMP_BY_COUNT:
1107 samp->method = PCAP_SAMP_1_EVERY_N;
1110 case CAPTURE_SAMP_BY_TIMER:
1111 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
1115 sync_msg_str = g_strdup_printf(
1116 "Unknown sampling method %d specified,\n"
1117 "continue without packet sampling",
1118 capture_opts->sampling_method);
1119 report_capture_error("Couldn't set the capture "
1120 "sampling", sync_msg_str);
1121 g_free(sync_msg_str);
1123 samp->value = capture_opts->sampling_param;
1127 report_capture_error("Couldn't set the capture sampling",
1128 "Cannot get packet sampling data structure");
1134 /* setting the data link type only works on real interfaces */
1135 if (capture_opts->linktype != -1) {
1136 set_linktype_err_str = set_pcap_linktype(ld->pcap_h, capture_opts->iface,
1137 capture_opts->linktype);
1138 if (set_linktype_err_str != NULL) {
1139 g_snprintf(errmsg, errmsg_len, "Unable to set data link type (%s).",
1140 set_linktype_err_str);
1141 g_snprintf(secondary_errmsg, secondary_errmsg_len, please_report);
1145 ld->linktype = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
1147 /* We couldn't open "iface" as a network device. */
1148 /* Try to open it as a pipe */
1149 ld->cap_pipe_fd = cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, errmsg_len);
1151 if (ld->cap_pipe_fd == -1) {
1153 if (ld->cap_pipe_err == PIPNEXIST) {
1154 /* Pipe doesn't exist, so output message for interface */
1156 /* If we got a "can't find PPA for X" message, warn the user (who
1157 is running (T)Wireshark on HP-UX) that they don't have a version
1158 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1159 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1160 PPA for X" rather than "can't find PPA for X"). */
1161 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1164 "You are running (T)Wireshark with a version of the libpcap library\n"
1165 "that doesn't handle HP-UX network devices well; this means that\n"
1166 "(T)Wireshark may not be able to capture packets.\n"
1168 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1169 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1170 "packaged binary form from the Software Porting And Archive Centre\n"
1171 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1172 "at the URL lists a number of mirror sites.";
1175 g_snprintf(errmsg, errmsg_len,
1176 "The capture session could not be initiated (%s).", open_err_str);
1178 g_snprintf(secondary_errmsg, secondary_errmsg_len,
1179 "Please check to make sure you have sufficient permissions, and that you have "
1180 "the proper interface or pipe specified.%s", libpcap_warn);
1182 g_snprintf(secondary_errmsg, secondary_errmsg_len,
1184 "Please check that \"%s\" is the proper interface.\n"
1187 "Help can be found at:\n"
1189 " http://wiki.wireshark.org/CaptureSetup\n"
1192 "WinPcap does not support 64-bit Windows; you will have to use some other\n"
1193 "tool to capture traffic, such as netcap.\n"
1194 "For netcap details see: http://support.microsoft.com/?id=310875\n"
1196 "Modem (PPP/WAN):\n"
1197 "Note that version 3.0 of WinPcap, and earlier versions of WinPcap, don't\n"
1198 "support capturing on PPP/WAN interfaces on Windows NT 4.0 / 2000 / XP /\n"
1200 "WinPcap 3.1 has support for it on Windows 2000 / XP / Server 2003, but has no\n"
1201 "support for it on Windows NT 4.0 or Windows Vista (Beta 1).",
1202 capture_opts->iface);
1206 * Else pipe (or file) does exist and cap_pipe_open_live() has
1211 /* cap_pipe_open_live() succeeded; don't want
1212 error message from pcap_open_live() */
1213 open_err_str[0] = '\0';
1216 /* XXX - will this work for tshark? */
1217 #ifdef MUST_DO_SELECT
1218 if (!ld->from_cap_pipe) {
1219 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
1220 ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
1222 ld->pcap_fd = pcap_fileno(ld->pcap_h);
1227 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1228 returned a warning; print it, but keep capturing. */
1229 if (open_err_str[0] != '\0') {
1230 sync_msg_str = g_strdup_printf("%s.", open_err_str);
1231 report_capture_error(sync_msg_str, "");
1232 g_free(sync_msg_str);
1239 /* close the capture input file (pcap or capture pipe) */
1240 static void capture_loop_close_input(loop_data *ld) {
1242 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
1244 /* if open, close the capture pipe "input file" */
1245 if (ld->cap_pipe_fd >= 0) {
1246 g_assert(ld->from_cap_pipe);
1247 eth_close(ld->cap_pipe_fd);
1248 ld->cap_pipe_fd = 0;
1251 /* if open, close the pcap "input file" */
1252 if(ld->pcap_h != NULL) {
1253 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", ld->pcap_h);
1254 g_assert(!ld->from_cap_pipe);
1255 pcap_close(ld->pcap_h);
1262 /* Shut down windows sockets */
1268 /* init the capture filter */
1269 static initfilter_status_t
1270 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe, gchar * iface, gchar * cfilter) {
1271 bpf_u_int32 netnum, netmask;
1272 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
1273 struct bpf_program fcode;
1276 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
1278 /* capture filters only work on real interfaces */
1279 if (cfilter && !from_cap_pipe) {
1280 /* A capture filter was specified; set it up. */
1281 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1283 * Well, we can't get the netmask for this interface; it's used
1284 * only for filters that check for broadcast IP addresses, so
1285 * we just punt and use 0. It might be nice to warn the user,
1286 * but that's a pain in a GUI application, as it'd involve popping
1287 * up a message box, and it's not clear how often this would make
1288 * a difference (only filters that check for IP broadcast addresses
1292 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
1295 if (pcap_compile(pcap_h, &fcode, cfilter, 1, netmask) < 0) {
1296 /* Treat this specially - our caller might try to compile this
1297 as a display filter and, if that succeeds, warn the user that
1298 the display and capture filter syntaxes are different. */
1299 return INITFILTER_BAD_FILTER;
1301 if (pcap_setfilter(pcap_h, &fcode) < 0) {
1302 #ifdef HAVE_PCAP_FREECODE
1303 pcap_freecode(&fcode);
1305 return INITFILTER_OTHER_ERROR;
1307 #ifdef HAVE_PCAP_FREECODE
1308 pcap_freecode(&fcode);
1312 return INITFILTER_NO_ERROR;
1316 /* set up to write to the already-opened capture output file/files */
1318 capture_loop_init_output(capture_options *capture_opts, int save_file_fd, loop_data *ld, char *errmsg, int errmsg_len) {
1323 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
1326 if (ld->from_cap_pipe) {
1327 file_snaplen = ld->cap_pipe_hdr.snaplen;
1330 file_snaplen = pcap_snapshot(ld->pcap_h);
1333 /* Set up to write to the capture file. */
1334 if (capture_opts->multi_files_on) {
1335 ld->pdh = ringbuf_init_libpcap_fdopen(ld->linktype, file_snaplen,
1336 &ld->bytes_written, &err);
1338 ld->pdh = libpcap_fdopen(save_file_fd, ld->linktype, file_snaplen,
1339 &ld->bytes_written, &err);
1342 if (ld->pdh == NULL) {
1343 /* We couldn't set up to write to the capture file. */
1344 /* XXX - use cf_open_error_message from tshark instead? */
1347 case WTAP_ERR_CANT_OPEN:
1348 g_snprintf(errmsg, errmsg_len, "The file to which the capture would be saved"
1349 " couldn't be created for some unknown reason.");
1352 case WTAP_ERR_SHORT_WRITE:
1353 g_snprintf(errmsg, errmsg_len, "A full header couldn't be written to the file"
1354 " to which the capture would be saved.");
1359 g_snprintf(errmsg, errmsg_len,
1360 "The file to which the capture would be"
1361 " saved (\"%s\") could not be opened: Error %d.",
1362 capture_opts->save_file, err);
1364 g_snprintf(errmsg, errmsg_len,
1365 "The file to which the capture would be"
1366 " saved (\"%s\") could not be opened: %s.",
1367 capture_opts->save_file, strerror(err));
1379 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
1381 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
1383 if (capture_opts->multi_files_on) {
1384 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
1386 return libpcap_dump_close(ld->pdh, err_close);
1390 /* dispatch incoming packets (pcap or capture pipe)
1392 * Waits for incoming packets to be available, and calls pcap_dispatch()
1393 * to cause them to be processed.
1395 * Returns the number of packets which were processed.
1397 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
1398 * packet-batching behaviour does not cause packets to get held back
1402 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
1403 char *errmsg, int errmsg_len)
1407 gint packet_count_before;
1408 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1410 packet_count_before = ld->packet_count;
1411 if (ld->from_cap_pipe) {
1412 /* dispatch from capture pipe */
1413 #ifdef LOG_CAPTURE_VERBOSE
1414 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
1416 sel_ret = cap_pipe_select(ld->cap_pipe_fd);
1419 if (sel_ret < 0 && errno != EINTR) {
1420 g_snprintf(errmsg, errmsg_len,
1421 "Unexpected error from select: %s", strerror(errno));
1422 report_capture_error(errmsg, please_report);
1427 * "select()" says we can read from the pipe without blocking
1429 inpkts = cap_pipe_dispatch(ld, pcap_data, errmsg, errmsg_len);
1437 /* dispatch from pcap */
1438 #ifdef MUST_DO_SELECT
1440 * If we have "pcap_get_selectable_fd()", we use it to get the
1441 * descriptor on which to select; if that's -1, it means there
1442 * is no descriptor on which you can do a "select()" (perhaps
1443 * because you're capturing on a special device, and that device's
1444 * driver unfortunately doesn't support "select()", in which case
1445 * we don't do the select - which means it might not be possible
1446 * to stop a capture until a packet arrives. If that's unacceptable,
1447 * plead with whoever supplies the software for that device to add
1448 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
1449 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
1450 * later, so it can use pcap_breakloop().
1452 #ifdef LOG_CAPTURE_VERBOSE
1453 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
1455 if (ld->pcap_fd != -1) {
1456 sel_ret = cap_pipe_select(ld->pcap_fd);
1459 * "select()" says we can read from it without blocking; go for
1462 * We don't have pcap_breakloop(), so we only process one packet
1463 * per pcap_dispatch() call, to allow a signal to stop the
1464 * processing immediately, rather than processing all packets
1465 * in a batch before quitting.
1467 inpkts = pcap_dispatch(ld->pcap_h, 1, ld->packet_cb, (u_char *)ld);
1469 ld->pcap_err = TRUE;
1470 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1473 if (sel_ret < 0 && errno != EINTR) {
1474 g_snprintf(errmsg, errmsg_len,
1475 "Unexpected error from select: %s", strerror(errno));
1476 report_capture_error(errmsg, please_report);
1482 #endif /* MUST_DO_SELECT */
1484 /* dispatch from pcap without select */
1486 #ifdef LOG_CAPTURE_VERBOSE
1487 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
1491 * On Windows, we don't support asynchronously telling a process to
1492 * stop capturing; instead, we check for an indication on a pipe
1493 * after processing packets. We therefore process only one packet
1494 * at a time, so that we can check the pipe after every packet.
1496 inpkts = pcap_dispatch(ld->pcap_h, 1, ld->packet_cb, (u_char *) ld);
1498 inpkts = pcap_dispatch(ld->pcap_h, -1, ld->packet_cb, (u_char *) ld);
1502 /* Error, rather than pcap_breakloop(). */
1503 ld->pcap_err = TRUE;
1505 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1507 #else /* pcap_next_ex */
1508 #ifdef LOG_CAPTURE_VERBOSE
1509 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
1511 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
1514 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
1515 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
1516 * This should be fixed in the WinPcap 4.0 alpha release.
1518 * For reference, an example remote interface:
1519 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
1522 /* emulate dispatch from pcap */
1525 struct pcap_pkthdr *pkt_header;
1530 (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1)
1531 ld->packet_cb( (u_char *) ld, pkt_header, pkt_data);
1534 ld->pcap_err = TRUE;
1538 #endif /* pcap_next_ex */
1542 #ifdef LOG_CAPTURE_VERBOSE
1543 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
1546 return ld->packet_count - packet_count_before;
1550 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
1551 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
1553 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
1554 char *errmsg, int errmsg_len) {
1556 char tmpname[128+1];
1557 gchar *capfile_name;
1558 gboolean is_tempfile;
1561 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
1562 (capture_opts->save_file) ? capture_opts->save_file : "");
1564 if (capture_opts->save_file != NULL) {
1565 /* We return to the caller while the capture is in progress.
1566 * Therefore we need to take a copy of save_file in
1567 * case the caller destroys it after we return.
1569 capfile_name = g_strdup(capture_opts->save_file);
1571 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
1572 if (capture_opts->multi_files_on) {
1573 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
1574 g_snprintf(errmsg, errmsg_len,
1575 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
1576 g_free(capfile_name);
1579 if (strcmp(capfile_name, "-") == 0) {
1580 /* write to stdout */
1583 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
1584 _setmode(1, O_BINARY);
1587 } /* if (...output_to_pipe ... */
1590 if (capture_opts->multi_files_on) {
1591 /* ringbuffer is enabled */
1592 *save_file_fd = ringbuf_init(capfile_name,
1593 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
1595 /* we need the ringbuf name */
1596 if(*save_file_fd != -1) {
1597 g_free(capfile_name);
1598 capfile_name = g_strdup(ringbuf_current_filename());
1601 /* Try to open/create the specified file for use as a capture buffer. */
1602 *save_file_fd = eth_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
1606 is_tempfile = FALSE;
1608 /* Choose a random name for the temporary capture buffer */
1609 *save_file_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
1610 capfile_name = g_strdup(tmpname);
1614 /* did we fail to open the output file? */
1615 if (*save_file_fd == -1) {
1617 g_snprintf(errmsg, errmsg_len,
1618 "The temporary file to which the capture would be saved (\"%s\") "
1619 "could not be opened: %s.", capfile_name, strerror(errno));
1621 if (capture_opts->multi_files_on) {
1622 ringbuf_error_cleanup();
1625 g_snprintf(errmsg, errmsg_len,
1626 "The file to which the capture would be saved (\"%s\") "
1627 "could not be opened: %s.", capfile_name,
1630 g_free(capfile_name);
1634 if(capture_opts->save_file != NULL) {
1635 g_free(capture_opts->save_file);
1637 capture_opts->save_file = capfile_name;
1638 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
1639 "g_free(capfile_name)". */
1641 fchown(*save_file_fd, capture_opts->owner, capture_opts->group);
1649 capture_loop_stop_signal_handler(int signo _U_)
1651 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Signal: Stop capture");
1652 capture_loop_stop();
1656 #define TIME_GET() GetTickCount()
1658 #define TIME_GET() time(NULL)
1661 /* Do the low-level work of a capture.
1662 Returns TRUE if it succeeds, FALSE otherwise. */
1664 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
1667 struct sigaction act;
1669 time_t upd_time, cur_time;
1673 gint inpkts_to_sync_pipe = 0; /* packets not already send out to the sync_pipe */
1674 condition *cnd_file_duration = NULL;
1675 condition *cnd_autostop_files = NULL;
1676 condition *cnd_autostop_size = NULL;
1677 condition *cnd_autostop_duration = NULL;
1678 guint32 autostop_files = 0;
1681 gboolean cfilter_error = FALSE;
1682 #define MSG_MAX_LENGTH 4096
1683 char errmsg[MSG_MAX_LENGTH+1];
1684 char secondary_errmsg[MSG_MAX_LENGTH+1];
1685 int save_file_fd = -1;
1688 *secondary_errmsg = '\0';
1690 /* init the loop data */
1692 ld.packet_count = 0;
1693 if (capture_opts->has_autostop_packets)
1694 ld.packet_max = capture_opts->autostop_packets;
1696 ld.packet_max = 0; /* no limit */
1697 ld.err = 0; /* no error seen yet */
1698 ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
1699 ld.pcap_err = FALSE;
1700 ld.from_cap_pipe = FALSE;
1702 ld.cap_pipe_fd = -1;
1703 #ifdef MUST_DO_SELECT
1706 ld.packet_cb = capture_loop_packet_cb;
1709 /* We haven't yet gotten the capture statistics. */
1710 *stats_known = FALSE;
1714 * Catch SIGUSR1, so that we exit cleanly if the parent process
1715 * kills us with it due to the user selecting "Capture->Stop".
1717 act.sa_handler = capture_loop_stop_signal_handler;
1719 * Arrange that system calls not get restarted, because when
1720 * our signal handler returns we don't want to restart
1721 * a call that was waiting for packets to arrive.
1724 sigemptyset(&act.sa_mask);
1725 sigaction(SIGUSR1, &act, NULL);
1728 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
1729 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
1731 /* open the "input file" from network interface or capture pipe */
1732 if (!capture_loop_open_input(capture_opts, &ld, errmsg, sizeof(errmsg),
1733 secondary_errmsg, sizeof(secondary_errmsg))) {
1737 /* init the input filter from the network interface (capture pipe will do nothing) */
1738 switch (capture_loop_init_filter(ld.pcap_h, ld.from_cap_pipe, capture_opts->iface, capture_opts->cfilter)) {
1740 case INITFILTER_NO_ERROR:
1743 case INITFILTER_BAD_FILTER:
1744 cfilter_error = TRUE;
1745 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(ld.pcap_h));
1748 case INITFILTER_OTHER_ERROR:
1749 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
1750 pcap_geterr(ld.pcap_h));
1751 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
1755 /* If we're supposed to write to a capture file, open it for output
1756 (temporary/specified name/ringbuffer) */
1757 if (capture_opts->saving_to_file) {
1758 if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
1762 /* set up to write to the already-opened capture output file/files */
1763 if (!capture_loop_init_output(capture_opts, save_file_fd, &ld, errmsg, sizeof(errmsg))) {
1767 /* XXX - capture SIGTERM and close the capture, in case we're on a
1768 Linux 2.0[.x] system and you have to explicitly close the capture
1769 stream in order to turn promiscuous mode off? We need to do that
1770 in other places as well - and I don't think that works all the
1771 time in any case, due to libpcap bugs. */
1773 /* Well, we should be able to start capturing.
1775 Sync out the capture file, so the header makes it to the file system,
1776 and send a "capture started successfully and capture file created"
1777 message to our parent so that they'll open the capture file and
1778 update its windows to indicate that we have a live capture in
1780 libpcap_dump_flush(ld.pdh, NULL);
1781 report_new_capture_file(capture_opts->save_file);
1784 /* initialize capture stop (and alike) conditions */
1785 init_capture_stop_conditions();
1786 /* create stop conditions */
1787 if (capture_opts->has_autostop_filesize)
1789 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
1790 if (capture_opts->has_autostop_duration)
1791 cnd_autostop_duration =
1792 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
1794 if (capture_opts->multi_files_on) {
1795 if (capture_opts->has_file_duration)
1797 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
1799 if (capture_opts->has_autostop_files)
1800 cnd_autostop_files =
1801 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
1804 /* init the time values */
1805 start_time = TIME_GET();
1806 upd_time = TIME_GET();
1808 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
1810 /* WOW, everything is prepared! */
1811 /* please fasten your seat belts, we will enter now the actual capture loop */
1813 /* dispatch incoming packets */
1814 inpkts = capture_loop_dispatch(capture_opts, &ld, errmsg, sizeof(errmsg));
1817 /* any news from our parent (signal pipe)? -> just stop the capture */
1818 if (!signal_pipe_check_running()) {
1824 inpkts_to_sync_pipe += inpkts;
1826 /* check capture size condition */
1827 if (cnd_autostop_size != NULL &&
1828 cnd_eval(cnd_autostop_size, (guint32)ld.bytes_written)){
1829 /* Capture size limit reached, do we have another file? */
1830 if (capture_opts->multi_files_on) {
1831 if (cnd_autostop_files != NULL &&
1832 cnd_eval(cnd_autostop_files, ++autostop_files)) {
1833 /* no files left: stop here */
1838 /* Switch to the next ringbuffer file */
1839 if (ringbuf_switch_file(&ld.pdh, &capture_opts->save_file,
1840 &save_file_fd, &ld.bytes_written, &ld.err)) {
1841 /* File switch succeeded: reset the conditions */
1842 cnd_reset(cnd_autostop_size);
1843 if (cnd_file_duration) {
1844 cnd_reset(cnd_file_duration);
1846 libpcap_dump_flush(ld.pdh, NULL);
1847 report_packet_count(inpkts_to_sync_pipe);
1848 inpkts_to_sync_pipe = 0;
1849 report_new_capture_file(capture_opts->save_file);
1851 /* File switch failed: stop here */
1856 /* single file, stop now */
1860 } /* cnd_autostop_size */
1861 if (capture_opts->output_to_pipe) {
1862 libpcap_dump_flush(ld.pdh, NULL);
1866 /* Only update once a second (Win32: 500ms) so as not to overload slow
1867 * displays. This also prevents too much context-switching between the
1868 * dumpcap and wireshark processes */
1869 cur_time = TIME_GET();
1871 if ( (cur_time - upd_time) > 500) {
1873 if (cur_time - upd_time > 0) {
1875 upd_time = cur_time;
1877 /*if (pcap_stats(pch, stats) >= 0) {
1878 *stats_known = TRUE;
1881 /* Let the parent process know. */
1882 if (inpkts_to_sync_pipe) {
1884 libpcap_dump_flush(ld.pdh, NULL);
1886 /* Send our parent a message saying we've written out "inpkts_to_sync_pipe"
1887 packets to the capture file. */
1888 report_packet_count(inpkts_to_sync_pipe);
1890 inpkts_to_sync_pipe = 0;
1893 /* check capture duration condition */
1894 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
1895 /* The maximum capture time has elapsed; stop the capture. */
1900 /* check capture file duration condition */
1901 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
1902 /* duration limit reached, do we have another file? */
1903 if (capture_opts->multi_files_on) {
1904 if (cnd_autostop_files != NULL &&
1905 cnd_eval(cnd_autostop_files, ++autostop_files)) {
1906 /* no files left: stop here */
1911 /* Switch to the next ringbuffer file */
1912 if (ringbuf_switch_file(&ld.pdh, &capture_opts->save_file,
1913 &save_file_fd, &ld.bytes_written, &ld.err)) {
1914 /* file switch succeeded: reset the conditions */
1915 cnd_reset(cnd_file_duration);
1916 if(cnd_autostop_size)
1917 cnd_reset(cnd_autostop_size);
1918 libpcap_dump_flush(ld.pdh, NULL);
1919 report_packet_count(inpkts_to_sync_pipe);
1920 inpkts_to_sync_pipe = 0;
1921 report_new_capture_file(capture_opts->save_file);
1923 /* File switch failed: stop here */
1928 /* single file, stop now */
1932 } /* cnd_file_duration */
1935 } /* while (ld.go) */
1937 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
1939 /* delete stop conditions */
1940 if (cnd_file_duration != NULL)
1941 cnd_delete(cnd_file_duration);
1942 if (cnd_autostop_files != NULL)
1943 cnd_delete(cnd_autostop_files);
1944 if (cnd_autostop_size != NULL)
1945 cnd_delete(cnd_autostop_size);
1946 if (cnd_autostop_duration != NULL)
1947 cnd_delete(cnd_autostop_duration);
1949 /* did we had a pcap (input) error? */
1951 /* On Linux, if an interface goes down while you're capturing on it,
1952 you'll get a "recvfrom: Network is down" error (ENETDOWN).
1953 (At least you will if strerror() doesn't show a local translation
1956 On FreeBSD and OS X, if a network adapter disappears while
1957 you're capturing on it, you'll get a "read: Device not configured"
1958 error (ENXIO). (See previous parenthetical note.)
1960 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
1962 These should *not* be reported to the Wireshark developers. */
1965 cap_err_str = pcap_geterr(ld.pcap_h);
1966 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
1967 strcmp(cap_err_str, "read: Device not configured") == 0 ||
1968 strcmp(cap_err_str, "read: I/O error") == 0) {
1969 report_capture_error("The network adapter on which the capture was being done "
1970 "is no longer running; the capture has stopped.",
1973 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
1975 report_capture_error(errmsg, please_report);
1978 else if (ld.from_cap_pipe && ld.cap_pipe_err == PIPERR)
1979 report_capture_error(errmsg, "");
1981 /* did we had an error while capturing? */
1985 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, ld.err,
1987 report_capture_error(errmsg, please_report);
1991 if (capture_opts->saving_to_file) {
1992 /* close the wiretap (output) file */
1993 close_ok = capture_loop_close_output(capture_opts, &ld, &err_close);
1997 /* there might be packets not yet notified to the parent */
1998 /* (do this after closing the file, so all packets are already flushed) */
1999 if(inpkts_to_sync_pipe) {
2000 report_packet_count(inpkts_to_sync_pipe);
2001 inpkts_to_sync_pipe = 0;
2004 /* If we've displayed a message about a write error, there's no point
2005 in displaying another message about an error on close. */
2006 if (!close_ok && write_ok) {
2007 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
2009 report_capture_error(errmsg, "");
2013 * XXX We exhibit different behaviour between normal mode and sync mode
2014 * when the pipe is stdin and not already at EOF. If we're a child, the
2015 * parent's stdin isn't closed, so if the user starts another capture,
2016 * cap_pipe_open_live() will very likely not see the expected magic bytes and
2017 * will say "Unrecognized libpcap format". On the other hand, in normal
2018 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
2021 /* get packet drop statistics from pcap */
2022 if(ld.pcap_h != NULL) {
2023 g_assert(!ld.from_cap_pipe);
2024 /* Get the capture statistics, so we know how many packets were
2026 if (pcap_stats(ld.pcap_h, stats) >= 0) {
2027 *stats_known = TRUE;
2028 /* Let the parent process know. */
2029 report_packet_drops(stats->ps_drop);
2031 g_snprintf(errmsg, sizeof(errmsg),
2032 "Can't get packet-drop statistics: %s",
2033 pcap_geterr(ld.pcap_h));
2034 report_capture_error(errmsg, please_report);
2038 /* close the input file (pcap or capture pipe) */
2039 capture_loop_close_input(&ld);
2041 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
2043 /* ok, if the write and the close were successful. */
2044 return write_ok && close_ok;
2047 if (capture_opts->multi_files_on) {
2048 /* cleanup ringbuffer */
2049 ringbuf_error_cleanup();
2051 /* We can't use the save file, and we have no FILE * for the stream
2052 to close in order to close it, so close the FD directly. */
2053 if(save_file_fd != -1) {
2054 eth_close(save_file_fd);
2057 /* We couldn't even start the capture, so get rid of the capture
2059 if(capture_opts->save_file != NULL) {
2060 eth_unlink(capture_opts->save_file);
2061 g_free(capture_opts->save_file);
2064 capture_opts->save_file = NULL;
2066 report_cfilter_error(capture_opts->cfilter, errmsg);
2068 report_capture_error(errmsg, secondary_errmsg);
2070 /* close the input file (pcap or cap_pipe) */
2071 capture_loop_close_input(&ld);
2073 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
2079 static void capture_loop_stop(void)
2081 #ifdef HAVE_PCAP_BREAKLOOP
2082 if(ld.pcap_h != NULL)
2083 pcap_breakloop(ld.pcap_h);
2090 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
2091 int err, gboolean is_close)
2096 g_snprintf(errmsg, errmsglen,
2097 "Not all the packets could be written to the file"
2098 " to which the capture was being saved\n"
2099 "(\"%s\") because there is no space left on the file system\n"
2100 "on which that file resides.",
2106 g_snprintf(errmsg, errmsglen,
2107 "Not all the packets could be written to the file"
2108 " to which the capture was being saved\n"
2109 "(\"%s\") because you are too close to, or over,"
2110 " your disk quota\n"
2111 "on the file system on which that file resides.",
2116 case WTAP_ERR_CANT_CLOSE:
2117 g_snprintf(errmsg, errmsglen,
2118 "The file to which the capture was being saved"
2119 " couldn't be closed for some unknown reason.");
2122 case WTAP_ERR_SHORT_WRITE:
2123 g_snprintf(errmsg, errmsglen,
2124 "Not all the packets could be written to the file"
2125 " to which the capture was being saved\n"
2132 g_snprintf(errmsg, errmsglen,
2133 "The file to which the capture was being saved\n"
2134 "(\"%s\") could not be closed: %s.",
2135 fname, wtap_strerror(err));
2137 g_snprintf(errmsg, errmsglen,
2138 "An error occurred while writing to the file"
2139 " to which the capture was being saved\n"
2141 fname, wtap_strerror(err));
2148 /* one packet was captured, process it */
2150 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
2153 loop_data *ld = (void *) user;
2156 /* if the user told us to stop after x packets, do we already have enough? */
2157 if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
2163 /* We may be called multiple times from pcap_dispatch(); if we've set
2164 the "stop capturing" flag, ignore this packet, as we're not
2165 supposed to be saving any more packets. */
2170 /* We're supposed to write the packet to a file; do so.
2171 If this fails, set "ld->go" to FALSE, to stop the capture, and set
2172 "ld->err" to the error. */
2173 if (!libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err)) {
2182 /* And now our feature presentation... [ fade to music ] */
2184 main(int argc, char *argv[])
2187 extern char *optarg;
2188 gboolean arg_error = FALSE;
2194 struct sigaction action, oldaction;
2197 gboolean start_capture = TRUE;
2198 gboolean stats_known;
2199 struct pcap_stat stats;
2200 GLogLevelFlags log_flags;
2201 gboolean list_interfaces = FALSE;
2202 gboolean list_link_layer_types = FALSE;
2203 gboolean machine_readable = FALSE;
2204 gboolean print_statistics = FALSE;
2205 int status, run_once_args = 0;
2207 #ifdef HAVE_PCAP_REMOTE
2208 #define OPTSTRING_INIT "a:A:b:c:Df:hi:Lm:MprSs:uvw:y:Z:"
2210 #define OPTSTRING_INIT "a:b:c:Df:hi:LMpSs:vw:y:Z:"
2214 #define OPTSTRING_WIN32 "B:"
2216 #define OPTSTRING_WIN32 ""
2219 char optstring[sizeof(OPTSTRING_INIT) + sizeof(OPTSTRING_WIN32) - 1] =
2220 OPTSTRING_INIT OPTSTRING_WIN32;
2223 /* Load wpcap if possible. Do this before collecting the run-time version information */
2226 /* ... and also load the packet.dll from wpcap */
2227 /* XXX - currently not required, may change later. */
2228 /*wpcap_packet_load();*/
2230 /* Start windows sockets */
2231 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
2233 /* Set handler for Ctrl+C key */
2234 SetConsoleCtrlHandler(capture_cleanup, TRUE);
2236 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
2238 action.sa_handler = capture_cleanup;
2239 action.sa_flags = 0;
2240 sigemptyset(&action.sa_mask);
2241 sigaction(SIGTERM, &action, NULL);
2242 sigaction(SIGINT, &action, NULL);
2243 sigaction(SIGHUP, NULL, &oldaction);
2244 if (oldaction.sa_handler == SIG_DFL)
2245 sigaction(SIGHUP, &action, NULL);
2249 get_credential_info();
2250 relinquish_privs_except_capture();
2253 /* the default_log_handler will use stdout, which makes trouble in */
2254 /* capture child mode, as it uses stdout for it's sync_pipe */
2255 /* so do the filtering in the console_log_handler and not here */
2258 G_LOG_LEVEL_CRITICAL|
2259 G_LOG_LEVEL_WARNING|
2260 G_LOG_LEVEL_MESSAGE|
2263 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
2265 g_log_set_handler(NULL,
2267 console_log_handler, NULL /* user_data */);
2268 g_log_set_handler(LOG_DOMAIN_MAIN,
2270 console_log_handler, NULL /* user_data */);
2271 g_log_set_handler(LOG_DOMAIN_CAPTURE,
2273 console_log_handler, NULL /* user_data */);
2274 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
2276 console_log_handler, NULL /* user_data */);
2278 /* Set the initial values in the capture_opts. This might be overwritten
2279 by the command line parameters. */
2280 capture_opts_init(capture_opts, NULL);
2282 /* Default to capturing the entire packet. */
2283 capture_opts->snaplen = WTAP_MAX_PACKET_SIZE;
2285 /* We always save to a file - if no file was specified, we save to a
2287 capture_opts->saving_to_file = TRUE;
2288 capture_opts->has_ring_num_files = TRUE;
2290 /* Now get our args */
2291 while ((opt = getopt(argc, argv, optstring)) != -1) {
2293 case 'h': /* Print help and exit */
2297 case 'v': /* Show version and exit */
2299 GString *comp_info_str;
2300 GString *runtime_info_str;
2301 /* Assemble the compile-time version information string */
2302 comp_info_str = g_string_new("Compiled ");
2303 get_compiled_version_info(comp_info_str, NULL);
2305 /* Assemble the run-time version information string */
2306 runtime_info_str = g_string_new("Running ");
2307 get_runtime_version_info(runtime_info_str, NULL);
2308 show_version(comp_info_str, runtime_info_str);
2309 g_string_free(comp_info_str, TRUE);
2310 g_string_free(runtime_info_str, TRUE);
2314 /*** capture option specific ***/
2315 case 'a': /* autostop criteria */
2316 case 'b': /* Ringbuffer option */
2317 case 'c': /* Capture x packets */
2318 case 'f': /* capture filter */
2319 case 'i': /* Use interface x */
2320 case 'p': /* Don't capture in promiscuous mode */
2321 case 's': /* Set the snapshot (capture) length */
2322 case 'w': /* Write to capture file x */
2323 case 'y': /* Set the pcap data link type */
2324 #ifdef HAVE_PCAP_REMOTE
2325 case 'u': /* Use UDP for data transfer */
2326 case 'r': /* Capture own RPCAP traffic too */
2327 case 'A': /* Authentication */
2329 #ifdef HAVE_PCAP_SETSAMPLING
2330 case 'm': /* Sampling */
2333 case 'B': /* Buffer size */
2335 status = capture_opts_add_opt(capture_opts, opt, optarg, &start_capture);
2340 /*** hidden option: Wireshark child mode (using binary output messages) ***/
2342 capture_child = TRUE;
2344 /* set output pipe to binary mode, to avoid ugly text conversions */
2345 _setmode(2, O_BINARY);
2347 * optarg = the control ID, aka the PPID, currently used for the
2350 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
2351 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT,
2353 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
2354 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
2356 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
2357 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2358 "Signal pipe: Unable to open %s. Dead parent?",
2366 /*** all non capture option specific ***/
2367 case 'D': /* Print a list of capture devices and exit */
2368 list_interfaces = TRUE;
2371 case 'L': /* Print list of link-layer types and exit */
2372 list_link_layer_types = TRUE;
2375 case 'S': /* Print interface statistics once a second */
2376 print_statistics = TRUE;
2379 case 'M': /* For -D and -L, print machine-readable output */
2380 machine_readable = TRUE;
2383 case '?': /* Bad flag - print usage message */
2384 cmdarg_err("Invalid Option: %s", argv[optind-1]);
2392 /* user specified file name as regular command-line argument */
2393 /* XXX - use it as the capture file name (or something else)? */
2400 * Extra command line arguments were specified; complain.
2401 * XXX - interpret as capture filter, as tcpdump and tshark do?
2403 cmdarg_err("Invalid argument: %s", argv[0]);
2412 if (run_once_args > 1) {
2413 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
2415 } else if (list_link_layer_types) {
2416 /* We're supposed to list the link-layer types for an interface;
2417 did the user also specify a capture file to be read? */
2418 /* No - did they specify a ring buffer option? */
2419 if (capture_opts->multi_files_on) {
2420 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
2424 /* No - was the ring buffer option specified and, if so, does it make
2426 if (capture_opts->multi_files_on) {
2427 /* Ring buffer works only under certain conditions:
2428 a) ring buffer does not work with temporary files;
2429 b) it makes no sense to enable the ring buffer if the maximum
2430 file size is set to "infinite". */
2431 if (capture_opts->save_file == NULL) {
2432 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
2433 capture_opts->multi_files_on = FALSE;
2435 if (!capture_opts->has_autostop_filesize && !capture_opts->has_file_duration) {
2436 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
2437 /* XXX - this must be redesigned as the conditions changed */
2438 /* capture_opts->multi_files_on = FALSE;*/
2443 if (capture_opts_trim_iface(capture_opts, NULL) == FALSE) {
2444 cmdarg_err("No capture interfaces available (maybe lack of privileges?).");
2448 /* Let the user know what interface was chosen. */
2449 /* get_interface_descriptive_name() is not available! */
2450 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", capture_opts->iface);
2452 if (list_interfaces) {
2453 status = capture_opts_list_interfaces(machine_readable);
2455 } else if (list_link_layer_types) {
2456 status = capture_opts_list_link_layer_types(capture_opts, machine_readable);
2458 } else if (print_statistics) {
2459 status = capture_opts_print_statistics(machine_readable);
2463 capture_opts_trim_snaplen(capture_opts, MIN_PACKET_SIZE);
2464 capture_opts_trim_ring_num_files(capture_opts);
2466 /* Now start the capture. */
2468 if(capture_loop_start(capture_opts, &stats_known, &stats) == TRUE) {
2472 /* capture failed */
2479 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
2480 const char *message, gpointer user_data _U_)
2487 /* ignore log message, if log_level isn't interesting */
2488 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
2489 #ifndef DEBUG_DUMPCAP
2494 /* create a "timestamp" */
2496 today = localtime(&curr);
2498 switch(log_level & G_LOG_LEVEL_MASK) {
2499 case G_LOG_LEVEL_ERROR:
2502 case G_LOG_LEVEL_CRITICAL:
2505 case G_LOG_LEVEL_WARNING:
2508 case G_LOG_LEVEL_MESSAGE:
2511 case G_LOG_LEVEL_INFO:
2514 case G_LOG_LEVEL_DEBUG:
2518 fprintf(stderr, "unknown log_level %u\n", log_level);
2520 g_assert_not_reached();
2523 /* don't use printf (stdout), in child mode we're using stdout for the sync_pipe */
2524 if(log_level & G_LOG_LEVEL_MESSAGE) {
2525 /* normal user messages without additional infos */
2526 fprintf(stderr, "%s\n", message);
2529 /* info/debug messages with additional infos */
2530 fprintf(stderr, "%02u:%02u:%02u %8s %s %s\n",
2531 today->tm_hour, today->tm_min, today->tm_sec,
2532 log_domain != NULL ? log_domain : "",
2539 /****************************************************************************************************************/
2540 /* indication report routines */
2544 report_packet_count(int packet_count)
2546 char tmp[SP_DECISIZE+1+1];
2547 static int count = 0;
2550 g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
2551 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
2552 pipe_write_block(2, SP_PACKET_COUNT, tmp);
2554 count += packet_count;
2555 fprintf(stderr, "\rPackets: %u ", count);
2556 /* stderr could be line buffered */
2562 report_new_capture_file(const char *filename)
2565 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
2566 pipe_write_block(2, SP_FILE, filename);
2568 fprintf(stderr, "File: %s\n", filename);
2569 /* stderr could be line buffered */
2575 report_cfilter_error(const char *cfilter, const char *errmsg)
2577 if (capture_child) {
2578 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
2579 pipe_write_block(2, SP_BAD_FILTER, errmsg);
2582 "Invalid capture filter: \"%s\"!\n"
2584 "That string isn't a valid capture filter (%s).\n"
2585 "See the User's Guide for a description of the capture filter syntax.\n",
2591 report_capture_error(const char *error_msg, const char *secondary_error_msg)
2594 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
2595 "Primary Error: %s", error_msg);
2596 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
2597 "Secondary Error: %s", secondary_error_msg);
2598 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
2600 fprintf(stderr, "%s\n%s\n", error_msg, secondary_error_msg);
2605 report_packet_drops(int drops)
2607 char tmp[SP_DECISIZE+1+1];
2609 g_snprintf(tmp, sizeof(tmp), "%d", drops);
2612 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
2613 pipe_write_block(2, SP_DROPS, tmp);
2615 fprintf(stderr, "Packets dropped: %s\n", tmp);
2616 /* stderr could be line buffered */
2622 /****************************************************************************************************************/
2623 /* signal_pipe handling */
2628 signal_pipe_check_running(void)
2630 /* any news from our parent? -> just stop the capture */
2634 /* if we are running standalone, no check required */
2635 if(!capture_child) {
2639 if(!sig_pipe_name || !sig_pipe_handle) {
2640 /* This shouldn't happen */
2641 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2642 "Signal pipe: No name or handle");
2647 * XXX - We should have the process ID of the parent (from the "-Z" flag)
2648 * at this point. Should we check to see if the parent is still alive,
2649 * e.g. by using OpenProcess?
2652 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
2654 if(!result || avail > 0) {
2655 /* peek failed or some bytes really available */
2656 /* (if not piping from stdin this would fail) */
2657 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2658 "Signal pipe: Stop capture: %s", sig_pipe_name);
2659 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
2660 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
2661 sig_pipe_handle, result, avail);
2664 /* pipe ok and no bytes available */