5 * Wireshark - Network traffic analyzer
6 * By Gerald Combs <gerald@wireshark.org>
7 * Copyright 1998 Gerald Combs
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
28 #include <stdlib.h> /* for exit() */
34 #ifdef HAVE_SYS_TYPES_H
35 # include <sys/types.h>
38 #ifdef HAVE_SYS_STAT_H
39 # include <sys/stat.h>
62 # include <sys/prctl.h>
63 # include <sys/capability.h>
67 #include "ringbuffer.h"
68 #include "clopts_common.h"
69 #include "cmdarg_err.h"
70 #include "version_info.h"
75 #include "capture-pcap-util.h"
78 #include "capture-wpcap.h"
82 #include <wsutil/unicode-utils.h>
85 #include <wsutil/privileges.h>
87 #include "sync_pipe.h"
89 #include "capture_opts.h"
90 #include "capture_sync.h"
92 #include "conditions.h"
93 #include "capture_stop_conditions.h"
97 #include "wsutil/file_util.h"
100 * Get information about libpcap format from "wiretap/libpcap.h".
101 * XXX - can we just use pcap_open_offline() to read the pipe?
103 #include "wiretap/libpcap.h"
105 /**#define DEBUG_DUMPCAP**/
106 /**#define DEBUG_CHILD_DUMPCAP**/
108 #ifdef DEBUG_CHILD_DUMPCAP
109 FILE *debug_log; /* for logging debug messages to */
110 /* a file if DEBUG_CHILD_DUMPCAP */
114 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
116 static gchar *sig_pipe_name = NULL;
117 static HANDLE sig_pipe_handle = NULL;
120 /** Stop a low-level capture (stops the capture child). */
121 static void capture_loop_stop(void);
123 #if !defined (__linux__)
124 #ifndef HAVE_PCAP_BREAKLOOP
126 * We don't have pcap_breakloop(), which is the only way to ensure that
127 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
128 * won't, if the call to read the next packet or batch of packets is
129 * is interrupted by a signal on UN*X, just go back and try again to
132 * On UN*X, we catch SIGUSR1 as a "stop capturing" signal, and, in
133 * the signal handler, set a flag to stop capturing; however, without
134 * a guarantee of that sort, we can't guarantee that we'll stop capturing
135 * if the read will be retried and won't time out if no packets arrive.
137 * Therefore, on at least some platforms, we work around the lack of
138 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
139 * to wait for packets to arrive, so that we're probably going to be
140 * blocked in the select() when the signal arrives, and can just bail
141 * out of the loop at that point.
143 * However, we don't want to that on BSD (because "select()" doesn't work
144 * correctly on BPF devices on at least some releases of some flavors of
145 * BSD), and we don't want to do it on Windows (because "select()" is
146 * something for sockets, not for arbitrary handles). (Note that "Windows"
147 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
148 * using WinPcap, not a UNIX libpcap.)
150 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
151 * on BSD times out even if no packets have arrived, so we'll eventually
152 * exit pcap_dispatch() with an indication that no packets have arrived,
153 * and will break out of the capture loop at that point.
155 * On Windows, we can't send a SIGUSR1 to stop capturing, so none of this
156 * applies in any case.
158 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
159 * want to include it if it's not present on this platform, however.
161 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
162 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
164 # define MUST_DO_SELECT
165 # endif /* avoid select */
166 #endif /* HAVE_PCAP_BREAKLOOP */
168 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
169 * in pcap_dispatch(); on the other hand, select() works just fine there.
170 * Hence we use a select for that come what may.
172 #define MUST_DO_SELECT
175 /** init the capture filter */
178 INITFILTER_BAD_FILTER,
179 INITFILTER_OTHER_ERROR
180 } initfilter_status_t;
182 typedef struct _loop_data {
184 gboolean go; /* TRUE as long as we're supposed to keep capturing */
185 int err; /* if non-zero, error seen while capturing */
186 gint packet_count; /* Number of packets we have already captured */
187 gint packet_max; /* Number of packets we're supposed to capture - 0 means infinite */
189 /* pcap "input file" */
190 pcap_t *pcap_h; /* pcap handle */
191 gboolean pcap_err; /* TRUE if error from pcap */
192 #ifdef MUST_DO_SELECT
193 int pcap_fd; /* pcap file descriptor */
196 /* capture pipe (unix only "input file") */
197 gboolean from_cap_pipe; /* TRUE if we are capturing data from a capture pipe */
198 struct pcap_hdr cap_pipe_hdr; /* Pcap header when capturing from a pipe */
199 struct pcaprec_modified_hdr cap_pipe_rechdr; /* Pcap record header when capturing from a pipe */
200 int cap_pipe_fd; /* the file descriptor of the capture pipe */
201 gboolean cap_pipe_modified; /* TRUE if data in the pipe uses modified pcap headers */
202 gboolean cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
203 unsigned int cap_pipe_bytes_to_read;/* Used by cap_pipe_dispatch */
204 unsigned int cap_pipe_bytes_read; /* Used by cap_pipe_dispatch */
206 STATE_EXPECT_REC_HDR,
211 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
222 * Standard secondary message for unexpected errors.
224 static const char please_report[] =
225 "Please report this to the Wireshark developers.\n"
226 "(This is not a crash; please do not report it as such.)";
229 * This needs to be static, so that the SIGUSR1 handler can clear the "go"
232 static loop_data global_ld;
236 * Timeout, in milliseconds, for reads from the stream of captured packets.
238 #define CAP_READ_TIMEOUT 250
239 static char *cap_pipe_err_str;
242 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
243 const char *message, gpointer user_data _U_);
245 /* capture related options */
246 static capture_options global_capture_opts;
248 static void capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
250 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
251 int err, gboolean is_close);
255 static void exit_main(int err) __attribute__ ((noreturn));
257 static void exit_main(int err);
260 static void report_new_capture_file(const char *filename);
261 static void report_packet_count(int packet_count);
262 static void report_packet_drops(guint32 drops);
263 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
264 static void report_cfilter_error(const char *cfilter, const char *errmsg);
267 static gboolean signal_pipe_check_running(void);
271 print_usage(gboolean print_ver) {
279 "Dumpcap " VERSION "%s\n"
280 "Capture network packets and dump them into a libpcap file.\n"
281 "See http://www.wireshark.org for more information.\n",
282 wireshark_svnversion);
286 fprintf(output, "\nUsage: dumpcap [options] ...\n");
287 fprintf(output, "\n");
288 fprintf(output, "Capture interface:\n");
289 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
290 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
291 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
292 fprintf(output, " -p don't capture in promiscuous mode\n");
294 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
296 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
297 fprintf(output, " -D print list of interfaces and exit\n");
298 fprintf(output, " -L print list of link-layer types of iface and exit\n");
299 fprintf(output, " -S print statistics for each interface once every second\n");
300 fprintf(output, " -M for -D, -L, and -S produce machine-readable output\n");
301 fprintf(output, "\n");
302 #ifdef HAVE_PCAP_REMOTE
303 fprintf(output, "\nRPCAP options:\n");
304 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
305 fprintf(output, " -u use UDP for RPCAP data transfer\n");
306 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
307 #ifdef HAVE_PCAP_SETSAMPLING
308 fprintf(output, " -m <sampling type> use packet sampling\n");
309 fprintf(output, " count:NUM - capture one packet of every NUM\n");
310 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
313 fprintf(output, "Stop conditions:\n");
314 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
315 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
316 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
317 fprintf(output, " files:NUM - stop after NUM files\n");
318 /*fprintf(output, "\n");*/
319 fprintf(output, "Output (files):\n");
320 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
321 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
322 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
323 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
324 /*fprintf(output, "\n");*/
325 fprintf(output, "Miscellaneous:\n");
326 fprintf(output, " -v print version information and exit\n");
327 fprintf(output, " -h display this help and exit\n");
328 fprintf(output, "\n");
329 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcap\n");
330 fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcap\"\n");
331 fprintf(output, "\n");
332 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
336 show_version(GString *comp_info_str, GString *runtime_info_str)
340 "Dumpcap " VERSION "%s\n"
345 "See http://www.wireshark.org for more information.\n",
346 wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
350 * Report an error in command-line arguments.
353 cmdarg_err(const char *fmt, ...)
359 /* Generate a 'special format' message back to parent */
361 msg = g_strdup_vprintf(fmt, ap);
362 sync_pipe_errmsg_to_parent(2, msg, "");
367 fprintf(stderr, "dumpcap: ");
368 vfprintf(stderr, fmt, ap);
369 fprintf(stderr, "\n");
375 * Report additional information for an error in command-line arguments.
378 cmdarg_err_cont(const char *fmt, ...)
385 msg = g_strdup_vprintf(fmt, ap);
386 sync_pipe_errmsg_to_parent(2, msg, "");
391 vfprintf(stderr, fmt, ap);
392 fprintf(stderr, "\n");
402 /* Print the number of packets captured for each interface until we're killed. */
404 print_statistics_loop(gboolean machine_readable)
406 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
412 char errbuf[PCAP_ERRBUF_SIZE];
415 struct sigaction act;
418 if_list = get_interface_list(&err, &err_str);
419 if (if_list == NULL) {
421 case CANT_GET_INTERFACE_LIST:
422 cmdarg_err("%s", err_str);
426 case NO_INTERFACES_FOUND:
427 cmdarg_err("There are no interfaces on which a capture can be done");
433 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
434 if_info = if_entry->data;
435 #ifdef HAVE_PCAP_OPEN
436 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
438 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
442 if_stat = g_malloc(sizeof(if_stat_t));
443 if_stat->name = g_strdup(if_info->name);
445 stat_list = g_list_append(stat_list, if_stat);
450 cmdarg_err("There are no interfaces on which a capture can be done");
454 if (!machine_readable) {
455 printf("%-15s %10s %10s\n", "Interface", "Received",
460 /* handle SIGPIPE signal to default action */
461 act.sa_handler = SIG_DFL;
462 sigemptyset(&act.sa_mask);
463 act.sa_flags = SA_RESTART;
464 sigaction(SIGPIPE,&act,NULL);
468 while (global_ld.go) {
469 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
470 if_stat = stat_entry->data;
471 pcap_stats(if_stat->pch, &ps);
473 if (!machine_readable) {
474 printf("%-15s %10u %10u\n", if_stat->name,
475 ps.ps_recv, ps.ps_drop);
477 printf("%s\t%u\t%u\n", if_stat->name,
478 ps.ps_recv, ps.ps_drop);
489 /* XXX - Not reached. Should we look for 'q' in stdin? */
490 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
491 if_stat = stat_entry->data;
492 pcap_close(if_stat->pch);
493 g_free(if_stat->name);
496 g_list_free(stat_list);
497 free_interface_list(if_list);
505 capture_cleanup(DWORD dwCtrlType)
507 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
508 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
509 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
510 like SIGTERM at least when the machine's shutting down.
512 For now, if we're running as a command rather than a capture child,
513 we handle all but CTRL_LOGOFF_EVENT as indications that we should
514 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
517 If we're not running as a capture child, we might be running as
518 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
519 user logs out. (XXX - can we explicitly check whether we're
520 running as a service?) */
522 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
523 "Console: Control signal");
524 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
525 "Console: Control signal, CtrlType: %u", dwCtrlType);
527 /* Keep capture running if we're a service and a user logs off */
528 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
537 capture_cleanup(int signum)
539 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
540 SIGTERM. We assume that if the user wanted it to keep running
541 after they logged out, they'd have nohupped it. */
543 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
545 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
546 "Console: Signal, signal value: %u", signum);
552 static void exit_main(int status)
555 /* Shutdown windows sockets */
558 /* can be helpful for debugging */
560 printf("Press any key\n");
571 * If we were linked with libcap (not libpcap), make sure we have
572 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
573 * (See comment in main() for details)
577 #if 0 /* Set to enable capability debugging */
578 /* see 'man cap_to_text()' for explanation of output */
579 /* '=' means 'all= ' ie: no capabilities */
580 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
582 print_caps(char *pfx) {
583 cap_t caps = cap_get_proc();
584 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
585 "%s: EUID: %d Capabilities: %s", pfx,
586 geteuid(), cap_to_text(caps, NULL));
589 print_caps(char *pfx _U_) {
594 relinquish_privs_except_capture(void)
596 /* If 'started_with_special_privs' (ie: suid) then enable for
597 * ourself the NET_ADMIN and NET_RAW capabilities and then
598 * drop our suid privileges.
600 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
601 * stuff we don't need (and shouldn't have).
602 * CAP_NET_RAW: Packet capture (raw sockets).
605 if (started_with_special_privs()) {
606 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
607 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
609 cap_t caps = cap_init(); /* all capabilities initialized to off */
611 print_caps("Pre drop, pre set");
613 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
614 cmdarg_err("prctl() fail return: %s", strerror(errno));
617 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
618 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
620 if (cap_set_proc(caps)) {
621 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
623 print_caps("Pre drop, post set");
625 relinquish_special_privs_perm();
627 print_caps("Post drop, pre set");
628 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
629 if (cap_set_proc(caps)) {
630 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
632 print_caps("Post drop, post set");
640 relinquish_all_capabilities()
642 /* Drop any and all capabilities this process may have. */
643 /* Allowed whether or not process has any privileges. */
644 cap_t caps = cap_init(); /* all capabilities initialized to off */
645 print_caps("Pre-clear");
646 if (cap_set_proc(caps)) {
647 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
649 print_caps("Post-clear");
653 #endif /* HAVE_LIBCAP */
655 /* Take care of byte order in the libpcap headers read from pipes.
656 * (function taken from wiretap/libpcap.c) */
658 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
661 /* Byte-swap the record header fields. */
662 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
663 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
664 rechdr->incl_len = BSWAP32(rechdr->incl_len);
665 rechdr->orig_len = BSWAP32(rechdr->orig_len);
668 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
669 swapped, in order to match the BPF header layout.
671 Unfortunately, some files were, according to a comment in the "libpcap"
672 source, written with version 2.3 in their headers but without the
673 interchanged fields, so if "incl_len" is greater than "orig_len" - which
674 would make no sense - we assume that we need to swap them. */
675 if (hdr->version_major == 2 &&
676 (hdr->version_minor < 3 ||
677 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
680 temp = rechdr->orig_len;
681 rechdr->orig_len = rechdr->incl_len;
682 rechdr->incl_len = temp;
686 /* Provide select() functionality for a single file descriptor
687 * on both UNIX/POSIX and Windows.
689 * The Windows version calls WaitForSingleObject instead of
692 * Returns the same values as select. If an error is returned,
693 * the string cap_pipe_err_str should be used instead of errno.
696 cap_pipe_select(int pipe_fd) {
699 struct timeval timeout, *pto;
702 cap_pipe_err_str = "Unknown error";
705 FD_SET(pipe_fd, &rfds);
708 timeout.tv_usec = CAP_READ_TIMEOUT * 1000;
711 sel_ret = select(pipe_fd+1, &rfds, NULL, NULL, pto);
713 cap_pipe_err_str = strerror(errno);
717 /* XXX - Should we just use file handles exclusively under Windows?
718 * Otherwise we have to convert between file handles and file descriptors
719 * here and when we open a named pipe.
721 HANDLE hPipe = (HANDLE) _get_osfhandle(pipe_fd);
725 if (hPipe == INVALID_HANDLE_VALUE) {
726 cap_pipe_err_str = "Could not open standard input";
730 cap_pipe_err_str = "Unknown error";
732 wait_ret = WaitForSingleObject(hPipe, CAP_READ_TIMEOUT);
734 /* XXX - This probably isn't correct */
743 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
744 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
745 cap_pipe_err_str = utf_16to8(err_str);
749 g_assert_not_reached();
756 /* Mimic pcap_open_live() for pipe captures
757 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
759 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
760 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
762 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
763 char *errmsg, int errmsgl)
766 struct stat pipe_stat;
778 unsigned int bytes_read;
780 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
783 * XXX (T)Wireshark blocks until we return
785 if (strcmp(pipename, "-") == 0) {
786 fd = 0; /* read from stdin */
789 * This is needed to set the stdin pipe into binary mode, otherwise
790 * CR/LF are mangled...
792 _setmode(0, _O_BINARY);
796 if (ws_stat(pipename, &pipe_stat) < 0) {
797 if (errno == ENOENT || errno == ENOTDIR)
798 ld->cap_pipe_err = PIPNEXIST;
800 g_snprintf(errmsg, errmsgl,
801 "The capture session could not be initiated "
802 "due to error on pipe: %s", strerror(errno));
803 ld->cap_pipe_err = PIPERR;
807 if (! S_ISFIFO(pipe_stat.st_mode)) {
808 if (S_ISCHR(pipe_stat.st_mode)) {
810 * Assume the user specified an interface on a system where
811 * interfaces are in /dev. Pretend we haven't seen it.
813 ld->cap_pipe_err = PIPNEXIST;
816 g_snprintf(errmsg, errmsgl,
817 "The capture session could not be initiated because\n"
818 "\"%s\" is neither an interface nor a pipe", pipename);
819 ld->cap_pipe_err = PIPERR;
823 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
825 g_snprintf(errmsg, errmsgl,
826 "The capture session could not be initiated "
827 "due to error on pipe open: %s", strerror(errno));
828 ld->cap_pipe_err = PIPERR;
832 #define PIPE_STR "\\pipe\\"
833 /* Under Windows, named pipes _must_ have the form
834 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
836 pncopy = g_strdup(pipename);
837 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
838 pos = strchr(pncopy + 3, '\\');
839 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
846 g_snprintf(errmsg, errmsgl,
847 "The capture session could not be initiated because\n"
848 "\"%s\" is neither an interface nor a pipe", pipename);
849 ld->cap_pipe_err = PIPNEXIST;
853 /* Wait for the pipe to appear */
855 hPipe = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
856 OPEN_EXISTING, 0, NULL);
858 if (hPipe != INVALID_HANDLE_VALUE)
861 if (GetLastError() != ERROR_PIPE_BUSY) {
862 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
863 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
864 g_snprintf(errmsg, errmsgl,
865 "The capture session on \"%s\" could not be initiated "
866 "due to error on pipe open: pipe busy: %s (error %d)",
867 pipename, utf_16to8(err_str), GetLastError());
869 ld->cap_pipe_err = PIPERR;
873 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
874 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
875 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
876 g_snprintf(errmsg, errmsgl,
877 "The capture session could not be initiated "
878 "due to error on named pipe open: %s (error %d)",
879 utf_16to8(err_str), GetLastError());
881 ld->cap_pipe_err = PIPERR;
886 fd = _open_osfhandle((long) hPipe, _O_RDONLY);
888 g_snprintf(errmsg, errmsgl,
889 "The capture session could not be initiated "
890 "due to error on pipe open: %s", strerror(errno));
891 ld->cap_pipe_err = PIPERR;
897 ld->from_cap_pipe = TRUE;
899 /* read the pcap header */
901 while (bytes_read < sizeof magic) {
902 sel_ret = cap_pipe_select(fd);
904 g_snprintf(errmsg, errmsgl,
905 "Unexpected error from select: %s", strerror(errno));
907 } else if (sel_ret > 0) {
908 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
911 g_snprintf(errmsg, errmsgl, "End of file on pipe during open");
913 g_snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
923 /* Host that wrote it has our byte order, and was running
924 a program using either standard or ss990417 libpcap. */
925 ld->cap_pipe_byte_swapped = FALSE;
926 ld->cap_pipe_modified = FALSE;
928 case PCAP_MODIFIED_MAGIC:
929 /* Host that wrote it has our byte order, but was running
930 a program using either ss990915 or ss991029 libpcap. */
931 ld->cap_pipe_byte_swapped = FALSE;
932 ld->cap_pipe_modified = TRUE;
934 case PCAP_SWAPPED_MAGIC:
935 /* Host that wrote it has a byte order opposite to ours,
936 and was running a program using either standard or
938 ld->cap_pipe_byte_swapped = TRUE;
939 ld->cap_pipe_modified = FALSE;
941 case PCAP_SWAPPED_MODIFIED_MAGIC:
942 /* Host that wrote it out has a byte order opposite to
943 ours, and was running a program using either ss990915
944 or ss991029 libpcap. */
945 ld->cap_pipe_byte_swapped = TRUE;
946 ld->cap_pipe_modified = TRUE;
949 /* Not a "libpcap" type we know about. */
950 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
954 /* Read the rest of the header */
956 while (bytes_read < sizeof(struct pcap_hdr)) {
957 sel_ret = cap_pipe_select(fd);
959 g_snprintf(errmsg, errmsgl,
960 "Unexpected error from select: %s", strerror(errno));
962 } else if (sel_ret > 0) {
963 b = read(fd, ((char *)hdr)+bytes_read,
964 sizeof(struct pcap_hdr) - bytes_read);
967 g_snprintf(errmsg, errmsgl, "End of file on pipe during open");
969 g_snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
977 if (ld->cap_pipe_byte_swapped) {
978 /* Byte-swap the header fields about which we care. */
979 hdr->version_major = BSWAP16(hdr->version_major);
980 hdr->version_minor = BSWAP16(hdr->version_minor);
981 hdr->snaplen = BSWAP32(hdr->snaplen);
982 hdr->network = BSWAP32(hdr->network);
984 ld->linktype = hdr->network;
986 if (hdr->version_major < 2) {
987 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
991 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
992 ld->cap_pipe_err = PIPOK;
996 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
997 ld->cap_pipe_err = PIPERR;
1004 /* We read one record from the pipe, take care of byte order in the record
1005 * header, write the record to the capture file, and update capture statistics. */
1007 cap_pipe_dispatch(loop_data *ld, guchar *data, char *errmsg, int errmsgl)
1009 struct pcap_pkthdr phdr;
1011 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1015 #ifdef LOG_CAPTURE_VERBOSE
1016 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1019 switch (ld->cap_pipe_state) {
1021 case STATE_EXPECT_REC_HDR:
1022 ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
1023 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1024 ld->cap_pipe_bytes_read = 0;
1025 ld->cap_pipe_state = STATE_READ_REC_HDR;
1028 case STATE_READ_REC_HDR:
1029 b = read(ld->cap_pipe_fd, ((char *)&ld->cap_pipe_rechdr)+ld->cap_pipe_bytes_read,
1030 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1033 result = PD_PIPE_EOF;
1035 result = PD_PIPE_ERR;
1038 if ((ld->cap_pipe_bytes_read += b) < ld->cap_pipe_bytes_to_read)
1040 result = PD_REC_HDR_READ;
1043 case STATE_EXPECT_DATA:
1044 ld->cap_pipe_bytes_read = 0;
1045 ld->cap_pipe_state = STATE_READ_DATA;
1048 case STATE_READ_DATA:
1049 b = read(ld->cap_pipe_fd, data+ld->cap_pipe_bytes_read,
1050 ld->cap_pipe_rechdr.hdr.incl_len - ld->cap_pipe_bytes_read);
1053 result = PD_PIPE_EOF;
1055 result = PD_PIPE_ERR;
1058 if ((ld->cap_pipe_bytes_read += b) < ld->cap_pipe_rechdr.hdr.incl_len)
1060 result = PD_DATA_READ;
1064 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
1067 } /* switch (ld->cap_pipe_state) */
1070 * We've now read as much data as we were expecting, so process it.
1074 case PD_REC_HDR_READ:
1075 /* We've read the header. Take care of byte order. */
1076 cap_pipe_adjust_header(ld->cap_pipe_byte_swapped, &ld->cap_pipe_hdr,
1077 &ld->cap_pipe_rechdr.hdr);
1078 if (ld->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1079 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
1080 ld->packet_count+1, ld->cap_pipe_rechdr.hdr.incl_len);
1083 ld->cap_pipe_state = STATE_EXPECT_DATA;
1087 /* Fill in a "struct pcap_pkthdr", and process the packet. */
1088 phdr.ts.tv_sec = ld->cap_pipe_rechdr.hdr.ts_sec;
1089 phdr.ts.tv_usec = ld->cap_pipe_rechdr.hdr.ts_usec;
1090 phdr.caplen = ld->cap_pipe_rechdr.hdr.incl_len;
1091 phdr.len = ld->cap_pipe_rechdr.hdr.orig_len;
1093 capture_loop_packet_cb((u_char *)ld, &phdr, data);
1095 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1099 ld->cap_pipe_err = PIPEOF;
1103 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
1110 ld->cap_pipe_err = PIPERR;
1111 /* Return here rather than inside the switch to prevent GCC warning */
1116 /** Open the capture input file (pcap or capture pipe).
1117 * Returns TRUE if it succeeds, FALSE otherwise. */
1119 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
1120 char *errmsg, size_t errmsg_len,
1121 char *secondary_errmsg, size_t secondary_errmsg_len)
1123 gchar open_err_str[PCAP_ERRBUF_SIZE];
1124 gchar *sync_msg_str;
1125 static const char ppamsg[] = "can't find PPA for ";
1126 const char *set_linktype_err_str;
1127 const char *libpcap_warn;
1129 gchar *sync_secondary_msg_str;
1131 WORD wVersionRequested;
1134 #ifdef HAVE_PCAP_REMOTE
1135 struct pcap_rmtauth auth;
1139 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
1142 /* XXX - opening Winsock on tshark? */
1144 /* Initialize Windows Socket if we are in a WIN32 OS
1145 This needs to be done before querying the interface for network/netmask */
1147 /* XXX - do we really require 1.1 or earlier?
1148 Are there any versions that support only 2.0 or higher? */
1149 wVersionRequested = MAKEWORD(1, 1);
1150 err = WSAStartup(wVersionRequested, &wsaData);
1154 case WSASYSNOTREADY:
1155 g_snprintf(errmsg, errmsg_len,
1156 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
1159 case WSAVERNOTSUPPORTED:
1160 g_snprintf(errmsg, errmsg_len,
1161 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
1162 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
1165 case WSAEINPROGRESS:
1166 g_snprintf(errmsg, errmsg_len,
1167 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
1171 g_snprintf(errmsg, errmsg_len,
1172 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
1176 g_snprintf(errmsg, errmsg_len,
1177 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
1181 g_snprintf(errmsg, errmsg_len,
1182 "Couldn't initialize Windows Sockets: error %d", err);
1185 g_snprintf(secondary_errmsg, secondary_errmsg_len, please_report);
1190 /* Open the network interface to capture from it.
1191 Some versions of libpcap may put warnings into the error buffer
1192 if they succeed; to tell if that's happened, we have to clear
1193 the error buffer, and check if it's still a null string. */
1194 open_err_str[0] = '\0';
1195 #ifdef HAVE_PCAP_OPEN
1196 auth.type = capture_opts->auth_type == CAPTURE_AUTH_PWD ?
1197 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
1198 auth.username = capture_opts->auth_username;
1199 auth.password = capture_opts->auth_password;
1201 ld->pcap_h = pcap_open(capture_opts->iface,
1202 capture_opts->has_snaplen ? capture_opts->snaplen :
1203 WTAP_MAX_PACKET_SIZE,
1205 (capture_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
1206 (capture_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
1207 (capture_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
1208 CAP_READ_TIMEOUT, &auth, open_err_str);
1210 ld->pcap_h = pcap_open_live(capture_opts->iface,
1211 capture_opts->has_snaplen ? capture_opts->snaplen :
1212 WTAP_MAX_PACKET_SIZE,
1213 capture_opts->promisc_mode, CAP_READ_TIMEOUT,
1217 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
1218 /* to remove any suid privileges. */
1219 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
1220 /* (euid/egid have already previously been set to ruid/rgid. */
1221 /* (See comment in main() for details) */
1223 relinquish_special_privs_perm();
1225 relinquish_all_capabilities();
1228 if (ld->pcap_h != NULL) {
1229 /* we've opened "iface" as a network device */
1231 /* try to set the capture buffer size */
1232 if (capture_opts->buffer_size > 1 &&
1233 pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
1234 sync_secondary_msg_str = g_strdup_printf(
1235 "The capture buffer size of %luMB seems to be too high for your machine,\n"
1236 "the default of 1MB will be used.\n"
1238 "Nonetheless, the capture is started.\n",
1239 capture_opts->buffer_size);
1240 report_capture_error("Couldn't set the capture buffer size!",
1241 sync_secondary_msg_str);
1242 g_free(sync_secondary_msg_str);
1246 #if defined(HAVE_PCAP_REMOTE) && defined(HAVE_PCAP_SETSAMPLING)
1247 if (capture_opts->sampling_method != CAPTURE_SAMP_NONE)
1249 struct pcap_samp *samp;
1251 if ((samp = pcap_setsampling(ld->pcap_h)) != NULL)
1253 switch (capture_opts->sampling_method)
1255 case CAPTURE_SAMP_BY_COUNT:
1256 samp->method = PCAP_SAMP_1_EVERY_N;
1259 case CAPTURE_SAMP_BY_TIMER:
1260 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
1264 sync_msg_str = g_strdup_printf(
1265 "Unknown sampling method %d specified,\n"
1266 "continue without packet sampling",
1267 capture_opts->sampling_method);
1268 report_capture_error("Couldn't set the capture "
1269 "sampling", sync_msg_str);
1270 g_free(sync_msg_str);
1272 samp->value = capture_opts->sampling_param;
1276 report_capture_error("Couldn't set the capture sampling",
1277 "Cannot get packet sampling data structure");
1283 /* setting the data link type only works on real interfaces */
1284 if (capture_opts->linktype != -1) {
1285 set_linktype_err_str = set_pcap_linktype(ld->pcap_h, capture_opts->iface,
1286 capture_opts->linktype);
1287 if (set_linktype_err_str != NULL) {
1288 g_snprintf(errmsg, errmsg_len, "Unable to set data link type (%s).",
1289 set_linktype_err_str);
1290 g_snprintf(secondary_errmsg, secondary_errmsg_len, please_report);
1294 ld->linktype = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
1296 /* We couldn't open "iface" as a network device. */
1297 /* Try to open it as a pipe */
1298 ld->cap_pipe_fd = cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, errmsg_len);
1300 if (ld->cap_pipe_fd == -1) {
1302 if (ld->cap_pipe_err == PIPNEXIST) {
1303 /* Pipe doesn't exist, so output message for interface */
1305 /* If we got a "can't find PPA for X" message, warn the user (who
1306 is running (T)Wireshark on HP-UX) that they don't have a version
1307 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1308 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1309 PPA for X" rather than "can't find PPA for X"). */
1310 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1313 "You are running (T)Wireshark with a version of the libpcap library\n"
1314 "that doesn't handle HP-UX network devices well; this means that\n"
1315 "(T)Wireshark may not be able to capture packets.\n"
1317 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1318 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1319 "packaged binary form from the Software Porting And Archive Centre\n"
1320 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1321 "at the URL lists a number of mirror sites.";
1324 g_snprintf(errmsg, errmsg_len,
1325 "The capture session could not be initiated (%s).", open_err_str);
1327 g_snprintf(secondary_errmsg, secondary_errmsg_len,
1328 "Please check to make sure you have sufficient permissions, and that you have "
1329 "the proper interface or pipe specified.%s", libpcap_warn);
1331 g_snprintf(secondary_errmsg, secondary_errmsg_len,
1333 "Please check that \"%s\" is the proper interface.\n"
1336 "Help can be found at:\n"
1338 " http://wiki.wireshark.org/WinPcap\n"
1339 " http://wiki.wireshark.org/CaptureSetup\n",
1340 capture_opts->iface);
1344 * Else pipe (or file) does exist and cap_pipe_open_live() has
1349 /* cap_pipe_open_live() succeeded; don't want
1350 error message from pcap_open_live() */
1351 open_err_str[0] = '\0';
1354 /* XXX - will this work for tshark? */
1355 #ifdef MUST_DO_SELECT
1356 if (!ld->from_cap_pipe) {
1357 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
1358 ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
1360 ld->pcap_fd = pcap_fileno(ld->pcap_h);
1365 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1366 returned a warning; print it, but keep capturing. */
1367 if (open_err_str[0] != '\0') {
1368 sync_msg_str = g_strdup_printf("%s.", open_err_str);
1369 report_capture_error(sync_msg_str, "");
1370 g_free(sync_msg_str);
1377 /* close the capture input file (pcap or capture pipe) */
1378 static void capture_loop_close_input(loop_data *ld) {
1380 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
1382 /* if open, close the capture pipe "input file" */
1383 if (ld->cap_pipe_fd >= 0) {
1384 g_assert(ld->from_cap_pipe);
1385 ws_close(ld->cap_pipe_fd);
1386 ld->cap_pipe_fd = 0;
1389 /* if open, close the pcap "input file" */
1390 if(ld->pcap_h != NULL) {
1391 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", ld->pcap_h);
1392 g_assert(!ld->from_cap_pipe);
1393 pcap_close(ld->pcap_h);
1400 /* Shut down windows sockets */
1406 /* init the capture filter */
1407 static initfilter_status_t
1408 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe, gchar * iface, gchar * cfilter) {
1409 bpf_u_int32 netnum, netmask;
1410 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
1411 struct bpf_program fcode;
1414 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
1416 /* capture filters only work on real interfaces */
1417 if (cfilter && !from_cap_pipe) {
1418 /* A capture filter was specified; set it up. */
1419 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1421 * Well, we can't get the netmask for this interface; it's used
1422 * only for filters that check for broadcast IP addresses, so
1423 * we just punt and use 0. It might be nice to warn the user,
1424 * but that's a pain in a GUI application, as it'd involve popping
1425 * up a message box, and it's not clear how often this would make
1426 * a difference (only filters that check for IP broadcast addresses
1430 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
1433 if (pcap_compile(pcap_h, &fcode, cfilter, 1, netmask) < 0) {
1434 /* Treat this specially - our caller might try to compile this
1435 as a display filter and, if that succeeds, warn the user that
1436 the display and capture filter syntaxes are different. */
1437 return INITFILTER_BAD_FILTER;
1439 if (pcap_setfilter(pcap_h, &fcode) < 0) {
1440 #ifdef HAVE_PCAP_FREECODE
1441 pcap_freecode(&fcode);
1443 return INITFILTER_OTHER_ERROR;
1445 #ifdef HAVE_PCAP_FREECODE
1446 pcap_freecode(&fcode);
1450 return INITFILTER_NO_ERROR;
1454 /* set up to write to the already-opened capture output file/files */
1456 capture_loop_init_output(capture_options *capture_opts, int save_file_fd, loop_data *ld, char *errmsg, int errmsg_len) {
1461 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
1464 if (ld->from_cap_pipe) {
1465 file_snaplen = ld->cap_pipe_hdr.snaplen;
1468 file_snaplen = pcap_snapshot(ld->pcap_h);
1471 /* Set up to write to the capture file. */
1472 if (capture_opts->multi_files_on) {
1473 ld->pdh = ringbuf_init_libpcap_fdopen(ld->linktype, file_snaplen,
1474 &ld->bytes_written, &err);
1476 ld->pdh = libpcap_fdopen(save_file_fd, ld->linktype, file_snaplen,
1477 &ld->bytes_written, &err);
1480 if (ld->pdh == NULL) {
1481 /* We couldn't set up to write to the capture file. */
1482 /* XXX - use cf_open_error_message from tshark instead? */
1485 case WTAP_ERR_CANT_OPEN:
1486 g_snprintf(errmsg, errmsg_len, "The file to which the capture would be saved"
1487 " couldn't be created for some unknown reason.");
1490 case WTAP_ERR_SHORT_WRITE:
1491 g_snprintf(errmsg, errmsg_len, "A full header couldn't be written to the file"
1492 " to which the capture would be saved.");
1497 g_snprintf(errmsg, errmsg_len,
1498 "The file to which the capture would be"
1499 " saved (\"%s\") could not be opened: Error %d.",
1500 capture_opts->save_file, err);
1502 g_snprintf(errmsg, errmsg_len,
1503 "The file to which the capture would be"
1504 " saved (\"%s\") could not be opened: %s.",
1505 capture_opts->save_file, strerror(err));
1517 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
1519 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
1521 if (capture_opts->multi_files_on) {
1522 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
1524 return libpcap_dump_close(ld->pdh, err_close);
1528 /* dispatch incoming packets (pcap or capture pipe)
1530 * Waits for incoming packets to be available, and calls pcap_dispatch()
1531 * to cause them to be processed.
1533 * Returns the number of packets which were processed.
1535 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
1536 * packet-batching behaviour does not cause packets to get held back
1540 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
1541 char *errmsg, int errmsg_len)
1545 gint packet_count_before;
1546 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1548 packet_count_before = ld->packet_count;
1549 if (ld->from_cap_pipe) {
1550 /* dispatch from capture pipe */
1551 #ifdef LOG_CAPTURE_VERBOSE
1552 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
1554 sel_ret = cap_pipe_select(ld->cap_pipe_fd);
1557 if (sel_ret < 0 && errno != EINTR) {
1558 g_snprintf(errmsg, errmsg_len,
1559 "Unexpected error from select: %s", strerror(errno));
1560 report_capture_error(errmsg, please_report);
1565 * "select()" says we can read from the pipe without blocking
1567 inpkts = cap_pipe_dispatch(ld, pcap_data, errmsg, errmsg_len);
1575 /* dispatch from pcap */
1576 #ifdef MUST_DO_SELECT
1578 * If we have "pcap_get_selectable_fd()", we use it to get the
1579 * descriptor on which to select; if that's -1, it means there
1580 * is no descriptor on which you can do a "select()" (perhaps
1581 * because you're capturing on a special device, and that device's
1582 * driver unfortunately doesn't support "select()", in which case
1583 * we don't do the select - which means it might not be possible
1584 * to stop a capture until a packet arrives. If that's unacceptable,
1585 * plead with whoever supplies the software for that device to add
1586 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
1587 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
1588 * later, so it can use pcap_breakloop().
1590 #ifdef LOG_CAPTURE_VERBOSE
1591 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
1593 if (ld->pcap_fd != -1) {
1594 sel_ret = cap_pipe_select(ld->pcap_fd);
1597 * "select()" says we can read from it without blocking; go for
1600 * We don't have pcap_breakloop(), so we only process one packet
1601 * per pcap_dispatch() call, to allow a signal to stop the
1602 * processing immediately, rather than processing all packets
1603 * in a batch before quitting.
1605 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb,
1608 ld->pcap_err = TRUE;
1609 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1612 if (sel_ret < 0 && errno != EINTR) {
1613 g_snprintf(errmsg, errmsg_len,
1614 "Unexpected error from select: %s", strerror(errno));
1615 report_capture_error(errmsg, please_report);
1621 #endif /* MUST_DO_SELECT */
1623 /* dispatch from pcap without select */
1625 #ifdef LOG_CAPTURE_VERBOSE
1626 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
1630 * On Windows, we don't support asynchronously telling a process to
1631 * stop capturing; instead, we check for an indication on a pipe
1632 * after processing packets. We therefore process only one packet
1633 * at a time, so that we can check the pipe after every packet.
1635 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb, (u_char *) ld);
1637 inpkts = pcap_dispatch(ld->pcap_h, -1, capture_loop_packet_cb, (u_char *) ld);
1641 /* Error, rather than pcap_breakloop(). */
1642 ld->pcap_err = TRUE;
1644 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1646 #else /* pcap_next_ex */
1647 #ifdef LOG_CAPTURE_VERBOSE
1648 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
1650 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
1653 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
1654 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
1655 * This should be fixed in the WinPcap 4.0 alpha release.
1657 * For reference, an example remote interface:
1658 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
1661 /* emulate dispatch from pcap */
1664 struct pcap_pkthdr *pkt_header;
1669 (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1)
1670 capture_loop_packet_cb( (u_char *) ld, pkt_header, pkt_data);
1673 ld->pcap_err = TRUE;
1677 #endif /* pcap_next_ex */
1681 #ifdef LOG_CAPTURE_VERBOSE
1682 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
1685 return ld->packet_count - packet_count_before;
1689 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
1690 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
1692 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
1693 char *errmsg, int errmsg_len) {
1695 char tmpname[128+1];
1696 gchar *capfile_name;
1697 gboolean is_tempfile;
1702 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
1703 (capture_opts->save_file) ? capture_opts->save_file : "");
1705 if (capture_opts->save_file != NULL) {
1706 /* We return to the caller while the capture is in progress.
1707 * Therefore we need to take a copy of save_file in
1708 * case the caller destroys it after we return.
1710 capfile_name = g_strdup(capture_opts->save_file);
1712 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
1713 if (capture_opts->multi_files_on) {
1714 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
1715 g_snprintf(errmsg, errmsg_len,
1716 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
1717 g_free(capfile_name);
1720 if (strcmp(capfile_name, "-") == 0) {
1721 /* write to stdout */
1724 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
1725 _setmode(1, O_BINARY);
1728 } /* if (...output_to_pipe ... */
1731 if (capture_opts->multi_files_on) {
1732 /* ringbuffer is enabled */
1733 *save_file_fd = ringbuf_init(capfile_name,
1734 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
1736 /* we need the ringbuf name */
1737 if(*save_file_fd != -1) {
1738 g_free(capfile_name);
1739 capfile_name = g_strdup(ringbuf_current_filename());
1742 /* Try to open/create the specified file for use as a capture buffer. */
1743 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
1747 is_tempfile = FALSE;
1749 /* Choose a random name for the temporary capture buffer */
1750 *save_file_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
1751 capfile_name = g_strdup(tmpname);
1755 /* did we fail to open the output file? */
1756 if (*save_file_fd == -1) {
1758 g_snprintf(errmsg, errmsg_len,
1759 "The temporary file to which the capture would be saved (\"%s\") "
1760 "could not be opened: %s.", capfile_name, strerror(errno));
1762 if (capture_opts->multi_files_on) {
1763 ringbuf_error_cleanup();
1766 g_snprintf(errmsg, errmsg_len,
1767 "The file to which the capture would be saved (\"%s\") "
1768 "could not be opened: %s.", capfile_name,
1771 g_free(capfile_name);
1775 if(capture_opts->save_file != NULL) {
1776 g_free(capture_opts->save_file);
1778 capture_opts->save_file = capfile_name;
1779 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
1780 "g_free(capfile_name)". */
1782 ret = fchown(*save_file_fd, capture_opts->owner, capture_opts->group);
1790 capture_loop_stop_signal_handler(int signo _U_)
1792 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Signal: Stop capture");
1793 capture_loop_stop();
1797 #define TIME_GET() GetTickCount()
1799 #define TIME_GET() time(NULL)
1802 /* Do the low-level work of a capture.
1803 Returns TRUE if it succeeds, FALSE otherwise. */
1805 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
1808 struct sigaction act;
1810 time_t upd_time, cur_time;
1814 gint inpkts_to_sync_pipe = 0; /* packets not already send out to the sync_pipe */
1815 condition *cnd_file_duration = NULL;
1816 condition *cnd_autostop_files = NULL;
1817 condition *cnd_autostop_size = NULL;
1818 condition *cnd_autostop_duration = NULL;
1819 guint32 autostop_files = 0;
1822 gboolean cfilter_error = FALSE;
1823 #define MSG_MAX_LENGTH 4096
1824 char errmsg[MSG_MAX_LENGTH+1];
1825 char secondary_errmsg[MSG_MAX_LENGTH+1];
1826 int save_file_fd = -1;
1829 *secondary_errmsg = '\0';
1831 /* init the loop data */
1832 global_ld.go = TRUE;
1833 global_ld.packet_count = 0;
1834 if (capture_opts->has_autostop_packets)
1835 global_ld.packet_max = capture_opts->autostop_packets;
1837 global_ld.packet_max = 0; /* no limit */
1838 global_ld.err = 0; /* no error seen yet */
1839 global_ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
1840 global_ld.pcap_err = FALSE;
1841 global_ld.from_cap_pipe = FALSE;
1842 global_ld.pdh = NULL;
1843 global_ld.cap_pipe_fd = -1;
1844 #ifdef MUST_DO_SELECT
1845 global_ld.pcap_fd = 0;
1848 /* We haven't yet gotten the capture statistics. */
1849 *stats_known = FALSE;
1853 * Catch SIGUSR1, so that we exit cleanly if the parent process
1854 * kills us with it due to the user selecting "Capture->Stop".
1856 act.sa_handler = capture_loop_stop_signal_handler;
1858 * Arrange that system calls not get restarted, because when
1859 * our signal handler returns we don't want to restart
1860 * a call that was waiting for packets to arrive.
1863 sigemptyset(&act.sa_mask);
1864 sigaction(SIGUSR1, &act, NULL);
1867 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
1868 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
1870 /* open the "input file" from network interface or capture pipe */
1871 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
1872 secondary_errmsg, sizeof(secondary_errmsg))) {
1876 /* init the input filter from the network interface (capture pipe will do nothing) */
1877 switch (capture_loop_init_filter(global_ld.pcap_h, global_ld.from_cap_pipe,
1878 capture_opts->iface,
1879 capture_opts->cfilter)) {
1881 case INITFILTER_NO_ERROR:
1884 case INITFILTER_BAD_FILTER:
1885 cfilter_error = TRUE;
1886 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(global_ld.pcap_h));
1889 case INITFILTER_OTHER_ERROR:
1890 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
1891 pcap_geterr(global_ld.pcap_h));
1892 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
1896 /* If we're supposed to write to a capture file, open it for output
1897 (temporary/specified name/ringbuffer) */
1898 if (capture_opts->saving_to_file) {
1899 if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
1903 /* set up to write to the already-opened capture output file/files */
1904 if (!capture_loop_init_output(capture_opts, save_file_fd, &global_ld,
1905 errmsg, sizeof(errmsg))) {
1909 /* XXX - capture SIGTERM and close the capture, in case we're on a
1910 Linux 2.0[.x] system and you have to explicitly close the capture
1911 stream in order to turn promiscuous mode off? We need to do that
1912 in other places as well - and I don't think that works all the
1913 time in any case, due to libpcap bugs. */
1915 /* Well, we should be able to start capturing.
1917 Sync out the capture file, so the header makes it to the file system,
1918 and send a "capture started successfully and capture file created"
1919 message to our parent so that they'll open the capture file and
1920 update its windows to indicate that we have a live capture in
1922 libpcap_dump_flush(global_ld.pdh, NULL);
1923 report_new_capture_file(capture_opts->save_file);
1926 /* initialize capture stop (and alike) conditions */
1927 init_capture_stop_conditions();
1928 /* create stop conditions */
1929 if (capture_opts->has_autostop_filesize)
1931 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
1932 if (capture_opts->has_autostop_duration)
1933 cnd_autostop_duration =
1934 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
1936 if (capture_opts->multi_files_on) {
1937 if (capture_opts->has_file_duration)
1939 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
1941 if (capture_opts->has_autostop_files)
1942 cnd_autostop_files =
1943 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
1946 /* init the time values */
1947 start_time = TIME_GET();
1948 upd_time = TIME_GET();
1950 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
1952 /* WOW, everything is prepared! */
1953 /* please fasten your seat belts, we will enter now the actual capture loop */
1954 while (global_ld.go) {
1955 /* dispatch incoming packets */
1956 inpkts = capture_loop_dispatch(capture_opts, &global_ld, errmsg,
1960 /* any news from our parent (signal pipe)? -> just stop the capture */
1961 if (!signal_pipe_check_running()) {
1962 global_ld.go = FALSE;
1967 inpkts_to_sync_pipe += inpkts;
1969 /* check capture size condition */
1970 if (cnd_autostop_size != NULL &&
1971 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)){
1972 /* Capture size limit reached, do we have another file? */
1973 if (capture_opts->multi_files_on) {
1974 if (cnd_autostop_files != NULL &&
1975 cnd_eval(cnd_autostop_files, ++autostop_files)) {
1976 /* no files left: stop here */
1977 global_ld.go = FALSE;
1981 /* Switch to the next ringbuffer file */
1982 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
1983 &save_file_fd, &global_ld.bytes_written, &global_ld.err)) {
1984 /* File switch succeeded: reset the conditions */
1985 cnd_reset(cnd_autostop_size);
1986 if (cnd_file_duration) {
1987 cnd_reset(cnd_file_duration);
1989 libpcap_dump_flush(global_ld.pdh, NULL);
1990 report_packet_count(inpkts_to_sync_pipe);
1991 inpkts_to_sync_pipe = 0;
1992 report_new_capture_file(capture_opts->save_file);
1994 /* File switch failed: stop here */
1995 global_ld.go = FALSE;
1999 /* single file, stop now */
2000 global_ld.go = FALSE;
2003 } /* cnd_autostop_size */
2004 if (capture_opts->output_to_pipe) {
2005 libpcap_dump_flush(global_ld.pdh, NULL);
2009 /* Only update once a second (Win32: 500ms) so as not to overload slow
2010 * displays. This also prevents too much context-switching between the
2011 * dumpcap and wireshark processes */
2012 cur_time = TIME_GET();
2014 if ( (cur_time - upd_time) > 500) {
2016 if (cur_time - upd_time > 0) {
2018 upd_time = cur_time;
2020 /*if (pcap_stats(pch, stats) >= 0) {
2021 *stats_known = TRUE;
2024 /* Let the parent process know. */
2025 if (inpkts_to_sync_pipe) {
2027 libpcap_dump_flush(global_ld.pdh, NULL);
2029 /* Send our parent a message saying we've written out "inpkts_to_sync_pipe"
2030 packets to the capture file. */
2031 report_packet_count(inpkts_to_sync_pipe);
2033 inpkts_to_sync_pipe = 0;
2036 /* check capture duration condition */
2037 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
2038 /* The maximum capture time has elapsed; stop the capture. */
2039 global_ld.go = FALSE;
2043 /* check capture file duration condition */
2044 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
2045 /* duration limit reached, do we have another file? */
2046 if (capture_opts->multi_files_on) {
2047 if (cnd_autostop_files != NULL &&
2048 cnd_eval(cnd_autostop_files, ++autostop_files)) {
2049 /* no files left: stop here */
2050 global_ld.go = FALSE;
2054 /* Switch to the next ringbuffer file */
2055 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2056 &save_file_fd, &global_ld.bytes_written,
2058 /* file switch succeeded: reset the conditions */
2059 cnd_reset(cnd_file_duration);
2060 if(cnd_autostop_size)
2061 cnd_reset(cnd_autostop_size);
2062 libpcap_dump_flush(global_ld.pdh, NULL);
2063 report_packet_count(inpkts_to_sync_pipe);
2064 inpkts_to_sync_pipe = 0;
2065 report_new_capture_file(capture_opts->save_file);
2067 /* File switch failed: stop here */
2068 global_ld.go = FALSE;
2072 /* single file, stop now */
2073 global_ld.go = FALSE;
2076 } /* cnd_file_duration */
2079 } /* while (global_ld.go) */
2081 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
2083 /* delete stop conditions */
2084 if (cnd_file_duration != NULL)
2085 cnd_delete(cnd_file_duration);
2086 if (cnd_autostop_files != NULL)
2087 cnd_delete(cnd_autostop_files);
2088 if (cnd_autostop_size != NULL)
2089 cnd_delete(cnd_autostop_size);
2090 if (cnd_autostop_duration != NULL)
2091 cnd_delete(cnd_autostop_duration);
2093 /* did we had a pcap (input) error? */
2094 if (global_ld.pcap_err) {
2095 /* On Linux, if an interface goes down while you're capturing on it,
2096 you'll get a "recvfrom: Network is down" error (ENETDOWN).
2097 (At least you will if strerror() doesn't show a local translation
2100 On FreeBSD and OS X, if a network adapter disappears while
2101 you're capturing on it, you'll get a "read: Device not configured"
2102 error (ENXIO). (See previous parenthetical note.)
2104 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
2106 These should *not* be reported to the Wireshark developers. */
2109 cap_err_str = pcap_geterr(global_ld.pcap_h);
2110 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
2111 strcmp(cap_err_str, "read: Device not configured") == 0 ||
2112 strcmp(cap_err_str, "read: I/O error") == 0) {
2113 report_capture_error("The network adapter on which the capture was being done "
2114 "is no longer running; the capture has stopped.",
2117 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
2119 report_capture_error(errmsg, please_report);
2122 else if (global_ld.from_cap_pipe && global_ld.cap_pipe_err == PIPERR)
2123 report_capture_error(errmsg, "");
2125 /* did we had an error while capturing? */
2126 if (global_ld.err == 0) {
2129 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
2130 global_ld.err, FALSE);
2131 report_capture_error(errmsg, please_report);
2135 if (capture_opts->saving_to_file) {
2136 /* close the wiretap (output) file */
2137 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
2141 /* there might be packets not yet notified to the parent */
2142 /* (do this after closing the file, so all packets are already flushed) */
2143 if(inpkts_to_sync_pipe) {
2144 report_packet_count(inpkts_to_sync_pipe);
2145 inpkts_to_sync_pipe = 0;
2148 /* If we've displayed a message about a write error, there's no point
2149 in displaying another message about an error on close. */
2150 if (!close_ok && write_ok) {
2151 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
2153 report_capture_error(errmsg, "");
2157 * XXX We exhibit different behaviour between normal mode and sync mode
2158 * when the pipe is stdin and not already at EOF. If we're a child, the
2159 * parent's stdin isn't closed, so if the user starts another capture,
2160 * cap_pipe_open_live() will very likely not see the expected magic bytes and
2161 * will say "Unrecognized libpcap format". On the other hand, in normal
2162 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
2165 /* get packet drop statistics from pcap */
2166 if(global_ld.pcap_h != NULL) {
2167 g_assert(!global_ld.from_cap_pipe);
2168 /* Get the capture statistics, so we know how many packets were
2170 if (pcap_stats(global_ld.pcap_h, stats) >= 0) {
2171 *stats_known = TRUE;
2172 /* Let the parent process know. */
2173 report_packet_drops(stats->ps_drop);
2175 g_snprintf(errmsg, sizeof(errmsg),
2176 "Can't get packet-drop statistics: %s",
2177 pcap_geterr(global_ld.pcap_h));
2178 report_capture_error(errmsg, please_report);
2182 /* close the input file (pcap or capture pipe) */
2183 capture_loop_close_input(&global_ld);
2185 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
2187 /* ok, if the write and the close were successful. */
2188 return write_ok && close_ok;
2191 if (capture_opts->multi_files_on) {
2192 /* cleanup ringbuffer */
2193 ringbuf_error_cleanup();
2195 /* We can't use the save file, and we have no FILE * for the stream
2196 to close in order to close it, so close the FD directly. */
2197 if(save_file_fd != -1) {
2198 ws_close(save_file_fd);
2201 /* We couldn't even start the capture, so get rid of the capture
2203 if(capture_opts->save_file != NULL) {
2204 ws_unlink(capture_opts->save_file);
2205 g_free(capture_opts->save_file);
2208 capture_opts->save_file = NULL;
2210 report_cfilter_error(capture_opts->cfilter, errmsg);
2212 report_capture_error(errmsg, secondary_errmsg);
2214 /* close the input file (pcap or cap_pipe) */
2215 capture_loop_close_input(&global_ld);
2217 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
2223 static void capture_loop_stop(void)
2225 #ifdef HAVE_PCAP_BREAKLOOP
2226 if(global_ld.pcap_h != NULL)
2227 pcap_breakloop(global_ld.pcap_h);
2229 global_ld.go = FALSE;
2234 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
2235 int err, gboolean is_close)
2240 g_snprintf(errmsg, errmsglen,
2241 "Not all the packets could be written to the file"
2242 " to which the capture was being saved\n"
2243 "(\"%s\") because there is no space left on the file system\n"
2244 "on which that file resides.",
2250 g_snprintf(errmsg, errmsglen,
2251 "Not all the packets could be written to the file"
2252 " to which the capture was being saved\n"
2253 "(\"%s\") because you are too close to, or over,"
2254 " your disk quota\n"
2255 "on the file system on which that file resides.",
2260 case WTAP_ERR_CANT_CLOSE:
2261 g_snprintf(errmsg, errmsglen,
2262 "The file to which the capture was being saved"
2263 " couldn't be closed for some unknown reason.");
2266 case WTAP_ERR_SHORT_WRITE:
2267 g_snprintf(errmsg, errmsglen,
2268 "Not all the packets could be written to the file"
2269 " to which the capture was being saved\n"
2276 g_snprintf(errmsg, errmsglen,
2277 "The file to which the capture was being saved\n"
2278 "(\"%s\") could not be closed: %s.",
2279 fname, wtap_strerror(err));
2281 g_snprintf(errmsg, errmsglen,
2282 "An error occurred while writing to the file"
2283 " to which the capture was being saved\n"
2285 fname, wtap_strerror(err));
2292 /* one packet was captured, process it */
2294 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
2297 loop_data *ld = (void *) user;
2300 /* We may be called multiple times from pcap_dispatch(); if we've set
2301 the "stop capturing" flag, ignore this packet, as we're not
2302 supposed to be saving any more packets. */
2307 /* We're supposed to write the packet to a file; do so.
2308 If this fails, set "ld->go" to FALSE, to stop the capture, and set
2309 "ld->err" to the error. */
2310 if (!libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err)) {
2315 /* if the user told us to stop after x packets, do we already have enough? */
2316 if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
2325 /* And now our feature presentation... [ fade to music ] */
2327 main(int argc, char *argv[])
2330 extern char *optarg;
2331 gboolean arg_error = FALSE;
2336 struct sigaction action, oldaction;
2339 gboolean start_capture = TRUE;
2340 gboolean stats_known;
2341 struct pcap_stat stats;
2342 GLogLevelFlags log_flags;
2343 gboolean list_interfaces = FALSE;
2344 gboolean list_link_layer_types = FALSE;
2345 gboolean machine_readable = FALSE;
2346 gboolean print_statistics = FALSE;
2347 int status, run_once_args = 0;
2350 #ifdef HAVE_PCAP_REMOTE
2351 #define OPTSTRING_INIT "a:A:b:c:Df:hi:Lm:MprSs:uvw:y:Z:"
2353 #define OPTSTRING_INIT "a:b:c:Df:hi:LMpSs:vw:y:Z:"
2357 #define OPTSTRING_WIN32 "B:"
2359 #define OPTSTRING_WIN32 ""
2362 char optstring[sizeof(OPTSTRING_INIT) + sizeof(OPTSTRING_WIN32) - 1] =
2363 OPTSTRING_INIT OPTSTRING_WIN32;
2365 #ifdef DEBUG_CHILD_DUMPCAP
2366 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
2367 fprintf (stderr, "Unable to open debug log file !\n");
2372 /* Determine if dumpcap is being requested to run in a special */
2373 /* capture_child mode by going thru the command line args to see if */
2374 /* a -Z is present. (-Z is a hidden option). */
2375 /* The primary result of running in capture_child mode is that */
2376 /* all messages sent out on stderr are in a special type/len/string */
2377 /* format to allow message processing by type. */
2378 /* These messages include various 'status' messages which are sent */
2379 /* when an actual capture is in progress. Capture_child mode */
2380 /* would normally be requested by a parent process which invokes */
2381 /* dumpcap and obtains dumpcap stderr output via a pipe to which */
2382 /* dumpcap stderr has been redirected. */
2383 /* Capture_child mode needs to be determined immediately upon */
2384 /* startup so that any messages generated by dumpcap in this mode */
2385 /* (eg: during initialization) will be formatted properly. */
2387 for (i=1; i<argc; i++) {
2388 if (strcmp("-Z", argv[i]) == 0) {
2389 capture_child = TRUE;
2391 /* set output pipe to binary mode, to avoid ugly text conversions */
2392 _setmode(2, O_BINARY);
2397 /* The default_log_handler will use stdout, which makes trouble in */
2398 /* capture child mode, as it uses stdout for it's sync_pipe. */
2399 /* So: the filtering is done in the console_log_handler and not here.*/
2400 /* We set the log handlers right up front to make sure that any log */
2401 /* messages when running as child will be sent back to the parent */
2402 /* with the correct format. */
2406 G_LOG_LEVEL_CRITICAL|
2407 G_LOG_LEVEL_WARNING|
2408 G_LOG_LEVEL_MESSAGE|
2411 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
2413 g_log_set_handler(NULL,
2415 console_log_handler, NULL /* user_data */);
2416 g_log_set_handler(LOG_DOMAIN_MAIN,
2418 console_log_handler, NULL /* user_data */);
2419 g_log_set_handler(LOG_DOMAIN_CAPTURE,
2421 console_log_handler, NULL /* user_data */);
2422 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
2424 console_log_handler, NULL /* user_data */);
2427 /* Load wpcap if possible. Do this before collecting the run-time version information */
2430 /* ... and also load the packet.dll from wpcap */
2431 /* XXX - currently not required, may change later. */
2432 /*wpcap_packet_load();*/
2434 /* Start windows sockets */
2435 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
2437 /* Set handler for Ctrl+C key */
2438 SetConsoleCtrlHandler(capture_cleanup, TRUE);
2440 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
2442 action.sa_handler = capture_cleanup;
2443 action.sa_flags = 0;
2444 sigemptyset(&action.sa_mask);
2445 sigaction(SIGTERM, &action, NULL);
2446 sigaction(SIGINT, &action, NULL);
2447 sigaction(SIGHUP, NULL, &oldaction);
2448 if (oldaction.sa_handler == SIG_DFL)
2449 sigaction(SIGHUP, &action, NULL);
2452 /* ----------------------------------------------------------------- */
2453 /* Privilege and capability handling */
2455 /* 1. Running not as root or suid root; no special capabilities. */
2458 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
2461 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
2463 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
2464 /* capabilities; Drop all other capabilities; */
2465 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2466 /* else: after pcap_open_live() in capture_loop_open_input() */
2467 /* drop all capabilities (NET_RAW and NET_ADMIN); */
2468 /* (Note: this means that the process, although logged in */
2469 /* as root, does not have various permissions such as the */
2470 /* ability to bypass file access permissions). */
2471 /* XXX: Should we just leave capabilities alone in this case */
2472 /* so that user gets expected effect that root can do */
2475 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
2477 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2478 /* else: after pcap_open_live() in capture_loop_open_input() */
2479 /* drop suid root (set euid=ruid).(ie: keep suid until after */
2480 /* pcap_open_live). */
2482 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
2484 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
2485 /* capabilities; Drop all other capabilities; */
2486 /* Drop suid privileges (euid=ruid); */
2487 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2488 /* else: after pcap_open_live() in capture_loop_open_input() */
2489 /* drop all capabilities (NET_RAW and NET_ADMIN). */
2491 /* XXX: For some Linux versions/distros with capabilities */
2492 /* a 'normal' process with any capabilities cannot be */
2493 /* 'killed' (signaled) from another (same uid) non-privileged */
2495 /* For example: If (non-suid) Wireshark forks a */
2496 /* child suid dumpcap which acts as described here (case 5), */
2497 /* Wireshark will be unable to kill (signal) the child */
2498 /* dumpcap process until the capabilities have been dropped */
2499 /* (after pcap_open_live()). */
2500 /* This behaviour will apparently be changed in the kernel */
2501 /* to allow the kill (signal) in this case. */
2502 /* See the following for details: */
2503 /* http://www.mail-archive.com/ [wrapped] */
2504 /* linux-security-module@vger.kernel.org/msg02913.html */
2506 /* It is therefore conceivable that if dumpcap somehow hangs */
2507 /* in pcap_open_live or before that wireshark will not */
2508 /* be able to stop dumpcap using a signal (USR1, TERM, etc). */
2509 /* In this case, exiting wireshark will kill the child */
2510 /* dumpcap process. */
2512 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
2513 /* capabilities; Using libcap. Note: capset cmd (which see) */
2514 /* used to assign capabilities to file. */
2516 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2517 /* else: after pcap_open_live() in capture_loop_open_input() */
2518 /* drop all capabilities (NET_RAW and NET_ADMIN) */
2520 /* ToDo: -S (stats) should drop privileges/capabilities when no */
2521 /* longer required (similar to capture). */
2523 /* ----------------------------------------------------------------- */
2525 get_credential_info();
2528 /* If 'started with special privileges' (and using libcap) */
2529 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
2530 /* Set euid/egid = ruid/rgid to remove suid privileges */
2531 relinquish_privs_except_capture();
2534 /* Set the initial values in the capture options. This might be overwritten
2535 by the command line parameters. */
2536 capture_opts_init(&global_capture_opts, NULL);
2538 /* Default to capturing the entire packet. */
2539 global_capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
2541 /* We always save to a file - if no file was specified, we save to a
2543 global_capture_opts.saving_to_file = TRUE;
2544 global_capture_opts.has_ring_num_files = TRUE;
2546 /* Now get our args */
2547 while ((opt = getopt(argc, argv, optstring)) != -1) {
2549 case 'h': /* Print help and exit */
2553 case 'v': /* Show version and exit */
2555 GString *comp_info_str;
2556 GString *runtime_info_str;
2557 /* Assemble the compile-time version information string */
2558 comp_info_str = g_string_new("Compiled ");
2559 get_compiled_version_info(comp_info_str, NULL);
2561 /* Assemble the run-time version information string */
2562 runtime_info_str = g_string_new("Running ");
2563 get_runtime_version_info(runtime_info_str, NULL);
2564 show_version(comp_info_str, runtime_info_str);
2565 g_string_free(comp_info_str, TRUE);
2566 g_string_free(runtime_info_str, TRUE);
2570 /*** capture option specific ***/
2571 case 'a': /* autostop criteria */
2572 case 'b': /* Ringbuffer option */
2573 case 'c': /* Capture x packets */
2574 case 'f': /* capture filter */
2575 case 'i': /* Use interface x */
2576 case 'p': /* Don't capture in promiscuous mode */
2577 case 's': /* Set the snapshot (capture) length */
2578 case 'w': /* Write to capture file x */
2579 case 'y': /* Set the pcap data link type */
2580 #ifdef HAVE_PCAP_REMOTE
2581 case 'u': /* Use UDP for data transfer */
2582 case 'r': /* Capture own RPCAP traffic too */
2583 case 'A': /* Authentication */
2585 #ifdef HAVE_PCAP_SETSAMPLING
2586 case 'm': /* Sampling */
2589 case 'B': /* Buffer size */
2591 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
2596 /*** hidden option: Wireshark child mode (using binary output messages) ***/
2598 capture_child = TRUE;
2600 /* set output pipe to binary mode, to avoid ugly text conversions */
2601 _setmode(2, O_BINARY);
2603 * optarg = the control ID, aka the PPID, currently used for the
2606 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
2607 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
2608 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
2609 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
2611 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
2612 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2613 "Signal pipe: Unable to open %s. Dead parent?",
2621 /*** all non capture option specific ***/
2622 case 'D': /* Print a list of capture devices and exit */
2623 list_interfaces = TRUE;
2626 case 'L': /* Print list of link-layer types and exit */
2627 list_link_layer_types = TRUE;
2630 case 'S': /* Print interface statistics once a second */
2631 print_statistics = TRUE;
2634 case 'M': /* For -D and -L, print machine-readable output */
2635 machine_readable = TRUE;
2638 case '?': /* Bad flag - print usage message */
2639 cmdarg_err("Invalid Option: %s", argv[optind-1]);
2647 /* user specified file name as regular command-line argument */
2648 /* XXX - use it as the capture file name (or something else)? */
2655 * Extra command line arguments were specified; complain.
2656 * XXX - interpret as capture filter, as tcpdump and tshark do?
2658 cmdarg_err("Invalid argument: %s", argv[0]);
2667 if (run_once_args > 1) {
2668 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
2670 } else if (list_link_layer_types) {
2671 /* We're supposed to list the link-layer types for an interface;
2672 did the user also specify a capture file to be read? */
2673 /* No - did they specify a ring buffer option? */
2674 if (global_capture_opts.multi_files_on) {
2675 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
2679 /* No - was the ring buffer option specified and, if so, does it make
2681 if (global_capture_opts.multi_files_on) {
2682 /* Ring buffer works only under certain conditions:
2683 a) ring buffer does not work with temporary files;
2684 b) it makes no sense to enable the ring buffer if the maximum
2685 file size is set to "infinite". */
2686 if (global_capture_opts.save_file == NULL) {
2687 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
2688 global_capture_opts.multi_files_on = FALSE;
2690 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
2691 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
2692 /* XXX - this must be redesigned as the conditions changed */
2693 /* global_capture_opts.multi_files_on = FALSE;*/
2698 if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
2699 /* cmdarg_err() already called .... */
2703 /* Let the user know what interface was chosen. */
2704 /* get_interface_descriptive_name() is not available! */
2705 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", global_capture_opts.iface);
2707 if (list_interfaces) {
2708 status = capture_opts_list_interfaces(machine_readable);
2710 } else if (list_link_layer_types) {
2711 status = capture_opts_list_link_layer_types(&global_capture_opts, machine_readable);
2713 } else if (print_statistics) {
2714 status = print_statistics_loop(machine_readable);
2718 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
2719 capture_opts_trim_ring_num_files(&global_capture_opts);
2721 /* Now start the capture. */
2723 if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
2727 /* capture failed */
2734 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
2735 const char *message, gpointer user_data _U_)
2742 /* ignore log message, if log_level isn't interesting */
2743 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
2744 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
2749 /* create a "timestamp" */
2751 today = localtime(&curr);
2753 switch(log_level & G_LOG_LEVEL_MASK) {
2754 case G_LOG_LEVEL_ERROR:
2757 case G_LOG_LEVEL_CRITICAL:
2760 case G_LOG_LEVEL_WARNING:
2763 case G_LOG_LEVEL_MESSAGE:
2766 case G_LOG_LEVEL_INFO:
2769 case G_LOG_LEVEL_DEBUG:
2773 fprintf(stderr, "unknown log_level %u\n", log_level);
2775 g_assert_not_reached();
2778 /* Generate the output message */
2779 if(log_level & G_LOG_LEVEL_MESSAGE) {
2780 /* normal user messages without additional infos */
2781 msg = g_strdup_printf("%s\n", message);
2783 /* info/debug messages with additional infos */
2784 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
2785 today->tm_hour, today->tm_min, today->tm_sec,
2786 log_domain != NULL ? log_domain : "",
2790 /* DEBUG & INFO msgs (if we're debugging today) */
2791 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
2792 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
2793 #ifdef DEBUG_DUMPCAP
2794 fprintf(stderr, "%s", msg);
2797 #ifdef DEBUG_CHILD_DUMPCAP
2798 fprintf(debug_log, "%s", msg);
2806 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
2807 /* to parent especially formatted if dumpcap running as child. */
2808 if (capture_child) {
2809 sync_pipe_errmsg_to_parent(2, msg, "");
2811 fprintf(stderr, "%s", msg);
2818 /****************************************************************************************************************/
2819 /* indication report routines */
2823 report_packet_count(int packet_count)
2825 char tmp[SP_DECISIZE+1+1];
2826 static int count = 0;
2829 g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
2830 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
2831 pipe_write_block(2, SP_PACKET_COUNT, tmp);
2833 count += packet_count;
2834 fprintf(stderr, "\rPackets: %u ", count);
2835 /* stderr could be line buffered */
2841 report_new_capture_file(const char *filename)
2844 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
2845 pipe_write_block(2, SP_FILE, filename);
2847 fprintf(stderr, "File: %s\n", filename);
2848 /* stderr could be line buffered */
2854 report_cfilter_error(const char *cfilter, const char *errmsg)
2856 if (capture_child) {
2857 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
2858 pipe_write_block(2, SP_BAD_FILTER, errmsg);
2861 "Invalid capture filter: \"%s\"!\n"
2863 "That string isn't a valid capture filter (%s).\n"
2864 "See the User's Guide for a description of the capture filter syntax.\n",
2870 report_capture_error(const char *error_msg, const char *secondary_error_msg)
2873 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
2874 "Primary Error: %s", error_msg);
2875 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
2876 "Secondary Error: %s", secondary_error_msg);
2877 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
2879 fprintf(stderr, "%s\n%s\n", error_msg, secondary_error_msg);
2884 report_packet_drops(guint32 drops)
2886 char tmp[SP_DECISIZE+1+1];
2888 g_snprintf(tmp, sizeof(tmp), "%u", drops);
2891 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
2892 pipe_write_block(2, SP_DROPS, tmp);
2894 fprintf(stderr, "Packets dropped: %s\n", tmp);
2895 /* stderr could be line buffered */
2901 /****************************************************************************************************************/
2902 /* signal_pipe handling */
2907 signal_pipe_check_running(void)
2909 /* any news from our parent? -> just stop the capture */
2913 /* if we are running standalone, no check required */
2914 if(!capture_child) {
2918 if(!sig_pipe_name || !sig_pipe_handle) {
2919 /* This shouldn't happen */
2920 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2921 "Signal pipe: No name or handle");
2926 * XXX - We should have the process ID of the parent (from the "-Z" flag)
2927 * at this point. Should we check to see if the parent is still alive,
2928 * e.g. by using OpenProcess?
2931 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
2933 if(!result || avail > 0) {
2934 /* peek failed or some bytes really available */
2935 /* (if not piping from stdin this would fail) */
2936 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2937 "Signal pipe: Stop capture: %s", sig_pipe_name);
2938 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
2939 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
2940 sig_pipe_handle, result, avail);
2943 /* pipe ok and no bytes available */