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 SIGINT 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 SIGINT 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 SIGINT 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_handler(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_handler(int signum _U_)
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 /* Note: don't call g_log() in the signal handler: if we happened to be in
549 * g_log() in process context when the signal came in, g_log will detect
550 * the "recursion" and abort.
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", (void *)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 #define TIME_GET() GetTickCount()
1987 #define TIME_GET() time(NULL)
1990 /* Do the low-level work of a capture.
1991 Returns TRUE if it succeeds, FALSE otherwise. */
1993 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
1995 time_t upd_time, cur_time;
1999 gint inpkts_to_sync_pipe = 0; /* packets not already send out to the sync_pipe */
2000 condition *cnd_file_duration = NULL;
2001 condition *cnd_autostop_files = NULL;
2002 condition *cnd_autostop_size = NULL;
2003 condition *cnd_autostop_duration = NULL;
2004 guint32 autostop_files = 0;
2007 gboolean cfilter_error = FALSE;
2008 #define MSG_MAX_LENGTH 4096
2009 char errmsg[MSG_MAX_LENGTH+1];
2010 char secondary_errmsg[MSG_MAX_LENGTH+1];
2011 int save_file_fd = -1;
2014 *secondary_errmsg = '\0';
2016 /* init the loop data */
2017 global_ld.go = TRUE;
2018 global_ld.packet_count = 0;
2019 if (capture_opts->has_autostop_packets)
2020 global_ld.packet_max = capture_opts->autostop_packets;
2022 global_ld.packet_max = 0; /* no limit */
2023 global_ld.err = 0; /* no error seen yet */
2024 global_ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
2025 global_ld.pcap_err = FALSE;
2026 global_ld.from_cap_pipe = FALSE;
2027 global_ld.pdh = NULL;
2029 global_ld.cap_pipe_fd = -1;
2031 global_ld.cap_pipe_h = INVALID_HANDLE_VALUE;
2033 #ifdef MUST_DO_SELECT
2034 global_ld.pcap_fd = 0;
2037 /* We haven't yet gotten the capture statistics. */
2038 *stats_known = FALSE;
2040 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
2041 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
2043 /* open the "input file" from network interface or capture pipe */
2044 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
2045 secondary_errmsg, sizeof(secondary_errmsg))) {
2049 /* init the input filter from the network interface (capture pipe will do nothing) */
2050 switch (capture_loop_init_filter(global_ld.pcap_h, global_ld.from_cap_pipe,
2051 capture_opts->iface,
2052 capture_opts->cfilter)) {
2054 case INITFILTER_NO_ERROR:
2057 case INITFILTER_BAD_FILTER:
2058 cfilter_error = TRUE;
2059 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(global_ld.pcap_h));
2062 case INITFILTER_OTHER_ERROR:
2063 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
2064 pcap_geterr(global_ld.pcap_h));
2065 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
2069 /* If we're supposed to write to a capture file, open it for output
2070 (temporary/specified name/ringbuffer) */
2071 if (capture_opts->saving_to_file) {
2072 if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
2076 /* set up to write to the already-opened capture output file/files */
2077 if (!capture_loop_init_output(capture_opts, save_file_fd, &global_ld,
2078 errmsg, sizeof(errmsg))) {
2082 /* XXX - capture SIGTERM and close the capture, in case we're on a
2083 Linux 2.0[.x] system and you have to explicitly close the capture
2084 stream in order to turn promiscuous mode off? We need to do that
2085 in other places as well - and I don't think that works all the
2086 time in any case, due to libpcap bugs. */
2088 /* Well, we should be able to start capturing.
2090 Sync out the capture file, so the header makes it to the file system,
2091 and send a "capture started successfully and capture file created"
2092 message to our parent so that they'll open the capture file and
2093 update its windows to indicate that we have a live capture in
2095 libpcap_dump_flush(global_ld.pdh, NULL);
2096 report_new_capture_file(capture_opts->save_file);
2099 /* initialize capture stop (and alike) conditions */
2100 init_capture_stop_conditions();
2101 /* create stop conditions */
2102 if (capture_opts->has_autostop_filesize)
2104 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
2105 if (capture_opts->has_autostop_duration)
2106 cnd_autostop_duration =
2107 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
2109 if (capture_opts->multi_files_on) {
2110 if (capture_opts->has_file_duration)
2112 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
2114 if (capture_opts->has_autostop_files)
2115 cnd_autostop_files =
2116 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
2119 /* init the time values */
2120 start_time = TIME_GET();
2121 upd_time = TIME_GET();
2123 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
2125 /* WOW, everything is prepared! */
2126 /* please fasten your seat belts, we will enter now the actual capture loop */
2127 while (global_ld.go) {
2128 /* dispatch incoming packets */
2129 inpkts = capture_loop_dispatch(capture_opts, &global_ld, errmsg,
2133 /* any news from our parent (signal pipe)? -> just stop the capture */
2134 if (!signal_pipe_check_running()) {
2135 global_ld.go = FALSE;
2140 inpkts_to_sync_pipe += inpkts;
2142 /* check capture size condition */
2143 if (cnd_autostop_size != NULL &&
2144 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)){
2145 /* Capture size limit reached, do we have another file? */
2146 if (capture_opts->multi_files_on) {
2147 if (cnd_autostop_files != NULL &&
2148 cnd_eval(cnd_autostop_files, ++autostop_files)) {
2149 /* no files left: stop here */
2150 global_ld.go = FALSE;
2154 /* Switch to the next ringbuffer file */
2155 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2156 &save_file_fd, &global_ld.err)) {
2157 gboolean successful;
2159 /* File switch succeeded: reset the conditions */
2160 global_ld.bytes_written = 0;
2161 if (capture_opts->use_pcapng) {
2164 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2165 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2166 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);
2168 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2169 &global_ld.bytes_written, &global_ld.err);
2172 fclose(global_ld.pdh);
2173 global_ld.pdh = NULL;
2174 global_ld.go = FALSE;
2177 cnd_reset(cnd_autostop_size);
2178 if (cnd_file_duration) {
2179 cnd_reset(cnd_file_duration);
2181 libpcap_dump_flush(global_ld.pdh, NULL);
2182 report_packet_count(inpkts_to_sync_pipe);
2183 inpkts_to_sync_pipe = 0;
2184 report_new_capture_file(capture_opts->save_file);
2186 /* File switch failed: stop here */
2187 global_ld.go = FALSE;
2191 /* single file, stop now */
2192 global_ld.go = FALSE;
2195 } /* cnd_autostop_size */
2196 if (capture_opts->output_to_pipe) {
2197 libpcap_dump_flush(global_ld.pdh, NULL);
2201 /* Only update once a second (Win32: 500ms) so as not to overload slow
2202 * displays. This also prevents too much context-switching between the
2203 * dumpcap and wireshark processes */
2204 cur_time = TIME_GET();
2206 if ( (cur_time - upd_time) > 500) {
2208 if (cur_time - upd_time > 0) {
2210 upd_time = cur_time;
2212 /*if (pcap_stats(pch, stats) >= 0) {
2213 *stats_known = TRUE;
2216 /* Let the parent process know. */
2217 if (inpkts_to_sync_pipe) {
2219 libpcap_dump_flush(global_ld.pdh, NULL);
2221 /* Send our parent a message saying we've written out "inpkts_to_sync_pipe"
2222 packets to the capture file. */
2223 report_packet_count(inpkts_to_sync_pipe);
2225 inpkts_to_sync_pipe = 0;
2228 /* check capture duration condition */
2229 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
2230 /* The maximum capture time has elapsed; stop the capture. */
2231 global_ld.go = FALSE;
2235 /* check capture file duration condition */
2236 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
2237 /* duration limit reached, do we have another file? */
2238 if (capture_opts->multi_files_on) {
2239 if (cnd_autostop_files != NULL &&
2240 cnd_eval(cnd_autostop_files, ++autostop_files)) {
2241 /* no files left: stop here */
2242 global_ld.go = FALSE;
2246 /* Switch to the next ringbuffer file */
2247 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2248 &save_file_fd, &global_ld.err)) {
2249 gboolean successful;
2251 /* file switch succeeded: reset the conditions */
2252 global_ld.bytes_written = 0;
2253 if (capture_opts->use_pcapng) {
2256 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2257 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2258 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);
2260 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2261 &global_ld.bytes_written, &global_ld.err);
2264 fclose(global_ld.pdh);
2265 global_ld.pdh = NULL;
2266 global_ld.go = FALSE;
2269 cnd_reset(cnd_file_duration);
2270 if(cnd_autostop_size)
2271 cnd_reset(cnd_autostop_size);
2272 libpcap_dump_flush(global_ld.pdh, NULL);
2273 report_packet_count(inpkts_to_sync_pipe);
2274 inpkts_to_sync_pipe = 0;
2275 report_new_capture_file(capture_opts->save_file);
2277 /* File switch failed: stop here */
2278 global_ld.go = FALSE;
2282 /* single file, stop now */
2283 global_ld.go = FALSE;
2286 } /* cnd_file_duration */
2289 } /* while (global_ld.go) */
2291 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
2293 /* delete stop conditions */
2294 if (cnd_file_duration != NULL)
2295 cnd_delete(cnd_file_duration);
2296 if (cnd_autostop_files != NULL)
2297 cnd_delete(cnd_autostop_files);
2298 if (cnd_autostop_size != NULL)
2299 cnd_delete(cnd_autostop_size);
2300 if (cnd_autostop_duration != NULL)
2301 cnd_delete(cnd_autostop_duration);
2303 /* did we had a pcap (input) error? */
2304 if (global_ld.pcap_err) {
2305 /* On Linux, if an interface goes down while you're capturing on it,
2306 you'll get a "recvfrom: Network is down" error (ENETDOWN).
2307 (At least you will if strerror() doesn't show a local translation
2310 On FreeBSD and OS X, if a network adapter disappears while
2311 you're capturing on it, you'll get a "read: Device not configured"
2312 error (ENXIO). (See previous parenthetical note.)
2314 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
2316 These should *not* be reported to the Wireshark developers. */
2319 cap_err_str = pcap_geterr(global_ld.pcap_h);
2320 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
2321 strcmp(cap_err_str, "read: Device not configured") == 0 ||
2322 strcmp(cap_err_str, "read: I/O error") == 0) {
2323 report_capture_error("The network adapter on which the capture was being done "
2324 "is no longer running; the capture has stopped.",
2327 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
2329 report_capture_error(errmsg, please_report);
2332 else if (global_ld.from_cap_pipe && global_ld.cap_pipe_err == PIPERR)
2333 report_capture_error(errmsg, "");
2335 /* did we had an error while capturing? */
2336 if (global_ld.err == 0) {
2339 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
2340 global_ld.err, FALSE);
2341 report_capture_error(errmsg, please_report);
2345 if (capture_opts->saving_to_file) {
2346 /* close the wiretap (output) file */
2347 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
2351 /* there might be packets not yet notified to the parent */
2352 /* (do this after closing the file, so all packets are already flushed) */
2353 if(inpkts_to_sync_pipe) {
2354 report_packet_count(inpkts_to_sync_pipe);
2355 inpkts_to_sync_pipe = 0;
2358 /* If we've displayed a message about a write error, there's no point
2359 in displaying another message about an error on close. */
2360 if (!close_ok && write_ok) {
2361 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
2363 report_capture_error(errmsg, "");
2367 * XXX We exhibit different behaviour between normal mode and sync mode
2368 * when the pipe is stdin and not already at EOF. If we're a child, the
2369 * parent's stdin isn't closed, so if the user starts another capture,
2370 * cap_pipe_open_live() will very likely not see the expected magic bytes and
2371 * will say "Unrecognized libpcap format". On the other hand, in normal
2372 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
2375 /* get packet drop statistics from pcap */
2376 if(global_ld.pcap_h != NULL) {
2377 g_assert(!global_ld.from_cap_pipe);
2378 /* Get the capture statistics, so we know how many packets were
2380 if (pcap_stats(global_ld.pcap_h, stats) >= 0) {
2381 *stats_known = TRUE;
2382 /* Let the parent process know. */
2383 report_packet_drops(stats->ps_drop);
2385 g_snprintf(errmsg, sizeof(errmsg),
2386 "Can't get packet-drop statistics: %s",
2387 pcap_geterr(global_ld.pcap_h));
2388 report_capture_error(errmsg, please_report);
2392 /* close the input file (pcap or capture pipe) */
2393 capture_loop_close_input(&global_ld);
2395 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
2397 /* ok, if the write and the close were successful. */
2398 return write_ok && close_ok;
2401 if (capture_opts->multi_files_on) {
2402 /* cleanup ringbuffer */
2403 ringbuf_error_cleanup();
2405 /* We can't use the save file, and we have no FILE * for the stream
2406 to close in order to close it, so close the FD directly. */
2407 if(save_file_fd != -1) {
2408 ws_close(save_file_fd);
2411 /* We couldn't even start the capture, so get rid of the capture
2413 if(capture_opts->save_file != NULL) {
2414 ws_unlink(capture_opts->save_file);
2415 g_free(capture_opts->save_file);
2418 capture_opts->save_file = NULL;
2420 report_cfilter_error(capture_opts->cfilter, errmsg);
2422 report_capture_error(errmsg, secondary_errmsg);
2424 /* close the input file (pcap or cap_pipe) */
2425 capture_loop_close_input(&global_ld);
2427 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
2433 static void capture_loop_stop(void)
2435 #ifdef HAVE_PCAP_BREAKLOOP
2436 if(global_ld.pcap_h != NULL)
2437 pcap_breakloop(global_ld.pcap_h);
2439 global_ld.go = FALSE;
2444 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
2445 int err, gboolean is_close)
2450 g_snprintf(errmsg, errmsglen,
2451 "Not all the packets could be written to the file"
2452 " to which the capture was being saved\n"
2453 "(\"%s\") because there is no space left on the file system\n"
2454 "on which that file resides.",
2460 g_snprintf(errmsg, errmsglen,
2461 "Not all the packets could be written to the file"
2462 " to which the capture was being saved\n"
2463 "(\"%s\") because you are too close to, or over,"
2464 " your disk quota\n"
2465 "on the file system on which that file resides.",
2470 case WTAP_ERR_CANT_CLOSE:
2471 g_snprintf(errmsg, errmsglen,
2472 "The file to which the capture was being saved"
2473 " couldn't be closed for some unknown reason.");
2476 case WTAP_ERR_SHORT_WRITE:
2477 g_snprintf(errmsg, errmsglen,
2478 "Not all the packets could be written to the file"
2479 " to which the capture was being saved\n"
2486 g_snprintf(errmsg, errmsglen,
2487 "The file to which the capture was being saved\n"
2488 "(\"%s\") could not be closed: %s.",
2489 fname, wtap_strerror(err));
2491 g_snprintf(errmsg, errmsglen,
2492 "An error occurred while writing to the file"
2493 " to which the capture was being saved\n"
2495 fname, wtap_strerror(err));
2502 /* one packet was captured, process it */
2504 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
2507 loop_data *ld = (void *) user;
2510 /* We may be called multiple times from pcap_dispatch(); if we've set
2511 the "stop capturing" flag, ignore this packet, as we're not
2512 supposed to be saving any more packets. */
2517 gboolean successful;
2518 /* We're supposed to write the packet to a file; do so.
2519 If this fails, set "ld->go" to FALSE, to stop the capture, and set
2520 "ld->err" to the error. */
2521 if (global_capture_opts.use_pcapng) {
2522 successful = libpcap_write_enhanced_packet_block(ld->pdh, phdr, 0, pd, &ld->bytes_written, &err);
2524 successful = libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err);
2531 /* if the user told us to stop after x packets, do we already have enough? */
2532 if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
2541 /* And now our feature presentation... [ fade to music ] */
2543 main(int argc, char *argv[])
2546 extern char *optarg;
2547 gboolean arg_error = FALSE;
2552 struct sigaction action, oldaction;
2555 gboolean start_capture = TRUE;
2556 gboolean stats_known;
2557 struct pcap_stat stats;
2558 GLogLevelFlags log_flags;
2559 gboolean list_interfaces = FALSE;
2560 gboolean list_link_layer_types = FALSE;
2561 gboolean machine_readable = FALSE;
2562 gboolean print_statistics = FALSE;
2563 int status, run_once_args = 0;
2566 #ifdef HAVE_PCAP_REMOTE
2567 #define OPTSTRING_INIT "a:A:b:c:Df:hi:Lm:MnprSs:uvw:y:Z:"
2569 #define OPTSTRING_INIT "a:b:c:Df:hi:LMnpSs:vw:y:Z:"
2573 #define OPTSTRING_WIN32 "B:"
2575 #define OPTSTRING_WIN32 ""
2578 char optstring[sizeof(OPTSTRING_INIT) + sizeof(OPTSTRING_WIN32) - 1] =
2579 OPTSTRING_INIT OPTSTRING_WIN32;
2581 #ifdef DEBUG_CHILD_DUMPCAP
2582 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
2583 fprintf (stderr, "Unable to open debug log file !\n");
2588 /* Determine if dumpcap is being requested to run in a special */
2589 /* capture_child mode by going thru the command line args to see if */
2590 /* a -Z is present. (-Z is a hidden option). */
2591 /* The primary result of running in capture_child mode is that */
2592 /* all messages sent out on stderr are in a special type/len/string */
2593 /* format to allow message processing by type. */
2594 /* These messages include various 'status' messages which are sent */
2595 /* when an actual capture is in progress. Capture_child mode */
2596 /* would normally be requested by a parent process which invokes */
2597 /* dumpcap and obtains dumpcap stderr output via a pipe to which */
2598 /* dumpcap stderr has been redirected. */
2599 /* Capture_child mode needs to be determined immediately upon */
2600 /* startup so that any messages generated by dumpcap in this mode */
2601 /* (eg: during initialization) will be formatted properly. */
2603 for (i=1; i<argc; i++) {
2604 if (strcmp("-Z", argv[i]) == 0) {
2605 capture_child = TRUE;
2607 /* set output pipe to binary mode, to avoid ugly text conversions */
2608 _setmode(2, O_BINARY);
2613 /* The default_log_handler will use stdout, which makes trouble in */
2614 /* capture child mode, as it uses stdout for it's sync_pipe. */
2615 /* So: the filtering is done in the console_log_handler and not here.*/
2616 /* We set the log handlers right up front to make sure that any log */
2617 /* messages when running as child will be sent back to the parent */
2618 /* with the correct format. */
2622 G_LOG_LEVEL_CRITICAL|
2623 G_LOG_LEVEL_WARNING|
2624 G_LOG_LEVEL_MESSAGE|
2627 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
2629 g_log_set_handler(NULL,
2631 console_log_handler, NULL /* user_data */);
2632 g_log_set_handler(LOG_DOMAIN_MAIN,
2634 console_log_handler, NULL /* user_data */);
2635 g_log_set_handler(LOG_DOMAIN_CAPTURE,
2637 console_log_handler, NULL /* user_data */);
2638 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
2640 console_log_handler, NULL /* user_data */);
2643 /* Load wpcap if possible. Do this before collecting the run-time version information */
2646 /* ... and also load the packet.dll from wpcap */
2647 /* XXX - currently not required, may change later. */
2648 /*wpcap_packet_load();*/
2650 /* Start windows sockets */
2651 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
2653 /* Set handler for Ctrl+C key */
2654 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
2656 /* Prepare to read from a pipe */
2657 if (!g_thread_supported ())
2658 g_thread_init (NULL);
2659 cap_pipe_pending_q = g_async_queue_new();
2660 cap_pipe_done_q = g_async_queue_new();
2661 cap_pipe_read_mtx = g_mutex_new();
2664 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
2666 action.sa_handler = capture_cleanup_handler;
2668 * Arrange that system calls not get restarted, because when
2669 * our signal handler returns we don't want to restart
2670 * a call that was waiting for packets to arrive.
2672 action.sa_flags = 0;
2673 sigemptyset(&action.sa_mask);
2674 sigaction(SIGTERM, &action, NULL);
2675 sigaction(SIGINT, &action, NULL);
2676 sigaction(SIGPIPE, &action, NULL);
2677 sigaction(SIGHUP, NULL, &oldaction);
2678 if (oldaction.sa_handler == SIG_DFL)
2679 sigaction(SIGHUP, &action, NULL);
2682 /* ----------------------------------------------------------------- */
2683 /* Privilege and capability handling */
2685 /* 1. Running not as root or suid root; no special capabilities. */
2688 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
2691 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
2693 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
2694 /* capabilities; Drop all other capabilities; */
2695 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2696 /* else: after pcap_open_live() in capture_loop_open_input() */
2697 /* drop all capabilities (NET_RAW and NET_ADMIN); */
2698 /* (Note: this means that the process, although logged in */
2699 /* as root, does not have various permissions such as the */
2700 /* ability to bypass file access permissions). */
2701 /* XXX: Should we just leave capabilities alone in this case */
2702 /* so that user gets expected effect that root can do */
2705 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
2707 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2708 /* else: after pcap_open_live() in capture_loop_open_input() */
2709 /* drop suid root (set euid=ruid).(ie: keep suid until after */
2710 /* pcap_open_live). */
2712 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
2714 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
2715 /* capabilities; Drop all other capabilities; */
2716 /* Drop suid privileges (euid=ruid); */
2717 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2718 /* else: after pcap_open_live() in capture_loop_open_input() */
2719 /* drop all capabilities (NET_RAW and NET_ADMIN). */
2721 /* XXX: For some Linux versions/distros with capabilities */
2722 /* a 'normal' process with any capabilities cannot be */
2723 /* 'killed' (signaled) from another (same uid) non-privileged */
2725 /* For example: If (non-suid) Wireshark forks a */
2726 /* child suid dumpcap which acts as described here (case 5), */
2727 /* Wireshark will be unable to kill (signal) the child */
2728 /* dumpcap process until the capabilities have been dropped */
2729 /* (after pcap_open_live()). */
2730 /* This behaviour will apparently be changed in the kernel */
2731 /* to allow the kill (signal) in this case. */
2732 /* See the following for details: */
2733 /* http://www.mail-archive.com/ [wrapped] */
2734 /* linux-security-module@vger.kernel.org/msg02913.html */
2736 /* It is therefore conceivable that if dumpcap somehow hangs */
2737 /* in pcap_open_live or before that wireshark will not */
2738 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
2739 /* In this case, exiting wireshark will kill the child */
2740 /* dumpcap process. */
2742 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
2743 /* capabilities; Using libcap. Note: capset cmd (which see) */
2744 /* used to assign capabilities to file. */
2746 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2747 /* else: after pcap_open_live() in capture_loop_open_input() */
2748 /* drop all capabilities (NET_RAW and NET_ADMIN) */
2750 /* ToDo: -S (stats) should drop privileges/capabilities when no */
2751 /* longer required (similar to capture). */
2753 /* ----------------------------------------------------------------- */
2755 get_credential_info();
2758 /* If 'started with special privileges' (and using libcap) */
2759 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
2760 /* Set euid/egid = ruid/rgid to remove suid privileges */
2761 relinquish_privs_except_capture();
2764 /* Set the initial values in the capture options. This might be overwritten
2765 by the command line parameters. */
2766 capture_opts_init(&global_capture_opts, NULL);
2768 /* Default to capturing the entire packet. */
2769 global_capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
2771 /* We always save to a file - if no file was specified, we save to a
2773 global_capture_opts.saving_to_file = TRUE;
2774 global_capture_opts.has_ring_num_files = TRUE;
2776 /* Now get our args */
2777 while ((opt = getopt(argc, argv, optstring)) != -1) {
2779 case 'h': /* Print help and exit */
2783 case 'v': /* Show version and exit */
2785 GString *comp_info_str;
2786 GString *runtime_info_str;
2787 /* Assemble the compile-time version information string */
2788 comp_info_str = g_string_new("Compiled ");
2789 get_compiled_version_info(comp_info_str, NULL);
2791 /* Assemble the run-time version information string */
2792 runtime_info_str = g_string_new("Running ");
2793 get_runtime_version_info(runtime_info_str, NULL);
2794 show_version(comp_info_str, runtime_info_str);
2795 g_string_free(comp_info_str, TRUE);
2796 g_string_free(runtime_info_str, TRUE);
2800 /*** capture option specific ***/
2801 case 'a': /* autostop criteria */
2802 case 'b': /* Ringbuffer option */
2803 case 'c': /* Capture x packets */
2804 case 'f': /* capture filter */
2805 case 'i': /* Use interface x */
2806 case 'n': /* Use pcapng format */
2807 case 'p': /* Don't capture in promiscuous mode */
2808 case 's': /* Set the snapshot (capture) length */
2809 case 'w': /* Write to capture file x */
2810 case 'y': /* Set the pcap data link type */
2811 #ifdef HAVE_PCAP_REMOTE
2812 case 'u': /* Use UDP for data transfer */
2813 case 'r': /* Capture own RPCAP traffic too */
2814 case 'A': /* Authentication */
2816 #ifdef HAVE_PCAP_SETSAMPLING
2817 case 'm': /* Sampling */
2820 case 'B': /* Buffer size */
2822 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
2827 /*** hidden option: Wireshark child mode (using binary output messages) ***/
2829 capture_child = TRUE;
2831 /* set output pipe to binary mode, to avoid ugly text conversions */
2832 _setmode(2, O_BINARY);
2834 * optarg = the control ID, aka the PPID, currently used for the
2837 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
2838 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
2839 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
2840 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
2842 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
2843 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2844 "Signal pipe: Unable to open %s. Dead parent?",
2852 /*** all non capture option specific ***/
2853 case 'D': /* Print a list of capture devices and exit */
2854 list_interfaces = TRUE;
2857 case 'L': /* Print list of link-layer types and exit */
2858 list_link_layer_types = TRUE;
2861 case 'S': /* Print interface statistics once a second */
2862 print_statistics = TRUE;
2865 case 'M': /* For -D and -L, print machine-readable output */
2866 machine_readable = TRUE;
2869 case '?': /* Bad flag - print usage message */
2870 cmdarg_err("Invalid Option: %s", argv[optind-1]);
2878 /* user specified file name as regular command-line argument */
2879 /* XXX - use it as the capture file name (or something else)? */
2886 * Extra command line arguments were specified; complain.
2887 * XXX - interpret as capture filter, as tcpdump and tshark do?
2889 cmdarg_err("Invalid argument: %s", argv[0]);
2898 if (run_once_args > 1) {
2899 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
2901 } else if (list_link_layer_types) {
2902 /* We're supposed to list the link-layer types for an interface;
2903 did the user also specify a capture file to be read? */
2904 /* No - did they specify a ring buffer option? */
2905 if (global_capture_opts.multi_files_on) {
2906 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
2910 /* No - was the ring buffer option specified and, if so, does it make
2912 if (global_capture_opts.multi_files_on) {
2913 /* Ring buffer works only under certain conditions:
2914 a) ring buffer does not work with temporary files;
2915 b) it makes no sense to enable the ring buffer if the maximum
2916 file size is set to "infinite". */
2917 if (global_capture_opts.save_file == NULL) {
2918 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
2919 global_capture_opts.multi_files_on = FALSE;
2921 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
2922 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
2923 /* XXX - this must be redesigned as the conditions changed */
2924 /* global_capture_opts.multi_files_on = FALSE;*/
2929 if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
2930 /* cmdarg_err() already called .... */
2934 /* Let the user know what interface was chosen. */
2935 /* get_interface_descriptive_name() is not available! */
2936 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", global_capture_opts.iface);
2938 if (list_interfaces) {
2939 status = capture_opts_list_interfaces(machine_readable);
2941 } else if (list_link_layer_types) {
2942 status = capture_opts_list_link_layer_types(&global_capture_opts, machine_readable);
2944 } else if (print_statistics) {
2945 status = print_statistics_loop(machine_readable);
2949 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
2950 capture_opts_trim_ring_num_files(&global_capture_opts);
2952 /* Now start the capture. */
2954 if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
2958 /* capture failed */
2965 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
2966 const char *message, gpointer user_data _U_)
2973 /* ignore log message, if log_level isn't interesting */
2974 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
2975 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
2980 /* create a "timestamp" */
2982 today = localtime(&curr);
2984 switch(log_level & G_LOG_LEVEL_MASK) {
2985 case G_LOG_LEVEL_ERROR:
2988 case G_LOG_LEVEL_CRITICAL:
2991 case G_LOG_LEVEL_WARNING:
2994 case G_LOG_LEVEL_MESSAGE:
2997 case G_LOG_LEVEL_INFO:
3000 case G_LOG_LEVEL_DEBUG:
3004 fprintf(stderr, "unknown log_level %u\n", log_level);
3006 g_assert_not_reached();
3009 /* Generate the output message */
3010 if(log_level & G_LOG_LEVEL_MESSAGE) {
3011 /* normal user messages without additional infos */
3012 msg = g_strdup_printf("%s\n", message);
3014 /* info/debug messages with additional infos */
3015 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
3016 today->tm_hour, today->tm_min, today->tm_sec,
3017 log_domain != NULL ? log_domain : "",
3021 /* DEBUG & INFO msgs (if we're debugging today) */
3022 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3023 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3024 #ifdef DEBUG_DUMPCAP
3025 fprintf(stderr, "%s", msg);
3028 #ifdef DEBUG_CHILD_DUMPCAP
3029 fprintf(debug_log, "%s", msg);
3037 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
3038 /* to parent especially formatted if dumpcap running as child. */
3039 if (capture_child) {
3040 sync_pipe_errmsg_to_parent(2, msg, "");
3042 fprintf(stderr, "%s", msg);
3049 /****************************************************************************************************************/
3050 /* indication report routines */
3054 report_packet_count(int packet_count)
3056 char tmp[SP_DECISIZE+1+1];
3057 static int count = 0;
3060 g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
3061 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
3062 pipe_write_block(2, SP_PACKET_COUNT, tmp);
3064 count += packet_count;
3065 fprintf(stderr, "\rPackets: %u ", count);
3066 /* stderr could be line buffered */
3072 report_new_capture_file(const char *filename)
3075 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
3076 pipe_write_block(2, SP_FILE, filename);
3078 fprintf(stderr, "File: %s\n", filename);
3079 /* stderr could be line buffered */
3085 report_cfilter_error(const char *cfilter, const char *errmsg)
3087 if (capture_child) {
3088 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
3089 pipe_write_block(2, SP_BAD_FILTER, errmsg);
3092 "Invalid capture filter: \"%s\"!\n"
3094 "That string isn't a valid capture filter (%s).\n"
3095 "See the User's Guide for a description of the capture filter syntax.\n",
3101 report_capture_error(const char *error_msg, const char *secondary_error_msg)
3104 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3105 "Primary Error: %s", error_msg);
3106 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3107 "Secondary Error: %s", secondary_error_msg);
3108 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
3110 fprintf(stderr, "%s\n%s\n", error_msg, secondary_error_msg);
3115 report_packet_drops(guint32 drops)
3117 char tmp[SP_DECISIZE+1+1];
3119 g_snprintf(tmp, sizeof(tmp), "%u", drops);
3122 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
3123 pipe_write_block(2, SP_DROPS, tmp);
3125 fprintf(stderr, "Packets dropped: %s\n", tmp);
3126 /* stderr could be line buffered */
3132 /****************************************************************************************************************/
3133 /* signal_pipe handling */
3138 signal_pipe_check_running(void)
3140 /* any news from our parent? -> just stop the capture */
3144 /* if we are running standalone, no check required */
3145 if(!capture_child) {
3149 if(!sig_pipe_name || !sig_pipe_handle) {
3150 /* This shouldn't happen */
3151 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3152 "Signal pipe: No name or handle");
3157 * XXX - We should have the process ID of the parent (from the "-Z" flag)
3158 * at this point. Should we check to see if the parent is still alive,
3159 * e.g. by using OpenProcess?
3162 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
3164 if(!result || avail > 0) {
3165 /* peek failed or some bytes really available */
3166 /* (if not piping from stdin this would fail) */
3167 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3168 "Signal pipe: Stop capture: %s", sig_pipe_name);
3169 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3170 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
3171 sig_pipe_handle, result, avail);
3174 /* pipe ok and no bytes available */
3181 * Editor modelines - http://www.wireshark.org/tools/modelines.html
3186 * indent-tabs-mode: nil
3189 * vi: set shiftwidth=4 tabstop=8 expandtab
3190 * :indentSize=4:tabSize=8:noTabs=true: