5 * Wireshark - Network traffic analyzer
6 * By Gerald Combs <gerald@wireshark.org>
7 * Copyright 1998 Gerald Combs
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 #include <stdlib.h> /* for exit() */
35 #ifdef HAVE_SYS_TYPES_H
36 # include <sys/types.h>
39 #ifdef HAVE_SYS_STAT_H
40 # include <sys/stat.h>
63 # include <sys/prctl.h>
64 # 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"
79 #include <wsutil/unicode-utils.h>
82 #include <wsutil/privileges.h>
84 #include "sync_pipe.h"
86 #include "capture_opts.h"
87 #include "capture_sync.h"
89 #include "conditions.h"
90 #include "capture_stop_conditions.h"
94 #include "wsutil/file_util.h"
97 * Get information about libpcap format from "wiretap/libpcap.h".
98 * XXX - can we just use pcap_open_offline() to read the pipe?
100 #include "wiretap/libpcap.h"
102 /**#define DEBUG_DUMPCAP**/
103 /**#define DEBUG_CHILD_DUMPCAP**/
105 #ifdef DEBUG_CHILD_DUMPCAP
106 FILE *debug_log; /* for logging debug messages to */
107 /* a file if DEBUG_CHILD_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;
119 static gboolean signal_pipe_check_running(void);
123 static GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
124 static GMutex *cap_pipe_read_mtx;
127 /** Stop a low-level capture (stops the capture child). */
128 static void capture_loop_stop(void);
130 #if !defined (__linux__)
131 #ifndef HAVE_PCAP_BREAKLOOP
133 * We don't have pcap_breakloop(), which is the only way to ensure that
134 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
135 * won't, if the call to read the next packet or batch of packets is
136 * is interrupted by a signal on UN*X, just go back and try again to
139 * On UN*X, we catch SIGUSR1 as a "stop capturing" signal, and, in
140 * the signal handler, set a flag to stop capturing; however, without
141 * a guarantee of that sort, we can't guarantee that we'll stop capturing
142 * if the read will be retried and won't time out if no packets arrive.
144 * Therefore, on at least some platforms, we work around the lack of
145 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
146 * to wait for packets to arrive, so that we're probably going to be
147 * blocked in the select() when the signal arrives, and can just bail
148 * out of the loop at that point.
150 * However, we don't want to that on BSD (because "select()" doesn't work
151 * correctly on BPF devices on at least some releases of some flavors of
152 * BSD), and we don't want to do it on Windows (because "select()" is
153 * something for sockets, not for arbitrary handles). (Note that "Windows"
154 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
155 * using WinPcap, not a UNIX libpcap.)
157 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
158 * on BSD times out even if no packets have arrived, so we'll eventually
159 * exit pcap_dispatch() with an indication that no packets have arrived,
160 * and will break out of the capture loop at that point.
162 * On Windows, we can't send a SIGUSR1 to stop capturing, so none of this
163 * applies in any case.
165 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
166 * want to include it if it's not present on this platform, however.
168 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
169 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
171 # define MUST_DO_SELECT
172 # endif /* avoid select */
173 #endif /* HAVE_PCAP_BREAKLOOP */
175 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
176 * in pcap_dispatch(); on the other hand, select() works just fine there.
177 * Hence we use a select for that come what may.
179 #define MUST_DO_SELECT
182 /** init the capture filter */
185 INITFILTER_BAD_FILTER,
186 INITFILTER_OTHER_ERROR
187 } initfilter_status_t;
189 typedef struct _loop_data {
191 gboolean go; /* TRUE as long as we're supposed to keep capturing */
192 int err; /* if non-zero, error seen while capturing */
193 gint packet_count; /* Number of packets we have already captured */
194 gint packet_max; /* Number of packets we're supposed to capture - 0 means infinite */
196 /* pcap "input file" */
197 pcap_t *pcap_h; /* pcap handle */
198 gboolean pcap_err; /* TRUE if error from pcap */
199 #ifdef MUST_DO_SELECT
200 int pcap_fd; /* pcap file descriptor */
203 /* capture pipe (unix only "input file") */
204 gboolean from_cap_pipe; /* TRUE if we are capturing data from a capture pipe */
205 struct pcap_hdr cap_pipe_hdr; /* Pcap header when capturing from a pipe */
206 struct pcaprec_modified_hdr cap_pipe_rechdr; /* Pcap record header when capturing from a pipe */
208 HANDLE cap_pipe_h; /* The handle of the capture pipe */
210 int cap_pipe_fd; /* the file descriptor of the capture pipe */
212 gboolean cap_pipe_modified; /* TRUE if data in the pipe uses modified pcap headers */
213 gboolean cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
215 char * cap_pipe_buf; /* Pointer to the data buffer we read into */
216 #endif /* USE_THREADS */
217 int cap_pipe_bytes_to_read;/* Used by cap_pipe_dispatch */
218 int cap_pipe_bytes_read; /* Used by cap_pipe_dispatch */
220 STATE_EXPECT_REC_HDR,
225 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
237 * Standard secondary message for unexpected errors.
239 static const char please_report[] =
240 "Please report this to the Wireshark developers.\n"
241 "(This is not a crash; please do not report it as such.)";
244 * This needs to be static, so that the SIGUSR1 handler can clear the "go"
247 static loop_data global_ld;
251 * Timeout, in milliseconds, for reads from the stream of captured packets.
253 #if defined(__APPLE__) && defined(__LP64__)
254 #define CAP_READ_TIMEOUT 1000
256 #define CAP_READ_TIMEOUT 250
259 * Timeout, in microseconds, for threaded reads from a pipe.
261 #define THREAD_READ_TIMEOUT 100
262 static char *cap_pipe_err_str;
265 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
266 const char *message, gpointer user_data _U_);
268 /* capture related options */
269 static capture_options global_capture_opts;
271 static void capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
273 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
274 int err, gboolean is_close);
276 static void exit_main(int err) G_GNUC_NORETURN;
278 static void report_new_capture_file(const char *filename);
279 static void report_packet_count(int packet_count);
280 static void report_packet_drops(guint32 drops);
281 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
282 static void report_cfilter_error(const char *cfilter, const char *errmsg);
285 print_usage(gboolean print_ver) {
293 "Dumpcap " VERSION "%s\n"
294 "Capture network packets and dump them into a libpcap file.\n"
295 "See http://www.wireshark.org for more information.\n",
296 wireshark_svnversion);
300 fprintf(output, "\nUsage: dumpcap [options] ...\n");
301 fprintf(output, "\n");
302 fprintf(output, "Capture interface:\n");
303 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
304 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
305 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
306 fprintf(output, " -p don't capture in promiscuous mode\n");
308 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
310 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
311 fprintf(output, " -D print list of interfaces and exit\n");
312 fprintf(output, " -L print list of link-layer types of iface and exit\n");
313 fprintf(output, " -S print statistics for each interface once every second\n");
314 fprintf(output, " -M for -D, -L, and -S produce machine-readable output\n");
315 fprintf(output, "\n");
316 #ifdef HAVE_PCAP_REMOTE
317 fprintf(output, "\nRPCAP options:\n");
318 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
319 fprintf(output, " -u use UDP for RPCAP data transfer\n");
320 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
321 #ifdef HAVE_PCAP_SETSAMPLING
322 fprintf(output, " -m <sampling type> use packet sampling\n");
323 fprintf(output, " count:NUM - capture one packet of every NUM\n");
324 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
327 fprintf(output, "Stop conditions:\n");
328 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
329 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
330 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
331 fprintf(output, " files:NUM - stop after NUM files\n");
332 /*fprintf(output, "\n");*/
333 fprintf(output, "Output (files):\n");
334 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
335 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
336 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
337 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
338 fprintf(output, " -n use pcapng format instead of pcap\n");
339 /*fprintf(output, "\n");*/
340 fprintf(output, "Miscellaneous:\n");
341 fprintf(output, " -v print version information and exit\n");
342 fprintf(output, " -h display this help and exit\n");
343 fprintf(output, "\n");
344 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcap\n");
345 fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcap\"\n");
346 fprintf(output, "\n");
347 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
351 show_version(GString *comp_info_str, GString *runtime_info_str)
355 "Dumpcap " VERSION "%s\n"
360 "See http://www.wireshark.org for more information.\n",
361 wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
365 * Report an error in command-line arguments.
368 cmdarg_err(const char *fmt, ...)
374 /* Generate a 'special format' message back to parent */
376 msg = g_strdup_vprintf(fmt, ap);
377 sync_pipe_errmsg_to_parent(2, msg, "");
382 fprintf(stderr, "dumpcap: ");
383 vfprintf(stderr, fmt, ap);
384 fprintf(stderr, "\n");
390 * Report additional information for an error in command-line arguments.
393 cmdarg_err_cont(const char *fmt, ...)
400 msg = g_strdup_vprintf(fmt, ap);
401 sync_pipe_errmsg_to_parent(2, msg, "");
406 vfprintf(stderr, fmt, ap);
407 fprintf(stderr, "\n");
417 /* Print the number of packets captured for each interface until we're killed. */
419 print_statistics_loop(gboolean machine_readable)
421 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
427 char errbuf[PCAP_ERRBUF_SIZE];
430 if_list = get_interface_list(&err, &err_str);
431 if (if_list == NULL) {
433 case CANT_GET_INTERFACE_LIST:
434 cmdarg_err("%s", err_str);
438 case NO_INTERFACES_FOUND:
439 cmdarg_err("There are no interfaces on which a capture can be done");
445 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
446 if_info = if_entry->data;
447 #ifdef HAVE_PCAP_OPEN
448 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
450 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
454 if_stat = g_malloc(sizeof(if_stat_t));
455 if_stat->name = g_strdup(if_info->name);
457 stat_list = g_list_append(stat_list, if_stat);
462 cmdarg_err("There are no interfaces on which a capture can be done");
466 if (!machine_readable) {
467 printf("%-15s %10s %10s\n", "Interface", "Received",
472 while (global_ld.go) {
473 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
474 if_stat = stat_entry->data;
475 pcap_stats(if_stat->pch, &ps);
477 if (!machine_readable) {
478 printf("%-15s %10u %10u\n", if_stat->name,
479 ps.ps_recv, ps.ps_drop);
481 printf("%s\t%u\t%u\n", if_stat->name,
482 ps.ps_recv, ps.ps_drop);
487 if (! global_ld.from_cap_pipe)
494 /* XXX - Not reached. Should we look for 'q' in stdin? */
495 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
496 if_stat = stat_entry->data;
497 pcap_close(if_stat->pch);
498 g_free(if_stat->name);
501 g_list_free(stat_list);
502 free_interface_list(if_list);
510 capture_cleanup(DWORD dwCtrlType)
512 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
513 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
514 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
515 like SIGTERM at least when the machine's shutting down.
517 For now, if we're running as a command rather than a capture child,
518 we handle all but CTRL_LOGOFF_EVENT as indications that we should
519 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
522 If we're not running as a capture child, we might be running as
523 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
524 user logs out. (XXX - can we explicitly check whether we're
525 running as a service?) */
527 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
528 "Console: Control signal");
529 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
530 "Console: Control signal, CtrlType: %u", dwCtrlType);
532 /* Keep capture running if we're a service and a user logs off */
533 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
542 capture_cleanup(int signum)
544 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
545 SIGTERM. We assume that if the user wanted it to keep running
546 after they logged out, they'd have nohupped it. */
548 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
550 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
551 "Console: Signal, signal value: %u", signum);
557 static void exit_main(int status)
560 /* Shutdown windows sockets */
563 /* can be helpful for debugging */
565 printf("Press any key\n");
576 * If we were linked with libcap (not libpcap), make sure we have
577 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
578 * (See comment in main() for details)
582 #if 0 /* Set to enable capability debugging */
583 /* see 'man cap_to_text()' for explanation of output */
584 /* '=' means 'all= ' ie: no capabilities */
585 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
587 print_caps(char *pfx) {
588 cap_t caps = cap_get_proc();
589 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
590 "%s: EUID: %d Capabilities: %s", pfx,
591 geteuid(), cap_to_text(caps, NULL));
594 print_caps(char *pfx _U_) {
599 relinquish_privs_except_capture(void)
601 /* If 'started_with_special_privs' (ie: suid) then enable for
602 * ourself the NET_ADMIN and NET_RAW capabilities and then
603 * drop our suid privileges.
605 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
606 * stuff we don't need (and shouldn't have).
607 * CAP_NET_RAW: Packet capture (raw sockets).
610 if (started_with_special_privs()) {
611 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
612 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
614 cap_t caps = cap_init(); /* all capabilities initialized to off */
616 print_caps("Pre drop, pre set");
618 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
619 cmdarg_err("prctl() fail return: %s", strerror(errno));
622 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
623 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
625 if (cap_set_proc(caps)) {
626 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
628 print_caps("Pre drop, post set");
630 relinquish_special_privs_perm();
632 print_caps("Post drop, pre set");
633 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
634 if (cap_set_proc(caps)) {
635 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
637 print_caps("Post drop, post set");
645 relinquish_all_capabilities()
647 /* Drop any and all capabilities this process may have. */
648 /* Allowed whether or not process has any privileges. */
649 cap_t caps = cap_init(); /* all capabilities initialized to off */
650 print_caps("Pre-clear");
651 if (cap_set_proc(caps)) {
652 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
654 print_caps("Post-clear");
658 #endif /* HAVE_LIBCAP */
660 /* Take care of byte order in the libpcap headers read from pipes.
661 * (function taken from wiretap/libpcap.c) */
663 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
666 /* Byte-swap the record header fields. */
667 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
668 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
669 rechdr->incl_len = BSWAP32(rechdr->incl_len);
670 rechdr->orig_len = BSWAP32(rechdr->orig_len);
673 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
674 swapped, in order to match the BPF header layout.
676 Unfortunately, some files were, according to a comment in the "libpcap"
677 source, written with version 2.3 in their headers but without the
678 interchanged fields, so if "incl_len" is greater than "orig_len" - which
679 would make no sense - we assume that we need to swap them. */
680 if (hdr->version_major == 2 &&
681 (hdr->version_minor < 3 ||
682 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
685 temp = rechdr->orig_len;
686 rechdr->orig_len = rechdr->incl_len;
687 rechdr->incl_len = temp;
693 * Thread function that reads from a pipe and pushes the data
694 * to the main application thread.
697 * XXX Right now we use async queues for basic signaling. The main thread
698 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
699 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
700 * Iff the read is successful cap_pipe_read pushes an item onto
701 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
702 * the queues themselves (yet).
704 * We might want to move some of the cap_pipe_dispatch logic here so that
705 * we can let cap_pipe_read run independently, queuing up multiple reads
706 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
708 static void *cap_pipe_read(void *ld_ptr) {
709 loop_data *ld = (loop_data *)ld_ptr;
718 while (ld->cap_pipe_err == PIPOK) {
719 g_async_queue_pop(cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
720 g_mutex_lock(cap_pipe_read_mtx);
722 while (bytes_read < (int) ld->cap_pipe_bytes_to_read) {
724 /* If we try to use read() on a named pipe on Windows with partial
725 * data it appears to return EOF.
727 res = ReadFile(ld->cap_pipe_h, ld->cap_pipe_buf+bytes_read,
728 ld->cap_pipe_bytes_to_read - bytes_read,
733 last_err = GetLastError();
734 if (last_err == ERROR_MORE_DATA) {
736 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
737 ld->cap_pipe_err = PIPEOF;
741 ld->cap_pipe_err = PIPERR;
744 } else if (b == 0 && ld->cap_pipe_bytes_to_read > 0) {
745 ld->cap_pipe_err = PIPEOF;
750 b = read(ld->cap_pipe_fd, ld->cap_pipe_buf+bytes_read,
751 ld->cap_pipe_bytes_to_read - bytes_read);
754 ld->cap_pipe_err = PIPEOF;
758 ld->cap_pipe_err = PIPERR;
767 ld->cap_pipe_bytes_read = bytes_read;
768 if (ld->cap_pipe_bytes_read >= ld->cap_pipe_bytes_to_read) {
769 g_async_queue_push(cap_pipe_done_q, ld->cap_pipe_buf); /* Any non-NULL value will do */
771 g_mutex_unlock(cap_pipe_read_mtx);
775 #endif /* USE_THREADS */
777 /* Provide select() functionality for a single file descriptor
778 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
780 * Returns the same values as select. If an error is returned,
781 * the string cap_pipe_err_str should be used instead of errno.
784 cap_pipe_select(int pipe_fd) {
786 struct timeval timeout, *pto;
789 cap_pipe_err_str = "Unknown error";
792 FD_SET(pipe_fd, &rfds);
795 timeout.tv_usec = CAP_READ_TIMEOUT * 1000;
798 sel_ret = select(pipe_fd+1, &rfds, NULL, NULL, pto);
800 cap_pipe_err_str = strerror(errno);
805 /* Mimic pcap_open_live() for pipe captures
806 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
808 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
809 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
811 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
812 char *errmsg, int errmsgl)
815 struct stat pipe_stat;
818 unsigned int bytes_read;
829 ld->cap_pipe_fd = -1;
831 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
833 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
836 * XXX (T)Wireshark blocks until we return
838 if (strcmp(pipename, "-") == 0) {
840 fd = 0; /* read from stdin */
842 ld->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
846 if (ws_stat(pipename, &pipe_stat) < 0) {
847 if (errno == ENOENT || errno == ENOTDIR)
848 ld->cap_pipe_err = PIPNEXIST;
850 g_snprintf(errmsg, errmsgl,
851 "The capture session could not be initiated "
852 "due to error on pipe: %s", strerror(errno));
853 ld->cap_pipe_err = PIPERR;
857 if (! S_ISFIFO(pipe_stat.st_mode)) {
858 if (S_ISCHR(pipe_stat.st_mode)) {
860 * Assume the user specified an interface on a system where
861 * interfaces are in /dev. Pretend we haven't seen it.
863 ld->cap_pipe_err = PIPNEXIST;
866 g_snprintf(errmsg, errmsgl,
867 "The capture session could not be initiated because\n"
868 "\"%s\" is neither an interface nor a pipe", pipename);
869 ld->cap_pipe_err = PIPERR;
873 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
875 g_snprintf(errmsg, errmsgl,
876 "The capture session could not be initiated "
877 "due to error on pipe open: %s", strerror(errno));
878 ld->cap_pipe_err = PIPERR;
882 #define PIPE_STR "\\pipe\\"
883 /* Under Windows, named pipes _must_ have the form
884 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
886 pncopy = g_strdup(pipename);
887 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
888 pos = strchr(pncopy + 3, '\\');
889 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
896 g_snprintf(errmsg, errmsgl,
897 "The capture session could not be initiated because\n"
898 "\"%s\" is neither an interface nor a pipe", pipename);
899 ld->cap_pipe_err = PIPNEXIST;
903 /* Wait for the pipe to appear */
905 ld->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
906 OPEN_EXISTING, 0, NULL);
908 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE)
911 if (GetLastError() != ERROR_PIPE_BUSY) {
912 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
913 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
914 g_snprintf(errmsg, errmsgl,
915 "The capture session on \"%s\" could not be started "
916 "due to error on pipe open: %s (error %d)",
917 pipename, utf_16to8(err_str), GetLastError());
919 ld->cap_pipe_err = PIPERR;
923 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
924 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
925 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
926 g_snprintf(errmsg, errmsgl,
927 "The capture session on \"%s\" timed out during "
928 "pipe open: %s (error %d)",
929 pipename, utf_16to8(err_str), GetLastError());
931 ld->cap_pipe_err = PIPERR;
939 ld->from_cap_pipe = TRUE;
942 /* read the pcap header */
944 while (bytes_read < sizeof magic) {
945 sel_ret = cap_pipe_select(fd);
947 g_snprintf(errmsg, errmsgl,
948 "Unexpected error from select: %s", strerror(errno));
950 } else if (sel_ret > 0) {
951 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
954 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
956 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
963 #else /* USE_THREADS */
964 g_thread_create(&cap_pipe_read, ld, FALSE, NULL);
966 ld->cap_pipe_buf = (char *) &magic;
967 ld->cap_pipe_bytes_read = 0;
968 ld->cap_pipe_bytes_to_read = sizeof(magic);
969 /* We don't have to worry about cap_pipe_read_mtx here */
970 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
971 g_async_queue_pop(cap_pipe_done_q);
972 if (ld->cap_pipe_bytes_read <= 0) {
973 if (ld->cap_pipe_bytes_read == 0)
974 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
976 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
980 #endif /* USE_THREADS */
984 /* Host that wrote it has our byte order, and was running
985 a program using either standard or ss990417 libpcap. */
986 ld->cap_pipe_byte_swapped = FALSE;
987 ld->cap_pipe_modified = FALSE;
989 case PCAP_MODIFIED_MAGIC:
990 /* Host that wrote it has our byte order, but was running
991 a program using either ss990915 or ss991029 libpcap. */
992 ld->cap_pipe_byte_swapped = FALSE;
993 ld->cap_pipe_modified = TRUE;
995 case PCAP_SWAPPED_MAGIC:
996 /* Host that wrote it has a byte order opposite to ours,
997 and was running a program using either standard or
999 ld->cap_pipe_byte_swapped = TRUE;
1000 ld->cap_pipe_modified = FALSE;
1002 case PCAP_SWAPPED_MODIFIED_MAGIC:
1003 /* Host that wrote it out has a byte order opposite to
1004 ours, and was running a program using either ss990915
1005 or ss991029 libpcap. */
1006 ld->cap_pipe_byte_swapped = TRUE;
1007 ld->cap_pipe_modified = TRUE;
1010 /* Not a "libpcap" type we know about. */
1011 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
1016 /* Read the rest of the header */
1018 while (bytes_read < sizeof(struct pcap_hdr)) {
1019 sel_ret = cap_pipe_select(fd);
1021 g_snprintf(errmsg, errmsgl,
1022 "Unexpected error from select: %s", strerror(errno));
1024 } else if (sel_ret > 0) {
1025 b = read(fd, ((char *)hdr)+bytes_read,
1026 sizeof(struct pcap_hdr) - bytes_read);
1029 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1031 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
1038 #else /* USE_THREADS */
1039 ld->cap_pipe_buf = (char *) hdr;
1040 ld->cap_pipe_bytes_read = 0;
1041 ld->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1042 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1043 g_async_queue_pop(cap_pipe_done_q);
1044 if (ld->cap_pipe_bytes_read <= 0) {
1045 if (ld->cap_pipe_bytes_read == 0)
1046 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1048 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
1052 #endif /* USE_THREADS */
1054 if (ld->cap_pipe_byte_swapped) {
1055 /* Byte-swap the header fields about which we care. */
1056 hdr->version_major = BSWAP16(hdr->version_major);
1057 hdr->version_minor = BSWAP16(hdr->version_minor);
1058 hdr->snaplen = BSWAP32(hdr->snaplen);
1059 hdr->network = BSWAP32(hdr->network);
1061 ld->linktype = hdr->network;
1063 if (hdr->version_major < 2) {
1064 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1068 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1069 ld->cap_pipe_err = PIPOK;
1071 ld->cap_pipe_fd = fd;
1076 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1077 ld->cap_pipe_err = PIPERR;
1080 ld->cap_pipe_fd = -1;
1087 /* We read one record from the pipe, take care of byte order in the record
1088 * header, write the record to the capture file, and update capture statistics. */
1090 cap_pipe_dispatch(loop_data *ld, guchar *data, char *errmsg, int errmsgl)
1092 struct pcap_pkthdr phdr;
1093 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1105 #ifdef LOG_CAPTURE_VERBOSE
1106 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1109 switch (ld->cap_pipe_state) {
1111 case STATE_EXPECT_REC_HDR:
1113 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1116 ld->cap_pipe_state = STATE_READ_REC_HDR;
1117 ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
1118 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1119 ld->cap_pipe_bytes_read = 0;
1122 ld->cap_pipe_buf = (char *) &ld->cap_pipe_rechdr;
1123 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1124 g_mutex_unlock(cap_pipe_read_mtx);
1129 case STATE_READ_REC_HDR:
1131 b = read(ld->cap_pipe_fd, ((char *)&ld->cap_pipe_rechdr)+ld->cap_pipe_bytes_read,
1132 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1135 result = PD_PIPE_EOF;
1137 result = PD_PIPE_ERR;
1140 ld->cap_pipe_bytes_read += b;
1141 #else /* USE_THREADS */
1142 g_get_current_time(&wait_time);
1143 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1144 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1145 if (ld->cap_pipe_err == PIPEOF) {
1146 result = PD_PIPE_EOF;
1148 } else if (ld->cap_pipe_err == PIPERR) {
1149 result = PD_PIPE_ERR;
1155 #endif /* USE_THREADS */
1156 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1158 result = PD_REC_HDR_READ;
1161 case STATE_EXPECT_DATA:
1163 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1166 ld->cap_pipe_state = STATE_READ_DATA;
1167 ld->cap_pipe_bytes_to_read = ld->cap_pipe_rechdr.hdr.incl_len;
1168 ld->cap_pipe_bytes_read = 0;
1171 ld->cap_pipe_buf = (char *) data;
1172 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1173 g_mutex_unlock(cap_pipe_read_mtx);
1178 case STATE_READ_DATA:
1180 b = read(ld->cap_pipe_fd, data+ld->cap_pipe_bytes_read,
1181 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1184 result = PD_PIPE_EOF;
1186 result = PD_PIPE_ERR;
1189 ld->cap_pipe_bytes_read += b;
1190 #else /* USE_THREADS */
1191 g_get_current_time(&wait_time);
1192 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1193 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1194 if (ld->cap_pipe_err == PIPEOF) {
1195 result = PD_PIPE_EOF;
1197 } else if (ld->cap_pipe_err == PIPERR) {
1198 result = PD_PIPE_ERR;
1204 #endif /* USE_THREADS */
1205 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1207 result = PD_DATA_READ;
1211 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
1214 } /* switch (ld->cap_pipe_state) */
1217 * We've now read as much data as we were expecting, so process it.
1221 case PD_REC_HDR_READ:
1222 /* We've read the header. Take care of byte order. */
1223 cap_pipe_adjust_header(ld->cap_pipe_byte_swapped, &ld->cap_pipe_hdr,
1224 &ld->cap_pipe_rechdr.hdr);
1225 if (ld->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1226 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
1227 ld->packet_count+1, ld->cap_pipe_rechdr.hdr.incl_len);
1230 ld->cap_pipe_state = STATE_EXPECT_DATA;
1234 /* Fill in a "struct pcap_pkthdr", and process the packet. */
1235 phdr.ts.tv_sec = ld->cap_pipe_rechdr.hdr.ts_sec;
1236 phdr.ts.tv_usec = ld->cap_pipe_rechdr.hdr.ts_usec;
1237 phdr.caplen = ld->cap_pipe_rechdr.hdr.incl_len;
1238 phdr.len = ld->cap_pipe_rechdr.hdr.orig_len;
1240 capture_loop_packet_cb((u_char *)ld, &phdr, data);
1242 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1246 ld->cap_pipe_err = PIPEOF;
1251 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1252 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1253 g_snprintf(errmsg, errmsgl,
1254 "Error reading from pipe: %s (error %d)",
1255 utf_16to8(err_str), GetLastError());
1258 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
1266 ld->cap_pipe_err = PIPERR;
1267 /* Return here rather than inside the switch to prevent GCC warning */
1272 /** Open the capture input file (pcap or capture pipe).
1273 * Returns TRUE if it succeeds, FALSE otherwise. */
1275 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
1276 char *errmsg, size_t errmsg_len,
1277 char *secondary_errmsg, size_t secondary_errmsg_len)
1279 gchar open_err_str[PCAP_ERRBUF_SIZE];
1280 gchar *sync_msg_str;
1281 static const char ppamsg[] = "can't find PPA for ";
1282 const char *set_linktype_err_str;
1283 const char *libpcap_warn;
1285 gchar *sync_secondary_msg_str;
1287 WORD wVersionRequested;
1290 #ifdef HAVE_PCAP_REMOTE
1291 struct pcap_rmtauth auth;
1295 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
1298 /* XXX - opening Winsock on tshark? */
1300 /* Initialize Windows Socket if we are in a WIN32 OS
1301 This needs to be done before querying the interface for network/netmask */
1303 /* XXX - do we really require 1.1 or earlier?
1304 Are there any versions that support only 2.0 or higher? */
1305 wVersionRequested = MAKEWORD(1, 1);
1306 err = WSAStartup(wVersionRequested, &wsaData);
1310 case WSASYSNOTREADY:
1311 g_snprintf(errmsg, (gulong) errmsg_len,
1312 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
1315 case WSAVERNOTSUPPORTED:
1316 g_snprintf(errmsg, (gulong) errmsg_len,
1317 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
1318 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
1321 case WSAEINPROGRESS:
1322 g_snprintf(errmsg, (gulong) errmsg_len,
1323 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
1327 g_snprintf(errmsg, (gulong) errmsg_len,
1328 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
1332 g_snprintf(errmsg, (gulong) errmsg_len,
1333 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
1337 g_snprintf(errmsg, (gulong) errmsg_len,
1338 "Couldn't initialize Windows Sockets: error %d", err);
1341 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
1346 /* Open the network interface to capture from it.
1347 Some versions of libpcap may put warnings into the error buffer
1348 if they succeed; to tell if that's happened, we have to clear
1349 the error buffer, and check if it's still a null string. */
1350 open_err_str[0] = '\0';
1351 #ifdef HAVE_PCAP_OPEN
1352 auth.type = capture_opts->auth_type == CAPTURE_AUTH_PWD ?
1353 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
1354 auth.username = capture_opts->auth_username;
1355 auth.password = capture_opts->auth_password;
1357 ld->pcap_h = pcap_open(capture_opts->iface,
1358 capture_opts->has_snaplen ? capture_opts->snaplen :
1359 WTAP_MAX_PACKET_SIZE,
1361 (capture_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
1362 (capture_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
1363 (capture_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
1364 CAP_READ_TIMEOUT, &auth, open_err_str);
1366 ld->pcap_h = pcap_open_live(capture_opts->iface,
1367 capture_opts->has_snaplen ? capture_opts->snaplen :
1368 WTAP_MAX_PACKET_SIZE,
1369 capture_opts->promisc_mode, CAP_READ_TIMEOUT,
1373 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
1374 /* to remove any suid privileges. */
1375 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
1376 /* (euid/egid have already previously been set to ruid/rgid. */
1377 /* (See comment in main() for details) */
1379 relinquish_special_privs_perm();
1381 relinquish_all_capabilities();
1384 if (ld->pcap_h != NULL) {
1385 /* we've opened "iface" as a network device */
1387 /* try to set the capture buffer size */
1388 if (capture_opts->buffer_size > 1 &&
1389 pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
1390 sync_secondary_msg_str = g_strdup_printf(
1391 "The capture buffer size of %luMB seems to be too high for your machine,\n"
1392 "the default of 1MB will be used.\n"
1394 "Nonetheless, the capture is started.\n",
1395 capture_opts->buffer_size);
1396 report_capture_error("Couldn't set the capture buffer size!",
1397 sync_secondary_msg_str);
1398 g_free(sync_secondary_msg_str);
1402 #if defined(HAVE_PCAP_REMOTE) && defined(HAVE_PCAP_SETSAMPLING)
1403 if (capture_opts->sampling_method != CAPTURE_SAMP_NONE)
1405 struct pcap_samp *samp;
1407 if ((samp = pcap_setsampling(ld->pcap_h)) != NULL)
1409 switch (capture_opts->sampling_method)
1411 case CAPTURE_SAMP_BY_COUNT:
1412 samp->method = PCAP_SAMP_1_EVERY_N;
1415 case CAPTURE_SAMP_BY_TIMER:
1416 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
1420 sync_msg_str = g_strdup_printf(
1421 "Unknown sampling method %d specified,\n"
1422 "continue without packet sampling",
1423 capture_opts->sampling_method);
1424 report_capture_error("Couldn't set the capture "
1425 "sampling", sync_msg_str);
1426 g_free(sync_msg_str);
1428 samp->value = capture_opts->sampling_param;
1432 report_capture_error("Couldn't set the capture sampling",
1433 "Cannot get packet sampling data structure");
1439 /* setting the data link type only works on real interfaces */
1440 if (capture_opts->linktype != -1) {
1441 set_linktype_err_str = set_pcap_linktype(ld->pcap_h, capture_opts->iface,
1442 capture_opts->linktype);
1443 if (set_linktype_err_str != NULL) {
1444 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
1445 set_linktype_err_str);
1446 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
1450 ld->linktype = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
1452 /* We couldn't open "iface" as a network device. */
1453 /* Try to open it as a pipe */
1454 cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, (int) errmsg_len);
1457 if (ld->cap_pipe_fd == -1) {
1459 if (ld->cap_pipe_h == INVALID_HANDLE_VALUE) {
1462 if (ld->cap_pipe_err == PIPNEXIST) {
1463 /* Pipe doesn't exist, so output message for interface */
1465 /* If we got a "can't find PPA for X" message, warn the user (who
1466 is running (T)Wireshark on HP-UX) that they don't have a version
1467 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1468 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1469 PPA for X" rather than "can't find PPA for X"). */
1470 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1473 "You are running (T)Wireshark with a version of the libpcap library\n"
1474 "that doesn't handle HP-UX network devices well; this means that\n"
1475 "(T)Wireshark may not be able to capture packets.\n"
1477 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1478 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1479 "packaged binary form from the Software Porting And Archive Centre\n"
1480 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1481 "at the URL lists a number of mirror sites.";
1484 g_snprintf(errmsg, (gulong) errmsg_len,
1485 "The capture session could not be initiated (%s).", open_err_str);
1487 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
1488 "Please check to make sure you have sufficient permissions, and that you have "
1489 "the proper interface or pipe specified.%s", libpcap_warn);
1491 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
1493 "Please check that \"%s\" is the proper interface.\n"
1496 "Help can be found at:\n"
1498 " http://wiki.wireshark.org/WinPcap\n"
1499 " http://wiki.wireshark.org/CaptureSetup\n",
1500 capture_opts->iface);
1504 * Else pipe (or file) does exist and cap_pipe_open_live() has
1509 /* cap_pipe_open_live() succeeded; don't want
1510 error message from pcap_open_live() */
1511 open_err_str[0] = '\0';
1514 /* XXX - will this work for tshark? */
1515 #ifdef MUST_DO_SELECT
1516 if (!ld->from_cap_pipe) {
1517 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
1518 ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
1520 ld->pcap_fd = pcap_fileno(ld->pcap_h);
1525 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1526 returned a warning; print it, but keep capturing. */
1527 if (open_err_str[0] != '\0') {
1528 sync_msg_str = g_strdup_printf("%s.", open_err_str);
1529 report_capture_error(sync_msg_str, "");
1530 g_free(sync_msg_str);
1537 /* close the capture input file (pcap or capture pipe) */
1538 static void capture_loop_close_input(loop_data *ld) {
1540 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
1542 /* if open, close the capture pipe "input file" */
1544 if (ld->cap_pipe_fd >= 0) {
1545 g_assert(ld->from_cap_pipe);
1546 ws_close(ld->cap_pipe_fd);
1547 ld->cap_pipe_fd = 0;
1550 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE) {
1551 CloseHandle(ld->cap_pipe_h);
1552 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
1556 /* if open, close the pcap "input file" */
1557 if(ld->pcap_h != NULL) {
1558 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", ld->pcap_h);
1559 g_assert(!ld->from_cap_pipe);
1560 pcap_close(ld->pcap_h);
1567 /* Shut down windows sockets */
1573 /* init the capture filter */
1574 static initfilter_status_t
1575 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe, gchar * iface, gchar * cfilter) {
1576 bpf_u_int32 netnum, netmask;
1577 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
1578 struct bpf_program fcode;
1581 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
1583 /* capture filters only work on real interfaces */
1584 if (cfilter && !from_cap_pipe) {
1585 /* A capture filter was specified; set it up. */
1586 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1588 * Well, we can't get the netmask for this interface; it's used
1589 * only for filters that check for broadcast IP addresses, so
1590 * we just punt and use 0. It might be nice to warn the user,
1591 * but that's a pain in a GUI application, as it'd involve popping
1592 * up a message box, and it's not clear how often this would make
1593 * a difference (only filters that check for IP broadcast addresses
1597 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
1600 if (pcap_compile(pcap_h, &fcode, cfilter, 1, netmask) < 0) {
1601 /* Treat this specially - our caller might try to compile this
1602 as a display filter and, if that succeeds, warn the user that
1603 the display and capture filter syntaxes are different. */
1604 return INITFILTER_BAD_FILTER;
1606 if (pcap_setfilter(pcap_h, &fcode) < 0) {
1607 #ifdef HAVE_PCAP_FREECODE
1608 pcap_freecode(&fcode);
1610 return INITFILTER_OTHER_ERROR;
1612 #ifdef HAVE_PCAP_FREECODE
1613 pcap_freecode(&fcode);
1617 return INITFILTER_NO_ERROR;
1621 /* set up to write to the already-opened capture output file/files */
1623 capture_loop_init_output(capture_options *capture_opts, int save_file_fd, loop_data *ld, char *errmsg, int errmsg_len) {
1627 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
1630 if (ld->from_cap_pipe) {
1631 ld->file_snaplen = ld->cap_pipe_hdr.snaplen;
1634 ld->file_snaplen = pcap_snapshot(ld->pcap_h);
1637 /* Set up to write to the capture file. */
1638 if (capture_opts->multi_files_on) {
1639 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
1641 ld->pdh = libpcap_fdopen(save_file_fd, &err);
1644 gboolean successful;
1646 ld->bytes_written = 0;
1647 if (capture_opts->use_pcapng) {
1650 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
1651 successful = libpcap_write_session_header_block(ld->pdh, appname, &ld->bytes_written, &err) &&
1652 libpcap_write_interface_description_block(ld->pdh, capture_opts->iface, capture_opts->cfilter, ld->linktype, ld->file_snaplen, &ld->bytes_written, &err);
1654 successful = libpcap_write_file_header(ld->pdh, ld->linktype, ld->file_snaplen,
1655 &ld->bytes_written, &err);
1663 if (ld->pdh == NULL) {
1664 /* We couldn't set up to write to the capture file. */
1665 /* XXX - use cf_open_error_message from tshark instead? */
1668 case WTAP_ERR_CANT_OPEN:
1669 g_snprintf(errmsg, errmsg_len, "The file to which the capture would be saved"
1670 " couldn't be created for some unknown reason.");
1673 case WTAP_ERR_SHORT_WRITE:
1674 g_snprintf(errmsg, errmsg_len, "A full header couldn't be written to the file"
1675 " to which the capture would be saved.");
1680 g_snprintf(errmsg, errmsg_len,
1681 "The file to which the capture would be"
1682 " saved (\"%s\") could not be opened: Error %d.",
1683 capture_opts->save_file, err);
1685 g_snprintf(errmsg, errmsg_len,
1686 "The file to which the capture would be"
1687 " saved (\"%s\") could not be opened: %s.",
1688 capture_opts->save_file, strerror(err));
1700 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
1702 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
1704 if (capture_opts->multi_files_on) {
1705 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
1707 if (capture_opts->use_pcapng) {
1708 libpcap_write_interface_statistics_block(ld->pdh, 0, ld->pcap_h, &ld->bytes_written, err_close);
1710 return libpcap_dump_close(ld->pdh, err_close);
1714 /* dispatch incoming packets (pcap or capture pipe)
1716 * Waits for incoming packets to be available, and calls pcap_dispatch()
1717 * to cause them to be processed.
1719 * Returns the number of packets which were processed.
1721 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
1722 * packet-batching behaviour does not cause packets to get held back
1726 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
1727 char *errmsg, int errmsg_len)
1730 gint packet_count_before;
1731 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1736 packet_count_before = ld->packet_count;
1737 if (ld->from_cap_pipe) {
1738 /* dispatch from capture pipe */
1739 #ifdef LOG_CAPTURE_VERBOSE
1740 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
1743 sel_ret = cap_pipe_select(ld->cap_pipe_fd);
1746 if (sel_ret < 0 && errno != EINTR) {
1747 g_snprintf(errmsg, errmsg_len,
1748 "Unexpected error from select: %s", strerror(errno));
1749 report_capture_error(errmsg, please_report);
1754 * "select()" says we can read from the pipe without blocking
1756 #endif /* USE_THREADS */
1757 inpkts = cap_pipe_dispatch(ld, pcap_data, errmsg, errmsg_len);
1767 /* dispatch from pcap */
1768 #ifdef MUST_DO_SELECT
1770 * If we have "pcap_get_selectable_fd()", we use it to get the
1771 * descriptor on which to select; if that's -1, it means there
1772 * is no descriptor on which you can do a "select()" (perhaps
1773 * because you're capturing on a special device, and that device's
1774 * driver unfortunately doesn't support "select()", in which case
1775 * we don't do the select - which means it might not be possible
1776 * to stop a capture until a packet arrives. If that's unacceptable,
1777 * plead with whoever supplies the software for that device to add
1778 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
1779 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
1780 * later, so it can use pcap_breakloop().
1782 #ifdef LOG_CAPTURE_VERBOSE
1783 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
1785 if (ld->pcap_fd != -1) {
1786 sel_ret = cap_pipe_select(ld->pcap_fd);
1789 * "select()" says we can read from it without blocking; go for
1792 * We don't have pcap_breakloop(), so we only process one packet
1793 * per pcap_dispatch() call, to allow a signal to stop the
1794 * processing immediately, rather than processing all packets
1795 * in a batch before quitting.
1797 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb,
1801 /* Error, rather than pcap_breakloop(). */
1802 ld->pcap_err = TRUE;
1804 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1807 if (sel_ret < 0 && errno != EINTR) {
1808 g_snprintf(errmsg, errmsg_len,
1809 "Unexpected error from select: %s", strerror(errno));
1810 report_capture_error(errmsg, please_report);
1816 #endif /* MUST_DO_SELECT */
1818 /* dispatch from pcap without select */
1820 #ifdef LOG_CAPTURE_VERBOSE
1821 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
1825 * On Windows, we don't support asynchronously telling a process to
1826 * stop capturing; instead, we check for an indication on a pipe
1827 * after processing packets. We therefore process only one packet
1828 * at a time, so that we can check the pipe after every packet.
1830 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb, (u_char *) ld);
1832 inpkts = pcap_dispatch(ld->pcap_h, -1, capture_loop_packet_cb, (u_char *) ld);
1836 /* Error, rather than pcap_breakloop(). */
1837 ld->pcap_err = TRUE;
1839 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1841 #else /* pcap_next_ex */
1842 #ifdef LOG_CAPTURE_VERBOSE
1843 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
1845 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
1848 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
1849 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
1850 * This should be fixed in the WinPcap 4.0 alpha release.
1852 * For reference, an example remote interface:
1853 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
1856 /* emulate dispatch from pcap */
1859 struct pcap_pkthdr *pkt_header;
1864 (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1)
1865 capture_loop_packet_cb( (u_char *) ld, pkt_header, pkt_data);
1868 ld->pcap_err = TRUE;
1872 #endif /* pcap_next_ex */
1876 #ifdef LOG_CAPTURE_VERBOSE
1877 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
1880 return ld->packet_count - packet_count_before;
1884 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
1885 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
1887 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
1888 char *errmsg, int errmsg_len) {
1891 gchar *capfile_name;
1892 gboolean is_tempfile;
1897 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
1898 (capture_opts->save_file) ? capture_opts->save_file : "");
1900 if (capture_opts->save_file != NULL) {
1901 /* We return to the caller while the capture is in progress.
1902 * Therefore we need to take a copy of save_file in
1903 * case the caller destroys it after we return.
1905 capfile_name = g_strdup(capture_opts->save_file);
1907 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
1908 if (capture_opts->multi_files_on) {
1909 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
1910 g_snprintf(errmsg, errmsg_len,
1911 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
1912 g_free(capfile_name);
1915 if (strcmp(capfile_name, "-") == 0) {
1916 /* write to stdout */
1919 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
1920 _setmode(1, O_BINARY);
1923 } /* if (...output_to_pipe ... */
1926 if (capture_opts->multi_files_on) {
1927 /* ringbuffer is enabled */
1928 *save_file_fd = ringbuf_init(capfile_name,
1929 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
1931 /* we need the ringbuf name */
1932 if(*save_file_fd != -1) {
1933 g_free(capfile_name);
1934 capfile_name = g_strdup(ringbuf_current_filename());
1937 /* Try to open/create the specified file for use as a capture buffer. */
1938 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
1942 is_tempfile = FALSE;
1944 /* Choose a random name for the temporary capture buffer */
1945 *save_file_fd = create_tempfile(&tmpname, "wireshark");
1946 capfile_name = g_strdup(tmpname);
1950 /* did we fail to open the output file? */
1951 if (*save_file_fd == -1) {
1953 g_snprintf(errmsg, errmsg_len,
1954 "The temporary file to which the capture would be saved (\"%s\") "
1955 "could not be opened: %s.", capfile_name, strerror(errno));
1957 if (capture_opts->multi_files_on) {
1958 ringbuf_error_cleanup();
1961 g_snprintf(errmsg, errmsg_len,
1962 "The file to which the capture would be saved (\"%s\") "
1963 "could not be opened: %s.", capfile_name,
1966 g_free(capfile_name);
1970 if(capture_opts->save_file != NULL) {
1971 g_free(capture_opts->save_file);
1973 capture_opts->save_file = capfile_name;
1974 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
1975 "g_free(capfile_name)". */
1977 ret = fchown(*save_file_fd, capture_opts->owner, capture_opts->group);
1985 capture_loop_stop_signal_handler(int signo _U_)
1987 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Signal: Stop capture");
1988 capture_loop_stop();
1992 #define TIME_GET() GetTickCount()
1994 #define TIME_GET() time(NULL)
1997 /* Do the low-level work of a capture.
1998 Returns TRUE if it succeeds, FALSE otherwise. */
2000 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
2003 struct sigaction act;
2005 time_t upd_time, cur_time;
2009 gint inpkts_to_sync_pipe = 0; /* packets not already send out to the sync_pipe */
2010 condition *cnd_file_duration = NULL;
2011 condition *cnd_autostop_files = NULL;
2012 condition *cnd_autostop_size = NULL;
2013 condition *cnd_autostop_duration = NULL;
2014 guint32 autostop_files = 0;
2017 gboolean cfilter_error = FALSE;
2018 #define MSG_MAX_LENGTH 4096
2019 char errmsg[MSG_MAX_LENGTH+1];
2020 char secondary_errmsg[MSG_MAX_LENGTH+1];
2021 int save_file_fd = -1;
2024 *secondary_errmsg = '\0';
2026 /* init the loop data */
2027 global_ld.go = TRUE;
2028 global_ld.packet_count = 0;
2029 if (capture_opts->has_autostop_packets)
2030 global_ld.packet_max = capture_opts->autostop_packets;
2032 global_ld.packet_max = 0; /* no limit */
2033 global_ld.err = 0; /* no error seen yet */
2034 global_ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
2035 global_ld.pcap_err = FALSE;
2036 global_ld.from_cap_pipe = FALSE;
2037 global_ld.pdh = NULL;
2039 global_ld.cap_pipe_fd = -1;
2041 global_ld.cap_pipe_h = INVALID_HANDLE_VALUE;
2043 #ifdef MUST_DO_SELECT
2044 global_ld.pcap_fd = 0;
2047 /* We haven't yet gotten the capture statistics. */
2048 *stats_known = FALSE;
2052 * Catch SIGUSR1, so that we exit cleanly if the parent process
2053 * kills us with it due to the user selecting "Capture->Stop".
2055 act.sa_handler = capture_loop_stop_signal_handler;
2057 * Arrange that system calls not get restarted, because when
2058 * our signal handler returns we don't want to restart
2059 * a call that was waiting for packets to arrive.
2062 sigemptyset(&act.sa_mask);
2063 sigaction(SIGUSR1, &act, NULL);
2066 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
2067 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
2069 /* open the "input file" from network interface or capture pipe */
2070 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
2071 secondary_errmsg, sizeof(secondary_errmsg))) {
2075 /* init the input filter from the network interface (capture pipe will do nothing) */
2076 switch (capture_loop_init_filter(global_ld.pcap_h, global_ld.from_cap_pipe,
2077 capture_opts->iface,
2078 capture_opts->cfilter)) {
2080 case INITFILTER_NO_ERROR:
2083 case INITFILTER_BAD_FILTER:
2084 cfilter_error = TRUE;
2085 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(global_ld.pcap_h));
2088 case INITFILTER_OTHER_ERROR:
2089 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
2090 pcap_geterr(global_ld.pcap_h));
2091 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
2095 /* If we're supposed to write to a capture file, open it for output
2096 (temporary/specified name/ringbuffer) */
2097 if (capture_opts->saving_to_file) {
2098 if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
2102 /* set up to write to the already-opened capture output file/files */
2103 if (!capture_loop_init_output(capture_opts, save_file_fd, &global_ld,
2104 errmsg, sizeof(errmsg))) {
2108 /* XXX - capture SIGTERM and close the capture, in case we're on a
2109 Linux 2.0[.x] system and you have to explicitly close the capture
2110 stream in order to turn promiscuous mode off? We need to do that
2111 in other places as well - and I don't think that works all the
2112 time in any case, due to libpcap bugs. */
2114 /* Well, we should be able to start capturing.
2116 Sync out the capture file, so the header makes it to the file system,
2117 and send a "capture started successfully and capture file created"
2118 message to our parent so that they'll open the capture file and
2119 update its windows to indicate that we have a live capture in
2121 libpcap_dump_flush(global_ld.pdh, NULL);
2122 report_new_capture_file(capture_opts->save_file);
2125 /* initialize capture stop (and alike) conditions */
2126 init_capture_stop_conditions();
2127 /* create stop conditions */
2128 if (capture_opts->has_autostop_filesize)
2130 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
2131 if (capture_opts->has_autostop_duration)
2132 cnd_autostop_duration =
2133 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
2135 if (capture_opts->multi_files_on) {
2136 if (capture_opts->has_file_duration)
2138 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
2140 if (capture_opts->has_autostop_files)
2141 cnd_autostop_files =
2142 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
2145 /* init the time values */
2146 start_time = TIME_GET();
2147 upd_time = TIME_GET();
2149 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
2151 /* WOW, everything is prepared! */
2152 /* please fasten your seat belts, we will enter now the actual capture loop */
2153 while (global_ld.go) {
2154 /* dispatch incoming packets */
2155 inpkts = capture_loop_dispatch(capture_opts, &global_ld, errmsg,
2159 /* any news from our parent (signal pipe)? -> just stop the capture */
2160 if (!signal_pipe_check_running()) {
2161 global_ld.go = FALSE;
2166 inpkts_to_sync_pipe += inpkts;
2168 /* check capture size condition */
2169 if (cnd_autostop_size != NULL &&
2170 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)){
2171 /* Capture size limit reached, do we have another file? */
2172 if (capture_opts->multi_files_on) {
2173 if (cnd_autostop_files != NULL &&
2174 cnd_eval(cnd_autostop_files, ++autostop_files)) {
2175 /* no files left: stop here */
2176 global_ld.go = FALSE;
2180 /* Switch to the next ringbuffer file */
2181 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2182 &save_file_fd, &global_ld.err)) {
2183 gboolean successful;
2185 /* File switch succeeded: reset the conditions */
2186 global_ld.bytes_written = 0;
2187 if (capture_opts->use_pcapng) {
2190 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2191 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2192 libpcap_write_interface_description_block(global_ld.pdh, capture_opts->iface, capture_opts->cfilter, global_ld.linktype, global_ld.file_snaplen, &global_ld.bytes_written, &global_ld.err);
2194 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2195 &global_ld.bytes_written, &global_ld.err);
2198 fclose(global_ld.pdh);
2199 global_ld.pdh = NULL;
2200 global_ld.go = FALSE;
2203 cnd_reset(cnd_autostop_size);
2204 if (cnd_file_duration) {
2205 cnd_reset(cnd_file_duration);
2207 libpcap_dump_flush(global_ld.pdh, NULL);
2208 report_packet_count(inpkts_to_sync_pipe);
2209 inpkts_to_sync_pipe = 0;
2210 report_new_capture_file(capture_opts->save_file);
2212 /* File switch failed: stop here */
2213 global_ld.go = FALSE;
2217 /* single file, stop now */
2218 global_ld.go = FALSE;
2221 } /* cnd_autostop_size */
2222 if (capture_opts->output_to_pipe) {
2223 libpcap_dump_flush(global_ld.pdh, NULL);
2227 /* Only update once a second (Win32: 500ms) so as not to overload slow
2228 * displays. This also prevents too much context-switching between the
2229 * dumpcap and wireshark processes */
2230 cur_time = TIME_GET();
2232 if ( (cur_time - upd_time) > 500) {
2234 if (cur_time - upd_time > 0) {
2236 upd_time = cur_time;
2238 /*if (pcap_stats(pch, stats) >= 0) {
2239 *stats_known = TRUE;
2242 /* Let the parent process know. */
2243 if (inpkts_to_sync_pipe) {
2245 libpcap_dump_flush(global_ld.pdh, NULL);
2247 /* Send our parent a message saying we've written out "inpkts_to_sync_pipe"
2248 packets to the capture file. */
2249 report_packet_count(inpkts_to_sync_pipe);
2251 inpkts_to_sync_pipe = 0;
2254 /* check capture duration condition */
2255 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
2256 /* The maximum capture time has elapsed; stop the capture. */
2257 global_ld.go = FALSE;
2261 /* check capture file duration condition */
2262 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
2263 /* duration limit reached, do we have another file? */
2264 if (capture_opts->multi_files_on) {
2265 if (cnd_autostop_files != NULL &&
2266 cnd_eval(cnd_autostop_files, ++autostop_files)) {
2267 /* no files left: stop here */
2268 global_ld.go = FALSE;
2272 /* Switch to the next ringbuffer file */
2273 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2274 &save_file_fd, &global_ld.err)) {
2275 gboolean successful;
2277 /* file switch succeeded: reset the conditions */
2278 global_ld.bytes_written = 0;
2279 if (capture_opts->use_pcapng) {
2282 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2283 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2284 libpcap_write_interface_description_block(global_ld.pdh, capture_opts->iface, capture_opts->cfilter, global_ld.linktype, global_ld.file_snaplen, &global_ld.bytes_written, &global_ld.err);
2286 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2287 &global_ld.bytes_written, &global_ld.err);
2290 fclose(global_ld.pdh);
2291 global_ld.pdh = NULL;
2292 global_ld.go = FALSE;
2295 cnd_reset(cnd_file_duration);
2296 if(cnd_autostop_size)
2297 cnd_reset(cnd_autostop_size);
2298 libpcap_dump_flush(global_ld.pdh, NULL);
2299 report_packet_count(inpkts_to_sync_pipe);
2300 inpkts_to_sync_pipe = 0;
2301 report_new_capture_file(capture_opts->save_file);
2303 /* File switch failed: stop here */
2304 global_ld.go = FALSE;
2308 /* single file, stop now */
2309 global_ld.go = FALSE;
2312 } /* cnd_file_duration */
2315 } /* while (global_ld.go) */
2317 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
2319 /* delete stop conditions */
2320 if (cnd_file_duration != NULL)
2321 cnd_delete(cnd_file_duration);
2322 if (cnd_autostop_files != NULL)
2323 cnd_delete(cnd_autostop_files);
2324 if (cnd_autostop_size != NULL)
2325 cnd_delete(cnd_autostop_size);
2326 if (cnd_autostop_duration != NULL)
2327 cnd_delete(cnd_autostop_duration);
2329 /* did we had a pcap (input) error? */
2330 if (global_ld.pcap_err) {
2331 /* On Linux, if an interface goes down while you're capturing on it,
2332 you'll get a "recvfrom: Network is down" error (ENETDOWN).
2333 (At least you will if strerror() doesn't show a local translation
2336 On FreeBSD and OS X, if a network adapter disappears while
2337 you're capturing on it, you'll get a "read: Device not configured"
2338 error (ENXIO). (See previous parenthetical note.)
2340 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
2342 These should *not* be reported to the Wireshark developers. */
2345 cap_err_str = pcap_geterr(global_ld.pcap_h);
2346 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
2347 strcmp(cap_err_str, "read: Device not configured") == 0 ||
2348 strcmp(cap_err_str, "read: I/O error") == 0) {
2349 report_capture_error("The network adapter on which the capture was being done "
2350 "is no longer running; the capture has stopped.",
2353 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
2355 report_capture_error(errmsg, please_report);
2358 else if (global_ld.from_cap_pipe && global_ld.cap_pipe_err == PIPERR)
2359 report_capture_error(errmsg, "");
2361 /* did we had an error while capturing? */
2362 if (global_ld.err == 0) {
2365 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
2366 global_ld.err, FALSE);
2367 report_capture_error(errmsg, please_report);
2371 if (capture_opts->saving_to_file) {
2372 /* close the wiretap (output) file */
2373 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
2377 /* there might be packets not yet notified to the parent */
2378 /* (do this after closing the file, so all packets are already flushed) */
2379 if(inpkts_to_sync_pipe) {
2380 report_packet_count(inpkts_to_sync_pipe);
2381 inpkts_to_sync_pipe = 0;
2384 /* If we've displayed a message about a write error, there's no point
2385 in displaying another message about an error on close. */
2386 if (!close_ok && write_ok) {
2387 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
2389 report_capture_error(errmsg, "");
2393 * XXX We exhibit different behaviour between normal mode and sync mode
2394 * when the pipe is stdin and not already at EOF. If we're a child, the
2395 * parent's stdin isn't closed, so if the user starts another capture,
2396 * cap_pipe_open_live() will very likely not see the expected magic bytes and
2397 * will say "Unrecognized libpcap format". On the other hand, in normal
2398 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
2401 /* get packet drop statistics from pcap */
2402 if(global_ld.pcap_h != NULL) {
2403 g_assert(!global_ld.from_cap_pipe);
2404 /* Get the capture statistics, so we know how many packets were
2406 if (pcap_stats(global_ld.pcap_h, stats) >= 0) {
2407 *stats_known = TRUE;
2408 /* Let the parent process know. */
2409 report_packet_drops(stats->ps_drop);
2411 g_snprintf(errmsg, sizeof(errmsg),
2412 "Can't get packet-drop statistics: %s",
2413 pcap_geterr(global_ld.pcap_h));
2414 report_capture_error(errmsg, please_report);
2418 /* close the input file (pcap or capture pipe) */
2419 capture_loop_close_input(&global_ld);
2421 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
2423 /* ok, if the write and the close were successful. */
2424 return write_ok && close_ok;
2427 if (capture_opts->multi_files_on) {
2428 /* cleanup ringbuffer */
2429 ringbuf_error_cleanup();
2431 /* We can't use the save file, and we have no FILE * for the stream
2432 to close in order to close it, so close the FD directly. */
2433 if(save_file_fd != -1) {
2434 ws_close(save_file_fd);
2437 /* We couldn't even start the capture, so get rid of the capture
2439 if(capture_opts->save_file != NULL) {
2440 ws_unlink(capture_opts->save_file);
2441 g_free(capture_opts->save_file);
2444 capture_opts->save_file = NULL;
2446 report_cfilter_error(capture_opts->cfilter, errmsg);
2448 report_capture_error(errmsg, secondary_errmsg);
2450 /* close the input file (pcap or cap_pipe) */
2451 capture_loop_close_input(&global_ld);
2453 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
2459 static void capture_loop_stop(void)
2461 #ifdef HAVE_PCAP_BREAKLOOP
2462 if(global_ld.pcap_h != NULL)
2463 pcap_breakloop(global_ld.pcap_h);
2465 global_ld.go = FALSE;
2470 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
2471 int err, gboolean is_close)
2476 g_snprintf(errmsg, errmsglen,
2477 "Not all the packets could be written to the file"
2478 " to which the capture was being saved\n"
2479 "(\"%s\") because there is no space left on the file system\n"
2480 "on which that file resides.",
2486 g_snprintf(errmsg, errmsglen,
2487 "Not all the packets could be written to the file"
2488 " to which the capture was being saved\n"
2489 "(\"%s\") because you are too close to, or over,"
2490 " your disk quota\n"
2491 "on the file system on which that file resides.",
2496 case WTAP_ERR_CANT_CLOSE:
2497 g_snprintf(errmsg, errmsglen,
2498 "The file to which the capture was being saved"
2499 " couldn't be closed for some unknown reason.");
2502 case WTAP_ERR_SHORT_WRITE:
2503 g_snprintf(errmsg, errmsglen,
2504 "Not all the packets could be written to the file"
2505 " to which the capture was being saved\n"
2512 g_snprintf(errmsg, errmsglen,
2513 "The file to which the capture was being saved\n"
2514 "(\"%s\") could not be closed: %s.",
2515 fname, wtap_strerror(err));
2517 g_snprintf(errmsg, errmsglen,
2518 "An error occurred while writing to the file"
2519 " to which the capture was being saved\n"
2521 fname, wtap_strerror(err));
2528 /* one packet was captured, process it */
2530 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
2533 loop_data *ld = (void *) user;
2536 /* We may be called multiple times from pcap_dispatch(); if we've set
2537 the "stop capturing" flag, ignore this packet, as we're not
2538 supposed to be saving any more packets. */
2543 gboolean successful;
2544 /* We're supposed to write the packet to a file; do so.
2545 If this fails, set "ld->go" to FALSE, to stop the capture, and set
2546 "ld->err" to the error. */
2547 if (global_capture_opts.use_pcapng) {
2548 successful = libpcap_write_enhanced_packet_block(ld->pdh, phdr, 0, pd, &ld->bytes_written, &err);
2550 successful = libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err);
2557 /* if the user told us to stop after x packets, do we already have enough? */
2558 if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
2567 /* And now our feature presentation... [ fade to music ] */
2569 main(int argc, char *argv[])
2572 extern char *optarg;
2573 gboolean arg_error = FALSE;
2578 struct sigaction action, oldaction;
2581 gboolean start_capture = TRUE;
2582 gboolean stats_known;
2583 struct pcap_stat stats;
2584 GLogLevelFlags log_flags;
2585 gboolean list_interfaces = FALSE;
2586 gboolean list_link_layer_types = FALSE;
2587 gboolean machine_readable = FALSE;
2588 gboolean print_statistics = FALSE;
2589 int status, run_once_args = 0;
2592 #ifdef HAVE_PCAP_REMOTE
2593 #define OPTSTRING_INIT "a:A:b:c:Df:hi:Lm:MnprSs:uvw:y:Z:"
2595 #define OPTSTRING_INIT "a:b:c:Df:hi:LMnpSs:vw:y:Z:"
2599 #define OPTSTRING_WIN32 "B:"
2601 #define OPTSTRING_WIN32 ""
2604 char optstring[sizeof(OPTSTRING_INIT) + sizeof(OPTSTRING_WIN32) - 1] =
2605 OPTSTRING_INIT OPTSTRING_WIN32;
2607 #ifdef DEBUG_CHILD_DUMPCAP
2608 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
2609 fprintf (stderr, "Unable to open debug log file !\n");
2614 /* Determine if dumpcap is being requested to run in a special */
2615 /* capture_child mode by going thru the command line args to see if */
2616 /* a -Z is present. (-Z is a hidden option). */
2617 /* The primary result of running in capture_child mode is that */
2618 /* all messages sent out on stderr are in a special type/len/string */
2619 /* format to allow message processing by type. */
2620 /* These messages include various 'status' messages which are sent */
2621 /* when an actual capture is in progress. Capture_child mode */
2622 /* would normally be requested by a parent process which invokes */
2623 /* dumpcap and obtains dumpcap stderr output via a pipe to which */
2624 /* dumpcap stderr has been redirected. */
2625 /* Capture_child mode needs to be determined immediately upon */
2626 /* startup so that any messages generated by dumpcap in this mode */
2627 /* (eg: during initialization) will be formatted properly. */
2629 for (i=1; i<argc; i++) {
2630 if (strcmp("-Z", argv[i]) == 0) {
2631 capture_child = TRUE;
2633 /* set output pipe to binary mode, to avoid ugly text conversions */
2634 _setmode(2, O_BINARY);
2639 /* The default_log_handler will use stdout, which makes trouble in */
2640 /* capture child mode, as it uses stdout for it's sync_pipe. */
2641 /* So: the filtering is done in the console_log_handler and not here.*/
2642 /* We set the log handlers right up front to make sure that any log */
2643 /* messages when running as child will be sent back to the parent */
2644 /* with the correct format. */
2648 G_LOG_LEVEL_CRITICAL|
2649 G_LOG_LEVEL_WARNING|
2650 G_LOG_LEVEL_MESSAGE|
2653 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
2655 g_log_set_handler(NULL,
2657 console_log_handler, NULL /* user_data */);
2658 g_log_set_handler(LOG_DOMAIN_MAIN,
2660 console_log_handler, NULL /* user_data */);
2661 g_log_set_handler(LOG_DOMAIN_CAPTURE,
2663 console_log_handler, NULL /* user_data */);
2664 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
2666 console_log_handler, NULL /* user_data */);
2669 /* Load wpcap if possible. Do this before collecting the run-time version information */
2672 /* ... and also load the packet.dll from wpcap */
2673 /* XXX - currently not required, may change later. */
2674 /*wpcap_packet_load();*/
2676 /* Start windows sockets */
2677 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
2679 /* Set handler for Ctrl+C key */
2680 SetConsoleCtrlHandler(capture_cleanup, TRUE);
2682 /* Prepare to read from a pipe */
2683 if (!g_thread_supported ())
2684 g_thread_init (NULL);
2685 cap_pipe_pending_q = g_async_queue_new();
2686 cap_pipe_done_q = g_async_queue_new();
2687 cap_pipe_read_mtx = g_mutex_new();
2690 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
2692 action.sa_handler = capture_cleanup;
2693 action.sa_flags = 0;
2694 sigemptyset(&action.sa_mask);
2695 sigaction(SIGTERM, &action, NULL);
2696 sigaction(SIGINT, &action, NULL);
2697 sigaction(SIGPIPE, &action, NULL);
2698 sigaction(SIGHUP, NULL, &oldaction);
2699 if (oldaction.sa_handler == SIG_DFL)
2700 sigaction(SIGHUP, &action, NULL);
2703 /* ----------------------------------------------------------------- */
2704 /* Privilege and capability handling */
2706 /* 1. Running not as root or suid root; no special capabilities. */
2709 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
2712 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
2714 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
2715 /* capabilities; Drop all other capabilities; */
2716 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2717 /* else: after pcap_open_live() in capture_loop_open_input() */
2718 /* drop all capabilities (NET_RAW and NET_ADMIN); */
2719 /* (Note: this means that the process, although logged in */
2720 /* as root, does not have various permissions such as the */
2721 /* ability to bypass file access permissions). */
2722 /* XXX: Should we just leave capabilities alone in this case */
2723 /* so that user gets expected effect that root can do */
2726 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
2728 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2729 /* else: after pcap_open_live() in capture_loop_open_input() */
2730 /* drop suid root (set euid=ruid).(ie: keep suid until after */
2731 /* pcap_open_live). */
2733 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
2735 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
2736 /* capabilities; Drop all other capabilities; */
2737 /* Drop suid privileges (euid=ruid); */
2738 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2739 /* else: after pcap_open_live() in capture_loop_open_input() */
2740 /* drop all capabilities (NET_RAW and NET_ADMIN). */
2742 /* XXX: For some Linux versions/distros with capabilities */
2743 /* a 'normal' process with any capabilities cannot be */
2744 /* 'killed' (signaled) from another (same uid) non-privileged */
2746 /* For example: If (non-suid) Wireshark forks a */
2747 /* child suid dumpcap which acts as described here (case 5), */
2748 /* Wireshark will be unable to kill (signal) the child */
2749 /* dumpcap process until the capabilities have been dropped */
2750 /* (after pcap_open_live()). */
2751 /* This behaviour will apparently be changed in the kernel */
2752 /* to allow the kill (signal) in this case. */
2753 /* See the following for details: */
2754 /* http://www.mail-archive.com/ [wrapped] */
2755 /* linux-security-module@vger.kernel.org/msg02913.html */
2757 /* It is therefore conceivable that if dumpcap somehow hangs */
2758 /* in pcap_open_live or before that wireshark will not */
2759 /* be able to stop dumpcap using a signal (USR1, TERM, etc). */
2760 /* In this case, exiting wireshark will kill the child */
2761 /* dumpcap process. */
2763 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
2764 /* capabilities; Using libcap. Note: capset cmd (which see) */
2765 /* used to assign capabilities to file. */
2767 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2768 /* else: after pcap_open_live() in capture_loop_open_input() */
2769 /* drop all capabilities (NET_RAW and NET_ADMIN) */
2771 /* ToDo: -S (stats) should drop privileges/capabilities when no */
2772 /* longer required (similar to capture). */
2774 /* ----------------------------------------------------------------- */
2776 get_credential_info();
2779 /* If 'started with special privileges' (and using libcap) */
2780 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
2781 /* Set euid/egid = ruid/rgid to remove suid privileges */
2782 relinquish_privs_except_capture();
2785 /* Set the initial values in the capture options. This might be overwritten
2786 by the command line parameters. */
2787 capture_opts_init(&global_capture_opts, NULL);
2789 /* Default to capturing the entire packet. */
2790 global_capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
2792 /* We always save to a file - if no file was specified, we save to a
2794 global_capture_opts.saving_to_file = TRUE;
2795 global_capture_opts.has_ring_num_files = TRUE;
2797 /* Now get our args */
2798 while ((opt = getopt(argc, argv, optstring)) != -1) {
2800 case 'h': /* Print help and exit */
2804 case 'v': /* Show version and exit */
2806 GString *comp_info_str;
2807 GString *runtime_info_str;
2808 /* Assemble the compile-time version information string */
2809 comp_info_str = g_string_new("Compiled ");
2810 get_compiled_version_info(comp_info_str, NULL);
2812 /* Assemble the run-time version information string */
2813 runtime_info_str = g_string_new("Running ");
2814 get_runtime_version_info(runtime_info_str, NULL);
2815 show_version(comp_info_str, runtime_info_str);
2816 g_string_free(comp_info_str, TRUE);
2817 g_string_free(runtime_info_str, TRUE);
2821 /*** capture option specific ***/
2822 case 'a': /* autostop criteria */
2823 case 'b': /* Ringbuffer option */
2824 case 'c': /* Capture x packets */
2825 case 'f': /* capture filter */
2826 case 'i': /* Use interface x */
2827 case 'n': /* Use pcapng format */
2828 case 'p': /* Don't capture in promiscuous mode */
2829 case 's': /* Set the snapshot (capture) length */
2830 case 'w': /* Write to capture file x */
2831 case 'y': /* Set the pcap data link type */
2832 #ifdef HAVE_PCAP_REMOTE
2833 case 'u': /* Use UDP for data transfer */
2834 case 'r': /* Capture own RPCAP traffic too */
2835 case 'A': /* Authentication */
2837 #ifdef HAVE_PCAP_SETSAMPLING
2838 case 'm': /* Sampling */
2841 case 'B': /* Buffer size */
2843 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
2848 /*** hidden option: Wireshark child mode (using binary output messages) ***/
2850 capture_child = TRUE;
2852 /* set output pipe to binary mode, to avoid ugly text conversions */
2853 _setmode(2, O_BINARY);
2855 * optarg = the control ID, aka the PPID, currently used for the
2858 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
2859 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
2860 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
2861 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
2863 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
2864 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2865 "Signal pipe: Unable to open %s. Dead parent?",
2873 /*** all non capture option specific ***/
2874 case 'D': /* Print a list of capture devices and exit */
2875 list_interfaces = TRUE;
2878 case 'L': /* Print list of link-layer types and exit */
2879 list_link_layer_types = TRUE;
2882 case 'S': /* Print interface statistics once a second */
2883 print_statistics = TRUE;
2886 case 'M': /* For -D and -L, print machine-readable output */
2887 machine_readable = TRUE;
2890 case '?': /* Bad flag - print usage message */
2891 cmdarg_err("Invalid Option: %s", argv[optind-1]);
2899 /* user specified file name as regular command-line argument */
2900 /* XXX - use it as the capture file name (or something else)? */
2907 * Extra command line arguments were specified; complain.
2908 * XXX - interpret as capture filter, as tcpdump and tshark do?
2910 cmdarg_err("Invalid argument: %s", argv[0]);
2919 if (run_once_args > 1) {
2920 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
2922 } else if (list_link_layer_types) {
2923 /* We're supposed to list the link-layer types for an interface;
2924 did the user also specify a capture file to be read? */
2925 /* No - did they specify a ring buffer option? */
2926 if (global_capture_opts.multi_files_on) {
2927 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
2931 /* No - was the ring buffer option specified and, if so, does it make
2933 if (global_capture_opts.multi_files_on) {
2934 /* Ring buffer works only under certain conditions:
2935 a) ring buffer does not work with temporary files;
2936 b) it makes no sense to enable the ring buffer if the maximum
2937 file size is set to "infinite". */
2938 if (global_capture_opts.save_file == NULL) {
2939 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
2940 global_capture_opts.multi_files_on = FALSE;
2942 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
2943 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
2944 /* XXX - this must be redesigned as the conditions changed */
2945 /* global_capture_opts.multi_files_on = FALSE;*/
2950 if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
2951 /* cmdarg_err() already called .... */
2955 /* Let the user know what interface was chosen. */
2956 /* get_interface_descriptive_name() is not available! */
2957 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", global_capture_opts.iface);
2959 if (list_interfaces) {
2960 status = capture_opts_list_interfaces(machine_readable);
2962 } else if (list_link_layer_types) {
2963 status = capture_opts_list_link_layer_types(&global_capture_opts, machine_readable);
2965 } else if (print_statistics) {
2966 status = print_statistics_loop(machine_readable);
2970 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
2971 capture_opts_trim_ring_num_files(&global_capture_opts);
2973 /* Now start the capture. */
2975 if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
2979 /* capture failed */
2986 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
2987 const char *message, gpointer user_data _U_)
2994 /* ignore log message, if log_level isn't interesting */
2995 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
2996 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
3001 /* create a "timestamp" */
3003 today = localtime(&curr);
3005 switch(log_level & G_LOG_LEVEL_MASK) {
3006 case G_LOG_LEVEL_ERROR:
3009 case G_LOG_LEVEL_CRITICAL:
3012 case G_LOG_LEVEL_WARNING:
3015 case G_LOG_LEVEL_MESSAGE:
3018 case G_LOG_LEVEL_INFO:
3021 case G_LOG_LEVEL_DEBUG:
3025 fprintf(stderr, "unknown log_level %u\n", log_level);
3027 g_assert_not_reached();
3030 /* Generate the output message */
3031 if(log_level & G_LOG_LEVEL_MESSAGE) {
3032 /* normal user messages without additional infos */
3033 msg = g_strdup_printf("%s\n", message);
3035 /* info/debug messages with additional infos */
3036 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
3037 today->tm_hour, today->tm_min, today->tm_sec,
3038 log_domain != NULL ? log_domain : "",
3042 /* DEBUG & INFO msgs (if we're debugging today) */
3043 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3044 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3045 #ifdef DEBUG_DUMPCAP
3046 fprintf(stderr, "%s", msg);
3049 #ifdef DEBUG_CHILD_DUMPCAP
3050 fprintf(debug_log, "%s", msg);
3058 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
3059 /* to parent especially formatted if dumpcap running as child. */
3060 if (capture_child) {
3061 sync_pipe_errmsg_to_parent(2, msg, "");
3063 fprintf(stderr, "%s", msg);
3070 /****************************************************************************************************************/
3071 /* indication report routines */
3075 report_packet_count(int packet_count)
3077 char tmp[SP_DECISIZE+1+1];
3078 static int count = 0;
3081 g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
3082 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
3083 pipe_write_block(2, SP_PACKET_COUNT, tmp);
3085 count += packet_count;
3086 fprintf(stderr, "\rPackets: %u ", count);
3087 /* stderr could be line buffered */
3093 report_new_capture_file(const char *filename)
3096 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
3097 pipe_write_block(2, SP_FILE, filename);
3099 fprintf(stderr, "File: %s\n", filename);
3100 /* stderr could be line buffered */
3106 report_cfilter_error(const char *cfilter, const char *errmsg)
3108 if (capture_child) {
3109 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
3110 pipe_write_block(2, SP_BAD_FILTER, errmsg);
3113 "Invalid capture filter: \"%s\"!\n"
3115 "That string isn't a valid capture filter (%s).\n"
3116 "See the User's Guide for a description of the capture filter syntax.\n",
3122 report_capture_error(const char *error_msg, const char *secondary_error_msg)
3125 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3126 "Primary Error: %s", error_msg);
3127 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3128 "Secondary Error: %s", secondary_error_msg);
3129 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
3131 fprintf(stderr, "%s\n%s\n", error_msg, secondary_error_msg);
3136 report_packet_drops(guint32 drops)
3138 char tmp[SP_DECISIZE+1+1];
3140 g_snprintf(tmp, sizeof(tmp), "%u", drops);
3143 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
3144 pipe_write_block(2, SP_DROPS, tmp);
3146 fprintf(stderr, "Packets dropped: %s\n", tmp);
3147 /* stderr could be line buffered */
3153 /****************************************************************************************************************/
3154 /* signal_pipe handling */
3159 signal_pipe_check_running(void)
3161 /* any news from our parent? -> just stop the capture */
3165 /* if we are running standalone, no check required */
3166 if(!capture_child) {
3170 if(!sig_pipe_name || !sig_pipe_handle) {
3171 /* This shouldn't happen */
3172 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3173 "Signal pipe: No name or handle");
3178 * XXX - We should have the process ID of the parent (from the "-Z" flag)
3179 * at this point. Should we check to see if the parent is still alive,
3180 * e.g. by using OpenProcess?
3183 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
3185 if(!result || avail > 0) {
3186 /* peek failed or some bytes really available */
3187 /* (if not piping from stdin this would fail) */
3188 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3189 "Signal pipe: Stop capture: %s", sig_pipe_name);
3190 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3191 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
3192 sig_pipe_handle, result, avail);
3195 /* pipe ok and no bytes available */
3202 * Editor modelines - http://www.wireshark.org/tools/modelines.html
3207 * indent-tabs-mode: nil
3210 * vi: set shiftwidth=4 tabstop=8 expandtab
3211 * :indentSize=4:tabSize=8:noTabs=true: