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>
65 # include <sys/prctl.h>
66 # include <sys/capability.h>
69 #include "ringbuffer.h"
70 #include "clopts_common.h"
71 #include "cmdarg_err.h"
72 #include "version_info.h"
77 #include "capture-pcap-util.h"
80 #include "capture-wpcap.h"
81 #include <wsutil/unicode-utils.h>
84 #include <wsutil/privileges.h>
86 #include "sync_pipe.h"
88 #include "capture_opts.h"
89 #include "capture_sync.h"
91 #include "conditions.h"
92 #include "capture_stop_conditions.h"
96 #include "wsutil/file_util.h"
99 * Get information about libpcap format from "wiretap/libpcap.h".
100 * XXX - can we just use pcap_open_offline() to read the pipe?
102 #include "wiretap/libpcap.h"
104 /**#define DEBUG_DUMPCAP**/
105 /**#define DEBUG_CHILD_DUMPCAP**/
107 #ifdef DEBUG_CHILD_DUMPCAP
108 FILE *debug_log; /* for logging debug messages to */
109 /* a file if DEBUG_CHILD_DUMPCAP */
117 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
119 static gchar *sig_pipe_name = NULL;
120 static HANDLE sig_pipe_handle = NULL;
121 static gboolean signal_pipe_check_running(void);
125 static GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
126 static GMutex *cap_pipe_read_mtx;
129 /** Stop a low-level capture (stops the capture child). */
130 static void capture_loop_stop(void);
132 #if !defined (__linux__)
133 #ifndef HAVE_PCAP_BREAKLOOP
135 * We don't have pcap_breakloop(), which is the only way to ensure that
136 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
137 * won't, if the call to read the next packet or batch of packets is
138 * is interrupted by a signal on UN*X, just go back and try again to
141 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
142 * the signal handler, set a flag to stop capturing; however, without
143 * a guarantee of that sort, we can't guarantee that we'll stop capturing
144 * if the read will be retried and won't time out if no packets arrive.
146 * Therefore, on at least some platforms, we work around the lack of
147 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
148 * to wait for packets to arrive, so that we're probably going to be
149 * blocked in the select() when the signal arrives, and can just bail
150 * out of the loop at that point.
152 * However, we don't want to that on BSD (because "select()" doesn't work
153 * correctly on BPF devices on at least some releases of some flavors of
154 * BSD), and we don't want to do it on Windows (because "select()" is
155 * something for sockets, not for arbitrary handles). (Note that "Windows"
156 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
157 * using WinPcap, not a UNIX libpcap.)
159 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
160 * on BSD times out even if no packets have arrived, so we'll eventually
161 * exit pcap_dispatch() with an indication that no packets have arrived,
162 * and will break out of the capture loop at that point.
164 * On Windows, we can't send a SIGINT to stop capturing, so none of this
165 * applies in any case.
167 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
168 * want to include it if it's not present on this platform, however.
170 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
171 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
173 # define MUST_DO_SELECT
174 # endif /* avoid select */
175 #endif /* HAVE_PCAP_BREAKLOOP */
177 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
178 * in pcap_dispatch(); on the other hand, select() works just fine there.
179 * Hence we use a select for that come what may.
181 #define MUST_DO_SELECT
184 /** init the capture filter */
187 INITFILTER_BAD_FILTER,
188 INITFILTER_OTHER_ERROR
189 } initfilter_status_t;
191 typedef struct _loop_data {
193 gboolean go; /* TRUE as long as we're supposed to keep capturing */
194 int err; /* if non-zero, error seen while capturing */
195 gint packet_count; /* Number of packets we have already captured */
196 gint packet_max; /* Number of packets we're supposed to capture - 0 means infinite */
198 /* pcap "input file" */
199 pcap_t *pcap_h; /* pcap handle */
200 gboolean pcap_err; /* TRUE if error from pcap */
201 #ifdef MUST_DO_SELECT
202 int pcap_fd; /* pcap file descriptor */
205 /* capture pipe (unix only "input file") */
206 gboolean from_cap_pipe; /* TRUE if we are capturing data from a capture pipe */
207 struct pcap_hdr cap_pipe_hdr; /* Pcap header when capturing from a pipe */
208 struct pcaprec_modified_hdr cap_pipe_rechdr; /* Pcap record header when capturing from a pipe */
210 HANDLE cap_pipe_h; /* The handle of the capture pipe */
212 int cap_pipe_fd; /* the file descriptor of the capture pipe */
214 gboolean cap_pipe_modified; /* TRUE if data in the pipe uses modified pcap headers */
215 gboolean cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
217 char * cap_pipe_buf; /* Pointer to the data buffer we read into */
218 #endif /* USE_THREADS */
219 int cap_pipe_bytes_to_read;/* Used by cap_pipe_dispatch */
220 int cap_pipe_bytes_read; /* Used by cap_pipe_dispatch */
222 STATE_EXPECT_REC_HDR,
227 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
239 * Standard secondary message for unexpected errors.
241 static const char please_report[] =
242 "Please report this to the Wireshark developers.\n"
243 "(This is not a crash; please do not report it as such.)";
246 * This needs to be static, so that the SIGINT handler can clear the "go"
249 static loop_data global_ld;
253 * Timeout, in milliseconds, for reads from the stream of captured packets.
255 #if defined(__APPLE__) && defined(__LP64__)
256 #define CAP_READ_TIMEOUT 1000
258 #define CAP_READ_TIMEOUT 250
261 * Timeout, in microseconds, for threaded reads from a pipe.
263 #define THREAD_READ_TIMEOUT 100
264 static char *cap_pipe_err_str;
267 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
268 const char *message, gpointer user_data _U_);
270 /* capture related options */
271 static capture_options global_capture_opts;
273 static void capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
275 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
276 int err, gboolean is_close);
278 static void exit_main(int err) G_GNUC_NORETURN;
280 static void report_new_capture_file(const char *filename);
281 static void report_packet_count(int packet_count);
282 static void report_packet_drops(guint32 drops);
283 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
284 static void report_cfilter_error(const char *cfilter, const char *errmsg);
287 print_usage(gboolean print_ver) {
295 "Dumpcap " VERSION "%s\n"
296 "Capture network packets and dump them into a libpcap file.\n"
297 "See http://www.wireshark.org for more information.\n",
298 wireshark_svnversion);
302 fprintf(output, "\nUsage: dumpcap [options] ...\n");
303 fprintf(output, "\n");
304 fprintf(output, "Capture interface:\n");
305 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
306 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
307 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
308 fprintf(output, " -p don't capture in promiscuous mode\n");
310 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
312 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
313 fprintf(output, " -D print list of interfaces and exit\n");
314 fprintf(output, " -L print list of link-layer types of iface and exit\n");
315 fprintf(output, " -S print statistics for each interface once every second\n");
316 fprintf(output, " -M for -D, -L, and -S produce machine-readable output\n");
317 fprintf(output, "\n");
318 #ifdef HAVE_PCAP_REMOTE
319 fprintf(output, "\nRPCAP options:\n");
320 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
321 fprintf(output, " -u use UDP for RPCAP data transfer\n");
322 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
323 #ifdef HAVE_PCAP_SETSAMPLING
324 fprintf(output, " -m <sampling type> use packet sampling\n");
325 fprintf(output, " count:NUM - capture one packet of every NUM\n");
326 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
329 fprintf(output, "Stop conditions:\n");
330 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
331 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
332 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
333 fprintf(output, " files:NUM - stop after NUM files\n");
334 /*fprintf(output, "\n");*/
335 fprintf(output, "Output (files):\n");
336 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
337 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
338 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
339 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
340 fprintf(output, " -n use pcapng format instead of pcap\n");
341 /*fprintf(output, "\n");*/
342 fprintf(output, "Miscellaneous:\n");
343 fprintf(output, " -v print version information and exit\n");
344 fprintf(output, " -h display this help and exit\n");
345 fprintf(output, "\n");
346 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcap\n");
347 fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcap\"\n");
348 fprintf(output, "\n");
349 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
353 show_version(GString *comp_info_str, GString *runtime_info_str)
357 "Dumpcap " VERSION "%s\n"
362 "See http://www.wireshark.org for more information.\n",
363 wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
367 * Report an error in command-line arguments.
370 cmdarg_err(const char *fmt, ...)
376 /* Generate a 'special format' message back to parent */
378 msg = g_strdup_vprintf(fmt, ap);
379 sync_pipe_errmsg_to_parent(2, msg, "");
384 fprintf(stderr, "dumpcap: ");
385 vfprintf(stderr, fmt, ap);
386 fprintf(stderr, "\n");
392 * Report additional information for an error in command-line arguments.
395 cmdarg_err_cont(const char *fmt, ...)
402 msg = g_strdup_vprintf(fmt, ap);
403 sync_pipe_errmsg_to_parent(2, msg, "");
408 vfprintf(stderr, fmt, ap);
409 fprintf(stderr, "\n");
419 /* Print the number of packets captured for each interface until we're killed. */
421 print_statistics_loop(gboolean machine_readable)
423 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
429 char errbuf[PCAP_ERRBUF_SIZE];
432 if_list = get_interface_list(&err, &err_str);
433 if (if_list == NULL) {
435 case CANT_GET_INTERFACE_LIST:
436 cmdarg_err("%s", err_str);
440 case NO_INTERFACES_FOUND:
441 cmdarg_err("There are no interfaces on which a capture can be done");
447 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
448 if_info = if_entry->data;
449 #ifdef HAVE_PCAP_OPEN
450 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
452 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
456 if_stat = g_malloc(sizeof(if_stat_t));
457 if_stat->name = g_strdup(if_info->name);
459 stat_list = g_list_append(stat_list, if_stat);
464 cmdarg_err("There are no interfaces on which a capture can be done");
468 if (!machine_readable) {
469 printf("%-15s %10s %10s\n", "Interface", "Received",
474 while (global_ld.go) {
475 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
476 if_stat = stat_entry->data;
477 pcap_stats(if_stat->pch, &ps);
479 if (!machine_readable) {
480 printf("%-15s %10u %10u\n", if_stat->name,
481 ps.ps_recv, ps.ps_drop);
483 printf("%s\t%u\t%u\n", if_stat->name,
484 ps.ps_recv, ps.ps_drop);
489 if (! global_ld.from_cap_pipe)
496 /* XXX - Not reached. Should we look for 'q' in stdin? */
497 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
498 if_stat = stat_entry->data;
499 pcap_close(if_stat->pch);
500 g_free(if_stat->name);
503 g_list_free(stat_list);
504 free_interface_list(if_list);
512 capture_cleanup_handler(DWORD dwCtrlType)
514 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
515 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
516 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
517 like SIGTERM at least when the machine's shutting down.
519 For now, if we're running as a command rather than a capture child,
520 we handle all but CTRL_LOGOFF_EVENT as indications that we should
521 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
524 If we're not running as a capture child, we might be running as
525 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
526 user logs out. (XXX - can we explicitly check whether we're
527 running as a service?) */
529 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
530 "Console: Control signal");
531 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
532 "Console: Control signal, CtrlType: %u", dwCtrlType);
534 /* Keep capture running if we're a service and a user logs off */
535 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
544 capture_cleanup_handler(int signum _U_)
546 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
547 SIGTERM. We assume that if the user wanted it to keep running
548 after they logged out, they'd have nohupped it. */
550 /* Note: don't call g_log() in the signal handler: if we happened to be in
551 * g_log() in process context when the signal came in, g_log will detect
552 * the "recursion" and abort.
559 static void exit_main(int status)
562 /* Shutdown windows sockets */
565 /* can be helpful for debugging */
567 printf("Press any key\n");
578 * If we were linked with libcap (not libpcap), make sure we have
579 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
580 * (See comment in main() for details)
584 #if 0 /* Set to enable capability debugging */
585 /* see 'man cap_to_text()' for explanation of output */
586 /* '=' means 'all= ' ie: no capabilities */
587 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
589 print_caps(char *pfx) {
590 cap_t caps = cap_get_proc();
591 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
592 "%s: EUID: %d Capabilities: %s", pfx,
593 geteuid(), cap_to_text(caps, NULL));
596 print_caps(char *pfx _U_) {
601 relinquish_privs_except_capture(void)
603 /* If 'started_with_special_privs' (ie: suid) then enable for
604 * ourself the NET_ADMIN and NET_RAW capabilities and then
605 * drop our suid privileges.
607 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
608 * stuff we don't need (and shouldn't have).
609 * CAP_NET_RAW: Packet capture (raw sockets).
612 if (started_with_special_privs()) {
613 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
614 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
616 cap_t caps = cap_init(); /* all capabilities initialized to off */
618 print_caps("Pre drop, pre set");
620 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
621 cmdarg_err("prctl() fail return: %s", strerror(errno));
624 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
625 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
627 if (cap_set_proc(caps)) {
628 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
630 print_caps("Pre drop, post set");
632 relinquish_special_privs_perm();
634 print_caps("Post drop, pre set");
635 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
636 if (cap_set_proc(caps)) {
637 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
639 print_caps("Post drop, post set");
647 relinquish_all_capabilities()
649 /* Drop any and all capabilities this process may have. */
650 /* Allowed whether or not process has any privileges. */
651 cap_t caps = cap_init(); /* all capabilities initialized to off */
652 print_caps("Pre-clear");
653 if (cap_set_proc(caps)) {
654 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
656 print_caps("Post-clear");
660 #endif /* HAVE_LIBCAP */
662 /* Take care of byte order in the libpcap headers read from pipes.
663 * (function taken from wiretap/libpcap.c) */
665 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
668 /* Byte-swap the record header fields. */
669 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
670 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
671 rechdr->incl_len = BSWAP32(rechdr->incl_len);
672 rechdr->orig_len = BSWAP32(rechdr->orig_len);
675 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
676 swapped, in order to match the BPF header layout.
678 Unfortunately, some files were, according to a comment in the "libpcap"
679 source, written with version 2.3 in their headers but without the
680 interchanged fields, so if "incl_len" is greater than "orig_len" - which
681 would make no sense - we assume that we need to swap them. */
682 if (hdr->version_major == 2 &&
683 (hdr->version_minor < 3 ||
684 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
687 temp = rechdr->orig_len;
688 rechdr->orig_len = rechdr->incl_len;
689 rechdr->incl_len = temp;
695 * Thread function that reads from a pipe and pushes the data
696 * to the main application thread.
699 * XXX Right now we use async queues for basic signaling. The main thread
700 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
701 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
702 * Iff the read is successful cap_pipe_read pushes an item onto
703 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
704 * the queues themselves (yet).
706 * We might want to move some of the cap_pipe_dispatch logic here so that
707 * we can let cap_pipe_read run independently, queuing up multiple reads
708 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
710 static void *cap_pipe_read(void *ld_ptr) {
711 loop_data *ld = (loop_data *)ld_ptr;
720 while (ld->cap_pipe_err == PIPOK) {
721 g_async_queue_pop(cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
722 g_mutex_lock(cap_pipe_read_mtx);
724 while (bytes_read < (int) ld->cap_pipe_bytes_to_read) {
726 /* If we try to use read() on a named pipe on Windows with partial
727 * data it appears to return EOF.
729 res = ReadFile(ld->cap_pipe_h, ld->cap_pipe_buf+bytes_read,
730 ld->cap_pipe_bytes_to_read - bytes_read,
735 last_err = GetLastError();
736 if (last_err == ERROR_MORE_DATA) {
738 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
739 ld->cap_pipe_err = PIPEOF;
743 ld->cap_pipe_err = PIPERR;
746 } else if (b == 0 && ld->cap_pipe_bytes_to_read > 0) {
747 ld->cap_pipe_err = PIPEOF;
752 b = read(ld->cap_pipe_fd, ld->cap_pipe_buf+bytes_read,
753 ld->cap_pipe_bytes_to_read - bytes_read);
756 ld->cap_pipe_err = PIPEOF;
760 ld->cap_pipe_err = PIPERR;
769 ld->cap_pipe_bytes_read = bytes_read;
770 if (ld->cap_pipe_bytes_read >= ld->cap_pipe_bytes_to_read) {
771 g_async_queue_push(cap_pipe_done_q, ld->cap_pipe_buf); /* Any non-NULL value will do */
773 g_mutex_unlock(cap_pipe_read_mtx);
777 #endif /* USE_THREADS */
779 /* Provide select() functionality for a single file descriptor
780 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
782 * Returns the same values as select. If an error is returned,
783 * the string cap_pipe_err_str should be used instead of errno.
786 cap_pipe_select(int pipe_fd) {
788 struct timeval timeout, *pto;
791 cap_pipe_err_str = "Unknown error";
794 FD_SET(pipe_fd, &rfds);
797 timeout.tv_usec = CAP_READ_TIMEOUT * 1000;
800 sel_ret = select(pipe_fd+1, &rfds, NULL, NULL, pto);
802 cap_pipe_err_str = strerror(errno);
807 /* Mimic pcap_open_live() for pipe captures
808 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
810 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
811 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
813 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
814 char *errmsg, int errmsgl)
817 struct stat pipe_stat;
820 unsigned int bytes_read;
831 ld->cap_pipe_fd = -1;
833 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
835 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
838 * XXX (T)Wireshark blocks until we return
840 if (strcmp(pipename, "-") == 0) {
842 fd = 0; /* read from stdin */
844 ld->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
848 if (ws_stat(pipename, &pipe_stat) < 0) {
849 if (errno == ENOENT || errno == ENOTDIR)
850 ld->cap_pipe_err = PIPNEXIST;
852 g_snprintf(errmsg, errmsgl,
853 "The capture session could not be initiated "
854 "due to error on pipe: %s", strerror(errno));
855 ld->cap_pipe_err = PIPERR;
859 if (! S_ISFIFO(pipe_stat.st_mode)) {
860 if (S_ISCHR(pipe_stat.st_mode)) {
862 * Assume the user specified an interface on a system where
863 * interfaces are in /dev. Pretend we haven't seen it.
865 ld->cap_pipe_err = PIPNEXIST;
868 g_snprintf(errmsg, errmsgl,
869 "The capture session could not be initiated because\n"
870 "\"%s\" is neither an interface nor a pipe", pipename);
871 ld->cap_pipe_err = PIPERR;
875 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
877 g_snprintf(errmsg, errmsgl,
878 "The capture session could not be initiated "
879 "due to error on pipe open: %s", strerror(errno));
880 ld->cap_pipe_err = PIPERR;
884 #define PIPE_STR "\\pipe\\"
885 /* Under Windows, named pipes _must_ have the form
886 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
888 pncopy = g_strdup(pipename);
889 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
890 pos = strchr(pncopy + 3, '\\');
891 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
898 g_snprintf(errmsg, errmsgl,
899 "The capture session could not be initiated because\n"
900 "\"%s\" is neither an interface nor a pipe", pipename);
901 ld->cap_pipe_err = PIPNEXIST;
905 /* Wait for the pipe to appear */
907 ld->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
908 OPEN_EXISTING, 0, NULL);
910 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE)
913 if (GetLastError() != ERROR_PIPE_BUSY) {
914 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
915 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
916 g_snprintf(errmsg, errmsgl,
917 "The capture session on \"%s\" could not be started "
918 "due to error on pipe open: %s (error %d)",
919 pipename, utf_16to8(err_str), GetLastError());
921 ld->cap_pipe_err = PIPERR;
925 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
926 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
927 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
928 g_snprintf(errmsg, errmsgl,
929 "The capture session on \"%s\" timed out during "
930 "pipe open: %s (error %d)",
931 pipename, utf_16to8(err_str), GetLastError());
933 ld->cap_pipe_err = PIPERR;
941 ld->from_cap_pipe = TRUE;
944 /* read the pcap header */
946 while (bytes_read < sizeof magic) {
947 sel_ret = cap_pipe_select(fd);
949 g_snprintf(errmsg, errmsgl,
950 "Unexpected error from select: %s", strerror(errno));
952 } else if (sel_ret > 0) {
953 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
956 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
958 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
965 #else /* USE_THREADS */
966 g_thread_create(&cap_pipe_read, ld, FALSE, NULL);
968 ld->cap_pipe_buf = (char *) &magic;
969 ld->cap_pipe_bytes_read = 0;
970 ld->cap_pipe_bytes_to_read = sizeof(magic);
971 /* We don't have to worry about cap_pipe_read_mtx here */
972 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
973 g_async_queue_pop(cap_pipe_done_q);
974 if (ld->cap_pipe_bytes_read <= 0) {
975 if (ld->cap_pipe_bytes_read == 0)
976 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
978 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
982 #endif /* USE_THREADS */
986 /* Host that wrote it has our byte order, and was running
987 a program using either standard or ss990417 libpcap. */
988 ld->cap_pipe_byte_swapped = FALSE;
989 ld->cap_pipe_modified = FALSE;
991 case PCAP_MODIFIED_MAGIC:
992 /* Host that wrote it has our byte order, but was running
993 a program using either ss990915 or ss991029 libpcap. */
994 ld->cap_pipe_byte_swapped = FALSE;
995 ld->cap_pipe_modified = TRUE;
997 case PCAP_SWAPPED_MAGIC:
998 /* Host that wrote it has a byte order opposite to ours,
999 and was running a program using either standard or
1000 ss990417 libpcap. */
1001 ld->cap_pipe_byte_swapped = TRUE;
1002 ld->cap_pipe_modified = FALSE;
1004 case PCAP_SWAPPED_MODIFIED_MAGIC:
1005 /* Host that wrote it out has a byte order opposite to
1006 ours, and was running a program using either ss990915
1007 or ss991029 libpcap. */
1008 ld->cap_pipe_byte_swapped = TRUE;
1009 ld->cap_pipe_modified = TRUE;
1012 /* Not a "libpcap" type we know about. */
1013 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
1018 /* Read the rest of the header */
1020 while (bytes_read < sizeof(struct pcap_hdr)) {
1021 sel_ret = cap_pipe_select(fd);
1023 g_snprintf(errmsg, errmsgl,
1024 "Unexpected error from select: %s", strerror(errno));
1026 } else if (sel_ret > 0) {
1027 b = read(fd, ((char *)hdr)+bytes_read,
1028 sizeof(struct pcap_hdr) - bytes_read);
1031 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1033 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
1040 #else /* USE_THREADS */
1041 ld->cap_pipe_buf = (char *) hdr;
1042 ld->cap_pipe_bytes_read = 0;
1043 ld->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1044 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1045 g_async_queue_pop(cap_pipe_done_q);
1046 if (ld->cap_pipe_bytes_read <= 0) {
1047 if (ld->cap_pipe_bytes_read == 0)
1048 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1050 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
1054 #endif /* USE_THREADS */
1056 if (ld->cap_pipe_byte_swapped) {
1057 /* Byte-swap the header fields about which we care. */
1058 hdr->version_major = BSWAP16(hdr->version_major);
1059 hdr->version_minor = BSWAP16(hdr->version_minor);
1060 hdr->snaplen = BSWAP32(hdr->snaplen);
1061 hdr->network = BSWAP32(hdr->network);
1063 ld->linktype = hdr->network;
1065 if (hdr->version_major < 2) {
1066 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1070 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1071 ld->cap_pipe_err = PIPOK;
1073 ld->cap_pipe_fd = fd;
1078 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1079 ld->cap_pipe_err = PIPERR;
1082 ld->cap_pipe_fd = -1;
1089 /* We read one record from the pipe, take care of byte order in the record
1090 * header, write the record to the capture file, and update capture statistics. */
1092 cap_pipe_dispatch(loop_data *ld, guchar *data, char *errmsg, int errmsgl)
1094 struct pcap_pkthdr phdr;
1095 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1107 #ifdef LOG_CAPTURE_VERBOSE
1108 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1111 switch (ld->cap_pipe_state) {
1113 case STATE_EXPECT_REC_HDR:
1115 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1118 ld->cap_pipe_state = STATE_READ_REC_HDR;
1119 ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
1120 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1121 ld->cap_pipe_bytes_read = 0;
1124 ld->cap_pipe_buf = (char *) &ld->cap_pipe_rechdr;
1125 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1126 g_mutex_unlock(cap_pipe_read_mtx);
1131 case STATE_READ_REC_HDR:
1133 b = read(ld->cap_pipe_fd, ((char *)&ld->cap_pipe_rechdr)+ld->cap_pipe_bytes_read,
1134 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1137 result = PD_PIPE_EOF;
1139 result = PD_PIPE_ERR;
1142 ld->cap_pipe_bytes_read += b;
1143 #else /* USE_THREADS */
1144 g_get_current_time(&wait_time);
1145 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1146 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1147 if (ld->cap_pipe_err == PIPEOF) {
1148 result = PD_PIPE_EOF;
1150 } else if (ld->cap_pipe_err == PIPERR) {
1151 result = PD_PIPE_ERR;
1157 #endif /* USE_THREADS */
1158 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1160 result = PD_REC_HDR_READ;
1163 case STATE_EXPECT_DATA:
1165 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1168 ld->cap_pipe_state = STATE_READ_DATA;
1169 ld->cap_pipe_bytes_to_read = ld->cap_pipe_rechdr.hdr.incl_len;
1170 ld->cap_pipe_bytes_read = 0;
1173 ld->cap_pipe_buf = (char *) data;
1174 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1175 g_mutex_unlock(cap_pipe_read_mtx);
1180 case STATE_READ_DATA:
1182 b = read(ld->cap_pipe_fd, data+ld->cap_pipe_bytes_read,
1183 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1186 result = PD_PIPE_EOF;
1188 result = PD_PIPE_ERR;
1191 ld->cap_pipe_bytes_read += b;
1192 #else /* USE_THREADS */
1193 g_get_current_time(&wait_time);
1194 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1195 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1196 if (ld->cap_pipe_err == PIPEOF) {
1197 result = PD_PIPE_EOF;
1199 } else if (ld->cap_pipe_err == PIPERR) {
1200 result = PD_PIPE_ERR;
1206 #endif /* USE_THREADS */
1207 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1209 result = PD_DATA_READ;
1213 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
1216 } /* switch (ld->cap_pipe_state) */
1219 * We've now read as much data as we were expecting, so process it.
1223 case PD_REC_HDR_READ:
1224 /* We've read the header. Take care of byte order. */
1225 cap_pipe_adjust_header(ld->cap_pipe_byte_swapped, &ld->cap_pipe_hdr,
1226 &ld->cap_pipe_rechdr.hdr);
1227 if (ld->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1228 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
1229 ld->packet_count+1, ld->cap_pipe_rechdr.hdr.incl_len);
1232 ld->cap_pipe_state = STATE_EXPECT_DATA;
1236 /* Fill in a "struct pcap_pkthdr", and process the packet. */
1237 phdr.ts.tv_sec = ld->cap_pipe_rechdr.hdr.ts_sec;
1238 phdr.ts.tv_usec = ld->cap_pipe_rechdr.hdr.ts_usec;
1239 phdr.caplen = ld->cap_pipe_rechdr.hdr.incl_len;
1240 phdr.len = ld->cap_pipe_rechdr.hdr.orig_len;
1242 capture_loop_packet_cb((u_char *)ld, &phdr, data);
1244 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1248 ld->cap_pipe_err = PIPEOF;
1253 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1254 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1255 g_snprintf(errmsg, errmsgl,
1256 "Error reading from pipe: %s (error %d)",
1257 utf_16to8(err_str), GetLastError());
1260 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
1268 ld->cap_pipe_err = PIPERR;
1269 /* Return here rather than inside the switch to prevent GCC warning */
1274 /** Open the capture input file (pcap or capture pipe).
1275 * Returns TRUE if it succeeds, FALSE otherwise. */
1277 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
1278 char *errmsg, size_t errmsg_len,
1279 char *secondary_errmsg, size_t secondary_errmsg_len)
1281 gchar open_err_str[PCAP_ERRBUF_SIZE];
1282 gchar *sync_msg_str;
1283 static const char ppamsg[] = "can't find PPA for ";
1284 const char *set_linktype_err_str;
1285 const char *libpcap_warn;
1287 gchar *sync_secondary_msg_str;
1289 WORD wVersionRequested;
1292 #ifdef HAVE_PCAP_REMOTE
1293 struct pcap_rmtauth auth;
1297 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
1300 /* XXX - opening Winsock on tshark? */
1302 /* Initialize Windows Socket if we are in a WIN32 OS
1303 This needs to be done before querying the interface for network/netmask */
1305 /* XXX - do we really require 1.1 or earlier?
1306 Are there any versions that support only 2.0 or higher? */
1307 wVersionRequested = MAKEWORD(1, 1);
1308 err = WSAStartup(wVersionRequested, &wsaData);
1312 case WSASYSNOTREADY:
1313 g_snprintf(errmsg, (gulong) errmsg_len,
1314 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
1317 case WSAVERNOTSUPPORTED:
1318 g_snprintf(errmsg, (gulong) errmsg_len,
1319 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
1320 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
1323 case WSAEINPROGRESS:
1324 g_snprintf(errmsg, (gulong) errmsg_len,
1325 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
1329 g_snprintf(errmsg, (gulong) errmsg_len,
1330 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
1334 g_snprintf(errmsg, (gulong) errmsg_len,
1335 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
1339 g_snprintf(errmsg, (gulong) errmsg_len,
1340 "Couldn't initialize Windows Sockets: error %d", err);
1343 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
1348 /* Open the network interface to capture from it.
1349 Some versions of libpcap may put warnings into the error buffer
1350 if they succeed; to tell if that's happened, we have to clear
1351 the error buffer, and check if it's still a null string. */
1352 open_err_str[0] = '\0';
1353 #ifdef HAVE_PCAP_OPEN
1354 auth.type = capture_opts->auth_type == CAPTURE_AUTH_PWD ?
1355 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
1356 auth.username = capture_opts->auth_username;
1357 auth.password = capture_opts->auth_password;
1359 ld->pcap_h = pcap_open(capture_opts->iface,
1360 capture_opts->has_snaplen ? capture_opts->snaplen :
1361 WTAP_MAX_PACKET_SIZE,
1363 (capture_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
1364 (capture_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
1365 (capture_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
1366 CAP_READ_TIMEOUT, &auth, open_err_str);
1368 ld->pcap_h = pcap_open_live(capture_opts->iface,
1369 capture_opts->has_snaplen ? capture_opts->snaplen :
1370 WTAP_MAX_PACKET_SIZE,
1371 capture_opts->promisc_mode, CAP_READ_TIMEOUT,
1375 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
1376 /* to remove any suid privileges. */
1377 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
1378 /* (euid/egid have already previously been set to ruid/rgid. */
1379 /* (See comment in main() for details) */
1381 relinquish_special_privs_perm();
1383 relinquish_all_capabilities();
1386 if (ld->pcap_h != NULL) {
1387 /* we've opened "iface" as a network device */
1389 /* try to set the capture buffer size */
1390 if (capture_opts->buffer_size > 1 &&
1391 pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
1392 sync_secondary_msg_str = g_strdup_printf(
1393 "The capture buffer size of %luMB seems to be too high for your machine,\n"
1394 "the default of 1MB will be used.\n"
1396 "Nonetheless, the capture is started.\n",
1397 capture_opts->buffer_size);
1398 report_capture_error("Couldn't set the capture buffer size!",
1399 sync_secondary_msg_str);
1400 g_free(sync_secondary_msg_str);
1404 #if defined(HAVE_PCAP_REMOTE) && defined(HAVE_PCAP_SETSAMPLING)
1405 if (capture_opts->sampling_method != CAPTURE_SAMP_NONE)
1407 struct pcap_samp *samp;
1409 if ((samp = pcap_setsampling(ld->pcap_h)) != NULL)
1411 switch (capture_opts->sampling_method)
1413 case CAPTURE_SAMP_BY_COUNT:
1414 samp->method = PCAP_SAMP_1_EVERY_N;
1417 case CAPTURE_SAMP_BY_TIMER:
1418 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
1422 sync_msg_str = g_strdup_printf(
1423 "Unknown sampling method %d specified,\n"
1424 "continue without packet sampling",
1425 capture_opts->sampling_method);
1426 report_capture_error("Couldn't set the capture "
1427 "sampling", sync_msg_str);
1428 g_free(sync_msg_str);
1430 samp->value = capture_opts->sampling_param;
1434 report_capture_error("Couldn't set the capture sampling",
1435 "Cannot get packet sampling data structure");
1441 /* setting the data link type only works on real interfaces */
1442 if (capture_opts->linktype != -1) {
1443 set_linktype_err_str = set_pcap_linktype(ld->pcap_h, capture_opts->iface,
1444 capture_opts->linktype);
1445 if (set_linktype_err_str != NULL) {
1446 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
1447 set_linktype_err_str);
1448 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
1452 ld->linktype = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
1454 /* We couldn't open "iface" as a network device. */
1455 /* Try to open it as a pipe */
1456 cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, (int) errmsg_len);
1459 if (ld->cap_pipe_fd == -1) {
1461 if (ld->cap_pipe_h == INVALID_HANDLE_VALUE) {
1464 if (ld->cap_pipe_err == PIPNEXIST) {
1465 /* Pipe doesn't exist, so output message for interface */
1467 /* If we got a "can't find PPA for X" message, warn the user (who
1468 is running (T)Wireshark on HP-UX) that they don't have a version
1469 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1470 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1471 PPA for X" rather than "can't find PPA for X"). */
1472 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1475 "You are running (T)Wireshark with a version of the libpcap library\n"
1476 "that doesn't handle HP-UX network devices well; this means that\n"
1477 "(T)Wireshark may not be able to capture packets.\n"
1479 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1480 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1481 "packaged binary form from the Software Porting And Archive Centre\n"
1482 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1483 "at the URL lists a number of mirror sites.";
1486 g_snprintf(errmsg, (gulong) errmsg_len,
1487 "The capture session could not be initiated (%s).", open_err_str);
1489 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
1490 "Please check to make sure you have sufficient permissions, and that you have "
1491 "the proper interface or pipe specified.%s", libpcap_warn);
1493 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
1495 "Please check that \"%s\" is the proper interface.\n"
1498 "Help can be found at:\n"
1500 " http://wiki.wireshark.org/WinPcap\n"
1501 " http://wiki.wireshark.org/CaptureSetup\n",
1502 capture_opts->iface);
1506 * Else pipe (or file) does exist and cap_pipe_open_live() has
1511 /* cap_pipe_open_live() succeeded; don't want
1512 error message from pcap_open_live() */
1513 open_err_str[0] = '\0';
1516 /* XXX - will this work for tshark? */
1517 #ifdef MUST_DO_SELECT
1518 if (!ld->from_cap_pipe) {
1519 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
1520 ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
1522 ld->pcap_fd = pcap_fileno(ld->pcap_h);
1527 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1528 returned a warning; print it, but keep capturing. */
1529 if (open_err_str[0] != '\0') {
1530 sync_msg_str = g_strdup_printf("%s.", open_err_str);
1531 report_capture_error(sync_msg_str, "");
1532 g_free(sync_msg_str);
1539 /* close the capture input file (pcap or capture pipe) */
1540 static void capture_loop_close_input(loop_data *ld) {
1542 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
1544 /* if open, close the capture pipe "input file" */
1546 if (ld->cap_pipe_fd >= 0) {
1547 g_assert(ld->from_cap_pipe);
1548 ws_close(ld->cap_pipe_fd);
1549 ld->cap_pipe_fd = 0;
1552 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE) {
1553 CloseHandle(ld->cap_pipe_h);
1554 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
1558 /* if open, close the pcap "input file" */
1559 if(ld->pcap_h != NULL) {
1560 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)ld->pcap_h);
1561 g_assert(!ld->from_cap_pipe);
1562 pcap_close(ld->pcap_h);
1569 /* Shut down windows sockets */
1575 /* init the capture filter */
1576 static initfilter_status_t
1577 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe, gchar * iface, gchar * cfilter) {
1578 bpf_u_int32 netnum, netmask;
1579 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
1580 struct bpf_program fcode;
1583 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
1585 /* capture filters only work on real interfaces */
1586 if (cfilter && !from_cap_pipe) {
1587 /* A capture filter was specified; set it up. */
1588 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1590 * Well, we can't get the netmask for this interface; it's used
1591 * only for filters that check for broadcast IP addresses, so
1592 * we just punt and use 0. It might be nice to warn the user,
1593 * but that's a pain in a GUI application, as it'd involve popping
1594 * up a message box, and it's not clear how often this would make
1595 * a difference (only filters that check for IP broadcast addresses
1599 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
1602 if (pcap_compile(pcap_h, &fcode, cfilter, 1, netmask) < 0) {
1603 /* Treat this specially - our caller might try to compile this
1604 as a display filter and, if that succeeds, warn the user that
1605 the display and capture filter syntaxes are different. */
1606 return INITFILTER_BAD_FILTER;
1608 if (pcap_setfilter(pcap_h, &fcode) < 0) {
1609 #ifdef HAVE_PCAP_FREECODE
1610 pcap_freecode(&fcode);
1612 return INITFILTER_OTHER_ERROR;
1614 #ifdef HAVE_PCAP_FREECODE
1615 pcap_freecode(&fcode);
1619 return INITFILTER_NO_ERROR;
1623 /* set up to write to the already-opened capture output file/files */
1625 capture_loop_init_output(capture_options *capture_opts, int save_file_fd, loop_data *ld, char *errmsg, int errmsg_len) {
1629 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
1632 if (ld->from_cap_pipe) {
1633 ld->file_snaplen = ld->cap_pipe_hdr.snaplen;
1636 ld->file_snaplen = pcap_snapshot(ld->pcap_h);
1639 /* Set up to write to the capture file. */
1640 if (capture_opts->multi_files_on) {
1641 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
1643 ld->pdh = libpcap_fdopen(save_file_fd, &err);
1646 gboolean successful;
1648 ld->bytes_written = 0;
1649 if (capture_opts->use_pcapng) {
1652 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
1653 successful = libpcap_write_session_header_block(ld->pdh, appname, &ld->bytes_written, &err) &&
1654 libpcap_write_interface_description_block(ld->pdh, capture_opts->iface, capture_opts->cfilter, ld->linktype, ld->file_snaplen, &ld->bytes_written, &err);
1656 successful = libpcap_write_file_header(ld->pdh, ld->linktype, ld->file_snaplen,
1657 &ld->bytes_written, &err);
1665 if (ld->pdh == NULL) {
1666 /* We couldn't set up to write to the capture file. */
1667 /* XXX - use cf_open_error_message from tshark instead? */
1670 case WTAP_ERR_CANT_OPEN:
1671 g_snprintf(errmsg, errmsg_len, "The file to which the capture would be saved"
1672 " couldn't be created for some unknown reason.");
1675 case WTAP_ERR_SHORT_WRITE:
1676 g_snprintf(errmsg, errmsg_len, "A full header couldn't be written to the file"
1677 " to which the capture would be saved.");
1682 g_snprintf(errmsg, errmsg_len,
1683 "The file to which the capture would be"
1684 " saved (\"%s\") could not be opened: Error %d.",
1685 capture_opts->save_file, err);
1687 g_snprintf(errmsg, errmsg_len,
1688 "The file to which the capture would be"
1689 " saved (\"%s\") could not be opened: %s.",
1690 capture_opts->save_file, strerror(err));
1702 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
1704 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
1706 if (capture_opts->multi_files_on) {
1707 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
1709 if (capture_opts->use_pcapng) {
1710 libpcap_write_interface_statistics_block(ld->pdh, 0, ld->pcap_h, &ld->bytes_written, err_close);
1712 return libpcap_dump_close(ld->pdh, err_close);
1716 /* dispatch incoming packets (pcap or capture pipe)
1718 * Waits for incoming packets to be available, and calls pcap_dispatch()
1719 * to cause them to be processed.
1721 * Returns the number of packets which were processed.
1723 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
1724 * packet-batching behaviour does not cause packets to get held back
1728 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
1729 char *errmsg, int errmsg_len)
1732 gint packet_count_before;
1733 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1738 packet_count_before = ld->packet_count;
1739 if (ld->from_cap_pipe) {
1740 /* dispatch from capture pipe */
1741 #ifdef LOG_CAPTURE_VERBOSE
1742 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
1745 sel_ret = cap_pipe_select(ld->cap_pipe_fd);
1748 if (sel_ret < 0 && errno != EINTR) {
1749 g_snprintf(errmsg, errmsg_len,
1750 "Unexpected error from select: %s", strerror(errno));
1751 report_capture_error(errmsg, please_report);
1756 * "select()" says we can read from the pipe without blocking
1758 #endif /* USE_THREADS */
1759 inpkts = cap_pipe_dispatch(ld, pcap_data, errmsg, errmsg_len);
1769 /* dispatch from pcap */
1770 #ifdef MUST_DO_SELECT
1772 * If we have "pcap_get_selectable_fd()", we use it to get the
1773 * descriptor on which to select; if that's -1, it means there
1774 * is no descriptor on which you can do a "select()" (perhaps
1775 * because you're capturing on a special device, and that device's
1776 * driver unfortunately doesn't support "select()", in which case
1777 * we don't do the select - which means it might not be possible
1778 * to stop a capture until a packet arrives. If that's unacceptable,
1779 * plead with whoever supplies the software for that device to add
1780 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
1781 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
1782 * later, so it can use pcap_breakloop().
1784 #ifdef LOG_CAPTURE_VERBOSE
1785 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
1787 if (ld->pcap_fd != -1) {
1788 sel_ret = cap_pipe_select(ld->pcap_fd);
1791 * "select()" says we can read from it without blocking; go for
1794 * We don't have pcap_breakloop(), so we only process one packet
1795 * per pcap_dispatch() call, to allow a signal to stop the
1796 * processing immediately, rather than processing all packets
1797 * in a batch before quitting.
1799 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb,
1803 /* Error, rather than pcap_breakloop(). */
1804 ld->pcap_err = TRUE;
1806 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1809 if (sel_ret < 0 && errno != EINTR) {
1810 g_snprintf(errmsg, errmsg_len,
1811 "Unexpected error from select: %s", strerror(errno));
1812 report_capture_error(errmsg, please_report);
1818 #endif /* MUST_DO_SELECT */
1820 /* dispatch from pcap without select */
1822 #ifdef LOG_CAPTURE_VERBOSE
1823 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
1827 * On Windows, we don't support asynchronously telling a process to
1828 * stop capturing; instead, we check for an indication on a pipe
1829 * after processing packets. We therefore process only one packet
1830 * at a time, so that we can check the pipe after every packet.
1832 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb, (u_char *) ld);
1834 inpkts = pcap_dispatch(ld->pcap_h, -1, capture_loop_packet_cb, (u_char *) ld);
1838 /* Error, rather than pcap_breakloop(). */
1839 ld->pcap_err = TRUE;
1841 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1843 #else /* pcap_next_ex */
1844 #ifdef LOG_CAPTURE_VERBOSE
1845 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
1847 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
1850 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
1851 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
1852 * This should be fixed in the WinPcap 4.0 alpha release.
1854 * For reference, an example remote interface:
1855 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
1858 /* emulate dispatch from pcap */
1861 struct pcap_pkthdr *pkt_header;
1866 (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1)
1867 capture_loop_packet_cb( (u_char *) ld, pkt_header, pkt_data);
1870 ld->pcap_err = TRUE;
1874 #endif /* pcap_next_ex */
1878 #ifdef LOG_CAPTURE_VERBOSE
1879 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
1882 return ld->packet_count - packet_count_before;
1886 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
1887 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
1889 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
1890 char *errmsg, int errmsg_len) {
1893 gchar *capfile_name;
1894 gboolean is_tempfile;
1899 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
1900 (capture_opts->save_file) ? capture_opts->save_file : "");
1902 if (capture_opts->save_file != NULL) {
1903 /* We return to the caller while the capture is in progress.
1904 * Therefore we need to take a copy of save_file in
1905 * case the caller destroys it after we return.
1907 capfile_name = g_strdup(capture_opts->save_file);
1909 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
1910 if (capture_opts->multi_files_on) {
1911 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
1912 g_snprintf(errmsg, errmsg_len,
1913 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
1914 g_free(capfile_name);
1917 if (strcmp(capfile_name, "-") == 0) {
1918 /* write to stdout */
1921 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
1922 _setmode(1, O_BINARY);
1925 } /* if (...output_to_pipe ... */
1928 if (capture_opts->multi_files_on) {
1929 /* ringbuffer is enabled */
1930 *save_file_fd = ringbuf_init(capfile_name,
1931 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
1933 /* we need the ringbuf name */
1934 if(*save_file_fd != -1) {
1935 g_free(capfile_name);
1936 capfile_name = g_strdup(ringbuf_current_filename());
1939 /* Try to open/create the specified file for use as a capture buffer. */
1940 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
1944 is_tempfile = FALSE;
1946 /* Choose a random name for the temporary capture buffer */
1947 *save_file_fd = create_tempfile(&tmpname, "wireshark");
1948 capfile_name = g_strdup(tmpname);
1952 /* did we fail to open the output file? */
1953 if (*save_file_fd == -1) {
1955 g_snprintf(errmsg, errmsg_len,
1956 "The temporary file to which the capture would be saved (\"%s\") "
1957 "could not be opened: %s.", capfile_name, strerror(errno));
1959 if (capture_opts->multi_files_on) {
1960 ringbuf_error_cleanup();
1963 g_snprintf(errmsg, errmsg_len,
1964 "The file to which the capture would be saved (\"%s\") "
1965 "could not be opened: %s.", capfile_name,
1968 g_free(capfile_name);
1972 if(capture_opts->save_file != NULL) {
1973 g_free(capture_opts->save_file);
1975 capture_opts->save_file = capfile_name;
1976 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
1977 "g_free(capfile_name)". */
1979 ret = fchown(*save_file_fd, capture_opts->owner, capture_opts->group);
1987 #define TIME_GET() GetTickCount()
1989 #define TIME_GET() time(NULL)
1992 /* Do the low-level work of a capture.
1993 Returns TRUE if it succeeds, FALSE otherwise. */
1995 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
1997 time_t upd_time, cur_time;
2001 gint inpkts_to_sync_pipe = 0; /* packets not already send out to the sync_pipe */
2002 condition *cnd_file_duration = NULL;
2003 condition *cnd_autostop_files = NULL;
2004 condition *cnd_autostop_size = NULL;
2005 condition *cnd_autostop_duration = NULL;
2006 guint32 autostop_files = 0;
2009 gboolean cfilter_error = FALSE;
2010 #define MSG_MAX_LENGTH 4096
2011 char errmsg[MSG_MAX_LENGTH+1];
2012 char secondary_errmsg[MSG_MAX_LENGTH+1];
2013 int save_file_fd = -1;
2016 *secondary_errmsg = '\0';
2018 /* init the loop data */
2019 global_ld.go = TRUE;
2020 global_ld.packet_count = 0;
2021 if (capture_opts->has_autostop_packets)
2022 global_ld.packet_max = capture_opts->autostop_packets;
2024 global_ld.packet_max = 0; /* no limit */
2025 global_ld.err = 0; /* no error seen yet */
2026 global_ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
2027 global_ld.pcap_err = FALSE;
2028 global_ld.from_cap_pipe = FALSE;
2029 global_ld.pdh = NULL;
2031 global_ld.cap_pipe_fd = -1;
2033 global_ld.cap_pipe_h = INVALID_HANDLE_VALUE;
2035 #ifdef MUST_DO_SELECT
2036 global_ld.pcap_fd = 0;
2039 /* We haven't yet gotten the capture statistics. */
2040 *stats_known = FALSE;
2042 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
2043 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
2045 /* open the "input file" from network interface or capture pipe */
2046 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
2047 secondary_errmsg, sizeof(secondary_errmsg))) {
2051 /* init the input filter from the network interface (capture pipe will do nothing) */
2052 switch (capture_loop_init_filter(global_ld.pcap_h, global_ld.from_cap_pipe,
2053 capture_opts->iface,
2054 capture_opts->cfilter)) {
2056 case INITFILTER_NO_ERROR:
2059 case INITFILTER_BAD_FILTER:
2060 cfilter_error = TRUE;
2061 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(global_ld.pcap_h));
2064 case INITFILTER_OTHER_ERROR:
2065 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
2066 pcap_geterr(global_ld.pcap_h));
2067 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
2071 /* If we're supposed to write to a capture file, open it for output
2072 (temporary/specified name/ringbuffer) */
2073 if (capture_opts->saving_to_file) {
2074 if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
2078 /* set up to write to the already-opened capture output file/files */
2079 if (!capture_loop_init_output(capture_opts, save_file_fd, &global_ld,
2080 errmsg, sizeof(errmsg))) {
2084 /* XXX - capture SIGTERM and close the capture, in case we're on a
2085 Linux 2.0[.x] system and you have to explicitly close the capture
2086 stream in order to turn promiscuous mode off? We need to do that
2087 in other places as well - and I don't think that works all the
2088 time in any case, due to libpcap bugs. */
2090 /* Well, we should be able to start capturing.
2092 Sync out the capture file, so the header makes it to the file system,
2093 and send a "capture started successfully and capture file created"
2094 message to our parent so that they'll open the capture file and
2095 update its windows to indicate that we have a live capture in
2097 libpcap_dump_flush(global_ld.pdh, NULL);
2098 report_new_capture_file(capture_opts->save_file);
2101 /* initialize capture stop (and alike) conditions */
2102 init_capture_stop_conditions();
2103 /* create stop conditions */
2104 if (capture_opts->has_autostop_filesize)
2106 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
2107 if (capture_opts->has_autostop_duration)
2108 cnd_autostop_duration =
2109 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
2111 if (capture_opts->multi_files_on) {
2112 if (capture_opts->has_file_duration)
2114 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
2116 if (capture_opts->has_autostop_files)
2117 cnd_autostop_files =
2118 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
2121 /* init the time values */
2122 start_time = TIME_GET();
2123 upd_time = TIME_GET();
2125 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
2127 /* WOW, everything is prepared! */
2128 /* please fasten your seat belts, we will enter now the actual capture loop */
2129 while (global_ld.go) {
2130 /* dispatch incoming packets */
2131 inpkts = capture_loop_dispatch(capture_opts, &global_ld, errmsg,
2135 /* any news from our parent (signal pipe)? -> just stop the capture */
2136 if (!signal_pipe_check_running()) {
2137 global_ld.go = FALSE;
2142 inpkts_to_sync_pipe += inpkts;
2144 /* check capture size condition */
2145 if (cnd_autostop_size != NULL &&
2146 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)){
2147 /* Capture size limit reached, do we have another file? */
2148 if (capture_opts->multi_files_on) {
2149 if (cnd_autostop_files != NULL &&
2150 cnd_eval(cnd_autostop_files, ++autostop_files)) {
2151 /* no files left: stop here */
2152 global_ld.go = FALSE;
2156 /* Switch to the next ringbuffer file */
2157 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2158 &save_file_fd, &global_ld.err)) {
2159 gboolean successful;
2161 /* File switch succeeded: reset the conditions */
2162 global_ld.bytes_written = 0;
2163 if (capture_opts->use_pcapng) {
2166 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2167 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2168 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);
2170 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2171 &global_ld.bytes_written, &global_ld.err);
2174 fclose(global_ld.pdh);
2175 global_ld.pdh = NULL;
2176 global_ld.go = FALSE;
2179 cnd_reset(cnd_autostop_size);
2180 if (cnd_file_duration) {
2181 cnd_reset(cnd_file_duration);
2183 libpcap_dump_flush(global_ld.pdh, NULL);
2184 report_packet_count(inpkts_to_sync_pipe);
2185 inpkts_to_sync_pipe = 0;
2186 report_new_capture_file(capture_opts->save_file);
2188 /* File switch failed: stop here */
2189 global_ld.go = FALSE;
2193 /* single file, stop now */
2194 global_ld.go = FALSE;
2197 } /* cnd_autostop_size */
2198 if (capture_opts->output_to_pipe) {
2199 libpcap_dump_flush(global_ld.pdh, NULL);
2203 /* Only update once a second (Win32: 500ms) so as not to overload slow
2204 * displays. This also prevents too much context-switching between the
2205 * dumpcap and wireshark processes */
2206 cur_time = TIME_GET();
2208 if ( (cur_time - upd_time) > 500) {
2210 if (cur_time - upd_time > 0) {
2212 upd_time = cur_time;
2214 /*if (pcap_stats(pch, stats) >= 0) {
2215 *stats_known = TRUE;
2218 /* Let the parent process know. */
2219 if (inpkts_to_sync_pipe) {
2221 libpcap_dump_flush(global_ld.pdh, NULL);
2223 /* Send our parent a message saying we've written out "inpkts_to_sync_pipe"
2224 packets to the capture file. */
2225 report_packet_count(inpkts_to_sync_pipe);
2227 inpkts_to_sync_pipe = 0;
2230 /* check capture duration condition */
2231 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
2232 /* The maximum capture time has elapsed; stop the capture. */
2233 global_ld.go = FALSE;
2237 /* check capture file duration condition */
2238 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
2239 /* duration limit reached, do we have another file? */
2240 if (capture_opts->multi_files_on) {
2241 if (cnd_autostop_files != NULL &&
2242 cnd_eval(cnd_autostop_files, ++autostop_files)) {
2243 /* no files left: stop here */
2244 global_ld.go = FALSE;
2248 /* Switch to the next ringbuffer file */
2249 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2250 &save_file_fd, &global_ld.err)) {
2251 gboolean successful;
2253 /* file switch succeeded: reset the conditions */
2254 global_ld.bytes_written = 0;
2255 if (capture_opts->use_pcapng) {
2258 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2259 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2260 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);
2262 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2263 &global_ld.bytes_written, &global_ld.err);
2266 fclose(global_ld.pdh);
2267 global_ld.pdh = NULL;
2268 global_ld.go = FALSE;
2271 cnd_reset(cnd_file_duration);
2272 if(cnd_autostop_size)
2273 cnd_reset(cnd_autostop_size);
2274 libpcap_dump_flush(global_ld.pdh, NULL);
2275 report_packet_count(inpkts_to_sync_pipe);
2276 inpkts_to_sync_pipe = 0;
2277 report_new_capture_file(capture_opts->save_file);
2279 /* File switch failed: stop here */
2280 global_ld.go = FALSE;
2284 /* single file, stop now */
2285 global_ld.go = FALSE;
2288 } /* cnd_file_duration */
2291 } /* while (global_ld.go) */
2293 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
2295 /* delete stop conditions */
2296 if (cnd_file_duration != NULL)
2297 cnd_delete(cnd_file_duration);
2298 if (cnd_autostop_files != NULL)
2299 cnd_delete(cnd_autostop_files);
2300 if (cnd_autostop_size != NULL)
2301 cnd_delete(cnd_autostop_size);
2302 if (cnd_autostop_duration != NULL)
2303 cnd_delete(cnd_autostop_duration);
2305 /* did we had a pcap (input) error? */
2306 if (global_ld.pcap_err) {
2307 /* On Linux, if an interface goes down while you're capturing on it,
2308 you'll get a "recvfrom: Network is down" error (ENETDOWN).
2309 (At least you will if strerror() doesn't show a local translation
2312 On FreeBSD and OS X, if a network adapter disappears while
2313 you're capturing on it, you'll get a "read: Device not configured"
2314 error (ENXIO). (See previous parenthetical note.)
2316 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
2318 These should *not* be reported to the Wireshark developers. */
2321 cap_err_str = pcap_geterr(global_ld.pcap_h);
2322 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
2323 strcmp(cap_err_str, "read: Device not configured") == 0 ||
2324 strcmp(cap_err_str, "read: I/O error") == 0) {
2325 report_capture_error("The network adapter on which the capture was being done "
2326 "is no longer running; the capture has stopped.",
2329 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
2331 report_capture_error(errmsg, please_report);
2334 else if (global_ld.from_cap_pipe && global_ld.cap_pipe_err == PIPERR)
2335 report_capture_error(errmsg, "");
2337 /* did we had an error while capturing? */
2338 if (global_ld.err == 0) {
2341 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
2342 global_ld.err, FALSE);
2343 report_capture_error(errmsg, please_report);
2347 if (capture_opts->saving_to_file) {
2348 /* close the wiretap (output) file */
2349 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
2353 /* there might be packets not yet notified to the parent */
2354 /* (do this after closing the file, so all packets are already flushed) */
2355 if(inpkts_to_sync_pipe) {
2356 report_packet_count(inpkts_to_sync_pipe);
2357 inpkts_to_sync_pipe = 0;
2360 /* If we've displayed a message about a write error, there's no point
2361 in displaying another message about an error on close. */
2362 if (!close_ok && write_ok) {
2363 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
2365 report_capture_error(errmsg, "");
2369 * XXX We exhibit different behaviour between normal mode and sync mode
2370 * when the pipe is stdin and not already at EOF. If we're a child, the
2371 * parent's stdin isn't closed, so if the user starts another capture,
2372 * cap_pipe_open_live() will very likely not see the expected magic bytes and
2373 * will say "Unrecognized libpcap format". On the other hand, in normal
2374 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
2377 /* get packet drop statistics from pcap */
2378 if(global_ld.pcap_h != NULL) {
2379 g_assert(!global_ld.from_cap_pipe);
2380 /* Get the capture statistics, so we know how many packets were
2382 if (pcap_stats(global_ld.pcap_h, stats) >= 0) {
2383 *stats_known = TRUE;
2384 /* Let the parent process know. */
2385 report_packet_drops(stats->ps_drop);
2387 g_snprintf(errmsg, sizeof(errmsg),
2388 "Can't get packet-drop statistics: %s",
2389 pcap_geterr(global_ld.pcap_h));
2390 report_capture_error(errmsg, please_report);
2394 /* close the input file (pcap or capture pipe) */
2395 capture_loop_close_input(&global_ld);
2397 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
2399 /* ok, if the write and the close were successful. */
2400 return write_ok && close_ok;
2403 if (capture_opts->multi_files_on) {
2404 /* cleanup ringbuffer */
2405 ringbuf_error_cleanup();
2407 /* We can't use the save file, and we have no FILE * for the stream
2408 to close in order to close it, so close the FD directly. */
2409 if(save_file_fd != -1) {
2410 ws_close(save_file_fd);
2413 /* We couldn't even start the capture, so get rid of the capture
2415 if(capture_opts->save_file != NULL) {
2416 ws_unlink(capture_opts->save_file);
2417 g_free(capture_opts->save_file);
2420 capture_opts->save_file = NULL;
2422 report_cfilter_error(capture_opts->cfilter, errmsg);
2424 report_capture_error(errmsg, secondary_errmsg);
2426 /* close the input file (pcap or cap_pipe) */
2427 capture_loop_close_input(&global_ld);
2429 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
2435 static void capture_loop_stop(void)
2437 #ifdef HAVE_PCAP_BREAKLOOP
2438 if(global_ld.pcap_h != NULL)
2439 pcap_breakloop(global_ld.pcap_h);
2441 global_ld.go = FALSE;
2446 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
2447 int err, gboolean is_close)
2452 g_snprintf(errmsg, errmsglen,
2453 "Not all the packets could be written to the file"
2454 " to which the capture was being saved\n"
2455 "(\"%s\") because there is no space left on the file system\n"
2456 "on which that file resides.",
2462 g_snprintf(errmsg, errmsglen,
2463 "Not all the packets could be written to the file"
2464 " to which the capture was being saved\n"
2465 "(\"%s\") because you are too close to, or over,"
2466 " your disk quota\n"
2467 "on the file system on which that file resides.",
2472 case WTAP_ERR_CANT_CLOSE:
2473 g_snprintf(errmsg, errmsglen,
2474 "The file to which the capture was being saved"
2475 " couldn't be closed for some unknown reason.");
2478 case WTAP_ERR_SHORT_WRITE:
2479 g_snprintf(errmsg, errmsglen,
2480 "Not all the packets could be written to the file"
2481 " to which the capture was being saved\n"
2488 g_snprintf(errmsg, errmsglen,
2489 "The file to which the capture was being saved\n"
2490 "(\"%s\") could not be closed: %s.",
2491 fname, wtap_strerror(err));
2493 g_snprintf(errmsg, errmsglen,
2494 "An error occurred while writing to the file"
2495 " to which the capture was being saved\n"
2497 fname, wtap_strerror(err));
2504 /* one packet was captured, process it */
2506 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
2509 loop_data *ld = (void *) user;
2512 /* We may be called multiple times from pcap_dispatch(); if we've set
2513 the "stop capturing" flag, ignore this packet, as we're not
2514 supposed to be saving any more packets. */
2519 gboolean successful;
2520 /* We're supposed to write the packet to a file; do so.
2521 If this fails, set "ld->go" to FALSE, to stop the capture, and set
2522 "ld->err" to the error. */
2523 if (global_capture_opts.use_pcapng) {
2524 successful = libpcap_write_enhanced_packet_block(ld->pdh, phdr, 0, pd, &ld->bytes_written, &err);
2526 successful = libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err);
2533 /* if the user told us to stop after x packets, do we already have enough? */
2534 if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
2543 /* And now our feature presentation... [ fade to music ] */
2545 main(int argc, char *argv[])
2548 gboolean arg_error = FALSE;
2553 struct sigaction action, oldaction;
2556 gboolean start_capture = TRUE;
2557 gboolean stats_known;
2558 struct pcap_stat stats;
2559 GLogLevelFlags log_flags;
2560 gboolean list_interfaces = FALSE;
2561 gboolean list_link_layer_types = FALSE;
2562 gboolean machine_readable = FALSE;
2563 gboolean print_statistics = FALSE;
2564 int status, run_once_args = 0;
2567 #ifdef HAVE_PCAP_REMOTE
2568 #define OPTSTRING_INIT "a:A:b:c:Df:hi:Lm:MnprSs:uvw:y:Z:"
2570 #define OPTSTRING_INIT "a:b:c:Df:hi:LMnpSs:vw:y:Z:"
2574 #define OPTSTRING_WIN32 "B:"
2576 #define OPTSTRING_WIN32 ""
2579 char optstring[sizeof(OPTSTRING_INIT) + sizeof(OPTSTRING_WIN32) - 1] =
2580 OPTSTRING_INIT OPTSTRING_WIN32;
2582 #ifdef DEBUG_CHILD_DUMPCAP
2583 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
2584 fprintf (stderr, "Unable to open debug log file !\n");
2589 /* Determine if dumpcap is being requested to run in a special */
2590 /* capture_child mode by going thru the command line args to see if */
2591 /* a -Z is present. (-Z is a hidden option). */
2592 /* The primary result of running in capture_child mode is that */
2593 /* all messages sent out on stderr are in a special type/len/string */
2594 /* format to allow message processing by type. */
2595 /* These messages include various 'status' messages which are sent */
2596 /* when an actual capture is in progress. Capture_child mode */
2597 /* would normally be requested by a parent process which invokes */
2598 /* dumpcap and obtains dumpcap stderr output via a pipe to which */
2599 /* dumpcap stderr has been redirected. */
2600 /* Capture_child mode needs to be determined immediately upon */
2601 /* startup so that any messages generated by dumpcap in this mode */
2602 /* (eg: during initialization) will be formatted properly. */
2604 for (i=1; i<argc; i++) {
2605 if (strcmp("-Z", argv[i]) == 0) {
2606 capture_child = TRUE;
2608 /* set output pipe to binary mode, to avoid ugly text conversions */
2609 _setmode(2, O_BINARY);
2614 /* The default_log_handler will use stdout, which makes trouble in */
2615 /* capture child mode, as it uses stdout for it's sync_pipe. */
2616 /* So: the filtering is done in the console_log_handler and not here.*/
2617 /* We set the log handlers right up front to make sure that any log */
2618 /* messages when running as child will be sent back to the parent */
2619 /* with the correct format. */
2623 G_LOG_LEVEL_CRITICAL|
2624 G_LOG_LEVEL_WARNING|
2625 G_LOG_LEVEL_MESSAGE|
2628 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
2630 g_log_set_handler(NULL,
2632 console_log_handler, NULL /* user_data */);
2633 g_log_set_handler(LOG_DOMAIN_MAIN,
2635 console_log_handler, NULL /* user_data */);
2636 g_log_set_handler(LOG_DOMAIN_CAPTURE,
2638 console_log_handler, NULL /* user_data */);
2639 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
2641 console_log_handler, NULL /* user_data */);
2644 /* Load wpcap if possible. Do this before collecting the run-time version information */
2647 /* ... and also load the packet.dll from wpcap */
2648 /* XXX - currently not required, may change later. */
2649 /*wpcap_packet_load();*/
2651 /* Start windows sockets */
2652 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
2654 /* Set handler for Ctrl+C key */
2655 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
2657 /* Prepare to read from a pipe */
2658 if (!g_thread_supported ())
2659 g_thread_init (NULL);
2660 cap_pipe_pending_q = g_async_queue_new();
2661 cap_pipe_done_q = g_async_queue_new();
2662 cap_pipe_read_mtx = g_mutex_new();
2665 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
2667 action.sa_handler = capture_cleanup_handler;
2669 * Arrange that system calls not get restarted, because when
2670 * our signal handler returns we don't want to restart
2671 * a call that was waiting for packets to arrive.
2673 action.sa_flags = 0;
2674 sigemptyset(&action.sa_mask);
2675 sigaction(SIGTERM, &action, NULL);
2676 sigaction(SIGINT, &action, NULL);
2677 sigaction(SIGPIPE, &action, NULL);
2678 sigaction(SIGHUP, NULL, &oldaction);
2679 if (oldaction.sa_handler == SIG_DFL)
2680 sigaction(SIGHUP, &action, NULL);
2683 /* ----------------------------------------------------------------- */
2684 /* Privilege and capability handling */
2686 /* 1. Running not as root or suid root; no special capabilities. */
2689 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
2692 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
2694 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
2695 /* capabilities; Drop all other capabilities; */
2696 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2697 /* else: after pcap_open_live() in capture_loop_open_input() */
2698 /* drop all capabilities (NET_RAW and NET_ADMIN); */
2699 /* (Note: this means that the process, although logged in */
2700 /* as root, does not have various permissions such as the */
2701 /* ability to bypass file access permissions). */
2702 /* XXX: Should we just leave capabilities alone in this case */
2703 /* so that user gets expected effect that root can do */
2706 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
2708 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2709 /* else: after pcap_open_live() in capture_loop_open_input() */
2710 /* drop suid root (set euid=ruid).(ie: keep suid until after */
2711 /* pcap_open_live). */
2713 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
2715 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
2716 /* capabilities; Drop all other capabilities; */
2717 /* Drop suid privileges (euid=ruid); */
2718 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2719 /* else: after pcap_open_live() in capture_loop_open_input() */
2720 /* drop all capabilities (NET_RAW and NET_ADMIN). */
2722 /* XXX: For some Linux versions/distros with capabilities */
2723 /* a 'normal' process with any capabilities cannot be */
2724 /* 'killed' (signaled) from another (same uid) non-privileged */
2726 /* For example: If (non-suid) Wireshark forks a */
2727 /* child suid dumpcap which acts as described here (case 5), */
2728 /* Wireshark will be unable to kill (signal) the child */
2729 /* dumpcap process until the capabilities have been dropped */
2730 /* (after pcap_open_live()). */
2731 /* This behaviour will apparently be changed in the kernel */
2732 /* to allow the kill (signal) in this case. */
2733 /* See the following for details: */
2734 /* http://www.mail-archive.com/ [wrapped] */
2735 /* linux-security-module@vger.kernel.org/msg02913.html */
2737 /* It is therefore conceivable that if dumpcap somehow hangs */
2738 /* in pcap_open_live or before that wireshark will not */
2739 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
2740 /* In this case, exiting wireshark will kill the child */
2741 /* dumpcap process. */
2743 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
2744 /* capabilities; Using libcap. Note: capset cmd (which see) */
2745 /* used to assign capabilities to file. */
2747 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2748 /* else: after pcap_open_live() in capture_loop_open_input() */
2749 /* drop all capabilities (NET_RAW and NET_ADMIN) */
2751 /* ToDo: -S (stats) should drop privileges/capabilities when no */
2752 /* longer required (similar to capture). */
2754 /* ----------------------------------------------------------------- */
2756 get_credential_info();
2759 /* If 'started with special privileges' (and using libcap) */
2760 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
2761 /* Set euid/egid = ruid/rgid to remove suid privileges */
2762 relinquish_privs_except_capture();
2765 /* Set the initial values in the capture options. This might be overwritten
2766 by the command line parameters. */
2767 capture_opts_init(&global_capture_opts, NULL);
2769 /* Default to capturing the entire packet. */
2770 global_capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
2772 /* We always save to a file - if no file was specified, we save to a
2774 global_capture_opts.saving_to_file = TRUE;
2775 global_capture_opts.has_ring_num_files = TRUE;
2777 /* Now get our args */
2778 while ((opt = getopt(argc, argv, optstring)) != -1) {
2780 case 'h': /* Print help and exit */
2784 case 'v': /* Show version and exit */
2786 GString *comp_info_str;
2787 GString *runtime_info_str;
2788 /* Assemble the compile-time version information string */
2789 comp_info_str = g_string_new("Compiled ");
2790 get_compiled_version_info(comp_info_str, NULL);
2792 /* Assemble the run-time version information string */
2793 runtime_info_str = g_string_new("Running ");
2794 get_runtime_version_info(runtime_info_str, NULL);
2795 show_version(comp_info_str, runtime_info_str);
2796 g_string_free(comp_info_str, TRUE);
2797 g_string_free(runtime_info_str, TRUE);
2801 /*** capture option specific ***/
2802 case 'a': /* autostop criteria */
2803 case 'b': /* Ringbuffer option */
2804 case 'c': /* Capture x packets */
2805 case 'f': /* capture filter */
2806 case 'i': /* Use interface x */
2807 case 'n': /* Use pcapng format */
2808 case 'p': /* Don't capture in promiscuous mode */
2809 case 's': /* Set the snapshot (capture) length */
2810 case 'w': /* Write to capture file x */
2811 case 'y': /* Set the pcap data link type */
2812 #ifdef HAVE_PCAP_REMOTE
2813 case 'u': /* Use UDP for data transfer */
2814 case 'r': /* Capture own RPCAP traffic too */
2815 case 'A': /* Authentication */
2817 #ifdef HAVE_PCAP_SETSAMPLING
2818 case 'm': /* Sampling */
2821 case 'B': /* Buffer size */
2823 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
2828 /*** hidden option: Wireshark child mode (using binary output messages) ***/
2830 capture_child = TRUE;
2832 /* set output pipe to binary mode, to avoid ugly text conversions */
2833 _setmode(2, O_BINARY);
2835 * optarg = the control ID, aka the PPID, currently used for the
2838 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
2839 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
2840 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
2841 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
2843 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
2844 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2845 "Signal pipe: Unable to open %s. Dead parent?",
2853 /*** all non capture option specific ***/
2854 case 'D': /* Print a list of capture devices and exit */
2855 list_interfaces = TRUE;
2858 case 'L': /* Print list of link-layer types and exit */
2859 list_link_layer_types = TRUE;
2862 case 'S': /* Print interface statistics once a second */
2863 print_statistics = TRUE;
2866 case 'M': /* For -D and -L, print machine-readable output */
2867 machine_readable = TRUE;
2870 case '?': /* Bad flag - print usage message */
2871 cmdarg_err("Invalid Option: %s", argv[optind-1]);
2879 /* user specified file name as regular command-line argument */
2880 /* XXX - use it as the capture file name (or something else)? */
2887 * Extra command line arguments were specified; complain.
2888 * XXX - interpret as capture filter, as tcpdump and tshark do?
2890 cmdarg_err("Invalid argument: %s", argv[0]);
2899 if (run_once_args > 1) {
2900 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
2902 } else if (list_link_layer_types) {
2903 /* We're supposed to list the link-layer types for an interface;
2904 did the user also specify a capture file to be read? */
2905 /* No - did they specify a ring buffer option? */
2906 if (global_capture_opts.multi_files_on) {
2907 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
2911 /* No - was the ring buffer option specified and, if so, does it make
2913 if (global_capture_opts.multi_files_on) {
2914 /* Ring buffer works only under certain conditions:
2915 a) ring buffer does not work with temporary files;
2916 b) it makes no sense to enable the ring buffer if the maximum
2917 file size is set to "infinite". */
2918 if (global_capture_opts.save_file == NULL) {
2919 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
2920 global_capture_opts.multi_files_on = FALSE;
2922 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
2923 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
2924 /* XXX - this must be redesigned as the conditions changed */
2925 /* global_capture_opts.multi_files_on = FALSE;*/
2930 if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
2931 /* cmdarg_err() already called .... */
2935 /* Let the user know what interface was chosen. */
2936 /* get_interface_descriptive_name() is not available! */
2937 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", global_capture_opts.iface);
2939 if (list_interfaces) {
2940 status = capture_opts_list_interfaces(machine_readable);
2942 } else if (list_link_layer_types) {
2943 status = capture_opts_list_link_layer_types(&global_capture_opts, machine_readable);
2945 } else if (print_statistics) {
2946 status = print_statistics_loop(machine_readable);
2950 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
2951 capture_opts_trim_ring_num_files(&global_capture_opts);
2953 /* Now start the capture. */
2955 if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
2959 /* capture failed */
2966 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
2967 const char *message, gpointer user_data _U_)
2974 /* ignore log message, if log_level isn't interesting */
2975 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
2976 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
2981 /* create a "timestamp" */
2983 today = localtime(&curr);
2985 switch(log_level & G_LOG_LEVEL_MASK) {
2986 case G_LOG_LEVEL_ERROR:
2989 case G_LOG_LEVEL_CRITICAL:
2992 case G_LOG_LEVEL_WARNING:
2995 case G_LOG_LEVEL_MESSAGE:
2998 case G_LOG_LEVEL_INFO:
3001 case G_LOG_LEVEL_DEBUG:
3005 fprintf(stderr, "unknown log_level %u\n", log_level);
3007 g_assert_not_reached();
3010 /* Generate the output message */
3011 if(log_level & G_LOG_LEVEL_MESSAGE) {
3012 /* normal user messages without additional infos */
3013 msg = g_strdup_printf("%s\n", message);
3015 /* info/debug messages with additional infos */
3016 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
3017 today->tm_hour, today->tm_min, today->tm_sec,
3018 log_domain != NULL ? log_domain : "",
3022 /* DEBUG & INFO msgs (if we're debugging today) */
3023 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3024 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3025 #ifdef DEBUG_DUMPCAP
3026 fprintf(stderr, "%s", msg);
3029 #ifdef DEBUG_CHILD_DUMPCAP
3030 fprintf(debug_log, "%s", msg);
3038 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
3039 /* to parent especially formatted if dumpcap running as child. */
3040 if (capture_child) {
3041 sync_pipe_errmsg_to_parent(2, msg, "");
3043 fprintf(stderr, "%s", msg);
3050 /****************************************************************************************************************/
3051 /* indication report routines */
3055 report_packet_count(int packet_count)
3057 char tmp[SP_DECISIZE+1+1];
3058 static int count = 0;
3061 g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
3062 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
3063 pipe_write_block(2, SP_PACKET_COUNT, tmp);
3065 count += packet_count;
3066 fprintf(stderr, "\rPackets: %u ", count);
3067 /* stderr could be line buffered */
3073 report_new_capture_file(const char *filename)
3076 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
3077 pipe_write_block(2, SP_FILE, filename);
3079 fprintf(stderr, "File: %s\n", filename);
3080 /* stderr could be line buffered */
3086 report_cfilter_error(const char *cfilter, const char *errmsg)
3088 if (capture_child) {
3089 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
3090 pipe_write_block(2, SP_BAD_FILTER, errmsg);
3093 "Invalid capture filter: \"%s\"!\n"
3095 "That string isn't a valid capture filter (%s).\n"
3096 "See the User's Guide for a description of the capture filter syntax.\n",
3102 report_capture_error(const char *error_msg, const char *secondary_error_msg)
3105 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3106 "Primary Error: %s", error_msg);
3107 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3108 "Secondary Error: %s", secondary_error_msg);
3109 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
3111 fprintf(stderr, "%s\n%s\n", error_msg, secondary_error_msg);
3116 report_packet_drops(guint32 drops)
3118 char tmp[SP_DECISIZE+1+1];
3120 g_snprintf(tmp, sizeof(tmp), "%u", drops);
3123 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
3124 pipe_write_block(2, SP_DROPS, tmp);
3126 fprintf(stderr, "Packets dropped: %s\n", tmp);
3127 /* stderr could be line buffered */
3133 /****************************************************************************************************************/
3134 /* signal_pipe handling */
3139 signal_pipe_check_running(void)
3141 /* any news from our parent? -> just stop the capture */
3145 /* if we are running standalone, no check required */
3146 if(!capture_child) {
3150 if(!sig_pipe_name || !sig_pipe_handle) {
3151 /* This shouldn't happen */
3152 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3153 "Signal pipe: No name or handle");
3158 * XXX - We should have the process ID of the parent (from the "-Z" flag)
3159 * at this point. Should we check to see if the parent is still alive,
3160 * e.g. by using OpenProcess?
3163 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
3165 if(!result || avail > 0) {
3166 /* peek failed or some bytes really available */
3167 /* (if not piping from stdin this would fail) */
3168 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3169 "Signal pipe: Stop capture: %s", sig_pipe_name);
3170 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3171 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
3172 sig_pipe_handle, result, avail);
3175 /* pipe ok and no bytes available */
3182 * Editor modelines - http://www.wireshark.org/tools/modelines.html
3187 * indent-tabs-mode: nil
3190 * vi: set shiftwidth=4 tabstop=8 expandtab
3191 * :indentSize=4:tabSize=8:noTabs=true: