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>
51 #if defined(__APPLE__) && defined(__LP64__)
52 #include <sys/utsname.h>
69 # include <sys/prctl.h>
70 # include <sys/capability.h>
73 #include "ringbuffer.h"
74 #include "clopts_common.h"
75 #include "cmdarg_err.h"
76 #include "version_info.h"
81 #include "capture-pcap-util.h"
84 #include "capture-wpcap.h"
85 #include <wsutil/unicode-utils.h>
88 #include <wsutil/privileges.h>
90 #include "sync_pipe.h"
92 #include "capture_opts.h"
93 #include "capture_sync.h"
95 #include "conditions.h"
96 #include "capture_stop_conditions.h"
100 #include "wsutil/file_util.h"
103 * Get information about libpcap format from "wiretap/libpcap.h".
104 * XXX - can we just use pcap_open_offline() to read the pipe?
106 #include "wiretap/libpcap.h"
108 /**#define DEBUG_DUMPCAP**/
109 /**#define DEBUG_CHILD_DUMPCAP**/
111 #ifdef DEBUG_CHILD_DUMPCAP
112 FILE *debug_log; /* for logging debug messages to */
113 /* a file if DEBUG_CHILD_DUMPCAP */
121 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
123 static gchar *sig_pipe_name = NULL;
124 static HANDLE sig_pipe_handle = NULL;
125 static gboolean signal_pipe_check_running(void);
129 static GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
130 static GMutex *cap_pipe_read_mtx;
133 /** Stop a low-level capture (stops the capture child). */
134 static void capture_loop_stop(void);
136 #if !defined (__linux__)
137 #ifndef HAVE_PCAP_BREAKLOOP
139 * We don't have pcap_breakloop(), which is the only way to ensure that
140 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
141 * won't, if the call to read the next packet or batch of packets is
142 * is interrupted by a signal on UN*X, just go back and try again to
145 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
146 * the signal handler, set a flag to stop capturing; however, without
147 * a guarantee of that sort, we can't guarantee that we'll stop capturing
148 * if the read will be retried and won't time out if no packets arrive.
150 * Therefore, on at least some platforms, we work around the lack of
151 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
152 * to wait for packets to arrive, so that we're probably going to be
153 * blocked in the select() when the signal arrives, and can just bail
154 * out of the loop at that point.
156 * However, we don't want to that on BSD (because "select()" doesn't work
157 * correctly on BPF devices on at least some releases of some flavors of
158 * BSD), and we don't want to do it on Windows (because "select()" is
159 * something for sockets, not for arbitrary handles). (Note that "Windows"
160 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
161 * using WinPcap, not a UNIX libpcap.)
163 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
164 * on BSD times out even if no packets have arrived, so we'll eventually
165 * exit pcap_dispatch() with an indication that no packets have arrived,
166 * and will break out of the capture loop at that point.
168 * On Windows, we can't send a SIGINT to stop capturing, so none of this
169 * applies in any case.
171 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
172 * want to include it if it's not present on this platform, however.
174 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
175 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
177 # define MUST_DO_SELECT
178 # endif /* avoid select */
179 #endif /* HAVE_PCAP_BREAKLOOP */
181 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
182 * in pcap_dispatch(); on the other hand, select() works just fine there.
183 * Hence we use a select for that come what may.
185 #define MUST_DO_SELECT
188 /** init the capture filter */
191 INITFILTER_BAD_FILTER,
192 INITFILTER_OTHER_ERROR
193 } initfilter_status_t;
195 typedef struct _loop_data {
197 gboolean go; /* TRUE as long as we're supposed to keep capturing */
198 int err; /* if non-zero, error seen while capturing */
199 gint packet_count; /* Number of packets we have already captured */
200 gint packet_max; /* Number of packets we're supposed to capture - 0 means infinite */
202 /* pcap "input file" */
203 pcap_t *pcap_h; /* pcap handle */
204 gboolean pcap_err; /* TRUE if error from pcap */
205 #ifdef MUST_DO_SELECT
206 int pcap_fd; /* pcap file descriptor */
209 /* capture pipe (unix only "input file") */
210 gboolean from_cap_pipe; /* TRUE if we are capturing data from a capture pipe */
211 struct pcap_hdr cap_pipe_hdr; /* Pcap header when capturing from a pipe */
212 struct pcaprec_modified_hdr cap_pipe_rechdr; /* Pcap record header when capturing from a pipe */
214 HANDLE cap_pipe_h; /* The handle of the capture pipe */
216 int cap_pipe_fd; /* the file descriptor of the capture pipe */
218 gboolean cap_pipe_modified; /* TRUE if data in the pipe uses modified pcap headers */
219 gboolean cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
221 char * cap_pipe_buf; /* Pointer to the data buffer we read into */
222 #endif /* USE_THREADS */
223 int cap_pipe_bytes_to_read;/* Used by cap_pipe_dispatch */
224 int cap_pipe_bytes_read; /* Used by cap_pipe_dispatch */
226 STATE_EXPECT_REC_HDR,
231 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
243 * Standard secondary message for unexpected errors.
245 static const char please_report[] =
246 "Please report this to the Wireshark developers.\n"
247 "(This is not a crash; please do not report it as such.)";
250 * This needs to be static, so that the SIGINT handler can clear the "go"
253 static loop_data global_ld;
257 * Timeout, in milliseconds, for reads from the stream of captured packets.
259 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
260 * 64-bit applications, with sub-second timeouts not to work. The bug is
263 #if defined(__APPLE__) && defined(__LP64__)
264 static int need_timeout_workaround;
266 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
268 #define CAP_READ_TIMEOUT 250
272 * Timeout, in microseconds, for threaded reads from a pipe.
274 #define THREAD_READ_TIMEOUT 100
275 #define THREAD_OPEN_TIMEOUT (5 * 1000000)
276 static char *cap_pipe_err_str;
279 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
280 const char *message, gpointer user_data _U_);
282 /* capture related options */
283 static capture_options global_capture_opts;
285 static void capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
287 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
288 int err, gboolean is_close);
290 static void exit_main(int err) G_GNUC_NORETURN;
292 static void report_new_capture_file(const char *filename);
293 static void report_packet_count(int packet_count);
294 static void report_packet_drops(guint32 drops);
295 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
296 static void report_cfilter_error(const char *cfilter, const char *errmsg);
299 print_usage(gboolean print_ver) {
307 "Dumpcap " VERSION "%s\n"
308 "Capture network packets and dump them into a libpcap file.\n"
309 "See http://www.wireshark.org for more information.\n",
310 wireshark_svnversion);
314 fprintf(output, "\nUsage: dumpcap [options] ...\n");
315 fprintf(output, "\n");
316 fprintf(output, "Capture interface:\n");
317 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
318 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
319 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
320 fprintf(output, " -p don't capture in promiscuous mode\n");
322 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
324 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
325 fprintf(output, " -D print list of interfaces and exit\n");
326 fprintf(output, " -L print list of link-layer types of iface and exit\n");
327 fprintf(output, " -S print statistics for each interface once every second\n");
328 fprintf(output, " -M for -D, -L, and -S produce machine-readable output\n");
329 fprintf(output, "\n");
330 #ifdef HAVE_PCAP_REMOTE
331 fprintf(output, "\nRPCAP options:\n");
332 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
333 fprintf(output, " -u use UDP for RPCAP data transfer\n");
334 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
335 #ifdef HAVE_PCAP_SETSAMPLING
336 fprintf(output, " -m <sampling type> use packet sampling\n");
337 fprintf(output, " count:NUM - capture one packet of every NUM\n");
338 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
341 fprintf(output, "Stop conditions:\n");
342 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
343 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
344 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
345 fprintf(output, " files:NUM - stop after NUM files\n");
346 /*fprintf(output, "\n");*/
347 fprintf(output, "Output (files):\n");
348 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
349 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
350 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
351 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
352 fprintf(output, " -n use pcapng format instead of pcap\n");
353 /*fprintf(output, "\n");*/
354 fprintf(output, "Miscellaneous:\n");
355 fprintf(output, " -v print version information and exit\n");
356 fprintf(output, " -h display this help and exit\n");
357 fprintf(output, "\n");
358 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcap\n");
359 fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcap\"\n");
360 fprintf(output, "\n");
361 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
365 show_version(GString *comp_info_str, GString *runtime_info_str)
369 "Dumpcap " VERSION "%s\n"
374 "See http://www.wireshark.org for more information.\n",
375 wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
379 * Report an error in command-line arguments.
382 cmdarg_err(const char *fmt, ...)
388 /* Generate a 'special format' message back to parent */
390 msg = g_strdup_vprintf(fmt, ap);
391 sync_pipe_errmsg_to_parent(2, msg, "");
396 fprintf(stderr, "dumpcap: ");
397 vfprintf(stderr, fmt, ap);
398 fprintf(stderr, "\n");
404 * Report additional information for an error in command-line arguments.
407 cmdarg_err_cont(const char *fmt, ...)
414 msg = g_strdup_vprintf(fmt, ap);
415 sync_pipe_errmsg_to_parent(2, msg, "");
420 vfprintf(stderr, fmt, ap);
421 fprintf(stderr, "\n");
431 /* Print the number of packets captured for each interface until we're killed. */
433 print_statistics_loop(gboolean machine_readable)
435 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
441 char errbuf[PCAP_ERRBUF_SIZE];
444 if_list = get_interface_list(&err, &err_str);
445 if (if_list == NULL) {
447 case CANT_GET_INTERFACE_LIST:
448 cmdarg_err("%s", err_str);
452 case NO_INTERFACES_FOUND:
453 cmdarg_err("There are no interfaces on which a capture can be done");
459 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
460 if_info = if_entry->data;
461 #ifdef HAVE_PCAP_OPEN
462 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
464 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
468 if_stat = g_malloc(sizeof(if_stat_t));
469 if_stat->name = g_strdup(if_info->name);
471 stat_list = g_list_append(stat_list, if_stat);
476 cmdarg_err("There are no interfaces on which a capture can be done");
480 if (!machine_readable) {
481 printf("%-15s %10s %10s\n", "Interface", "Received",
486 while (global_ld.go) {
487 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
488 if_stat = stat_entry->data;
489 pcap_stats(if_stat->pch, &ps);
491 if (!machine_readable) {
492 printf("%-15s %10u %10u\n", if_stat->name,
493 ps.ps_recv, ps.ps_drop);
495 printf("%s\t%u\t%u\n", if_stat->name,
496 ps.ps_recv, ps.ps_drop);
501 if (! global_ld.from_cap_pipe)
508 /* XXX - Not reached. Should we look for 'q' in stdin? */
509 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
510 if_stat = stat_entry->data;
511 pcap_close(if_stat->pch);
512 g_free(if_stat->name);
515 g_list_free(stat_list);
516 free_interface_list(if_list);
524 capture_cleanup_handler(DWORD dwCtrlType)
526 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
527 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
528 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
529 like SIGTERM at least when the machine's shutting down.
531 For now, if we're running as a command rather than a capture child,
532 we handle all but CTRL_LOGOFF_EVENT as indications that we should
533 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
536 If we're not running as a capture child, we might be running as
537 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
538 user logs out. (XXX - can we explicitly check whether we're
539 running as a service?) */
541 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
542 "Console: Control signal");
543 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
544 "Console: Control signal, CtrlType: %u", dwCtrlType);
546 /* Keep capture running if we're a service and a user logs off */
547 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
556 capture_cleanup_handler(int signum _U_)
558 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
559 SIGTERM. We assume that if the user wanted it to keep running
560 after they logged out, they'd have nohupped it. */
562 /* Note: don't call g_log() in the signal handler: if we happened to be in
563 * g_log() in process context when the signal came in, g_log will detect
564 * the "recursion" and abort.
571 static void exit_main(int status)
574 /* Shutdown windows sockets */
577 /* can be helpful for debugging */
579 printf("Press any key\n");
590 * If we were linked with libcap (not libpcap), make sure we have
591 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
592 * (See comment in main() for details)
596 #if 0 /* Set to enable capability debugging */
597 /* see 'man cap_to_text()' for explanation of output */
598 /* '=' means 'all= ' ie: no capabilities */
599 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
601 print_caps(char *pfx) {
602 cap_t caps = cap_get_proc();
603 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
604 "%s: EUID: %d Capabilities: %s", pfx,
605 geteuid(), cap_to_text(caps, NULL));
608 print_caps(char *pfx _U_) {
613 relinquish_privs_except_capture(void)
615 /* If 'started_with_special_privs' (ie: suid) then enable for
616 * ourself the NET_ADMIN and NET_RAW capabilities and then
617 * drop our suid privileges.
619 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
620 * stuff we don't need (and shouldn't have).
621 * CAP_NET_RAW: Packet capture (raw sockets).
624 if (started_with_special_privs()) {
625 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
626 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
628 cap_t caps = cap_init(); /* all capabilities initialized to off */
630 print_caps("Pre drop, pre set");
632 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
633 cmdarg_err("prctl() fail return: %s", strerror(errno));
636 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
637 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
639 if (cap_set_proc(caps)) {
640 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
642 print_caps("Pre drop, post set");
644 relinquish_special_privs_perm();
646 print_caps("Post drop, pre set");
647 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
648 if (cap_set_proc(caps)) {
649 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
651 print_caps("Post drop, post set");
659 relinquish_all_capabilities()
661 /* Drop any and all capabilities this process may have. */
662 /* Allowed whether or not process has any privileges. */
663 cap_t caps = cap_init(); /* all capabilities initialized to off */
664 print_caps("Pre-clear");
665 if (cap_set_proc(caps)) {
666 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
668 print_caps("Post-clear");
672 #endif /* HAVE_LIBCAP */
674 /* Take care of byte order in the libpcap headers read from pipes.
675 * (function taken from wiretap/libpcap.c) */
677 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
680 /* Byte-swap the record header fields. */
681 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
682 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
683 rechdr->incl_len = BSWAP32(rechdr->incl_len);
684 rechdr->orig_len = BSWAP32(rechdr->orig_len);
687 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
688 swapped, in order to match the BPF header layout.
690 Unfortunately, some files were, according to a comment in the "libpcap"
691 source, written with version 2.3 in their headers but without the
692 interchanged fields, so if "incl_len" is greater than "orig_len" - which
693 would make no sense - we assume that we need to swap them. */
694 if (hdr->version_major == 2 &&
695 (hdr->version_minor < 3 ||
696 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
699 temp = rechdr->orig_len;
700 rechdr->orig_len = rechdr->incl_len;
701 rechdr->incl_len = temp;
707 * Thread function that reads from a pipe and pushes the data
708 * to the main application thread.
711 * XXX Right now we use async queues for basic signaling. The main thread
712 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
713 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
714 * Iff the read is successful cap_pipe_read pushes an item onto
715 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
716 * the queues themselves (yet).
718 * We might want to move some of the cap_pipe_dispatch logic here so that
719 * we can let cap_pipe_read run independently, queuing up multiple reads
720 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
722 static void *cap_pipe_read(void *ld_ptr) {
723 loop_data *ld = (loop_data *)ld_ptr;
732 while (ld->cap_pipe_err == PIPOK) {
733 g_async_queue_pop(cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
734 g_mutex_lock(cap_pipe_read_mtx);
736 while (bytes_read < (int) ld->cap_pipe_bytes_to_read) {
738 /* If we try to use read() on a named pipe on Windows with partial
739 * data it appears to return EOF.
741 res = ReadFile(ld->cap_pipe_h, ld->cap_pipe_buf+bytes_read,
742 ld->cap_pipe_bytes_to_read - bytes_read,
747 last_err = GetLastError();
748 if (last_err == ERROR_MORE_DATA) {
750 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
751 ld->cap_pipe_err = PIPEOF;
755 ld->cap_pipe_err = PIPERR;
758 } else if (b == 0 && ld->cap_pipe_bytes_to_read > 0) {
759 ld->cap_pipe_err = PIPEOF;
764 b = read(ld->cap_pipe_fd, ld->cap_pipe_buf+bytes_read,
765 ld->cap_pipe_bytes_to_read - bytes_read);
768 ld->cap_pipe_err = PIPEOF;
772 ld->cap_pipe_err = PIPERR;
781 ld->cap_pipe_bytes_read = bytes_read;
782 if (ld->cap_pipe_bytes_read >= ld->cap_pipe_bytes_to_read) {
783 g_async_queue_push(cap_pipe_done_q, ld->cap_pipe_buf); /* Any non-NULL value will do */
785 g_mutex_unlock(cap_pipe_read_mtx);
789 #endif /* USE_THREADS */
791 /* Provide select() functionality for a single file descriptor
792 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
794 * Returns the same values as select. If an error is returned,
795 * the string cap_pipe_err_str should be used instead of errno.
798 cap_pipe_select(int pipe_fd) {
800 struct timeval timeout, *pto;
803 cap_pipe_err_str = "Unknown error";
806 FD_SET(pipe_fd, &rfds);
809 timeout.tv_usec = CAP_READ_TIMEOUT * 1000;
812 sel_ret = select(pipe_fd+1, &rfds, NULL, NULL, pto);
814 cap_pipe_err_str = strerror(errno);
819 /* Mimic pcap_open_live() for pipe captures
820 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
822 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
823 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
825 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
826 char *errmsg, int errmsgl)
833 struct stat pipe_stat;
836 unsigned int bytes_read;
847 ld->cap_pipe_fd = -1;
849 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
851 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
854 * XXX (T)Wireshark blocks until we return
856 if (strcmp(pipename, "-") == 0) {
858 fd = 0; /* read from stdin */
860 ld->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
864 if (ws_stat(pipename, &pipe_stat) < 0) {
865 if (errno == ENOENT || errno == ENOTDIR)
866 ld->cap_pipe_err = PIPNEXIST;
868 g_snprintf(errmsg, errmsgl,
869 "The capture session could not be initiated "
870 "due to error on pipe: %s", strerror(errno));
871 ld->cap_pipe_err = PIPERR;
875 if (! S_ISFIFO(pipe_stat.st_mode)) {
876 if (S_ISCHR(pipe_stat.st_mode)) {
878 * Assume the user specified an interface on a system where
879 * interfaces are in /dev. Pretend we haven't seen it.
881 ld->cap_pipe_err = PIPNEXIST;
884 g_snprintf(errmsg, errmsgl,
885 "The capture session could not be initiated because\n"
886 "\"%s\" is neither an interface nor a pipe", pipename);
887 ld->cap_pipe_err = PIPERR;
891 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
893 g_snprintf(errmsg, errmsgl,
894 "The capture session could not be initiated "
895 "due to error on pipe open: %s", strerror(errno));
896 ld->cap_pipe_err = PIPERR;
900 #define PIPE_STR "\\pipe\\"
901 /* Under Windows, named pipes _must_ have the form
902 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
904 pncopy = g_strdup(pipename);
905 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
906 pos = strchr(pncopy + 3, '\\');
907 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
914 g_snprintf(errmsg, errmsgl,
915 "The capture session could not be initiated because\n"
916 "\"%s\" is neither an interface nor a pipe", pipename);
917 ld->cap_pipe_err = PIPNEXIST;
921 /* Wait for the pipe to appear */
923 ld->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
924 OPEN_EXISTING, 0, NULL);
926 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE)
929 if (GetLastError() != ERROR_PIPE_BUSY) {
930 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
931 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
932 g_snprintf(errmsg, errmsgl,
933 "The capture session on \"%s\" could not be started "
934 "due to error on pipe open: %s (error %d)",
935 pipename, utf_16to8(err_str), GetLastError());
937 ld->cap_pipe_err = PIPERR;
941 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
942 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
943 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
944 g_snprintf(errmsg, errmsgl,
945 "The capture session on \"%s\" timed out during "
946 "pipe open: %s (error %d)",
947 pipename, utf_16to8(err_str), GetLastError());
949 ld->cap_pipe_err = PIPERR;
957 ld->from_cap_pipe = TRUE;
960 /* read the pcap header */
962 while (bytes_read < sizeof magic) {
963 sel_ret = cap_pipe_select(fd);
965 g_snprintf(errmsg, errmsgl,
966 "Unexpected error from select: %s", strerror(errno));
968 } else if (sel_ret > 0) {
969 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
972 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
974 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
981 #else /* USE_THREADS */
982 g_thread_create(&cap_pipe_read, ld, FALSE, NULL);
984 ld->cap_pipe_buf = (char *) &magic;
985 ld->cap_pipe_bytes_read = 0;
986 ld->cap_pipe_bytes_to_read = sizeof(magic);
987 /* We don't have to worry about cap_pipe_read_mtx here */
988 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
989 g_get_current_time(&wait_time);
990 g_time_val_add(&wait_time, THREAD_OPEN_TIMEOUT);
991 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
993 /* XXX - Are there more appropriate values we should use? */
994 g_snprintf(errmsg, errmsgl, "Timeout on pipe magic during open");
996 } else if (ld->cap_pipe_bytes_read <= 0) {
997 if (ld->cap_pipe_bytes_read == 0)
998 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1000 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1005 #endif /* USE_THREADS */
1009 /* Host that wrote it has our byte order, and was running
1010 a program using either standard or ss990417 libpcap. */
1011 ld->cap_pipe_byte_swapped = FALSE;
1012 ld->cap_pipe_modified = FALSE;
1014 case PCAP_MODIFIED_MAGIC:
1015 /* Host that wrote it has our byte order, but was running
1016 a program using either ss990915 or ss991029 libpcap. */
1017 ld->cap_pipe_byte_swapped = FALSE;
1018 ld->cap_pipe_modified = TRUE;
1020 case PCAP_SWAPPED_MAGIC:
1021 /* Host that wrote it has a byte order opposite to ours,
1022 and was running a program using either standard or
1023 ss990417 libpcap. */
1024 ld->cap_pipe_byte_swapped = TRUE;
1025 ld->cap_pipe_modified = FALSE;
1027 case PCAP_SWAPPED_MODIFIED_MAGIC:
1028 /* Host that wrote it out has a byte order opposite to
1029 ours, and was running a program using either ss990915
1030 or ss991029 libpcap. */
1031 ld->cap_pipe_byte_swapped = TRUE;
1032 ld->cap_pipe_modified = TRUE;
1035 /* Not a "libpcap" type we know about. */
1036 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
1041 /* Read the rest of the header */
1043 while (bytes_read < sizeof(struct pcap_hdr)) {
1044 sel_ret = cap_pipe_select(fd);
1046 g_snprintf(errmsg, errmsgl,
1047 "Unexpected error from select: %s", strerror(errno));
1049 } else if (sel_ret > 0) {
1050 b = read(fd, ((char *)hdr)+bytes_read,
1051 sizeof(struct pcap_hdr) - bytes_read);
1054 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1056 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
1063 #else /* USE_THREADS */
1064 ld->cap_pipe_buf = (char *) hdr;
1065 ld->cap_pipe_bytes_read = 0;
1066 ld->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1067 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1068 g_get_current_time(&wait_time);
1069 g_time_val_add(&wait_time, THREAD_OPEN_TIMEOUT);
1070 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1072 g_snprintf(errmsg, errmsgl, "Timeout on pipe header during open");
1074 } else if (ld->cap_pipe_bytes_read <= 0) {
1075 if (ld->cap_pipe_bytes_read == 0)
1076 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1078 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
1082 #endif /* USE_THREADS */
1084 if (ld->cap_pipe_byte_swapped) {
1085 /* Byte-swap the header fields about which we care. */
1086 hdr->version_major = BSWAP16(hdr->version_major);
1087 hdr->version_minor = BSWAP16(hdr->version_minor);
1088 hdr->snaplen = BSWAP32(hdr->snaplen);
1089 hdr->network = BSWAP32(hdr->network);
1091 ld->linktype = hdr->network;
1093 if (hdr->version_major < 2) {
1094 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1098 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1099 ld->cap_pipe_err = PIPOK;
1101 ld->cap_pipe_fd = fd;
1106 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1107 ld->cap_pipe_err = PIPERR;
1110 ld->cap_pipe_fd = -1;
1112 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE) {
1113 CloseHandle(ld->cap_pipe_h);
1114 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
1122 /* We read one record from the pipe, take care of byte order in the record
1123 * header, write the record to the capture file, and update capture statistics. */
1125 cap_pipe_dispatch(loop_data *ld, guchar *data, char *errmsg, int errmsgl)
1127 struct pcap_pkthdr phdr;
1128 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1140 #ifdef LOG_CAPTURE_VERBOSE
1141 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1144 switch (ld->cap_pipe_state) {
1146 case STATE_EXPECT_REC_HDR:
1148 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1151 ld->cap_pipe_state = STATE_READ_REC_HDR;
1152 ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
1153 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1154 ld->cap_pipe_bytes_read = 0;
1157 ld->cap_pipe_buf = (char *) &ld->cap_pipe_rechdr;
1158 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1159 g_mutex_unlock(cap_pipe_read_mtx);
1164 case STATE_READ_REC_HDR:
1166 b = read(ld->cap_pipe_fd, ((char *)&ld->cap_pipe_rechdr)+ld->cap_pipe_bytes_read,
1167 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1170 result = PD_PIPE_EOF;
1172 result = PD_PIPE_ERR;
1175 ld->cap_pipe_bytes_read += b;
1176 #else /* USE_THREADS */
1177 g_get_current_time(&wait_time);
1178 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1179 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1180 if (ld->cap_pipe_err == PIPEOF) {
1181 result = PD_PIPE_EOF;
1183 } else if (ld->cap_pipe_err == PIPERR) {
1184 result = PD_PIPE_ERR;
1190 #endif /* USE_THREADS */
1191 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1193 result = PD_REC_HDR_READ;
1196 case STATE_EXPECT_DATA:
1198 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1201 ld->cap_pipe_state = STATE_READ_DATA;
1202 ld->cap_pipe_bytes_to_read = ld->cap_pipe_rechdr.hdr.incl_len;
1203 ld->cap_pipe_bytes_read = 0;
1206 ld->cap_pipe_buf = (char *) data;
1207 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1208 g_mutex_unlock(cap_pipe_read_mtx);
1213 case STATE_READ_DATA:
1215 b = read(ld->cap_pipe_fd, data+ld->cap_pipe_bytes_read,
1216 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1219 result = PD_PIPE_EOF;
1221 result = PD_PIPE_ERR;
1224 ld->cap_pipe_bytes_read += b;
1225 #else /* USE_THREADS */
1226 g_get_current_time(&wait_time);
1227 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1228 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1229 if (ld->cap_pipe_err == PIPEOF) {
1230 result = PD_PIPE_EOF;
1232 } else if (ld->cap_pipe_err == PIPERR) {
1233 result = PD_PIPE_ERR;
1239 #endif /* USE_THREADS */
1240 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1242 result = PD_DATA_READ;
1246 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
1249 } /* switch (ld->cap_pipe_state) */
1252 * We've now read as much data as we were expecting, so process it.
1256 case PD_REC_HDR_READ:
1257 /* We've read the header. Take care of byte order. */
1258 cap_pipe_adjust_header(ld->cap_pipe_byte_swapped, &ld->cap_pipe_hdr,
1259 &ld->cap_pipe_rechdr.hdr);
1260 if (ld->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1261 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
1262 ld->packet_count+1, ld->cap_pipe_rechdr.hdr.incl_len);
1265 ld->cap_pipe_state = STATE_EXPECT_DATA;
1269 /* Fill in a "struct pcap_pkthdr", and process the packet. */
1270 phdr.ts.tv_sec = ld->cap_pipe_rechdr.hdr.ts_sec;
1271 phdr.ts.tv_usec = ld->cap_pipe_rechdr.hdr.ts_usec;
1272 phdr.caplen = ld->cap_pipe_rechdr.hdr.incl_len;
1273 phdr.len = ld->cap_pipe_rechdr.hdr.orig_len;
1275 capture_loop_packet_cb((u_char *)ld, &phdr, data);
1277 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1281 ld->cap_pipe_err = PIPEOF;
1286 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1287 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1288 g_snprintf(errmsg, errmsgl,
1289 "Error reading from pipe: %s (error %d)",
1290 utf_16to8(err_str), GetLastError());
1293 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
1301 ld->cap_pipe_err = PIPERR;
1302 /* Return here rather than inside the switch to prevent GCC warning */
1307 /** Open the capture input file (pcap or capture pipe).
1308 * Returns TRUE if it succeeds, FALSE otherwise. */
1310 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
1311 char *errmsg, size_t errmsg_len,
1312 char *secondary_errmsg, size_t secondary_errmsg_len)
1314 gchar open_err_str[PCAP_ERRBUF_SIZE];
1315 gchar *sync_msg_str;
1316 static const char ppamsg[] = "can't find PPA for ";
1317 const char *set_linktype_err_str;
1318 const char *libpcap_warn;
1320 gchar *sync_secondary_msg_str;
1322 WORD wVersionRequested;
1325 #ifdef HAVE_PCAP_REMOTE
1326 struct pcap_rmtauth auth;
1330 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
1333 /* XXX - opening Winsock on tshark? */
1335 /* Initialize Windows Socket if we are in a WIN32 OS
1336 This needs to be done before querying the interface for network/netmask */
1338 /* XXX - do we really require 1.1 or earlier?
1339 Are there any versions that support only 2.0 or higher? */
1340 wVersionRequested = MAKEWORD(1, 1);
1341 err = WSAStartup(wVersionRequested, &wsaData);
1345 case WSASYSNOTREADY:
1346 g_snprintf(errmsg, (gulong) errmsg_len,
1347 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
1350 case WSAVERNOTSUPPORTED:
1351 g_snprintf(errmsg, (gulong) errmsg_len,
1352 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
1353 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
1356 case WSAEINPROGRESS:
1357 g_snprintf(errmsg, (gulong) errmsg_len,
1358 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
1362 g_snprintf(errmsg, (gulong) errmsg_len,
1363 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
1367 g_snprintf(errmsg, (gulong) errmsg_len,
1368 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
1372 g_snprintf(errmsg, (gulong) errmsg_len,
1373 "Couldn't initialize Windows Sockets: error %d", err);
1376 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
1381 /* Open the network interface to capture from it.
1382 Some versions of libpcap may put warnings into the error buffer
1383 if they succeed; to tell if that's happened, we have to clear
1384 the error buffer, and check if it's still a null string. */
1385 open_err_str[0] = '\0';
1386 #ifdef HAVE_PCAP_OPEN
1387 auth.type = capture_opts->auth_type == CAPTURE_AUTH_PWD ?
1388 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
1389 auth.username = capture_opts->auth_username;
1390 auth.password = capture_opts->auth_password;
1392 ld->pcap_h = pcap_open(capture_opts->iface,
1393 capture_opts->has_snaplen ? capture_opts->snaplen :
1394 WTAP_MAX_PACKET_SIZE,
1396 (capture_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
1397 (capture_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
1398 (capture_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
1399 CAP_READ_TIMEOUT, &auth, open_err_str);
1401 ld->pcap_h = pcap_open_live(capture_opts->iface,
1402 capture_opts->has_snaplen ? capture_opts->snaplen :
1403 WTAP_MAX_PACKET_SIZE,
1404 capture_opts->promisc_mode, CAP_READ_TIMEOUT,
1408 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
1409 /* to remove any suid privileges. */
1410 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
1411 /* (euid/egid have already previously been set to ruid/rgid. */
1412 /* (See comment in main() for details) */
1414 relinquish_special_privs_perm();
1416 relinquish_all_capabilities();
1419 if (ld->pcap_h != NULL) {
1420 /* we've opened "iface" as a network device */
1422 /* try to set the capture buffer size */
1423 if (capture_opts->buffer_size > 1 &&
1424 pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
1425 sync_secondary_msg_str = g_strdup_printf(
1426 "The capture buffer size of %luMB seems to be too high for your machine,\n"
1427 "the default of 1MB will be used.\n"
1429 "Nonetheless, the capture is started.\n",
1430 capture_opts->buffer_size);
1431 report_capture_error("Couldn't set the capture buffer size!",
1432 sync_secondary_msg_str);
1433 g_free(sync_secondary_msg_str);
1437 #if defined(HAVE_PCAP_REMOTE) && defined(HAVE_PCAP_SETSAMPLING)
1438 if (capture_opts->sampling_method != CAPTURE_SAMP_NONE)
1440 struct pcap_samp *samp;
1442 if ((samp = pcap_setsampling(ld->pcap_h)) != NULL)
1444 switch (capture_opts->sampling_method)
1446 case CAPTURE_SAMP_BY_COUNT:
1447 samp->method = PCAP_SAMP_1_EVERY_N;
1450 case CAPTURE_SAMP_BY_TIMER:
1451 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
1455 sync_msg_str = g_strdup_printf(
1456 "Unknown sampling method %d specified,\n"
1457 "continue without packet sampling",
1458 capture_opts->sampling_method);
1459 report_capture_error("Couldn't set the capture "
1460 "sampling", sync_msg_str);
1461 g_free(sync_msg_str);
1463 samp->value = capture_opts->sampling_param;
1467 report_capture_error("Couldn't set the capture sampling",
1468 "Cannot get packet sampling data structure");
1474 /* setting the data link type only works on real interfaces */
1475 if (capture_opts->linktype != -1) {
1476 set_linktype_err_str = set_pcap_linktype(ld->pcap_h, capture_opts->iface,
1477 capture_opts->linktype);
1478 if (set_linktype_err_str != NULL) {
1479 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
1480 set_linktype_err_str);
1481 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
1485 ld->linktype = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
1487 /* We couldn't open "iface" as a network device. */
1488 /* Try to open it as a pipe */
1489 cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, (int) errmsg_len);
1492 if (ld->cap_pipe_fd == -1) {
1494 if (ld->cap_pipe_h == INVALID_HANDLE_VALUE) {
1497 if (ld->cap_pipe_err == PIPNEXIST) {
1498 /* Pipe doesn't exist, so output message for interface */
1500 /* If we got a "can't find PPA for X" message, warn the user (who
1501 is running (T)Wireshark on HP-UX) that they don't have a version
1502 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1503 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1504 PPA for X" rather than "can't find PPA for X"). */
1505 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1508 "You are running (T)Wireshark with a version of the libpcap library\n"
1509 "that doesn't handle HP-UX network devices well; this means that\n"
1510 "(T)Wireshark may not be able to capture packets.\n"
1512 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1513 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1514 "packaged binary form from the Software Porting And Archive Centre\n"
1515 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1516 "at the URL lists a number of mirror sites.";
1519 g_snprintf(errmsg, (gulong) errmsg_len,
1520 "The capture session could not be initiated (%s).", open_err_str);
1522 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
1523 "Please check to make sure you have sufficient permissions, and that you have "
1524 "the proper interface or pipe specified.%s", libpcap_warn);
1526 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
1528 "Please check that \"%s\" is the proper interface.\n"
1531 "Help can be found at:\n"
1533 " http://wiki.wireshark.org/WinPcap\n"
1534 " http://wiki.wireshark.org/CaptureSetup\n",
1535 capture_opts->iface);
1539 * Else pipe (or file) does exist and cap_pipe_open_live() has
1544 /* cap_pipe_open_live() succeeded; don't want
1545 error message from pcap_open_live() */
1546 open_err_str[0] = '\0';
1549 /* XXX - will this work for tshark? */
1550 #ifdef MUST_DO_SELECT
1551 if (!ld->from_cap_pipe) {
1552 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
1553 ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
1555 ld->pcap_fd = pcap_fileno(ld->pcap_h);
1560 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1561 returned a warning; print it, but keep capturing. */
1562 if (open_err_str[0] != '\0') {
1563 sync_msg_str = g_strdup_printf("%s.", open_err_str);
1564 report_capture_error(sync_msg_str, "");
1565 g_free(sync_msg_str);
1572 /* close the capture input file (pcap or capture pipe) */
1573 static void capture_loop_close_input(loop_data *ld) {
1575 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
1577 /* if open, close the capture pipe "input file" */
1579 if (ld->cap_pipe_fd >= 0) {
1580 g_assert(ld->from_cap_pipe);
1581 ws_close(ld->cap_pipe_fd);
1582 ld->cap_pipe_fd = 0;
1585 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE) {
1586 CloseHandle(ld->cap_pipe_h);
1587 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
1591 /* if open, close the pcap "input file" */
1592 if(ld->pcap_h != NULL) {
1593 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)ld->pcap_h);
1594 g_assert(!ld->from_cap_pipe);
1595 pcap_close(ld->pcap_h);
1602 /* Shut down windows sockets */
1608 /* init the capture filter */
1609 static initfilter_status_t
1610 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe, gchar * iface, gchar * cfilter) {
1611 bpf_u_int32 netnum, netmask;
1612 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
1613 struct bpf_program fcode;
1616 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
1618 /* capture filters only work on real interfaces */
1619 if (cfilter && !from_cap_pipe) {
1620 /* A capture filter was specified; set it up. */
1621 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1623 * Well, we can't get the netmask for this interface; it's used
1624 * only for filters that check for broadcast IP addresses, so
1625 * we just punt and use 0. It might be nice to warn the user,
1626 * but that's a pain in a GUI application, as it'd involve popping
1627 * up a message box, and it's not clear how often this would make
1628 * a difference (only filters that check for IP broadcast addresses
1632 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
1635 if (pcap_compile(pcap_h, &fcode, cfilter, 1, netmask) < 0) {
1636 /* Treat this specially - our caller might try to compile this
1637 as a display filter and, if that succeeds, warn the user that
1638 the display and capture filter syntaxes are different. */
1639 return INITFILTER_BAD_FILTER;
1641 if (pcap_setfilter(pcap_h, &fcode) < 0) {
1642 #ifdef HAVE_PCAP_FREECODE
1643 pcap_freecode(&fcode);
1645 return INITFILTER_OTHER_ERROR;
1647 #ifdef HAVE_PCAP_FREECODE
1648 pcap_freecode(&fcode);
1652 return INITFILTER_NO_ERROR;
1656 /* set up to write to the already-opened capture output file/files */
1658 capture_loop_init_output(capture_options *capture_opts, int save_file_fd, loop_data *ld, char *errmsg, int errmsg_len) {
1662 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
1665 if (ld->from_cap_pipe) {
1666 ld->file_snaplen = ld->cap_pipe_hdr.snaplen;
1669 ld->file_snaplen = pcap_snapshot(ld->pcap_h);
1672 /* Set up to write to the capture file. */
1673 if (capture_opts->multi_files_on) {
1674 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
1676 ld->pdh = libpcap_fdopen(save_file_fd, &err);
1679 gboolean successful;
1681 ld->bytes_written = 0;
1682 if (capture_opts->use_pcapng) {
1685 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
1686 successful = libpcap_write_session_header_block(ld->pdh, appname, &ld->bytes_written, &err) &&
1687 libpcap_write_interface_description_block(ld->pdh, capture_opts->iface, capture_opts->cfilter, ld->linktype, ld->file_snaplen, &ld->bytes_written, &err);
1689 successful = libpcap_write_file_header(ld->pdh, ld->linktype, ld->file_snaplen,
1690 &ld->bytes_written, &err);
1698 if (ld->pdh == NULL) {
1699 /* We couldn't set up to write to the capture file. */
1700 /* XXX - use cf_open_error_message from tshark instead? */
1703 case WTAP_ERR_CANT_OPEN:
1704 g_snprintf(errmsg, errmsg_len, "The file to which the capture would be saved"
1705 " couldn't be created for some unknown reason.");
1708 case WTAP_ERR_SHORT_WRITE:
1709 g_snprintf(errmsg, errmsg_len, "A full header couldn't be written to the file"
1710 " to which the capture would be saved.");
1715 g_snprintf(errmsg, errmsg_len,
1716 "The file to which the capture would be"
1717 " saved (\"%s\") could not be opened: Error %d.",
1718 capture_opts->save_file, err);
1720 g_snprintf(errmsg, errmsg_len,
1721 "The file to which the capture would be"
1722 " saved (\"%s\") could not be opened: %s.",
1723 capture_opts->save_file, strerror(err));
1735 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
1737 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
1739 if (capture_opts->multi_files_on) {
1740 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
1742 if (capture_opts->use_pcapng) {
1743 libpcap_write_interface_statistics_block(ld->pdh, 0, ld->pcap_h, &ld->bytes_written, err_close);
1745 return libpcap_dump_close(ld->pdh, err_close);
1749 /* dispatch incoming packets (pcap or capture pipe)
1751 * Waits for incoming packets to be available, and calls pcap_dispatch()
1752 * to cause them to be processed.
1754 * Returns the number of packets which were processed.
1756 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
1757 * packet-batching behaviour does not cause packets to get held back
1761 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
1762 char *errmsg, int errmsg_len)
1765 gint packet_count_before;
1766 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1771 packet_count_before = ld->packet_count;
1772 if (ld->from_cap_pipe) {
1773 /* dispatch from capture pipe */
1774 #ifdef LOG_CAPTURE_VERBOSE
1775 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
1778 sel_ret = cap_pipe_select(ld->cap_pipe_fd);
1781 if (sel_ret < 0 && errno != EINTR) {
1782 g_snprintf(errmsg, errmsg_len,
1783 "Unexpected error from select: %s", strerror(errno));
1784 report_capture_error(errmsg, please_report);
1789 * "select()" says we can read from the pipe without blocking
1791 #endif /* USE_THREADS */
1792 inpkts = cap_pipe_dispatch(ld, pcap_data, errmsg, errmsg_len);
1802 /* dispatch from pcap */
1803 #ifdef MUST_DO_SELECT
1805 * If we have "pcap_get_selectable_fd()", we use it to get the
1806 * descriptor on which to select; if that's -1, it means there
1807 * is no descriptor on which you can do a "select()" (perhaps
1808 * because you're capturing on a special device, and that device's
1809 * driver unfortunately doesn't support "select()", in which case
1810 * we don't do the select - which means it might not be possible
1811 * to stop a capture until a packet arrives. If that's unacceptable,
1812 * plead with whoever supplies the software for that device to add
1813 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
1814 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
1815 * later, so it can use pcap_breakloop().
1817 #ifdef LOG_CAPTURE_VERBOSE
1818 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
1820 if (ld->pcap_fd != -1) {
1821 sel_ret = cap_pipe_select(ld->pcap_fd);
1824 * "select()" says we can read from it without blocking; go for
1827 * We don't have pcap_breakloop(), so we only process one packet
1828 * per pcap_dispatch() call, to allow a signal to stop the
1829 * processing immediately, rather than processing all packets
1830 * in a batch before quitting.
1832 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb,
1836 /* Error, rather than pcap_breakloop(). */
1837 ld->pcap_err = TRUE;
1839 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1842 if (sel_ret < 0 && errno != EINTR) {
1843 g_snprintf(errmsg, errmsg_len,
1844 "Unexpected error from select: %s", strerror(errno));
1845 report_capture_error(errmsg, please_report);
1851 #endif /* MUST_DO_SELECT */
1853 /* dispatch from pcap without select */
1855 #ifdef LOG_CAPTURE_VERBOSE
1856 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
1860 * On Windows, we don't support asynchronously telling a process to
1861 * stop capturing; instead, we check for an indication on a pipe
1862 * after processing packets. We therefore process only one packet
1863 * at a time, so that we can check the pipe after every packet.
1865 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb, (u_char *) ld);
1867 inpkts = pcap_dispatch(ld->pcap_h, -1, capture_loop_packet_cb, (u_char *) ld);
1871 /* Error, rather than pcap_breakloop(). */
1872 ld->pcap_err = TRUE;
1874 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1876 #else /* pcap_next_ex */
1877 #ifdef LOG_CAPTURE_VERBOSE
1878 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
1880 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
1883 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
1884 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
1885 * This should be fixed in the WinPcap 4.0 alpha release.
1887 * For reference, an example remote interface:
1888 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
1891 /* emulate dispatch from pcap */
1894 struct pcap_pkthdr *pkt_header;
1899 (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1)
1900 capture_loop_packet_cb( (u_char *) ld, pkt_header, pkt_data);
1903 ld->pcap_err = TRUE;
1907 #endif /* pcap_next_ex */
1911 #ifdef LOG_CAPTURE_VERBOSE
1912 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
1915 return ld->packet_count - packet_count_before;
1919 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
1920 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
1922 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
1923 char *errmsg, int errmsg_len) {
1926 gchar *capfile_name;
1927 gboolean is_tempfile;
1932 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
1933 (capture_opts->save_file) ? capture_opts->save_file : "");
1935 if (capture_opts->save_file != NULL) {
1936 /* We return to the caller while the capture is in progress.
1937 * Therefore we need to take a copy of save_file in
1938 * case the caller destroys it after we return.
1940 capfile_name = g_strdup(capture_opts->save_file);
1942 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
1943 if (capture_opts->multi_files_on) {
1944 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
1945 g_snprintf(errmsg, errmsg_len,
1946 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
1947 g_free(capfile_name);
1950 if (strcmp(capfile_name, "-") == 0) {
1951 /* write to stdout */
1954 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
1955 _setmode(1, O_BINARY);
1958 } /* if (...output_to_pipe ... */
1961 if (capture_opts->multi_files_on) {
1962 /* ringbuffer is enabled */
1963 *save_file_fd = ringbuf_init(capfile_name,
1964 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
1966 /* we need the ringbuf name */
1967 if(*save_file_fd != -1) {
1968 g_free(capfile_name);
1969 capfile_name = g_strdup(ringbuf_current_filename());
1972 /* Try to open/create the specified file for use as a capture buffer. */
1973 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
1977 is_tempfile = FALSE;
1979 /* Choose a random name for the temporary capture buffer */
1980 *save_file_fd = create_tempfile(&tmpname, "wireshark");
1981 capfile_name = g_strdup(tmpname);
1985 /* did we fail to open the output file? */
1986 if (*save_file_fd == -1) {
1988 g_snprintf(errmsg, errmsg_len,
1989 "The temporary file to which the capture would be saved (\"%s\") "
1990 "could not be opened: %s.", capfile_name, strerror(errno));
1992 if (capture_opts->multi_files_on) {
1993 ringbuf_error_cleanup();
1996 g_snprintf(errmsg, errmsg_len,
1997 "The file to which the capture would be saved (\"%s\") "
1998 "could not be opened: %s.", capfile_name,
2001 g_free(capfile_name);
2005 if(capture_opts->save_file != NULL) {
2006 g_free(capture_opts->save_file);
2008 capture_opts->save_file = capfile_name;
2009 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2010 "g_free(capfile_name)". */
2012 ret = fchown(*save_file_fd, capture_opts->owner, capture_opts->group);
2020 #define TIME_GET() GetTickCount()
2022 #define TIME_GET() time(NULL)
2025 /* Do the low-level work of a capture.
2026 Returns TRUE if it succeeds, FALSE otherwise. */
2028 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
2030 time_t upd_time, cur_time;
2034 gint inpkts_to_sync_pipe = 0; /* packets not already send out to the sync_pipe */
2035 condition *cnd_file_duration = NULL;
2036 condition *cnd_autostop_files = NULL;
2037 condition *cnd_autostop_size = NULL;
2038 condition *cnd_autostop_duration = NULL;
2039 guint32 autostop_files = 0;
2042 gboolean cfilter_error = FALSE;
2043 #define MSG_MAX_LENGTH 4096
2044 char errmsg[MSG_MAX_LENGTH+1];
2045 char secondary_errmsg[MSG_MAX_LENGTH+1];
2046 int save_file_fd = -1;
2049 *secondary_errmsg = '\0';
2051 /* init the loop data */
2052 global_ld.go = TRUE;
2053 global_ld.packet_count = 0;
2054 if (capture_opts->has_autostop_packets)
2055 global_ld.packet_max = capture_opts->autostop_packets;
2057 global_ld.packet_max = 0; /* no limit */
2058 global_ld.err = 0; /* no error seen yet */
2059 global_ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
2060 global_ld.pcap_err = FALSE;
2061 global_ld.from_cap_pipe = FALSE;
2062 global_ld.pdh = NULL;
2064 global_ld.cap_pipe_fd = -1;
2066 global_ld.cap_pipe_h = INVALID_HANDLE_VALUE;
2068 #ifdef MUST_DO_SELECT
2069 global_ld.pcap_fd = 0;
2072 /* We haven't yet gotten the capture statistics. */
2073 *stats_known = FALSE;
2075 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
2076 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
2078 /* open the "input file" from network interface or capture pipe */
2079 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
2080 secondary_errmsg, sizeof(secondary_errmsg))) {
2084 /* init the input filter from the network interface (capture pipe will do nothing) */
2085 switch (capture_loop_init_filter(global_ld.pcap_h, global_ld.from_cap_pipe,
2086 capture_opts->iface,
2087 capture_opts->cfilter)) {
2089 case INITFILTER_NO_ERROR:
2092 case INITFILTER_BAD_FILTER:
2093 cfilter_error = TRUE;
2094 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(global_ld.pcap_h));
2097 case INITFILTER_OTHER_ERROR:
2098 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
2099 pcap_geterr(global_ld.pcap_h));
2100 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
2104 /* If we're supposed to write to a capture file, open it for output
2105 (temporary/specified name/ringbuffer) */
2106 if (capture_opts->saving_to_file) {
2107 if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
2111 /* set up to write to the already-opened capture output file/files */
2112 if (!capture_loop_init_output(capture_opts, save_file_fd, &global_ld,
2113 errmsg, sizeof(errmsg))) {
2117 /* XXX - capture SIGTERM and close the capture, in case we're on a
2118 Linux 2.0[.x] system and you have to explicitly close the capture
2119 stream in order to turn promiscuous mode off? We need to do that
2120 in other places as well - and I don't think that works all the
2121 time in any case, due to libpcap bugs. */
2123 /* Well, we should be able to start capturing.
2125 Sync out the capture file, so the header makes it to the file system,
2126 and send a "capture started successfully and capture file created"
2127 message to our parent so that they'll open the capture file and
2128 update its windows to indicate that we have a live capture in
2130 libpcap_dump_flush(global_ld.pdh, NULL);
2131 report_new_capture_file(capture_opts->save_file);
2134 /* initialize capture stop (and alike) conditions */
2135 init_capture_stop_conditions();
2136 /* create stop conditions */
2137 if (capture_opts->has_autostop_filesize)
2139 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
2140 if (capture_opts->has_autostop_duration)
2141 cnd_autostop_duration =
2142 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
2144 if (capture_opts->multi_files_on) {
2145 if (capture_opts->has_file_duration)
2147 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
2149 if (capture_opts->has_autostop_files)
2150 cnd_autostop_files =
2151 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
2154 /* init the time values */
2155 start_time = TIME_GET();
2156 upd_time = TIME_GET();
2158 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
2160 /* WOW, everything is prepared! */
2161 /* please fasten your seat belts, we will enter now the actual capture loop */
2162 while (global_ld.go) {
2163 /* dispatch incoming packets */
2164 inpkts = capture_loop_dispatch(capture_opts, &global_ld, errmsg,
2168 /* any news from our parent (signal pipe)? -> just stop the capture */
2169 if (!signal_pipe_check_running()) {
2170 global_ld.go = FALSE;
2175 inpkts_to_sync_pipe += inpkts;
2177 /* check capture size condition */
2178 if (cnd_autostop_size != NULL &&
2179 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)){
2180 /* Capture size limit reached, do we have another file? */
2181 if (capture_opts->multi_files_on) {
2182 if (cnd_autostop_files != NULL &&
2183 cnd_eval(cnd_autostop_files, ++autostop_files)) {
2184 /* no files left: stop here */
2185 global_ld.go = FALSE;
2189 /* Switch to the next ringbuffer file */
2190 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2191 &save_file_fd, &global_ld.err)) {
2192 gboolean successful;
2194 /* File switch succeeded: reset the conditions */
2195 global_ld.bytes_written = 0;
2196 if (capture_opts->use_pcapng) {
2199 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2200 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2201 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);
2203 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2204 &global_ld.bytes_written, &global_ld.err);
2207 fclose(global_ld.pdh);
2208 global_ld.pdh = NULL;
2209 global_ld.go = FALSE;
2212 cnd_reset(cnd_autostop_size);
2213 if (cnd_file_duration) {
2214 cnd_reset(cnd_file_duration);
2216 libpcap_dump_flush(global_ld.pdh, NULL);
2217 report_packet_count(inpkts_to_sync_pipe);
2218 inpkts_to_sync_pipe = 0;
2219 report_new_capture_file(capture_opts->save_file);
2221 /* File switch failed: stop here */
2222 global_ld.go = FALSE;
2226 /* single file, stop now */
2227 global_ld.go = FALSE;
2230 } /* cnd_autostop_size */
2231 if (capture_opts->output_to_pipe) {
2232 libpcap_dump_flush(global_ld.pdh, NULL);
2236 /* Only update once a second (Win32: 500ms) so as not to overload slow
2237 * displays. This also prevents too much context-switching between the
2238 * dumpcap and wireshark processes */
2239 cur_time = TIME_GET();
2241 if ( (cur_time - upd_time) > 500) {
2243 if (cur_time - upd_time > 0) {
2245 upd_time = cur_time;
2247 /*if (pcap_stats(pch, stats) >= 0) {
2248 *stats_known = TRUE;
2251 /* Let the parent process know. */
2252 if (inpkts_to_sync_pipe) {
2254 libpcap_dump_flush(global_ld.pdh, NULL);
2256 /* Send our parent a message saying we've written out "inpkts_to_sync_pipe"
2257 packets to the capture file. */
2258 report_packet_count(inpkts_to_sync_pipe);
2260 inpkts_to_sync_pipe = 0;
2263 /* check capture duration condition */
2264 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
2265 /* The maximum capture time has elapsed; stop the capture. */
2266 global_ld.go = FALSE;
2270 /* check capture file duration condition */
2271 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
2272 /* duration limit reached, do we have another file? */
2273 if (capture_opts->multi_files_on) {
2274 if (cnd_autostop_files != NULL &&
2275 cnd_eval(cnd_autostop_files, ++autostop_files)) {
2276 /* no files left: stop here */
2277 global_ld.go = FALSE;
2281 /* Switch to the next ringbuffer file */
2282 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2283 &save_file_fd, &global_ld.err)) {
2284 gboolean successful;
2286 /* file switch succeeded: reset the conditions */
2287 global_ld.bytes_written = 0;
2288 if (capture_opts->use_pcapng) {
2291 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2292 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2293 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);
2295 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2296 &global_ld.bytes_written, &global_ld.err);
2299 fclose(global_ld.pdh);
2300 global_ld.pdh = NULL;
2301 global_ld.go = FALSE;
2304 cnd_reset(cnd_file_duration);
2305 if(cnd_autostop_size)
2306 cnd_reset(cnd_autostop_size);
2307 libpcap_dump_flush(global_ld.pdh, NULL);
2308 report_packet_count(inpkts_to_sync_pipe);
2309 inpkts_to_sync_pipe = 0;
2310 report_new_capture_file(capture_opts->save_file);
2312 /* File switch failed: stop here */
2313 global_ld.go = FALSE;
2317 /* single file, stop now */
2318 global_ld.go = FALSE;
2321 } /* cnd_file_duration */
2324 } /* while (global_ld.go) */
2326 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
2328 /* delete stop conditions */
2329 if (cnd_file_duration != NULL)
2330 cnd_delete(cnd_file_duration);
2331 if (cnd_autostop_files != NULL)
2332 cnd_delete(cnd_autostop_files);
2333 if (cnd_autostop_size != NULL)
2334 cnd_delete(cnd_autostop_size);
2335 if (cnd_autostop_duration != NULL)
2336 cnd_delete(cnd_autostop_duration);
2338 /* did we had a pcap (input) error? */
2339 if (global_ld.pcap_err) {
2340 /* On Linux, if an interface goes down while you're capturing on it,
2341 you'll get a "recvfrom: Network is down" error (ENETDOWN).
2342 (At least you will if strerror() doesn't show a local translation
2345 On FreeBSD and OS X, if a network adapter disappears while
2346 you're capturing on it, you'll get a "read: Device not configured"
2347 error (ENXIO). (See previous parenthetical note.)
2349 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
2351 These should *not* be reported to the Wireshark developers. */
2354 cap_err_str = pcap_geterr(global_ld.pcap_h);
2355 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
2356 strcmp(cap_err_str, "read: Device not configured") == 0 ||
2357 strcmp(cap_err_str, "read: I/O error") == 0) {
2358 report_capture_error("The network adapter on which the capture was being done "
2359 "is no longer running; the capture has stopped.",
2362 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
2364 report_capture_error(errmsg, please_report);
2367 else if (global_ld.from_cap_pipe && global_ld.cap_pipe_err == PIPERR)
2368 report_capture_error(errmsg, "");
2370 /* did we had an error while capturing? */
2371 if (global_ld.err == 0) {
2374 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
2375 global_ld.err, FALSE);
2376 report_capture_error(errmsg, please_report);
2380 if (capture_opts->saving_to_file) {
2381 /* close the wiretap (output) file */
2382 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
2386 /* there might be packets not yet notified to the parent */
2387 /* (do this after closing the file, so all packets are already flushed) */
2388 if(inpkts_to_sync_pipe) {
2389 report_packet_count(inpkts_to_sync_pipe);
2390 inpkts_to_sync_pipe = 0;
2393 /* If we've displayed a message about a write error, there's no point
2394 in displaying another message about an error on close. */
2395 if (!close_ok && write_ok) {
2396 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
2398 report_capture_error(errmsg, "");
2402 * XXX We exhibit different behaviour between normal mode and sync mode
2403 * when the pipe is stdin and not already at EOF. If we're a child, the
2404 * parent's stdin isn't closed, so if the user starts another capture,
2405 * cap_pipe_open_live() will very likely not see the expected magic bytes and
2406 * will say "Unrecognized libpcap format". On the other hand, in normal
2407 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
2410 /* get packet drop statistics from pcap */
2411 if(global_ld.pcap_h != NULL) {
2412 g_assert(!global_ld.from_cap_pipe);
2413 /* Get the capture statistics, so we know how many packets were
2415 if (pcap_stats(global_ld.pcap_h, stats) >= 0) {
2416 *stats_known = TRUE;
2417 /* Let the parent process know. */
2418 report_packet_drops(stats->ps_drop);
2420 g_snprintf(errmsg, sizeof(errmsg),
2421 "Can't get packet-drop statistics: %s",
2422 pcap_geterr(global_ld.pcap_h));
2423 report_capture_error(errmsg, please_report);
2427 /* close the input file (pcap or capture pipe) */
2428 capture_loop_close_input(&global_ld);
2430 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
2432 /* ok, if the write and the close were successful. */
2433 return write_ok && close_ok;
2436 if (capture_opts->multi_files_on) {
2437 /* cleanup ringbuffer */
2438 ringbuf_error_cleanup();
2440 /* We can't use the save file, and we have no FILE * for the stream
2441 to close in order to close it, so close the FD directly. */
2442 if(save_file_fd != -1) {
2443 ws_close(save_file_fd);
2446 /* We couldn't even start the capture, so get rid of the capture
2448 if(capture_opts->save_file != NULL) {
2449 ws_unlink(capture_opts->save_file);
2450 g_free(capture_opts->save_file);
2453 capture_opts->save_file = NULL;
2455 report_cfilter_error(capture_opts->cfilter, errmsg);
2457 report_capture_error(errmsg, secondary_errmsg);
2459 /* close the input file (pcap or cap_pipe) */
2460 capture_loop_close_input(&global_ld);
2462 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
2468 static void capture_loop_stop(void)
2470 #ifdef HAVE_PCAP_BREAKLOOP
2471 if(global_ld.pcap_h != NULL)
2472 pcap_breakloop(global_ld.pcap_h);
2474 global_ld.go = FALSE;
2479 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
2480 int err, gboolean is_close)
2485 g_snprintf(errmsg, errmsglen,
2486 "Not all the packets could be written to the file"
2487 " to which the capture was being saved\n"
2488 "(\"%s\") because there is no space left on the file system\n"
2489 "on which that file resides.",
2495 g_snprintf(errmsg, errmsglen,
2496 "Not all the packets could be written to the file"
2497 " to which the capture was being saved\n"
2498 "(\"%s\") because you are too close to, or over,"
2499 " your disk quota\n"
2500 "on the file system on which that file resides.",
2505 case WTAP_ERR_CANT_CLOSE:
2506 g_snprintf(errmsg, errmsglen,
2507 "The file to which the capture was being saved"
2508 " couldn't be closed for some unknown reason.");
2511 case WTAP_ERR_SHORT_WRITE:
2512 g_snprintf(errmsg, errmsglen,
2513 "Not all the packets could be written to the file"
2514 " to which the capture was being saved\n"
2521 g_snprintf(errmsg, errmsglen,
2522 "The file to which the capture was being saved\n"
2523 "(\"%s\") could not be closed: %s.",
2524 fname, wtap_strerror(err));
2526 g_snprintf(errmsg, errmsglen,
2527 "An error occurred while writing to the file"
2528 " to which the capture was being saved\n"
2530 fname, wtap_strerror(err));
2537 /* one packet was captured, process it */
2539 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
2542 loop_data *ld = (void *) user;
2545 /* We may be called multiple times from pcap_dispatch(); if we've set
2546 the "stop capturing" flag, ignore this packet, as we're not
2547 supposed to be saving any more packets. */
2552 gboolean successful;
2553 /* We're supposed to write the packet to a file; do so.
2554 If this fails, set "ld->go" to FALSE, to stop the capture, and set
2555 "ld->err" to the error. */
2556 if (global_capture_opts.use_pcapng) {
2557 successful = libpcap_write_enhanced_packet_block(ld->pdh, phdr, 0, pd, &ld->bytes_written, &err);
2559 successful = libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err);
2566 /* if the user told us to stop after x packets, do we already have enough? */
2567 if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
2576 /* And now our feature presentation... [ fade to music ] */
2578 main(int argc, char *argv[])
2581 gboolean arg_error = FALSE;
2586 struct sigaction action, oldaction;
2589 gboolean start_capture = TRUE;
2590 gboolean stats_known;
2591 struct pcap_stat stats;
2592 GLogLevelFlags log_flags;
2593 gboolean list_interfaces = FALSE;
2594 gboolean list_link_layer_types = FALSE;
2595 gboolean machine_readable = FALSE;
2596 gboolean print_statistics = FALSE;
2597 int status, run_once_args = 0;
2599 #if defined(__APPLE__) && defined(__LP64__)
2600 struct utsname osinfo;
2603 #ifdef HAVE_PCAP_REMOTE
2604 #define OPTSTRING_INIT "a:A:b:c:Df:hi:Lm:MnprSs:uvw:y:Z:"
2606 #define OPTSTRING_INIT "a:b:c:Df:hi:LMnpSs:vw:y:Z:"
2610 #define OPTSTRING_WIN32 "B:"
2612 #define OPTSTRING_WIN32 ""
2615 char optstring[sizeof(OPTSTRING_INIT) + sizeof(OPTSTRING_WIN32) - 1] =
2616 OPTSTRING_INIT OPTSTRING_WIN32;
2618 #ifdef DEBUG_CHILD_DUMPCAP
2619 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
2620 fprintf (stderr, "Unable to open debug log file !\n");
2625 #if defined(__APPLE__) && defined(__LP64__)
2627 * Is this Mac OS X 10.6 or 10.6.1? If so, we need a bug workaround.
2629 if (uname(&osinfo) == 0) {
2631 * Mac OS X 10.x uses Darwin x.0.0. Mac OS X 10.x.y uses Darwin
2632 * x.y.0 (except that 10.6.1 appears to have a uname version
2633 * number of 10.0.0, not 10.1.0 - go figure).
2635 if (strcmp(osinfo.release, "10.0.0") == 0 ||
2636 strcmp(osinfo.release, "10.1.0") == 0)
2637 need_timeout_workaround = 1;
2641 /* Determine if dumpcap is being requested to run in a special */
2642 /* capture_child mode by going thru the command line args to see if */
2643 /* a -Z is present. (-Z is a hidden option). */
2644 /* The primary result of running in capture_child mode is that */
2645 /* all messages sent out on stderr are in a special type/len/string */
2646 /* format to allow message processing by type. */
2647 /* These messages include various 'status' messages which are sent */
2648 /* when an actual capture is in progress. Capture_child mode */
2649 /* would normally be requested by a parent process which invokes */
2650 /* dumpcap and obtains dumpcap stderr output via a pipe to which */
2651 /* dumpcap stderr has been redirected. */
2652 /* Capture_child mode needs to be determined immediately upon */
2653 /* startup so that any messages generated by dumpcap in this mode */
2654 /* (eg: during initialization) will be formatted properly. */
2656 for (i=1; i<argc; i++) {
2657 if (strcmp("-Z", argv[i]) == 0) {
2658 capture_child = TRUE;
2660 /* set output pipe to binary mode, to avoid ugly text conversions */
2661 _setmode(2, O_BINARY);
2666 /* The default_log_handler will use stdout, which makes trouble in */
2667 /* capture child mode, as it uses stdout for it's sync_pipe. */
2668 /* So: the filtering is done in the console_log_handler and not here.*/
2669 /* We set the log handlers right up front to make sure that any log */
2670 /* messages when running as child will be sent back to the parent */
2671 /* with the correct format. */
2675 G_LOG_LEVEL_CRITICAL|
2676 G_LOG_LEVEL_WARNING|
2677 G_LOG_LEVEL_MESSAGE|
2680 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
2682 g_log_set_handler(NULL,
2684 console_log_handler, NULL /* user_data */);
2685 g_log_set_handler(LOG_DOMAIN_MAIN,
2687 console_log_handler, NULL /* user_data */);
2688 g_log_set_handler(LOG_DOMAIN_CAPTURE,
2690 console_log_handler, NULL /* user_data */);
2691 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
2693 console_log_handler, NULL /* user_data */);
2696 /* Load wpcap if possible. Do this before collecting the run-time version information */
2699 /* ... and also load the packet.dll from wpcap */
2700 /* XXX - currently not required, may change later. */
2701 /*wpcap_packet_load();*/
2703 /* Start windows sockets */
2704 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
2706 /* Set handler for Ctrl+C key */
2707 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
2709 /* Prepare to read from a pipe */
2710 if (!g_thread_supported ())
2711 g_thread_init (NULL);
2712 cap_pipe_pending_q = g_async_queue_new();
2713 cap_pipe_done_q = g_async_queue_new();
2714 cap_pipe_read_mtx = g_mutex_new();
2717 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
2719 action.sa_handler = capture_cleanup_handler;
2721 * Arrange that system calls not get restarted, because when
2722 * our signal handler returns we don't want to restart
2723 * a call that was waiting for packets to arrive.
2725 action.sa_flags = 0;
2726 sigemptyset(&action.sa_mask);
2727 sigaction(SIGTERM, &action, NULL);
2728 sigaction(SIGINT, &action, NULL);
2729 sigaction(SIGPIPE, &action, NULL);
2730 sigaction(SIGHUP, NULL, &oldaction);
2731 if (oldaction.sa_handler == SIG_DFL)
2732 sigaction(SIGHUP, &action, NULL);
2735 /* ----------------------------------------------------------------- */
2736 /* Privilege and capability handling */
2738 /* 1. Running not as root or suid root; no special capabilities. */
2741 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
2744 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
2746 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
2747 /* capabilities; Drop all other capabilities; */
2748 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2749 /* else: after pcap_open_live() in capture_loop_open_input() */
2750 /* drop all capabilities (NET_RAW and NET_ADMIN); */
2751 /* (Note: this means that the process, although logged in */
2752 /* as root, does not have various permissions such as the */
2753 /* ability to bypass file access permissions). */
2754 /* XXX: Should we just leave capabilities alone in this case */
2755 /* so that user gets expected effect that root can do */
2758 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
2760 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2761 /* else: after pcap_open_live() in capture_loop_open_input() */
2762 /* drop suid root (set euid=ruid).(ie: keep suid until after */
2763 /* pcap_open_live). */
2765 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
2767 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
2768 /* capabilities; Drop all other capabilities; */
2769 /* Drop suid privileges (euid=ruid); */
2770 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2771 /* else: after pcap_open_live() in capture_loop_open_input() */
2772 /* drop all capabilities (NET_RAW and NET_ADMIN). */
2774 /* XXX: For some Linux versions/distros with capabilities */
2775 /* a 'normal' process with any capabilities cannot be */
2776 /* 'killed' (signaled) from another (same uid) non-privileged */
2778 /* For example: If (non-suid) Wireshark forks a */
2779 /* child suid dumpcap which acts as described here (case 5), */
2780 /* Wireshark will be unable to kill (signal) the child */
2781 /* dumpcap process until the capabilities have been dropped */
2782 /* (after pcap_open_live()). */
2783 /* This behaviour will apparently be changed in the kernel */
2784 /* to allow the kill (signal) in this case. */
2785 /* See the following for details: */
2786 /* http://www.mail-archive.com/ [wrapped] */
2787 /* linux-security-module@vger.kernel.org/msg02913.html */
2789 /* It is therefore conceivable that if dumpcap somehow hangs */
2790 /* in pcap_open_live or before that wireshark will not */
2791 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
2792 /* In this case, exiting wireshark will kill the child */
2793 /* dumpcap process. */
2795 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
2796 /* capabilities; Using libcap. Note: capset cmd (which see) */
2797 /* used to assign capabilities to file. */
2799 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2800 /* else: after pcap_open_live() in capture_loop_open_input() */
2801 /* drop all capabilities (NET_RAW and NET_ADMIN) */
2803 /* ToDo: -S (stats) should drop privileges/capabilities when no */
2804 /* longer required (similar to capture). */
2806 /* ----------------------------------------------------------------- */
2808 get_credential_info();
2811 /* If 'started with special privileges' (and using libcap) */
2812 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
2813 /* Set euid/egid = ruid/rgid to remove suid privileges */
2814 relinquish_privs_except_capture();
2817 /* Set the initial values in the capture options. This might be overwritten
2818 by the command line parameters. */
2819 capture_opts_init(&global_capture_opts, NULL);
2821 /* Default to capturing the entire packet. */
2822 global_capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
2824 /* We always save to a file - if no file was specified, we save to a
2826 global_capture_opts.saving_to_file = TRUE;
2827 global_capture_opts.has_ring_num_files = TRUE;
2829 /* Now get our args */
2830 while ((opt = getopt(argc, argv, optstring)) != -1) {
2832 case 'h': /* Print help and exit */
2836 case 'v': /* Show version and exit */
2838 GString *comp_info_str;
2839 GString *runtime_info_str;
2840 /* Assemble the compile-time version information string */
2841 comp_info_str = g_string_new("Compiled ");
2842 get_compiled_version_info(comp_info_str, NULL);
2844 /* Assemble the run-time version information string */
2845 runtime_info_str = g_string_new("Running ");
2846 get_runtime_version_info(runtime_info_str, NULL);
2847 show_version(comp_info_str, runtime_info_str);
2848 g_string_free(comp_info_str, TRUE);
2849 g_string_free(runtime_info_str, TRUE);
2853 /*** capture option specific ***/
2854 case 'a': /* autostop criteria */
2855 case 'b': /* Ringbuffer option */
2856 case 'c': /* Capture x packets */
2857 case 'f': /* capture filter */
2858 case 'i': /* Use interface x */
2859 case 'n': /* Use pcapng format */
2860 case 'p': /* Don't capture in promiscuous mode */
2861 case 's': /* Set the snapshot (capture) length */
2862 case 'w': /* Write to capture file x */
2863 case 'y': /* Set the pcap data link type */
2864 #ifdef HAVE_PCAP_REMOTE
2865 case 'u': /* Use UDP for data transfer */
2866 case 'r': /* Capture own RPCAP traffic too */
2867 case 'A': /* Authentication */
2869 #ifdef HAVE_PCAP_SETSAMPLING
2870 case 'm': /* Sampling */
2873 case 'B': /* Buffer size */
2875 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
2880 /*** hidden option: Wireshark child mode (using binary output messages) ***/
2882 capture_child = TRUE;
2884 /* set output pipe to binary mode, to avoid ugly text conversions */
2885 _setmode(2, O_BINARY);
2887 * optarg = the control ID, aka the PPID, currently used for the
2890 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
2891 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
2892 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
2893 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
2895 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
2896 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2897 "Signal pipe: Unable to open %s. Dead parent?",
2905 /*** all non capture option specific ***/
2906 case 'D': /* Print a list of capture devices and exit */
2907 list_interfaces = TRUE;
2910 case 'L': /* Print list of link-layer types and exit */
2911 list_link_layer_types = TRUE;
2914 case 'S': /* Print interface statistics once a second */
2915 print_statistics = TRUE;
2918 case 'M': /* For -D and -L, print machine-readable output */
2919 machine_readable = TRUE;
2922 case '?': /* Bad flag - print usage message */
2923 cmdarg_err("Invalid Option: %s", argv[optind-1]);
2931 /* user specified file name as regular command-line argument */
2932 /* XXX - use it as the capture file name (or something else)? */
2939 * Extra command line arguments were specified; complain.
2940 * XXX - interpret as capture filter, as tcpdump and tshark do?
2942 cmdarg_err("Invalid argument: %s", argv[0]);
2951 if (run_once_args > 1) {
2952 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
2954 } else if (list_link_layer_types) {
2955 /* We're supposed to list the link-layer types for an interface;
2956 did the user also specify a capture file to be read? */
2957 /* No - did they specify a ring buffer option? */
2958 if (global_capture_opts.multi_files_on) {
2959 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
2963 /* No - was the ring buffer option specified and, if so, does it make
2965 if (global_capture_opts.multi_files_on) {
2966 /* Ring buffer works only under certain conditions:
2967 a) ring buffer does not work with temporary files;
2968 b) it makes no sense to enable the ring buffer if the maximum
2969 file size is set to "infinite". */
2970 if (global_capture_opts.save_file == NULL) {
2971 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
2972 global_capture_opts.multi_files_on = FALSE;
2974 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
2975 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
2976 /* XXX - this must be redesigned as the conditions changed */
2977 /* global_capture_opts.multi_files_on = FALSE;*/
2982 if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
2983 /* cmdarg_err() already called .... */
2987 /* Let the user know what interface was chosen. */
2988 /* get_interface_descriptive_name() is not available! */
2989 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", global_capture_opts.iface);
2991 if (list_interfaces) {
2992 status = capture_opts_list_interfaces(machine_readable);
2994 } else if (list_link_layer_types) {
2995 status = capture_opts_list_link_layer_types(&global_capture_opts, machine_readable);
2997 } else if (print_statistics) {
2998 status = print_statistics_loop(machine_readable);
3002 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
3003 capture_opts_trim_ring_num_files(&global_capture_opts);
3005 /* Now start the capture. */
3007 if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
3011 /* capture failed */
3018 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
3019 const char *message, gpointer user_data _U_)
3026 /* ignore log message, if log_level isn't interesting */
3027 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3028 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
3033 /* create a "timestamp" */
3035 today = localtime(&curr);
3037 switch(log_level & G_LOG_LEVEL_MASK) {
3038 case G_LOG_LEVEL_ERROR:
3041 case G_LOG_LEVEL_CRITICAL:
3044 case G_LOG_LEVEL_WARNING:
3047 case G_LOG_LEVEL_MESSAGE:
3050 case G_LOG_LEVEL_INFO:
3053 case G_LOG_LEVEL_DEBUG:
3057 fprintf(stderr, "unknown log_level %u\n", log_level);
3059 g_assert_not_reached();
3062 /* Generate the output message */
3063 if(log_level & G_LOG_LEVEL_MESSAGE) {
3064 /* normal user messages without additional infos */
3065 msg = g_strdup_printf("%s\n", message);
3067 /* info/debug messages with additional infos */
3068 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
3069 today->tm_hour, today->tm_min, today->tm_sec,
3070 log_domain != NULL ? log_domain : "",
3074 /* DEBUG & INFO msgs (if we're debugging today) */
3075 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3076 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3077 #ifdef DEBUG_DUMPCAP
3078 fprintf(stderr, "%s", msg);
3081 #ifdef DEBUG_CHILD_DUMPCAP
3082 fprintf(debug_log, "%s", msg);
3090 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
3091 /* to parent especially formatted if dumpcap running as child. */
3092 if (capture_child) {
3093 sync_pipe_errmsg_to_parent(2, msg, "");
3095 fprintf(stderr, "%s", msg);
3102 /****************************************************************************************************************/
3103 /* indication report routines */
3107 report_packet_count(int packet_count)
3109 char tmp[SP_DECISIZE+1+1];
3110 static int count = 0;
3113 g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
3114 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
3115 pipe_write_block(2, SP_PACKET_COUNT, tmp);
3117 count += packet_count;
3118 fprintf(stderr, "\rPackets: %u ", count);
3119 /* stderr could be line buffered */
3125 report_new_capture_file(const char *filename)
3128 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
3129 pipe_write_block(2, SP_FILE, filename);
3131 fprintf(stderr, "File: %s\n", filename);
3132 /* stderr could be line buffered */
3138 report_cfilter_error(const char *cfilter, const char *errmsg)
3140 if (capture_child) {
3141 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
3142 pipe_write_block(2, SP_BAD_FILTER, errmsg);
3145 "Invalid capture filter: \"%s\"!\n"
3147 "That string isn't a valid capture filter (%s).\n"
3148 "See the User's Guide for a description of the capture filter syntax.\n",
3154 report_capture_error(const char *error_msg, const char *secondary_error_msg)
3157 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3158 "Primary Error: %s", error_msg);
3159 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3160 "Secondary Error: %s", secondary_error_msg);
3161 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
3163 fprintf(stderr, "%s\n%s\n", error_msg, secondary_error_msg);
3168 report_packet_drops(guint32 drops)
3170 char tmp[SP_DECISIZE+1+1];
3172 g_snprintf(tmp, sizeof(tmp), "%u", drops);
3175 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
3176 pipe_write_block(2, SP_DROPS, tmp);
3178 fprintf(stderr, "Packets dropped: %s\n", tmp);
3179 /* stderr could be line buffered */
3185 /****************************************************************************************************************/
3186 /* signal_pipe handling */
3191 signal_pipe_check_running(void)
3193 /* any news from our parent? -> just stop the capture */
3197 /* if we are running standalone, no check required */
3198 if(!capture_child) {
3202 if(!sig_pipe_name || !sig_pipe_handle) {
3203 /* This shouldn't happen */
3204 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3205 "Signal pipe: No name or handle");
3210 * XXX - We should have the process ID of the parent (from the "-Z" flag)
3211 * at this point. Should we check to see if the parent is still alive,
3212 * e.g. by using OpenProcess?
3215 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
3217 if(!result || avail > 0) {
3218 /* peek failed or some bytes really available */
3219 /* (if not piping from stdin this would fail) */
3220 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3221 "Signal pipe: Stop capture: %s", sig_pipe_name);
3222 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3223 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
3224 sig_pipe_handle, result, avail);
3227 /* pipe ok and no bytes available */
3234 * Editor modelines - http://www.wireshark.org/tools/modelines.html
3239 * indent-tabs-mode: nil
3242 * vi: set shiftwidth=4 tabstop=8 expandtab
3243 * :indentSize=4:tabSize=8:noTabs=true: