5 * Wireshark - Network traffic analyzer
6 * By Gerald Combs <gerald@wireshark.org>
7 * Copyright 1998 Gerald Combs
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 #include <stdlib.h> /* for exit() */
35 #ifdef HAVE_SYS_TYPES_H
36 # include <sys/types.h>
39 #ifdef HAVE_SYS_STAT_H
40 # include <sys/stat.h>
63 # include <sys/prctl.h>
64 # include <sys/capability.h>
67 #include "ringbuffer.h"
68 #include "clopts_common.h"
69 #include "cmdarg_err.h"
70 #include "version_info.h"
75 #include "capture-pcap-util.h"
78 #include "capture-wpcap.h"
79 #include <wsutil/unicode-utils.h>
82 #include <wsutil/privileges.h>
84 #include "sync_pipe.h"
86 #include "capture_opts.h"
87 #include "capture_sync.h"
89 #include "conditions.h"
90 #include "capture_stop_conditions.h"
94 #include "wsutil/file_util.h"
97 * Get information about libpcap format from "wiretap/libpcap.h".
98 * XXX - can we just use pcap_open_offline() to read the pipe?
100 #include "wiretap/libpcap.h"
102 /**#define DEBUG_DUMPCAP**/
103 /**#define DEBUG_CHILD_DUMPCAP**/
105 #ifdef DEBUG_CHILD_DUMPCAP
106 FILE *debug_log; /* for logging debug messages to */
107 /* a file if DEBUG_CHILD_DUMPCAP */
115 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
117 static gchar *sig_pipe_name = NULL;
118 static HANDLE sig_pipe_handle = NULL;
119 static gboolean signal_pipe_check_running(void);
123 static GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
124 static GMutex *cap_pipe_read_mtx;
127 /** Stop a low-level capture (stops the capture child). */
128 static void capture_loop_stop(void);
130 #if !defined (__linux__)
131 #ifndef HAVE_PCAP_BREAKLOOP
133 * We don't have pcap_breakloop(), which is the only way to ensure that
134 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
135 * won't, if the call to read the next packet or batch of packets is
136 * is interrupted by a signal on UN*X, just go back and try again to
139 * On UN*X, we catch SIGUSR1 as a "stop capturing" signal, and, in
140 * the signal handler, set a flag to stop capturing; however, without
141 * a guarantee of that sort, we can't guarantee that we'll stop capturing
142 * if the read will be retried and won't time out if no packets arrive.
144 * Therefore, on at least some platforms, we work around the lack of
145 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
146 * to wait for packets to arrive, so that we're probably going to be
147 * blocked in the select() when the signal arrives, and can just bail
148 * out of the loop at that point.
150 * However, we don't want to that on BSD (because "select()" doesn't work
151 * correctly on BPF devices on at least some releases of some flavors of
152 * BSD), and we don't want to do it on Windows (because "select()" is
153 * something for sockets, not for arbitrary handles). (Note that "Windows"
154 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
155 * using WinPcap, not a UNIX libpcap.)
157 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
158 * on BSD times out even if no packets have arrived, so we'll eventually
159 * exit pcap_dispatch() with an indication that no packets have arrived,
160 * and will break out of the capture loop at that point.
162 * On Windows, we can't send a SIGUSR1 to stop capturing, so none of this
163 * applies in any case.
165 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
166 * want to include it if it's not present on this platform, however.
168 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
169 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
171 # define MUST_DO_SELECT
172 # endif /* avoid select */
173 #endif /* HAVE_PCAP_BREAKLOOP */
175 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
176 * in pcap_dispatch(); on the other hand, select() works just fine there.
177 * Hence we use a select for that come what may.
179 #define MUST_DO_SELECT
182 /** init the capture filter */
185 INITFILTER_BAD_FILTER,
186 INITFILTER_OTHER_ERROR
187 } initfilter_status_t;
189 typedef struct _loop_data {
191 gboolean go; /* TRUE as long as we're supposed to keep capturing */
192 int err; /* if non-zero, error seen while capturing */
193 gint packet_count; /* Number of packets we have already captured */
194 gint packet_max; /* Number of packets we're supposed to capture - 0 means infinite */
196 /* pcap "input file" */
197 pcap_t *pcap_h; /* pcap handle */
198 gboolean pcap_err; /* TRUE if error from pcap */
199 #ifdef MUST_DO_SELECT
200 int pcap_fd; /* pcap file descriptor */
203 /* capture pipe (unix only "input file") */
204 gboolean from_cap_pipe; /* TRUE if we are capturing data from a capture pipe */
205 struct pcap_hdr cap_pipe_hdr; /* Pcap header when capturing from a pipe */
206 struct pcaprec_modified_hdr cap_pipe_rechdr; /* Pcap record header when capturing from a pipe */
208 HANDLE cap_pipe_h; /* The handle of the capture pipe */
210 int cap_pipe_fd; /* the file descriptor of the capture pipe */
212 gboolean cap_pipe_modified; /* TRUE if data in the pipe uses modified pcap headers */
213 gboolean cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
215 char * cap_pipe_buf; /* Pointer to the data buffer we read into */
216 #endif /* USE_THREADS */
217 int cap_pipe_bytes_to_read;/* Used by cap_pipe_dispatch */
218 int cap_pipe_bytes_read; /* Used by cap_pipe_dispatch */
220 STATE_EXPECT_REC_HDR,
225 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
237 * Standard secondary message for unexpected errors.
239 static const char please_report[] =
240 "Please report this to the Wireshark developers.\n"
241 "(This is not a crash; please do not report it as such.)";
244 * This needs to be static, so that the SIGUSR1 handler can clear the "go"
247 static loop_data global_ld;
251 * Timeout, in milliseconds, for reads from the stream of captured packets.
253 #if defined(__APPLE__) && defined(__LP64__)
254 #define CAP_READ_TIMEOUT 1000
256 #define CAP_READ_TIMEOUT 250
259 * Timeout, in microseconds, for threaded reads from a pipe.
261 #define THREAD_READ_TIMEOUT 100
262 static char *cap_pipe_err_str;
265 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
266 const char *message, gpointer user_data _U_);
268 /* capture related options */
269 static capture_options global_capture_opts;
271 static void capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
273 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
274 int err, gboolean is_close);
278 static void exit_main(int err) __attribute__ ((noreturn));
280 static void exit_main(int err);
283 static void report_new_capture_file(const char *filename);
284 static void report_packet_count(int packet_count);
285 static void report_packet_drops(guint32 drops);
286 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
287 static void report_cfilter_error(const char *cfilter, const char *errmsg);
290 print_usage(gboolean print_ver) {
298 "Dumpcap " VERSION "%s\n"
299 "Capture network packets and dump them into a libpcap file.\n"
300 "See http://www.wireshark.org for more information.\n",
301 wireshark_svnversion);
305 fprintf(output, "\nUsage: dumpcap [options] ...\n");
306 fprintf(output, "\n");
307 fprintf(output, "Capture interface:\n");
308 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
309 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
310 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
311 fprintf(output, " -p don't capture in promiscuous mode\n");
313 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
315 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
316 fprintf(output, " -D print list of interfaces and exit\n");
317 fprintf(output, " -L print list of link-layer types of iface and exit\n");
318 fprintf(output, " -S print statistics for each interface once every second\n");
319 fprintf(output, " -M for -D, -L, and -S produce machine-readable output\n");
320 fprintf(output, "\n");
321 #ifdef HAVE_PCAP_REMOTE
322 fprintf(output, "\nRPCAP options:\n");
323 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
324 fprintf(output, " -u use UDP for RPCAP data transfer\n");
325 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
326 #ifdef HAVE_PCAP_SETSAMPLING
327 fprintf(output, " -m <sampling type> use packet sampling\n");
328 fprintf(output, " count:NUM - capture one packet of every NUM\n");
329 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
332 fprintf(output, "Stop conditions:\n");
333 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
334 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
335 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
336 fprintf(output, " files:NUM - stop after NUM files\n");
337 /*fprintf(output, "\n");*/
338 fprintf(output, "Output (files):\n");
339 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
340 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
341 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
342 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
343 fprintf(output, " -n use pcapng format instead of pcap\n");
344 /*fprintf(output, "\n");*/
345 fprintf(output, "Miscellaneous:\n");
346 fprintf(output, " -v print version information and exit\n");
347 fprintf(output, " -h display this help and exit\n");
348 fprintf(output, "\n");
349 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcap\n");
350 fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcap\"\n");
351 fprintf(output, "\n");
352 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
356 show_version(GString *comp_info_str, GString *runtime_info_str)
360 "Dumpcap " VERSION "%s\n"
365 "See http://www.wireshark.org for more information.\n",
366 wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
370 * Report an error in command-line arguments.
373 cmdarg_err(const char *fmt, ...)
379 /* Generate a 'special format' message back to parent */
381 msg = g_strdup_vprintf(fmt, ap);
382 sync_pipe_errmsg_to_parent(2, msg, "");
387 fprintf(stderr, "dumpcap: ");
388 vfprintf(stderr, fmt, ap);
389 fprintf(stderr, "\n");
395 * Report additional information for an error in command-line arguments.
398 cmdarg_err_cont(const char *fmt, ...)
405 msg = g_strdup_vprintf(fmt, ap);
406 sync_pipe_errmsg_to_parent(2, msg, "");
411 vfprintf(stderr, fmt, ap);
412 fprintf(stderr, "\n");
422 /* Print the number of packets captured for each interface until we're killed. */
424 print_statistics_loop(gboolean machine_readable)
426 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
432 char errbuf[PCAP_ERRBUF_SIZE];
435 if_list = get_interface_list(&err, &err_str);
436 if (if_list == NULL) {
438 case CANT_GET_INTERFACE_LIST:
439 cmdarg_err("%s", err_str);
443 case NO_INTERFACES_FOUND:
444 cmdarg_err("There are no interfaces on which a capture can be done");
450 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
451 if_info = if_entry->data;
452 #ifdef HAVE_PCAP_OPEN
453 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
455 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
459 if_stat = g_malloc(sizeof(if_stat_t));
460 if_stat->name = g_strdup(if_info->name);
462 stat_list = g_list_append(stat_list, if_stat);
467 cmdarg_err("There are no interfaces on which a capture can be done");
471 if (!machine_readable) {
472 printf("%-15s %10s %10s\n", "Interface", "Received",
477 while (global_ld.go) {
478 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
479 if_stat = stat_entry->data;
480 pcap_stats(if_stat->pch, &ps);
482 if (!machine_readable) {
483 printf("%-15s %10u %10u\n", if_stat->name,
484 ps.ps_recv, ps.ps_drop);
486 printf("%s\t%u\t%u\n", if_stat->name,
487 ps.ps_recv, ps.ps_drop);
492 if (! global_ld.from_cap_pipe)
499 /* XXX - Not reached. Should we look for 'q' in stdin? */
500 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
501 if_stat = stat_entry->data;
502 pcap_close(if_stat->pch);
503 g_free(if_stat->name);
506 g_list_free(stat_list);
507 free_interface_list(if_list);
515 capture_cleanup(DWORD dwCtrlType)
517 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
518 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
519 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
520 like SIGTERM at least when the machine's shutting down.
522 For now, if we're running as a command rather than a capture child,
523 we handle all but CTRL_LOGOFF_EVENT as indications that we should
524 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
527 If we're not running as a capture child, we might be running as
528 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
529 user logs out. (XXX - can we explicitly check whether we're
530 running as a service?) */
532 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
533 "Console: Control signal");
534 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
535 "Console: Control signal, CtrlType: %u", dwCtrlType);
537 /* Keep capture running if we're a service and a user logs off */
538 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
547 capture_cleanup(int signum)
549 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
550 SIGTERM. We assume that if the user wanted it to keep running
551 after they logged out, they'd have nohupped it. */
553 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
555 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
556 "Console: Signal, signal value: %u", signum);
562 static void exit_main(int status)
565 /* Shutdown windows sockets */
568 /* can be helpful for debugging */
570 printf("Press any key\n");
581 * If we were linked with libcap (not libpcap), make sure we have
582 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
583 * (See comment in main() for details)
587 #if 0 /* Set to enable capability debugging */
588 /* see 'man cap_to_text()' for explanation of output */
589 /* '=' means 'all= ' ie: no capabilities */
590 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
592 print_caps(char *pfx) {
593 cap_t caps = cap_get_proc();
594 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
595 "%s: EUID: %d Capabilities: %s", pfx,
596 geteuid(), cap_to_text(caps, NULL));
599 print_caps(char *pfx _U_) {
604 relinquish_privs_except_capture(void)
606 /* If 'started_with_special_privs' (ie: suid) then enable for
607 * ourself the NET_ADMIN and NET_RAW capabilities and then
608 * drop our suid privileges.
610 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
611 * stuff we don't need (and shouldn't have).
612 * CAP_NET_RAW: Packet capture (raw sockets).
615 if (started_with_special_privs()) {
616 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
617 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
619 cap_t caps = cap_init(); /* all capabilities initialized to off */
621 print_caps("Pre drop, pre set");
623 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
624 cmdarg_err("prctl() fail return: %s", strerror(errno));
627 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
628 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
630 if (cap_set_proc(caps)) {
631 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
633 print_caps("Pre drop, post set");
635 relinquish_special_privs_perm();
637 print_caps("Post drop, pre set");
638 cap_set_flag(caps, CAP_EFFECTIVE, 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("Post drop, post set");
650 relinquish_all_capabilities()
652 /* Drop any and all capabilities this process may have. */
653 /* Allowed whether or not process has any privileges. */
654 cap_t caps = cap_init(); /* all capabilities initialized to off */
655 print_caps("Pre-clear");
656 if (cap_set_proc(caps)) {
657 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
659 print_caps("Post-clear");
663 #endif /* HAVE_LIBCAP */
665 /* Take care of byte order in the libpcap headers read from pipes.
666 * (function taken from wiretap/libpcap.c) */
668 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
671 /* Byte-swap the record header fields. */
672 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
673 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
674 rechdr->incl_len = BSWAP32(rechdr->incl_len);
675 rechdr->orig_len = BSWAP32(rechdr->orig_len);
678 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
679 swapped, in order to match the BPF header layout.
681 Unfortunately, some files were, according to a comment in the "libpcap"
682 source, written with version 2.3 in their headers but without the
683 interchanged fields, so if "incl_len" is greater than "orig_len" - which
684 would make no sense - we assume that we need to swap them. */
685 if (hdr->version_major == 2 &&
686 (hdr->version_minor < 3 ||
687 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
690 temp = rechdr->orig_len;
691 rechdr->orig_len = rechdr->incl_len;
692 rechdr->incl_len = temp;
698 * Thread function that reads from a pipe and pushes the data
699 * to the main application thread.
702 * XXX Right now we use async queues for basic signaling. The main thread
703 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
704 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
705 * Iff the read is successful cap_pipe_read pushes an item onto
706 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
707 * the queues themselves (yet).
709 * We might want to move some of the cap_pipe_dispatch logic here so that
710 * we can let cap_pipe_read run independently, queuing up multiple reads
711 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
713 static void *cap_pipe_read(void *ld_ptr) {
714 loop_data *ld = (loop_data *)ld_ptr;
723 while (ld->cap_pipe_err == PIPOK) {
724 g_async_queue_pop(cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
725 g_mutex_lock(cap_pipe_read_mtx);
727 while (bytes_read < (int) ld->cap_pipe_bytes_to_read) {
729 /* If we try to use read() on a named pipe on Windows with partial
730 * data it appears to return EOF.
732 res = ReadFile(ld->cap_pipe_h, ld->cap_pipe_buf+bytes_read,
733 ld->cap_pipe_bytes_to_read - bytes_read,
738 last_err = GetLastError();
739 if (last_err == ERROR_MORE_DATA) {
741 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
742 ld->cap_pipe_err = PIPEOF;
746 ld->cap_pipe_err = PIPERR;
749 } else if (b == 0 && ld->cap_pipe_bytes_to_read > 0) {
750 ld->cap_pipe_err = PIPEOF;
755 b = read(ld->cap_pipe_fd, ld->cap_pipe_buf+bytes_read,
756 ld->cap_pipe_bytes_to_read - bytes_read);
759 ld->cap_pipe_err = PIPEOF;
763 ld->cap_pipe_err = PIPERR;
772 ld->cap_pipe_bytes_read = bytes_read;
773 if (ld->cap_pipe_bytes_read >= ld->cap_pipe_bytes_to_read) {
774 g_async_queue_push(cap_pipe_done_q, ld->cap_pipe_buf); /* Any non-NULL value will do */
776 g_mutex_unlock(cap_pipe_read_mtx);
780 #endif /* USE_THREADS */
782 /* Provide select() functionality for a single file descriptor
783 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
785 * Returns the same values as select. If an error is returned,
786 * the string cap_pipe_err_str should be used instead of errno.
789 cap_pipe_select(int pipe_fd) {
791 struct timeval timeout, *pto;
794 cap_pipe_err_str = "Unknown error";
797 FD_SET(pipe_fd, &rfds);
800 timeout.tv_usec = CAP_READ_TIMEOUT * 1000;
803 sel_ret = select(pipe_fd+1, &rfds, NULL, NULL, pto);
805 cap_pipe_err_str = strerror(errno);
810 /* Mimic pcap_open_live() for pipe captures
811 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
813 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
814 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
816 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
817 char *errmsg, int errmsgl)
820 struct stat pipe_stat;
823 unsigned int bytes_read;
834 ld->cap_pipe_fd = -1;
836 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
838 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
841 * XXX (T)Wireshark blocks until we return
843 if (strcmp(pipename, "-") == 0) {
845 fd = 0; /* read from stdin */
847 ld->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
851 if (ws_stat(pipename, &pipe_stat) < 0) {
852 if (errno == ENOENT || errno == ENOTDIR)
853 ld->cap_pipe_err = PIPNEXIST;
855 g_snprintf(errmsg, errmsgl,
856 "The capture session could not be initiated "
857 "due to error on pipe: %s", strerror(errno));
858 ld->cap_pipe_err = PIPERR;
862 if (! S_ISFIFO(pipe_stat.st_mode)) {
863 if (S_ISCHR(pipe_stat.st_mode)) {
865 * Assume the user specified an interface on a system where
866 * interfaces are in /dev. Pretend we haven't seen it.
868 ld->cap_pipe_err = PIPNEXIST;
871 g_snprintf(errmsg, errmsgl,
872 "The capture session could not be initiated because\n"
873 "\"%s\" is neither an interface nor a pipe", pipename);
874 ld->cap_pipe_err = PIPERR;
878 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
880 g_snprintf(errmsg, errmsgl,
881 "The capture session could not be initiated "
882 "due to error on pipe open: %s", strerror(errno));
883 ld->cap_pipe_err = PIPERR;
887 #define PIPE_STR "\\pipe\\"
888 /* Under Windows, named pipes _must_ have the form
889 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
891 pncopy = g_strdup(pipename);
892 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
893 pos = strchr(pncopy + 3, '\\');
894 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
901 g_snprintf(errmsg, errmsgl,
902 "The capture session could not be initiated because\n"
903 "\"%s\" is neither an interface nor a pipe", pipename);
904 ld->cap_pipe_err = PIPNEXIST;
908 /* Wait for the pipe to appear */
910 ld->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
911 OPEN_EXISTING, 0, NULL);
913 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE)
916 if (GetLastError() != ERROR_PIPE_BUSY) {
917 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
918 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
919 g_snprintf(errmsg, errmsgl,
920 "The capture session on \"%s\" could not be started "
921 "due to error on pipe open: %s (error %d)",
922 pipename, utf_16to8(err_str), GetLastError());
924 ld->cap_pipe_err = PIPERR;
928 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
929 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
930 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
931 g_snprintf(errmsg, errmsgl,
932 "The capture session on \"%s\" timed out during "
933 "pipe open: %s (error %d)",
934 pipename, utf_16to8(err_str), GetLastError());
936 ld->cap_pipe_err = PIPERR;
944 ld->from_cap_pipe = TRUE;
947 /* read the pcap header */
949 while (bytes_read < sizeof magic) {
950 sel_ret = cap_pipe_select(fd);
952 g_snprintf(errmsg, errmsgl,
953 "Unexpected error from select: %s", strerror(errno));
955 } else if (sel_ret > 0) {
956 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
959 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
961 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
968 #else /* USE_THREADS */
969 g_thread_create(&cap_pipe_read, ld, FALSE, NULL);
971 ld->cap_pipe_buf = (char *) &magic;
972 ld->cap_pipe_bytes_read = 0;
973 ld->cap_pipe_bytes_to_read = sizeof(magic);
974 /* We don't have to worry about cap_pipe_read_mtx here */
975 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
976 g_async_queue_pop(cap_pipe_done_q);
977 if (ld->cap_pipe_bytes_read <= 0) {
978 if (ld->cap_pipe_bytes_read == 0)
979 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
981 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
985 #endif /* USE_THREADS */
989 /* Host that wrote it has our byte order, and was running
990 a program using either standard or ss990417 libpcap. */
991 ld->cap_pipe_byte_swapped = FALSE;
992 ld->cap_pipe_modified = FALSE;
994 case PCAP_MODIFIED_MAGIC:
995 /* Host that wrote it has our byte order, but was running
996 a program using either ss990915 or ss991029 libpcap. */
997 ld->cap_pipe_byte_swapped = FALSE;
998 ld->cap_pipe_modified = TRUE;
1000 case PCAP_SWAPPED_MAGIC:
1001 /* Host that wrote it has a byte order opposite to ours,
1002 and was running a program using either standard or
1003 ss990417 libpcap. */
1004 ld->cap_pipe_byte_swapped = TRUE;
1005 ld->cap_pipe_modified = FALSE;
1007 case PCAP_SWAPPED_MODIFIED_MAGIC:
1008 /* Host that wrote it out has a byte order opposite to
1009 ours, and was running a program using either ss990915
1010 or ss991029 libpcap. */
1011 ld->cap_pipe_byte_swapped = TRUE;
1012 ld->cap_pipe_modified = TRUE;
1015 /* Not a "libpcap" type we know about. */
1016 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
1021 /* Read the rest of the header */
1023 while (bytes_read < sizeof(struct pcap_hdr)) {
1024 sel_ret = cap_pipe_select(fd);
1026 g_snprintf(errmsg, errmsgl,
1027 "Unexpected error from select: %s", strerror(errno));
1029 } else if (sel_ret > 0) {
1030 b = read(fd, ((char *)hdr)+bytes_read,
1031 sizeof(struct pcap_hdr) - bytes_read);
1034 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1036 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
1043 #else /* USE_THREADS */
1044 ld->cap_pipe_buf = (char *) hdr;
1045 ld->cap_pipe_bytes_read = 0;
1046 ld->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1047 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1048 g_async_queue_pop(cap_pipe_done_q);
1049 if (ld->cap_pipe_bytes_read <= 0) {
1050 if (ld->cap_pipe_bytes_read == 0)
1051 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1053 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
1057 #endif /* USE_THREADS */
1059 if (ld->cap_pipe_byte_swapped) {
1060 /* Byte-swap the header fields about which we care. */
1061 hdr->version_major = BSWAP16(hdr->version_major);
1062 hdr->version_minor = BSWAP16(hdr->version_minor);
1063 hdr->snaplen = BSWAP32(hdr->snaplen);
1064 hdr->network = BSWAP32(hdr->network);
1066 ld->linktype = hdr->network;
1068 if (hdr->version_major < 2) {
1069 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1073 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1074 ld->cap_pipe_err = PIPOK;
1076 ld->cap_pipe_fd = fd;
1081 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1082 ld->cap_pipe_err = PIPERR;
1085 ld->cap_pipe_fd = -1;
1092 /* We read one record from the pipe, take care of byte order in the record
1093 * header, write the record to the capture file, and update capture statistics. */
1095 cap_pipe_dispatch(loop_data *ld, guchar *data, char *errmsg, int errmsgl)
1097 struct pcap_pkthdr phdr;
1098 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1110 #ifdef LOG_CAPTURE_VERBOSE
1111 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1114 switch (ld->cap_pipe_state) {
1116 case STATE_EXPECT_REC_HDR:
1118 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1121 ld->cap_pipe_state = STATE_READ_REC_HDR;
1122 ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
1123 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1124 ld->cap_pipe_bytes_read = 0;
1127 ld->cap_pipe_buf = (char *) &ld->cap_pipe_rechdr;
1128 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1129 g_mutex_unlock(cap_pipe_read_mtx);
1134 case STATE_READ_REC_HDR:
1136 b = read(ld->cap_pipe_fd, ((char *)&ld->cap_pipe_rechdr)+ld->cap_pipe_bytes_read,
1137 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1140 result = PD_PIPE_EOF;
1142 result = PD_PIPE_ERR;
1145 ld->cap_pipe_bytes_read += b;
1146 #else /* USE_THREADS */
1147 g_get_current_time(&wait_time);
1148 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1149 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1150 if (ld->cap_pipe_err == PIPEOF) {
1151 result = PD_PIPE_EOF;
1153 } else if (ld->cap_pipe_err == PIPERR) {
1154 result = PD_PIPE_ERR;
1160 #endif /* USE_THREADS */
1161 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1163 result = PD_REC_HDR_READ;
1166 case STATE_EXPECT_DATA:
1168 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1171 ld->cap_pipe_state = STATE_READ_DATA;
1172 ld->cap_pipe_bytes_to_read = ld->cap_pipe_rechdr.hdr.incl_len;
1173 ld->cap_pipe_bytes_read = 0;
1176 ld->cap_pipe_buf = (char *) data;
1177 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1178 g_mutex_unlock(cap_pipe_read_mtx);
1183 case STATE_READ_DATA:
1185 b = read(ld->cap_pipe_fd, data+ld->cap_pipe_bytes_read,
1186 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1189 result = PD_PIPE_EOF;
1191 result = PD_PIPE_ERR;
1194 ld->cap_pipe_bytes_read += b;
1195 #else /* USE_THREADS */
1196 g_get_current_time(&wait_time);
1197 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1198 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1199 if (ld->cap_pipe_err == PIPEOF) {
1200 result = PD_PIPE_EOF;
1202 } else if (ld->cap_pipe_err == PIPERR) {
1203 result = PD_PIPE_ERR;
1209 #endif /* USE_THREADS */
1210 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1212 result = PD_DATA_READ;
1216 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
1219 } /* switch (ld->cap_pipe_state) */
1222 * We've now read as much data as we were expecting, so process it.
1226 case PD_REC_HDR_READ:
1227 /* We've read the header. Take care of byte order. */
1228 cap_pipe_adjust_header(ld->cap_pipe_byte_swapped, &ld->cap_pipe_hdr,
1229 &ld->cap_pipe_rechdr.hdr);
1230 if (ld->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1231 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
1232 ld->packet_count+1, ld->cap_pipe_rechdr.hdr.incl_len);
1235 ld->cap_pipe_state = STATE_EXPECT_DATA;
1239 /* Fill in a "struct pcap_pkthdr", and process the packet. */
1240 phdr.ts.tv_sec = ld->cap_pipe_rechdr.hdr.ts_sec;
1241 phdr.ts.tv_usec = ld->cap_pipe_rechdr.hdr.ts_usec;
1242 phdr.caplen = ld->cap_pipe_rechdr.hdr.incl_len;
1243 phdr.len = ld->cap_pipe_rechdr.hdr.orig_len;
1245 capture_loop_packet_cb((u_char *)ld, &phdr, data);
1247 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1251 ld->cap_pipe_err = PIPEOF;
1256 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1257 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1258 g_snprintf(errmsg, errmsgl,
1259 "Error reading from pipe: %s (error %d)",
1260 utf_16to8(err_str), GetLastError());
1263 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
1271 ld->cap_pipe_err = PIPERR;
1272 /* Return here rather than inside the switch to prevent GCC warning */
1277 /** Open the capture input file (pcap or capture pipe).
1278 * Returns TRUE if it succeeds, FALSE otherwise. */
1280 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
1281 char *errmsg, size_t errmsg_len,
1282 char *secondary_errmsg, size_t secondary_errmsg_len)
1284 gchar open_err_str[PCAP_ERRBUF_SIZE];
1285 gchar *sync_msg_str;
1286 static const char ppamsg[] = "can't find PPA for ";
1287 const char *set_linktype_err_str;
1288 const char *libpcap_warn;
1290 gchar *sync_secondary_msg_str;
1292 WORD wVersionRequested;
1295 #ifdef HAVE_PCAP_REMOTE
1296 struct pcap_rmtauth auth;
1300 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
1303 /* XXX - opening Winsock on tshark? */
1305 /* Initialize Windows Socket if we are in a WIN32 OS
1306 This needs to be done before querying the interface for network/netmask */
1308 /* XXX - do we really require 1.1 or earlier?
1309 Are there any versions that support only 2.0 or higher? */
1310 wVersionRequested = MAKEWORD(1, 1);
1311 err = WSAStartup(wVersionRequested, &wsaData);
1315 case WSASYSNOTREADY:
1316 g_snprintf(errmsg, (gulong) errmsg_len,
1317 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
1320 case WSAVERNOTSUPPORTED:
1321 g_snprintf(errmsg, (gulong) errmsg_len,
1322 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
1323 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
1326 case WSAEINPROGRESS:
1327 g_snprintf(errmsg, (gulong) errmsg_len,
1328 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
1332 g_snprintf(errmsg, (gulong) errmsg_len,
1333 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
1337 g_snprintf(errmsg, (gulong) errmsg_len,
1338 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
1342 g_snprintf(errmsg, (gulong) errmsg_len,
1343 "Couldn't initialize Windows Sockets: error %d", err);
1346 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
1351 /* Open the network interface to capture from it.
1352 Some versions of libpcap may put warnings into the error buffer
1353 if they succeed; to tell if that's happened, we have to clear
1354 the error buffer, and check if it's still a null string. */
1355 open_err_str[0] = '\0';
1356 #ifdef HAVE_PCAP_OPEN
1357 auth.type = capture_opts->auth_type == CAPTURE_AUTH_PWD ?
1358 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
1359 auth.username = capture_opts->auth_username;
1360 auth.password = capture_opts->auth_password;
1362 ld->pcap_h = pcap_open(capture_opts->iface,
1363 capture_opts->has_snaplen ? capture_opts->snaplen :
1364 WTAP_MAX_PACKET_SIZE,
1366 (capture_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
1367 (capture_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
1368 (capture_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
1369 CAP_READ_TIMEOUT, &auth, open_err_str);
1371 ld->pcap_h = pcap_open_live(capture_opts->iface,
1372 capture_opts->has_snaplen ? capture_opts->snaplen :
1373 WTAP_MAX_PACKET_SIZE,
1374 capture_opts->promisc_mode, CAP_READ_TIMEOUT,
1378 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
1379 /* to remove any suid privileges. */
1380 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
1381 /* (euid/egid have already previously been set to ruid/rgid. */
1382 /* (See comment in main() for details) */
1384 relinquish_special_privs_perm();
1386 relinquish_all_capabilities();
1389 if (ld->pcap_h != NULL) {
1390 /* we've opened "iface" as a network device */
1392 /* try to set the capture buffer size */
1393 if (capture_opts->buffer_size > 1 &&
1394 pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
1395 sync_secondary_msg_str = g_strdup_printf(
1396 "The capture buffer size of %luMB seems to be too high for your machine,\n"
1397 "the default of 1MB will be used.\n"
1399 "Nonetheless, the capture is started.\n",
1400 capture_opts->buffer_size);
1401 report_capture_error("Couldn't set the capture buffer size!",
1402 sync_secondary_msg_str);
1403 g_free(sync_secondary_msg_str);
1407 #if defined(HAVE_PCAP_REMOTE) && defined(HAVE_PCAP_SETSAMPLING)
1408 if (capture_opts->sampling_method != CAPTURE_SAMP_NONE)
1410 struct pcap_samp *samp;
1412 if ((samp = pcap_setsampling(ld->pcap_h)) != NULL)
1414 switch (capture_opts->sampling_method)
1416 case CAPTURE_SAMP_BY_COUNT:
1417 samp->method = PCAP_SAMP_1_EVERY_N;
1420 case CAPTURE_SAMP_BY_TIMER:
1421 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
1425 sync_msg_str = g_strdup_printf(
1426 "Unknown sampling method %d specified,\n"
1427 "continue without packet sampling",
1428 capture_opts->sampling_method);
1429 report_capture_error("Couldn't set the capture "
1430 "sampling", sync_msg_str);
1431 g_free(sync_msg_str);
1433 samp->value = capture_opts->sampling_param;
1437 report_capture_error("Couldn't set the capture sampling",
1438 "Cannot get packet sampling data structure");
1444 /* setting the data link type only works on real interfaces */
1445 if (capture_opts->linktype != -1) {
1446 set_linktype_err_str = set_pcap_linktype(ld->pcap_h, capture_opts->iface,
1447 capture_opts->linktype);
1448 if (set_linktype_err_str != NULL) {
1449 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
1450 set_linktype_err_str);
1451 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
1455 ld->linktype = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
1457 /* We couldn't open "iface" as a network device. */
1458 /* Try to open it as a pipe */
1459 cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, (int) errmsg_len);
1462 if (ld->cap_pipe_fd == -1) {
1464 if (ld->cap_pipe_h == INVALID_HANDLE_VALUE) {
1467 if (ld->cap_pipe_err == PIPNEXIST) {
1468 /* Pipe doesn't exist, so output message for interface */
1470 /* If we got a "can't find PPA for X" message, warn the user (who
1471 is running (T)Wireshark on HP-UX) that they don't have a version
1472 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1473 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1474 PPA for X" rather than "can't find PPA for X"). */
1475 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1478 "You are running (T)Wireshark with a version of the libpcap library\n"
1479 "that doesn't handle HP-UX network devices well; this means that\n"
1480 "(T)Wireshark may not be able to capture packets.\n"
1482 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1483 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1484 "packaged binary form from the Software Porting And Archive Centre\n"
1485 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1486 "at the URL lists a number of mirror sites.";
1489 g_snprintf(errmsg, (gulong) errmsg_len,
1490 "The capture session could not be initiated (%s).", open_err_str);
1492 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
1493 "Please check to make sure you have sufficient permissions, and that you have "
1494 "the proper interface or pipe specified.%s", libpcap_warn);
1496 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
1498 "Please check that \"%s\" is the proper interface.\n"
1501 "Help can be found at:\n"
1503 " http://wiki.wireshark.org/WinPcap\n"
1504 " http://wiki.wireshark.org/CaptureSetup\n",
1505 capture_opts->iface);
1509 * Else pipe (or file) does exist and cap_pipe_open_live() has
1514 /* cap_pipe_open_live() succeeded; don't want
1515 error message from pcap_open_live() */
1516 open_err_str[0] = '\0';
1519 /* XXX - will this work for tshark? */
1520 #ifdef MUST_DO_SELECT
1521 if (!ld->from_cap_pipe) {
1522 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
1523 ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
1525 ld->pcap_fd = pcap_fileno(ld->pcap_h);
1530 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1531 returned a warning; print it, but keep capturing. */
1532 if (open_err_str[0] != '\0') {
1533 sync_msg_str = g_strdup_printf("%s.", open_err_str);
1534 report_capture_error(sync_msg_str, "");
1535 g_free(sync_msg_str);
1542 /* close the capture input file (pcap or capture pipe) */
1543 static void capture_loop_close_input(loop_data *ld) {
1545 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
1547 /* if open, close the capture pipe "input file" */
1549 if (ld->cap_pipe_fd >= 0) {
1550 g_assert(ld->from_cap_pipe);
1551 ws_close(ld->cap_pipe_fd);
1552 ld->cap_pipe_fd = 0;
1555 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE) {
1556 CloseHandle(ld->cap_pipe_h);
1557 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
1561 /* if open, close the pcap "input file" */
1562 if(ld->pcap_h != NULL) {
1563 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", ld->pcap_h);
1564 g_assert(!ld->from_cap_pipe);
1565 pcap_close(ld->pcap_h);
1572 /* Shut down windows sockets */
1578 /* init the capture filter */
1579 static initfilter_status_t
1580 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe, gchar * iface, gchar * cfilter) {
1581 bpf_u_int32 netnum, netmask;
1582 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
1583 struct bpf_program fcode;
1586 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
1588 /* capture filters only work on real interfaces */
1589 if (cfilter && !from_cap_pipe) {
1590 /* A capture filter was specified; set it up. */
1591 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1593 * Well, we can't get the netmask for this interface; it's used
1594 * only for filters that check for broadcast IP addresses, so
1595 * we just punt and use 0. It might be nice to warn the user,
1596 * but that's a pain in a GUI application, as it'd involve popping
1597 * up a message box, and it's not clear how often this would make
1598 * a difference (only filters that check for IP broadcast addresses
1602 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
1605 if (pcap_compile(pcap_h, &fcode, cfilter, 1, netmask) < 0) {
1606 /* Treat this specially - our caller might try to compile this
1607 as a display filter and, if that succeeds, warn the user that
1608 the display and capture filter syntaxes are different. */
1609 return INITFILTER_BAD_FILTER;
1611 if (pcap_setfilter(pcap_h, &fcode) < 0) {
1612 #ifdef HAVE_PCAP_FREECODE
1613 pcap_freecode(&fcode);
1615 return INITFILTER_OTHER_ERROR;
1617 #ifdef HAVE_PCAP_FREECODE
1618 pcap_freecode(&fcode);
1622 return INITFILTER_NO_ERROR;
1626 /* set up to write to the already-opened capture output file/files */
1628 capture_loop_init_output(capture_options *capture_opts, int save_file_fd, loop_data *ld, char *errmsg, int errmsg_len) {
1632 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
1635 if (ld->from_cap_pipe) {
1636 ld->file_snaplen = ld->cap_pipe_hdr.snaplen;
1639 ld->file_snaplen = pcap_snapshot(ld->pcap_h);
1642 /* Set up to write to the capture file. */
1643 if (capture_opts->multi_files_on) {
1644 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
1646 ld->pdh = libpcap_fdopen(save_file_fd, &err);
1649 gboolean successful;
1651 ld->bytes_written = 0;
1652 if (capture_opts->use_pcapng) {
1655 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
1656 successful = libpcap_write_session_header_block(ld->pdh, appname, &ld->bytes_written, &err) &&
1657 libpcap_write_interface_description_block(ld->pdh, capture_opts->iface, capture_opts->cfilter, ld->linktype, ld->file_snaplen, &ld->bytes_written, &err);
1659 successful = libpcap_write_file_header(ld->pdh, ld->linktype, ld->file_snaplen,
1660 &ld->bytes_written, &err);
1668 if (ld->pdh == NULL) {
1669 /* We couldn't set up to write to the capture file. */
1670 /* XXX - use cf_open_error_message from tshark instead? */
1673 case WTAP_ERR_CANT_OPEN:
1674 g_snprintf(errmsg, errmsg_len, "The file to which the capture would be saved"
1675 " couldn't be created for some unknown reason.");
1678 case WTAP_ERR_SHORT_WRITE:
1679 g_snprintf(errmsg, errmsg_len, "A full header couldn't be written to the file"
1680 " to which the capture would be saved.");
1685 g_snprintf(errmsg, errmsg_len,
1686 "The file to which the capture would be"
1687 " saved (\"%s\") could not be opened: Error %d.",
1688 capture_opts->save_file, err);
1690 g_snprintf(errmsg, errmsg_len,
1691 "The file to which the capture would be"
1692 " saved (\"%s\") could not be opened: %s.",
1693 capture_opts->save_file, strerror(err));
1705 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
1707 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
1709 if (capture_opts->multi_files_on) {
1710 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
1712 if (capture_opts->use_pcapng) {
1713 libpcap_write_interface_statistics_block(ld->pdh, 0, ld->pcap_h, &ld->bytes_written, err_close);
1715 return libpcap_dump_close(ld->pdh, err_close);
1719 /* dispatch incoming packets (pcap or capture pipe)
1721 * Waits for incoming packets to be available, and calls pcap_dispatch()
1722 * to cause them to be processed.
1724 * Returns the number of packets which were processed.
1726 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
1727 * packet-batching behaviour does not cause packets to get held back
1731 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
1732 char *errmsg, int errmsg_len)
1735 gint packet_count_before;
1736 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1741 packet_count_before = ld->packet_count;
1742 if (ld->from_cap_pipe) {
1743 /* dispatch from capture pipe */
1744 #ifdef LOG_CAPTURE_VERBOSE
1745 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
1748 sel_ret = cap_pipe_select(ld->cap_pipe_fd);
1751 if (sel_ret < 0 && errno != EINTR) {
1752 g_snprintf(errmsg, errmsg_len,
1753 "Unexpected error from select: %s", strerror(errno));
1754 report_capture_error(errmsg, please_report);
1759 * "select()" says we can read from the pipe without blocking
1761 #endif /* USE_THREADS */
1762 inpkts = cap_pipe_dispatch(ld, pcap_data, errmsg, errmsg_len);
1772 /* dispatch from pcap */
1773 #ifdef MUST_DO_SELECT
1775 * If we have "pcap_get_selectable_fd()", we use it to get the
1776 * descriptor on which to select; if that's -1, it means there
1777 * is no descriptor on which you can do a "select()" (perhaps
1778 * because you're capturing on a special device, and that device's
1779 * driver unfortunately doesn't support "select()", in which case
1780 * we don't do the select - which means it might not be possible
1781 * to stop a capture until a packet arrives. If that's unacceptable,
1782 * plead with whoever supplies the software for that device to add
1783 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
1784 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
1785 * later, so it can use pcap_breakloop().
1787 #ifdef LOG_CAPTURE_VERBOSE
1788 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
1790 if (ld->pcap_fd != -1) {
1791 sel_ret = cap_pipe_select(ld->pcap_fd);
1794 * "select()" says we can read from it without blocking; go for
1797 * We don't have pcap_breakloop(), so we only process one packet
1798 * per pcap_dispatch() call, to allow a signal to stop the
1799 * processing immediately, rather than processing all packets
1800 * in a batch before quitting.
1802 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb,
1806 /* Error, rather than pcap_breakloop(). */
1807 ld->pcap_err = TRUE;
1809 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1812 if (sel_ret < 0 && errno != EINTR) {
1813 g_snprintf(errmsg, errmsg_len,
1814 "Unexpected error from select: %s", strerror(errno));
1815 report_capture_error(errmsg, please_report);
1821 #endif /* MUST_DO_SELECT */
1823 /* dispatch from pcap without select */
1825 #ifdef LOG_CAPTURE_VERBOSE
1826 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
1830 * On Windows, we don't support asynchronously telling a process to
1831 * stop capturing; instead, we check for an indication on a pipe
1832 * after processing packets. We therefore process only one packet
1833 * at a time, so that we can check the pipe after every packet.
1835 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb, (u_char *) ld);
1837 inpkts = pcap_dispatch(ld->pcap_h, -1, capture_loop_packet_cb, (u_char *) ld);
1841 /* Error, rather than pcap_breakloop(). */
1842 ld->pcap_err = TRUE;
1844 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1846 #else /* pcap_next_ex */
1847 #ifdef LOG_CAPTURE_VERBOSE
1848 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
1850 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
1853 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
1854 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
1855 * This should be fixed in the WinPcap 4.0 alpha release.
1857 * For reference, an example remote interface:
1858 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
1861 /* emulate dispatch from pcap */
1864 struct pcap_pkthdr *pkt_header;
1869 (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1)
1870 capture_loop_packet_cb( (u_char *) ld, pkt_header, pkt_data);
1873 ld->pcap_err = TRUE;
1877 #endif /* pcap_next_ex */
1881 #ifdef LOG_CAPTURE_VERBOSE
1882 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
1885 return ld->packet_count - packet_count_before;
1889 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
1890 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
1892 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
1893 char *errmsg, int errmsg_len) {
1896 gchar *capfile_name;
1897 gboolean is_tempfile;
1902 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
1903 (capture_opts->save_file) ? capture_opts->save_file : "");
1905 if (capture_opts->save_file != NULL) {
1906 /* We return to the caller while the capture is in progress.
1907 * Therefore we need to take a copy of save_file in
1908 * case the caller destroys it after we return.
1910 capfile_name = g_strdup(capture_opts->save_file);
1912 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
1913 if (capture_opts->multi_files_on) {
1914 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
1915 g_snprintf(errmsg, errmsg_len,
1916 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
1917 g_free(capfile_name);
1920 if (strcmp(capfile_name, "-") == 0) {
1921 /* write to stdout */
1924 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
1925 _setmode(1, O_BINARY);
1928 } /* if (...output_to_pipe ... */
1931 if (capture_opts->multi_files_on) {
1932 /* ringbuffer is enabled */
1933 *save_file_fd = ringbuf_init(capfile_name,
1934 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
1936 /* we need the ringbuf name */
1937 if(*save_file_fd != -1) {
1938 g_free(capfile_name);
1939 capfile_name = g_strdup(ringbuf_current_filename());
1942 /* Try to open/create the specified file for use as a capture buffer. */
1943 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
1947 is_tempfile = FALSE;
1949 /* Choose a random name for the temporary capture buffer */
1950 *save_file_fd = create_tempfile(&tmpname, "wireshark");
1951 capfile_name = g_strdup(tmpname);
1955 /* did we fail to open the output file? */
1956 if (*save_file_fd == -1) {
1958 g_snprintf(errmsg, errmsg_len,
1959 "The temporary file to which the capture would be saved (\"%s\") "
1960 "could not be opened: %s.", capfile_name, strerror(errno));
1962 if (capture_opts->multi_files_on) {
1963 ringbuf_error_cleanup();
1966 g_snprintf(errmsg, errmsg_len,
1967 "The file to which the capture would be saved (\"%s\") "
1968 "could not be opened: %s.", capfile_name,
1971 g_free(capfile_name);
1975 if(capture_opts->save_file != NULL) {
1976 g_free(capture_opts->save_file);
1978 capture_opts->save_file = capfile_name;
1979 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
1980 "g_free(capfile_name)". */
1982 ret = fchown(*save_file_fd, capture_opts->owner, capture_opts->group);
1990 capture_loop_stop_signal_handler(int signo _U_)
1992 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Signal: Stop capture");
1993 capture_loop_stop();
1997 #define TIME_GET() GetTickCount()
1999 #define TIME_GET() time(NULL)
2002 /* Do the low-level work of a capture.
2003 Returns TRUE if it succeeds, FALSE otherwise. */
2005 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
2008 struct sigaction act;
2010 time_t upd_time, cur_time;
2014 gint inpkts_to_sync_pipe = 0; /* packets not already send out to the sync_pipe */
2015 condition *cnd_file_duration = NULL;
2016 condition *cnd_autostop_files = NULL;
2017 condition *cnd_autostop_size = NULL;
2018 condition *cnd_autostop_duration = NULL;
2019 guint32 autostop_files = 0;
2022 gboolean cfilter_error = FALSE;
2023 #define MSG_MAX_LENGTH 4096
2024 char errmsg[MSG_MAX_LENGTH+1];
2025 char secondary_errmsg[MSG_MAX_LENGTH+1];
2026 int save_file_fd = -1;
2029 *secondary_errmsg = '\0';
2031 /* init the loop data */
2032 global_ld.go = TRUE;
2033 global_ld.packet_count = 0;
2034 if (capture_opts->has_autostop_packets)
2035 global_ld.packet_max = capture_opts->autostop_packets;
2037 global_ld.packet_max = 0; /* no limit */
2038 global_ld.err = 0; /* no error seen yet */
2039 global_ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
2040 global_ld.pcap_err = FALSE;
2041 global_ld.from_cap_pipe = FALSE;
2042 global_ld.pdh = NULL;
2044 global_ld.cap_pipe_fd = -1;
2046 global_ld.cap_pipe_h = INVALID_HANDLE_VALUE;
2048 #ifdef MUST_DO_SELECT
2049 global_ld.pcap_fd = 0;
2052 /* We haven't yet gotten the capture statistics. */
2053 *stats_known = FALSE;
2057 * Catch SIGUSR1, so that we exit cleanly if the parent process
2058 * kills us with it due to the user selecting "Capture->Stop".
2060 act.sa_handler = capture_loop_stop_signal_handler;
2062 * Arrange that system calls not get restarted, because when
2063 * our signal handler returns we don't want to restart
2064 * a call that was waiting for packets to arrive.
2067 sigemptyset(&act.sa_mask);
2068 sigaction(SIGUSR1, &act, NULL);
2071 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
2072 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
2074 /* open the "input file" from network interface or capture pipe */
2075 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
2076 secondary_errmsg, sizeof(secondary_errmsg))) {
2080 /* init the input filter from the network interface (capture pipe will do nothing) */
2081 switch (capture_loop_init_filter(global_ld.pcap_h, global_ld.from_cap_pipe,
2082 capture_opts->iface,
2083 capture_opts->cfilter)) {
2085 case INITFILTER_NO_ERROR:
2088 case INITFILTER_BAD_FILTER:
2089 cfilter_error = TRUE;
2090 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(global_ld.pcap_h));
2093 case INITFILTER_OTHER_ERROR:
2094 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
2095 pcap_geterr(global_ld.pcap_h));
2096 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
2100 /* If we're supposed to write to a capture file, open it for output
2101 (temporary/specified name/ringbuffer) */
2102 if (capture_opts->saving_to_file) {
2103 if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
2107 /* set up to write to the already-opened capture output file/files */
2108 if (!capture_loop_init_output(capture_opts, save_file_fd, &global_ld,
2109 errmsg, sizeof(errmsg))) {
2113 /* XXX - capture SIGTERM and close the capture, in case we're on a
2114 Linux 2.0[.x] system and you have to explicitly close the capture
2115 stream in order to turn promiscuous mode off? We need to do that
2116 in other places as well - and I don't think that works all the
2117 time in any case, due to libpcap bugs. */
2119 /* Well, we should be able to start capturing.
2121 Sync out the capture file, so the header makes it to the file system,
2122 and send a "capture started successfully and capture file created"
2123 message to our parent so that they'll open the capture file and
2124 update its windows to indicate that we have a live capture in
2126 libpcap_dump_flush(global_ld.pdh, NULL);
2127 report_new_capture_file(capture_opts->save_file);
2130 /* initialize capture stop (and alike) conditions */
2131 init_capture_stop_conditions();
2132 /* create stop conditions */
2133 if (capture_opts->has_autostop_filesize)
2135 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
2136 if (capture_opts->has_autostop_duration)
2137 cnd_autostop_duration =
2138 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
2140 if (capture_opts->multi_files_on) {
2141 if (capture_opts->has_file_duration)
2143 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
2145 if (capture_opts->has_autostop_files)
2146 cnd_autostop_files =
2147 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
2150 /* init the time values */
2151 start_time = TIME_GET();
2152 upd_time = TIME_GET();
2154 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
2156 /* WOW, everything is prepared! */
2157 /* please fasten your seat belts, we will enter now the actual capture loop */
2158 while (global_ld.go) {
2159 /* dispatch incoming packets */
2160 inpkts = capture_loop_dispatch(capture_opts, &global_ld, errmsg,
2164 /* any news from our parent (signal pipe)? -> just stop the capture */
2165 if (!signal_pipe_check_running()) {
2166 global_ld.go = FALSE;
2171 inpkts_to_sync_pipe += inpkts;
2173 /* check capture size condition */
2174 if (cnd_autostop_size != NULL &&
2175 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)){
2176 /* Capture size limit reached, do we have another file? */
2177 if (capture_opts->multi_files_on) {
2178 if (cnd_autostop_files != NULL &&
2179 cnd_eval(cnd_autostop_files, ++autostop_files)) {
2180 /* no files left: stop here */
2181 global_ld.go = FALSE;
2185 /* Switch to the next ringbuffer file */
2186 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2187 &save_file_fd, &global_ld.err)) {
2188 gboolean successful;
2190 /* File switch succeeded: reset the conditions */
2191 global_ld.bytes_written = 0;
2192 if (capture_opts->use_pcapng) {
2195 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2196 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2197 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);
2199 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2200 &global_ld.bytes_written, &global_ld.err);
2203 fclose(global_ld.pdh);
2204 global_ld.pdh = NULL;
2205 global_ld.go = FALSE;
2208 cnd_reset(cnd_autostop_size);
2209 if (cnd_file_duration) {
2210 cnd_reset(cnd_file_duration);
2212 libpcap_dump_flush(global_ld.pdh, NULL);
2213 report_packet_count(inpkts_to_sync_pipe);
2214 inpkts_to_sync_pipe = 0;
2215 report_new_capture_file(capture_opts->save_file);
2217 /* File switch failed: stop here */
2218 global_ld.go = FALSE;
2222 /* single file, stop now */
2223 global_ld.go = FALSE;
2226 } /* cnd_autostop_size */
2227 if (capture_opts->output_to_pipe) {
2228 libpcap_dump_flush(global_ld.pdh, NULL);
2232 /* Only update once a second (Win32: 500ms) so as not to overload slow
2233 * displays. This also prevents too much context-switching between the
2234 * dumpcap and wireshark processes */
2235 cur_time = TIME_GET();
2237 if ( (cur_time - upd_time) > 500) {
2239 if (cur_time - upd_time > 0) {
2241 upd_time = cur_time;
2243 /*if (pcap_stats(pch, stats) >= 0) {
2244 *stats_known = TRUE;
2247 /* Let the parent process know. */
2248 if (inpkts_to_sync_pipe) {
2250 libpcap_dump_flush(global_ld.pdh, NULL);
2252 /* Send our parent a message saying we've written out "inpkts_to_sync_pipe"
2253 packets to the capture file. */
2254 report_packet_count(inpkts_to_sync_pipe);
2256 inpkts_to_sync_pipe = 0;
2259 /* check capture duration condition */
2260 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
2261 /* The maximum capture time has elapsed; stop the capture. */
2262 global_ld.go = FALSE;
2266 /* check capture file duration condition */
2267 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
2268 /* duration limit reached, do we have another file? */
2269 if (capture_opts->multi_files_on) {
2270 if (cnd_autostop_files != NULL &&
2271 cnd_eval(cnd_autostop_files, ++autostop_files)) {
2272 /* no files left: stop here */
2273 global_ld.go = FALSE;
2277 /* Switch to the next ringbuffer file */
2278 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2279 &save_file_fd, &global_ld.err)) {
2280 gboolean successful;
2282 /* file switch succeeded: reset the conditions */
2283 global_ld.bytes_written = 0;
2284 if (capture_opts->use_pcapng) {
2287 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2288 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2289 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);
2291 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2292 &global_ld.bytes_written, &global_ld.err);
2295 fclose(global_ld.pdh);
2296 global_ld.pdh = NULL;
2297 global_ld.go = FALSE;
2300 cnd_reset(cnd_file_duration);
2301 if(cnd_autostop_size)
2302 cnd_reset(cnd_autostop_size);
2303 libpcap_dump_flush(global_ld.pdh, NULL);
2304 report_packet_count(inpkts_to_sync_pipe);
2305 inpkts_to_sync_pipe = 0;
2306 report_new_capture_file(capture_opts->save_file);
2308 /* File switch failed: stop here */
2309 global_ld.go = FALSE;
2313 /* single file, stop now */
2314 global_ld.go = FALSE;
2317 } /* cnd_file_duration */
2320 } /* while (global_ld.go) */
2322 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
2324 /* delete stop conditions */
2325 if (cnd_file_duration != NULL)
2326 cnd_delete(cnd_file_duration);
2327 if (cnd_autostop_files != NULL)
2328 cnd_delete(cnd_autostop_files);
2329 if (cnd_autostop_size != NULL)
2330 cnd_delete(cnd_autostop_size);
2331 if (cnd_autostop_duration != NULL)
2332 cnd_delete(cnd_autostop_duration);
2334 /* did we had a pcap (input) error? */
2335 if (global_ld.pcap_err) {
2336 /* On Linux, if an interface goes down while you're capturing on it,
2337 you'll get a "recvfrom: Network is down" error (ENETDOWN).
2338 (At least you will if strerror() doesn't show a local translation
2341 On FreeBSD and OS X, if a network adapter disappears while
2342 you're capturing on it, you'll get a "read: Device not configured"
2343 error (ENXIO). (See previous parenthetical note.)
2345 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
2347 These should *not* be reported to the Wireshark developers. */
2350 cap_err_str = pcap_geterr(global_ld.pcap_h);
2351 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
2352 strcmp(cap_err_str, "read: Device not configured") == 0 ||
2353 strcmp(cap_err_str, "read: I/O error") == 0) {
2354 report_capture_error("The network adapter on which the capture was being done "
2355 "is no longer running; the capture has stopped.",
2358 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
2360 report_capture_error(errmsg, please_report);
2363 else if (global_ld.from_cap_pipe && global_ld.cap_pipe_err == PIPERR)
2364 report_capture_error(errmsg, "");
2366 /* did we had an error while capturing? */
2367 if (global_ld.err == 0) {
2370 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
2371 global_ld.err, FALSE);
2372 report_capture_error(errmsg, please_report);
2376 if (capture_opts->saving_to_file) {
2377 /* close the wiretap (output) file */
2378 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
2382 /* there might be packets not yet notified to the parent */
2383 /* (do this after closing the file, so all packets are already flushed) */
2384 if(inpkts_to_sync_pipe) {
2385 report_packet_count(inpkts_to_sync_pipe);
2386 inpkts_to_sync_pipe = 0;
2389 /* If we've displayed a message about a write error, there's no point
2390 in displaying another message about an error on close. */
2391 if (!close_ok && write_ok) {
2392 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
2394 report_capture_error(errmsg, "");
2398 * XXX We exhibit different behaviour between normal mode and sync mode
2399 * when the pipe is stdin and not already at EOF. If we're a child, the
2400 * parent's stdin isn't closed, so if the user starts another capture,
2401 * cap_pipe_open_live() will very likely not see the expected magic bytes and
2402 * will say "Unrecognized libpcap format". On the other hand, in normal
2403 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
2406 /* get packet drop statistics from pcap */
2407 if(global_ld.pcap_h != NULL) {
2408 g_assert(!global_ld.from_cap_pipe);
2409 /* Get the capture statistics, so we know how many packets were
2411 if (pcap_stats(global_ld.pcap_h, stats) >= 0) {
2412 *stats_known = TRUE;
2413 /* Let the parent process know. */
2414 report_packet_drops(stats->ps_drop);
2416 g_snprintf(errmsg, sizeof(errmsg),
2417 "Can't get packet-drop statistics: %s",
2418 pcap_geterr(global_ld.pcap_h));
2419 report_capture_error(errmsg, please_report);
2423 /* close the input file (pcap or capture pipe) */
2424 capture_loop_close_input(&global_ld);
2426 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
2428 /* ok, if the write and the close were successful. */
2429 return write_ok && close_ok;
2432 if (capture_opts->multi_files_on) {
2433 /* cleanup ringbuffer */
2434 ringbuf_error_cleanup();
2436 /* We can't use the save file, and we have no FILE * for the stream
2437 to close in order to close it, so close the FD directly. */
2438 if(save_file_fd != -1) {
2439 ws_close(save_file_fd);
2442 /* We couldn't even start the capture, so get rid of the capture
2444 if(capture_opts->save_file != NULL) {
2445 ws_unlink(capture_opts->save_file);
2446 g_free(capture_opts->save_file);
2449 capture_opts->save_file = NULL;
2451 report_cfilter_error(capture_opts->cfilter, errmsg);
2453 report_capture_error(errmsg, secondary_errmsg);
2455 /* close the input file (pcap or cap_pipe) */
2456 capture_loop_close_input(&global_ld);
2458 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
2464 static void capture_loop_stop(void)
2466 #ifdef HAVE_PCAP_BREAKLOOP
2467 if(global_ld.pcap_h != NULL)
2468 pcap_breakloop(global_ld.pcap_h);
2470 global_ld.go = FALSE;
2475 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
2476 int err, gboolean is_close)
2481 g_snprintf(errmsg, errmsglen,
2482 "Not all the packets could be written to the file"
2483 " to which the capture was being saved\n"
2484 "(\"%s\") because there is no space left on the file system\n"
2485 "on which that file resides.",
2491 g_snprintf(errmsg, errmsglen,
2492 "Not all the packets could be written to the file"
2493 " to which the capture was being saved\n"
2494 "(\"%s\") because you are too close to, or over,"
2495 " your disk quota\n"
2496 "on the file system on which that file resides.",
2501 case WTAP_ERR_CANT_CLOSE:
2502 g_snprintf(errmsg, errmsglen,
2503 "The file to which the capture was being saved"
2504 " couldn't be closed for some unknown reason.");
2507 case WTAP_ERR_SHORT_WRITE:
2508 g_snprintf(errmsg, errmsglen,
2509 "Not all the packets could be written to the file"
2510 " to which the capture was being saved\n"
2517 g_snprintf(errmsg, errmsglen,
2518 "The file to which the capture was being saved\n"
2519 "(\"%s\") could not be closed: %s.",
2520 fname, wtap_strerror(err));
2522 g_snprintf(errmsg, errmsglen,
2523 "An error occurred while writing to the file"
2524 " to which the capture was being saved\n"
2526 fname, wtap_strerror(err));
2533 /* one packet was captured, process it */
2535 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
2538 loop_data *ld = (void *) user;
2541 /* We may be called multiple times from pcap_dispatch(); if we've set
2542 the "stop capturing" flag, ignore this packet, as we're not
2543 supposed to be saving any more packets. */
2548 gboolean successful;
2549 /* We're supposed to write the packet to a file; do so.
2550 If this fails, set "ld->go" to FALSE, to stop the capture, and set
2551 "ld->err" to the error. */
2552 if (global_capture_opts.use_pcapng) {
2553 successful = libpcap_write_enhanced_packet_block(ld->pdh, phdr, 0, pd, &ld->bytes_written, &err);
2555 successful = libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err);
2562 /* if the user told us to stop after x packets, do we already have enough? */
2563 if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
2572 /* And now our feature presentation... [ fade to music ] */
2574 main(int argc, char *argv[])
2577 extern char *optarg;
2578 gboolean arg_error = FALSE;
2583 struct sigaction action, oldaction;
2586 gboolean start_capture = TRUE;
2587 gboolean stats_known;
2588 struct pcap_stat stats;
2589 GLogLevelFlags log_flags;
2590 gboolean list_interfaces = FALSE;
2591 gboolean list_link_layer_types = FALSE;
2592 gboolean machine_readable = FALSE;
2593 gboolean print_statistics = FALSE;
2594 int status, run_once_args = 0;
2597 #ifdef HAVE_PCAP_REMOTE
2598 #define OPTSTRING_INIT "a:A:b:c:Df:hi:Lm:MnprSs:uvw:y:Z:"
2600 #define OPTSTRING_INIT "a:b:c:Df:hi:LMnpSs:vw:y:Z:"
2604 #define OPTSTRING_WIN32 "B:"
2606 #define OPTSTRING_WIN32 ""
2609 char optstring[sizeof(OPTSTRING_INIT) + sizeof(OPTSTRING_WIN32) - 1] =
2610 OPTSTRING_INIT OPTSTRING_WIN32;
2612 #ifdef DEBUG_CHILD_DUMPCAP
2613 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
2614 fprintf (stderr, "Unable to open debug log file !\n");
2619 /* Determine if dumpcap is being requested to run in a special */
2620 /* capture_child mode by going thru the command line args to see if */
2621 /* a -Z is present. (-Z is a hidden option). */
2622 /* The primary result of running in capture_child mode is that */
2623 /* all messages sent out on stderr are in a special type/len/string */
2624 /* format to allow message processing by type. */
2625 /* These messages include various 'status' messages which are sent */
2626 /* when an actual capture is in progress. Capture_child mode */
2627 /* would normally be requested by a parent process which invokes */
2628 /* dumpcap and obtains dumpcap stderr output via a pipe to which */
2629 /* dumpcap stderr has been redirected. */
2630 /* Capture_child mode needs to be determined immediately upon */
2631 /* startup so that any messages generated by dumpcap in this mode */
2632 /* (eg: during initialization) will be formatted properly. */
2634 for (i=1; i<argc; i++) {
2635 if (strcmp("-Z", argv[i]) == 0) {
2636 capture_child = TRUE;
2638 /* set output pipe to binary mode, to avoid ugly text conversions */
2639 _setmode(2, O_BINARY);
2644 /* The default_log_handler will use stdout, which makes trouble in */
2645 /* capture child mode, as it uses stdout for it's sync_pipe. */
2646 /* So: the filtering is done in the console_log_handler and not here.*/
2647 /* We set the log handlers right up front to make sure that any log */
2648 /* messages when running as child will be sent back to the parent */
2649 /* with the correct format. */
2653 G_LOG_LEVEL_CRITICAL|
2654 G_LOG_LEVEL_WARNING|
2655 G_LOG_LEVEL_MESSAGE|
2658 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
2660 g_log_set_handler(NULL,
2662 console_log_handler, NULL /* user_data */);
2663 g_log_set_handler(LOG_DOMAIN_MAIN,
2665 console_log_handler, NULL /* user_data */);
2666 g_log_set_handler(LOG_DOMAIN_CAPTURE,
2668 console_log_handler, NULL /* user_data */);
2669 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
2671 console_log_handler, NULL /* user_data */);
2674 /* Load wpcap if possible. Do this before collecting the run-time version information */
2677 /* ... and also load the packet.dll from wpcap */
2678 /* XXX - currently not required, may change later. */
2679 /*wpcap_packet_load();*/
2681 /* Start windows sockets */
2682 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
2684 /* Set handler for Ctrl+C key */
2685 SetConsoleCtrlHandler(capture_cleanup, TRUE);
2687 /* Prepare to read from a pipe */
2688 if (!g_thread_supported ())
2689 g_thread_init (NULL);
2690 cap_pipe_pending_q = g_async_queue_new();
2691 cap_pipe_done_q = g_async_queue_new();
2692 cap_pipe_read_mtx = g_mutex_new();
2695 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
2697 action.sa_handler = capture_cleanup;
2698 action.sa_flags = 0;
2699 sigemptyset(&action.sa_mask);
2700 sigaction(SIGTERM, &action, NULL);
2701 sigaction(SIGINT, &action, NULL);
2702 sigaction(SIGPIPE, &action, NULL);
2703 sigaction(SIGHUP, NULL, &oldaction);
2704 if (oldaction.sa_handler == SIG_DFL)
2705 sigaction(SIGHUP, &action, NULL);
2708 /* ----------------------------------------------------------------- */
2709 /* Privilege and capability handling */
2711 /* 1. Running not as root or suid root; no special capabilities. */
2714 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
2717 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
2719 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
2720 /* capabilities; Drop all other capabilities; */
2721 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2722 /* else: after pcap_open_live() in capture_loop_open_input() */
2723 /* drop all capabilities (NET_RAW and NET_ADMIN); */
2724 /* (Note: this means that the process, although logged in */
2725 /* as root, does not have various permissions such as the */
2726 /* ability to bypass file access permissions). */
2727 /* XXX: Should we just leave capabilities alone in this case */
2728 /* so that user gets expected effect that root can do */
2731 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
2733 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2734 /* else: after pcap_open_live() in capture_loop_open_input() */
2735 /* drop suid root (set euid=ruid).(ie: keep suid until after */
2736 /* pcap_open_live). */
2738 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
2740 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
2741 /* capabilities; Drop all other capabilities; */
2742 /* Drop suid privileges (euid=ruid); */
2743 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2744 /* else: after pcap_open_live() in capture_loop_open_input() */
2745 /* drop all capabilities (NET_RAW and NET_ADMIN). */
2747 /* XXX: For some Linux versions/distros with capabilities */
2748 /* a 'normal' process with any capabilities cannot be */
2749 /* 'killed' (signaled) from another (same uid) non-privileged */
2751 /* For example: If (non-suid) Wireshark forks a */
2752 /* child suid dumpcap which acts as described here (case 5), */
2753 /* Wireshark will be unable to kill (signal) the child */
2754 /* dumpcap process until the capabilities have been dropped */
2755 /* (after pcap_open_live()). */
2756 /* This behaviour will apparently be changed in the kernel */
2757 /* to allow the kill (signal) in this case. */
2758 /* See the following for details: */
2759 /* http://www.mail-archive.com/ [wrapped] */
2760 /* linux-security-module@vger.kernel.org/msg02913.html */
2762 /* It is therefore conceivable that if dumpcap somehow hangs */
2763 /* in pcap_open_live or before that wireshark will not */
2764 /* be able to stop dumpcap using a signal (USR1, TERM, etc). */
2765 /* In this case, exiting wireshark will kill the child */
2766 /* dumpcap process. */
2768 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
2769 /* capabilities; Using libcap. Note: capset cmd (which see) */
2770 /* used to assign capabilities to file. */
2772 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2773 /* else: after pcap_open_live() in capture_loop_open_input() */
2774 /* drop all capabilities (NET_RAW and NET_ADMIN) */
2776 /* ToDo: -S (stats) should drop privileges/capabilities when no */
2777 /* longer required (similar to capture). */
2779 /* ----------------------------------------------------------------- */
2781 get_credential_info();
2784 /* If 'started with special privileges' (and using libcap) */
2785 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
2786 /* Set euid/egid = ruid/rgid to remove suid privileges */
2787 relinquish_privs_except_capture();
2790 /* Set the initial values in the capture options. This might be overwritten
2791 by the command line parameters. */
2792 capture_opts_init(&global_capture_opts, NULL);
2794 /* Default to capturing the entire packet. */
2795 global_capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
2797 /* We always save to a file - if no file was specified, we save to a
2799 global_capture_opts.saving_to_file = TRUE;
2800 global_capture_opts.has_ring_num_files = TRUE;
2802 /* Now get our args */
2803 while ((opt = getopt(argc, argv, optstring)) != -1) {
2805 case 'h': /* Print help and exit */
2809 case 'v': /* Show version and exit */
2811 GString *comp_info_str;
2812 GString *runtime_info_str;
2813 /* Assemble the compile-time version information string */
2814 comp_info_str = g_string_new("Compiled ");
2815 get_compiled_version_info(comp_info_str, NULL);
2817 /* Assemble the run-time version information string */
2818 runtime_info_str = g_string_new("Running ");
2819 get_runtime_version_info(runtime_info_str, NULL);
2820 show_version(comp_info_str, runtime_info_str);
2821 g_string_free(comp_info_str, TRUE);
2822 g_string_free(runtime_info_str, TRUE);
2826 /*** capture option specific ***/
2827 case 'a': /* autostop criteria */
2828 case 'b': /* Ringbuffer option */
2829 case 'c': /* Capture x packets */
2830 case 'f': /* capture filter */
2831 case 'i': /* Use interface x */
2832 case 'n': /* Use pcapng format */
2833 case 'p': /* Don't capture in promiscuous mode */
2834 case 's': /* Set the snapshot (capture) length */
2835 case 'w': /* Write to capture file x */
2836 case 'y': /* Set the pcap data link type */
2837 #ifdef HAVE_PCAP_REMOTE
2838 case 'u': /* Use UDP for data transfer */
2839 case 'r': /* Capture own RPCAP traffic too */
2840 case 'A': /* Authentication */
2842 #ifdef HAVE_PCAP_SETSAMPLING
2843 case 'm': /* Sampling */
2846 case 'B': /* Buffer size */
2848 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
2853 /*** hidden option: Wireshark child mode (using binary output messages) ***/
2855 capture_child = TRUE;
2857 /* set output pipe to binary mode, to avoid ugly text conversions */
2858 _setmode(2, O_BINARY);
2860 * optarg = the control ID, aka the PPID, currently used for the
2863 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
2864 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
2865 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
2866 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
2868 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
2869 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2870 "Signal pipe: Unable to open %s. Dead parent?",
2878 /*** all non capture option specific ***/
2879 case 'D': /* Print a list of capture devices and exit */
2880 list_interfaces = TRUE;
2883 case 'L': /* Print list of link-layer types and exit */
2884 list_link_layer_types = TRUE;
2887 case 'S': /* Print interface statistics once a second */
2888 print_statistics = TRUE;
2891 case 'M': /* For -D and -L, print machine-readable output */
2892 machine_readable = TRUE;
2895 case '?': /* Bad flag - print usage message */
2896 cmdarg_err("Invalid Option: %s", argv[optind-1]);
2904 /* user specified file name as regular command-line argument */
2905 /* XXX - use it as the capture file name (or something else)? */
2912 * Extra command line arguments were specified; complain.
2913 * XXX - interpret as capture filter, as tcpdump and tshark do?
2915 cmdarg_err("Invalid argument: %s", argv[0]);
2924 if (run_once_args > 1) {
2925 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
2927 } else if (list_link_layer_types) {
2928 /* We're supposed to list the link-layer types for an interface;
2929 did the user also specify a capture file to be read? */
2930 /* No - did they specify a ring buffer option? */
2931 if (global_capture_opts.multi_files_on) {
2932 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
2936 /* No - was the ring buffer option specified and, if so, does it make
2938 if (global_capture_opts.multi_files_on) {
2939 /* Ring buffer works only under certain conditions:
2940 a) ring buffer does not work with temporary files;
2941 b) it makes no sense to enable the ring buffer if the maximum
2942 file size is set to "infinite". */
2943 if (global_capture_opts.save_file == NULL) {
2944 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
2945 global_capture_opts.multi_files_on = FALSE;
2947 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
2948 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
2949 /* XXX - this must be redesigned as the conditions changed */
2950 /* global_capture_opts.multi_files_on = FALSE;*/
2955 if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
2956 /* cmdarg_err() already called .... */
2960 /* Let the user know what interface was chosen. */
2961 /* get_interface_descriptive_name() is not available! */
2962 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", global_capture_opts.iface);
2964 if (list_interfaces) {
2965 status = capture_opts_list_interfaces(machine_readable);
2967 } else if (list_link_layer_types) {
2968 status = capture_opts_list_link_layer_types(&global_capture_opts, machine_readable);
2970 } else if (print_statistics) {
2971 status = print_statistics_loop(machine_readable);
2975 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
2976 capture_opts_trim_ring_num_files(&global_capture_opts);
2978 /* Now start the capture. */
2980 if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
2984 /* capture failed */
2991 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
2992 const char *message, gpointer user_data _U_)
2999 /* ignore log message, if log_level isn't interesting */
3000 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3001 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
3006 /* create a "timestamp" */
3008 today = localtime(&curr);
3010 switch(log_level & G_LOG_LEVEL_MASK) {
3011 case G_LOG_LEVEL_ERROR:
3014 case G_LOG_LEVEL_CRITICAL:
3017 case G_LOG_LEVEL_WARNING:
3020 case G_LOG_LEVEL_MESSAGE:
3023 case G_LOG_LEVEL_INFO:
3026 case G_LOG_LEVEL_DEBUG:
3030 fprintf(stderr, "unknown log_level %u\n", log_level);
3032 g_assert_not_reached();
3035 /* Generate the output message */
3036 if(log_level & G_LOG_LEVEL_MESSAGE) {
3037 /* normal user messages without additional infos */
3038 msg = g_strdup_printf("%s\n", message);
3040 /* info/debug messages with additional infos */
3041 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
3042 today->tm_hour, today->tm_min, today->tm_sec,
3043 log_domain != NULL ? log_domain : "",
3047 /* DEBUG & INFO msgs (if we're debugging today) */
3048 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3049 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3050 #ifdef DEBUG_DUMPCAP
3051 fprintf(stderr, "%s", msg);
3054 #ifdef DEBUG_CHILD_DUMPCAP
3055 fprintf(debug_log, "%s", msg);
3063 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
3064 /* to parent especially formatted if dumpcap running as child. */
3065 if (capture_child) {
3066 sync_pipe_errmsg_to_parent(2, msg, "");
3068 fprintf(stderr, "%s", msg);
3075 /****************************************************************************************************************/
3076 /* indication report routines */
3080 report_packet_count(int packet_count)
3082 char tmp[SP_DECISIZE+1+1];
3083 static int count = 0;
3086 g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
3087 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
3088 pipe_write_block(2, SP_PACKET_COUNT, tmp);
3090 count += packet_count;
3091 fprintf(stderr, "\rPackets: %u ", count);
3092 /* stderr could be line buffered */
3098 report_new_capture_file(const char *filename)
3101 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
3102 pipe_write_block(2, SP_FILE, filename);
3104 fprintf(stderr, "File: %s\n", filename);
3105 /* stderr could be line buffered */
3111 report_cfilter_error(const char *cfilter, const char *errmsg)
3113 if (capture_child) {
3114 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
3115 pipe_write_block(2, SP_BAD_FILTER, errmsg);
3118 "Invalid capture filter: \"%s\"!\n"
3120 "That string isn't a valid capture filter (%s).\n"
3121 "See the User's Guide for a description of the capture filter syntax.\n",
3127 report_capture_error(const char *error_msg, const char *secondary_error_msg)
3130 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3131 "Primary Error: %s", error_msg);
3132 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3133 "Secondary Error: %s", secondary_error_msg);
3134 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
3136 fprintf(stderr, "%s\n%s\n", error_msg, secondary_error_msg);
3141 report_packet_drops(guint32 drops)
3143 char tmp[SP_DECISIZE+1+1];
3145 g_snprintf(tmp, sizeof(tmp), "%u", drops);
3148 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
3149 pipe_write_block(2, SP_DROPS, tmp);
3151 fprintf(stderr, "Packets dropped: %s\n", tmp);
3152 /* stderr could be line buffered */
3158 /****************************************************************************************************************/
3159 /* signal_pipe handling */
3164 signal_pipe_check_running(void)
3166 /* any news from our parent? -> just stop the capture */
3170 /* if we are running standalone, no check required */
3171 if(!capture_child) {
3175 if(!sig_pipe_name || !sig_pipe_handle) {
3176 /* This shouldn't happen */
3177 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3178 "Signal pipe: No name or handle");
3183 * XXX - We should have the process ID of the parent (from the "-Z" flag)
3184 * at this point. Should we check to see if the parent is still alive,
3185 * e.g. by using OpenProcess?
3188 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
3190 if(!result || avail > 0) {
3191 /* peek failed or some bytes really available */
3192 /* (if not piping from stdin this would fail) */
3193 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3194 "Signal pipe: Stop capture: %s", sig_pipe_name);
3195 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3196 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
3197 sig_pipe_handle, result, avail);
3200 /* pipe ok and no bytes available */
3207 * Editor modelines - http://www.wireshark.org/tools/modelines.html
3212 * indent-tabs-mode: nil
3215 * vi: set shiftwidth=4 tabstop=8 expandtab
3216 * :indentSize=4:tabSize=8:noTabs=true: