5 * Wireshark - Network traffic analyzer
6 * By Gerald Combs <gerald@wireshark.org>
7 * Copyright 1998 Gerald Combs
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 #include <stdlib.h> /* for exit() */
35 #ifdef HAVE_SYS_TYPES_H
36 # include <sys/types.h>
39 #ifdef HAVE_SYS_STAT_H
40 # include <sys/stat.h>
51 #if defined(__APPLE__) && defined(__LP64__)
52 #include <sys/utsname.h>
69 # include <sys/prctl.h>
70 # include <sys/capability.h>
73 #include "ringbuffer.h"
74 #include "clopts_common.h"
75 #include "cmdarg_err.h"
76 #include "version_info.h"
81 #include "capture-pcap-util.h"
84 #include "capture-wpcap.h"
85 #include <wsutil/unicode-utils.h>
88 #include <wsutil/privileges.h>
90 #include "sync_pipe.h"
92 #include "capture_opts.h"
93 #include "capture_sync.h"
95 #include "conditions.h"
96 #include "capture_stop_conditions.h"
100 #include "wsutil/file_util.h"
103 * Get information about libpcap format from "wiretap/libpcap.h".
104 * XXX - can we just use pcap_open_offline() to read the pipe?
106 #include "wiretap/libpcap.h"
108 /**#define DEBUG_DUMPCAP**/
109 /**#define DEBUG_CHILD_DUMPCAP**/
111 #ifdef DEBUG_CHILD_DUMPCAP
112 FILE *debug_log; /* for logging debug messages to */
113 /* a file if DEBUG_CHILD_DUMPCAP */
121 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
123 static gchar *sig_pipe_name = NULL;
124 static HANDLE sig_pipe_handle = NULL;
125 static gboolean signal_pipe_check_running(void);
129 static GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
130 static GMutex *cap_pipe_read_mtx;
133 /** Stop a low-level capture (stops the capture child). */
134 static void capture_loop_stop(void);
136 #if !defined (__linux__)
137 #ifndef HAVE_PCAP_BREAKLOOP
139 * We don't have pcap_breakloop(), which is the only way to ensure that
140 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
141 * won't, if the call to read the next packet or batch of packets is
142 * is interrupted by a signal on UN*X, just go back and try again to
145 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
146 * the signal handler, set a flag to stop capturing; however, without
147 * a guarantee of that sort, we can't guarantee that we'll stop capturing
148 * if the read will be retried and won't time out if no packets arrive.
150 * Therefore, on at least some platforms, we work around the lack of
151 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
152 * to wait for packets to arrive, so that we're probably going to be
153 * blocked in the select() when the signal arrives, and can just bail
154 * out of the loop at that point.
156 * However, we don't want to that on BSD (because "select()" doesn't work
157 * correctly on BPF devices on at least some releases of some flavors of
158 * BSD), and we don't want to do it on Windows (because "select()" is
159 * something for sockets, not for arbitrary handles). (Note that "Windows"
160 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
161 * using WinPcap, not a UNIX libpcap.)
163 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
164 * on BSD times out even if no packets have arrived, so we'll eventually
165 * exit pcap_dispatch() with an indication that no packets have arrived,
166 * and will break out of the capture loop at that point.
168 * On Windows, we can't send a SIGINT to stop capturing, so none of this
169 * applies in any case.
171 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
172 * want to include it if it's not present on this platform, however.
174 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
175 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
177 # define MUST_DO_SELECT
178 # endif /* avoid select */
179 #endif /* HAVE_PCAP_BREAKLOOP */
181 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
182 * in pcap_dispatch(); on the other hand, select() works just fine there.
183 * Hence we use a select for that come what may.
185 #define MUST_DO_SELECT
188 /** init the capture filter */
191 INITFILTER_BAD_FILTER,
192 INITFILTER_OTHER_ERROR
193 } initfilter_status_t;
195 typedef struct _loop_data {
197 gboolean go; /* TRUE as long as we're supposed to keep capturing */
198 int err; /* if non-zero, error seen while capturing */
199 gint packet_count; /* Number of packets we have already captured */
200 gint packet_max; /* Number of packets we're supposed to capture - 0 means infinite */
202 /* pcap "input file" */
203 pcap_t *pcap_h; /* pcap handle */
204 gboolean pcap_err; /* TRUE if error from pcap */
205 #ifdef MUST_DO_SELECT
206 int pcap_fd; /* pcap file descriptor */
209 /* capture pipe (unix only "input file") */
210 gboolean from_cap_pipe; /* TRUE if we are capturing data from a capture pipe */
211 struct pcap_hdr cap_pipe_hdr; /* Pcap header when capturing from a pipe */
212 struct pcaprec_modified_hdr cap_pipe_rechdr; /* Pcap record header when capturing from a pipe */
214 HANDLE cap_pipe_h; /* The handle of the capture pipe */
216 int cap_pipe_fd; /* the file descriptor of the capture pipe */
218 gboolean cap_pipe_modified; /* TRUE if data in the pipe uses modified pcap headers */
219 gboolean cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
221 char * cap_pipe_buf; /* Pointer to the data buffer we read into */
222 #endif /* USE_THREADS */
223 int cap_pipe_bytes_to_read;/* Used by cap_pipe_dispatch */
224 int cap_pipe_bytes_read; /* Used by cap_pipe_dispatch */
226 STATE_EXPECT_REC_HDR,
231 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
243 * Standard secondary message for unexpected errors.
245 static const char please_report[] =
246 "Please report this to the Wireshark developers.\n"
247 "(This is not a crash; please do not report it as such.)";
250 * This needs to be static, so that the SIGINT handler can clear the "go"
253 static loop_data global_ld;
257 * Timeout, in milliseconds, for reads from the stream of captured packets.
259 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
260 * 64-bit applications, with sub-second timeouts not to work. The bug is
263 #if defined(__APPLE__) && defined(__LP64__)
264 static int need_timeout_workaround;
266 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
268 #define CAP_READ_TIMEOUT 250
272 * Timeout, in microseconds, for threaded reads from a pipe.
274 #define THREAD_READ_TIMEOUT 100
276 static char *cap_pipe_err_str;
279 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
280 const char *message, gpointer user_data _U_);
282 /* capture related options */
283 static capture_options global_capture_opts;
285 static void capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
287 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
288 int err, gboolean is_close);
290 static void exit_main(int err) G_GNUC_NORETURN;
292 static void report_new_capture_file(const char *filename);
293 static void report_packet_count(int packet_count);
294 static void report_packet_drops(guint32 drops);
295 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
296 static void report_cfilter_error(const char *cfilter, const char *errmsg);
299 print_usage(gboolean print_ver) {
307 "Dumpcap " VERSION "%s\n"
308 "Capture network packets and dump them into a libpcap file.\n"
309 "See http://www.wireshark.org for more information.\n",
310 wireshark_svnversion);
314 fprintf(output, "\nUsage: dumpcap [options] ...\n");
315 fprintf(output, "\n");
316 fprintf(output, "Capture interface:\n");
317 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
318 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
319 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
320 fprintf(output, " -p don't capture in promiscuous mode\n");
322 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
324 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
325 fprintf(output, " -D print list of interfaces and exit\n");
326 fprintf(output, " -L print list of link-layer types of iface and exit\n");
327 fprintf(output, " -S print statistics for each interface once every second\n");
328 fprintf(output, " -M for -D, -L, and -S produce machine-readable output\n");
329 fprintf(output, "\n");
330 #ifdef HAVE_PCAP_REMOTE
331 fprintf(output, "\nRPCAP options:\n");
332 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
333 fprintf(output, " -u use UDP for RPCAP data transfer\n");
334 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
335 #ifdef HAVE_PCAP_SETSAMPLING
336 fprintf(output, " -m <sampling type> use packet sampling\n");
337 fprintf(output, " count:NUM - capture one packet of every NUM\n");
338 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
341 fprintf(output, "Stop conditions:\n");
342 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
343 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
344 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
345 fprintf(output, " files:NUM - stop after NUM files\n");
346 /*fprintf(output, "\n");*/
347 fprintf(output, "Output (files):\n");
348 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
349 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
350 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
351 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
352 fprintf(output, " -n use pcapng format instead of pcap\n");
353 /*fprintf(output, "\n");*/
354 fprintf(output, "Miscellaneous:\n");
355 fprintf(output, " -v print version information and exit\n");
356 fprintf(output, " -h display this help and exit\n");
357 fprintf(output, "\n");
358 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcap\n");
359 fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcap\"\n");
360 fprintf(output, "\n");
361 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
365 show_version(GString *comp_info_str, GString *runtime_info_str)
369 "Dumpcap " VERSION "%s\n"
374 "See http://www.wireshark.org for more information.\n",
375 wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
379 * Report an error in command-line arguments.
382 cmdarg_err(const char *fmt, ...)
388 /* Generate a 'special format' message back to parent */
390 msg = g_strdup_vprintf(fmt, ap);
391 sync_pipe_errmsg_to_parent(2, msg, "");
396 fprintf(stderr, "dumpcap: ");
397 vfprintf(stderr, fmt, ap);
398 fprintf(stderr, "\n");
404 * Report additional information for an error in command-line arguments.
407 cmdarg_err_cont(const char *fmt, ...)
414 msg = g_strdup_vprintf(fmt, ap);
415 sync_pipe_errmsg_to_parent(2, msg, "");
420 vfprintf(stderr, fmt, ap);
421 fprintf(stderr, "\n");
431 /* Print the number of packets captured for each interface until we're killed. */
433 print_statistics_loop(gboolean machine_readable)
435 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
441 char errbuf[PCAP_ERRBUF_SIZE];
444 if_list = get_interface_list(&err, &err_str);
445 if (if_list == NULL) {
447 case CANT_GET_INTERFACE_LIST:
448 cmdarg_err("%s", err_str);
452 case NO_INTERFACES_FOUND:
453 cmdarg_err("There are no interfaces on which a capture can be done");
459 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
460 if_info = if_entry->data;
461 #ifdef HAVE_PCAP_OPEN
462 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
464 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
468 if_stat = g_malloc(sizeof(if_stat_t));
469 if_stat->name = g_strdup(if_info->name);
471 stat_list = g_list_append(stat_list, if_stat);
476 cmdarg_err("There are no interfaces on which a capture can be done");
480 if (!machine_readable) {
481 printf("%-15s %10s %10s\n", "Interface", "Received",
486 while (global_ld.go) {
487 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
488 if_stat = stat_entry->data;
489 pcap_stats(if_stat->pch, &ps);
491 if (!machine_readable) {
492 printf("%-15s %10u %10u\n", if_stat->name,
493 ps.ps_recv, ps.ps_drop);
495 printf("%s\t%u\t%u\n", if_stat->name,
496 ps.ps_recv, ps.ps_drop);
501 if (! global_ld.from_cap_pipe)
508 /* XXX - Not reached. Should we look for 'q' in stdin? */
509 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
510 if_stat = stat_entry->data;
511 pcap_close(if_stat->pch);
512 g_free(if_stat->name);
515 g_list_free(stat_list);
516 free_interface_list(if_list);
524 capture_cleanup_handler(DWORD dwCtrlType)
526 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
527 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
528 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
529 like SIGTERM at least when the machine's shutting down.
531 For now, if we're running as a command rather than a capture child,
532 we handle all but CTRL_LOGOFF_EVENT as indications that we should
533 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
536 If we're not running as a capture child, we might be running as
537 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
538 user logs out. (XXX - can we explicitly check whether we're
539 running as a service?) */
541 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
542 "Console: Control signal");
543 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
544 "Console: Control signal, CtrlType: %u", dwCtrlType);
546 /* Keep capture running if we're a service and a user logs off */
547 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
556 capture_cleanup_handler(int signum _U_)
558 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
559 SIGTERM. We assume that if the user wanted it to keep running
560 after they logged out, they'd have nohupped it. */
562 /* Note: don't call g_log() in the signal handler: if we happened to be in
563 * g_log() in process context when the signal came in, g_log will detect
564 * the "recursion" and abort.
571 static void exit_main(int status)
574 /* Shutdown windows sockets */
577 /* can be helpful for debugging */
579 printf("Press any key\n");
590 * If we were linked with libcap (not libpcap), make sure we have
591 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
592 * (See comment in main() for details)
596 #if 0 /* Set to enable capability debugging */
597 /* see 'man cap_to_text()' for explanation of output */
598 /* '=' means 'all= ' ie: no capabilities */
599 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
601 print_caps(char *pfx) {
602 cap_t caps = cap_get_proc();
603 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
604 "%s: EUID: %d Capabilities: %s", pfx,
605 geteuid(), cap_to_text(caps, NULL));
608 print_caps(char *pfx _U_) {
613 relinquish_privs_except_capture(void)
615 /* If 'started_with_special_privs' (ie: suid) then enable for
616 * ourself the NET_ADMIN and NET_RAW capabilities and then
617 * drop our suid privileges.
619 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
620 * stuff we don't need (and shouldn't have).
621 * CAP_NET_RAW: Packet capture (raw sockets).
624 if (started_with_special_privs()) {
625 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
626 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
628 cap_t caps = cap_init(); /* all capabilities initialized to off */
630 print_caps("Pre drop, pre set");
632 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
633 cmdarg_err("prctl() fail return: %s", strerror(errno));
636 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
637 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
639 if (cap_set_proc(caps)) {
640 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
642 print_caps("Pre drop, post set");
644 relinquish_special_privs_perm();
646 print_caps("Post drop, pre set");
647 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
648 if (cap_set_proc(caps)) {
649 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
651 print_caps("Post drop, post set");
659 relinquish_all_capabilities()
661 /* Drop any and all capabilities this process may have. */
662 /* Allowed whether or not process has any privileges. */
663 cap_t caps = cap_init(); /* all capabilities initialized to off */
664 print_caps("Pre-clear");
665 if (cap_set_proc(caps)) {
666 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
668 print_caps("Post-clear");
672 #endif /* HAVE_LIBCAP */
674 /* Take care of byte order in the libpcap headers read from pipes.
675 * (function taken from wiretap/libpcap.c) */
677 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
680 /* Byte-swap the record header fields. */
681 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
682 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
683 rechdr->incl_len = BSWAP32(rechdr->incl_len);
684 rechdr->orig_len = BSWAP32(rechdr->orig_len);
687 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
688 swapped, in order to match the BPF header layout.
690 Unfortunately, some files were, according to a comment in the "libpcap"
691 source, written with version 2.3 in their headers but without the
692 interchanged fields, so if "incl_len" is greater than "orig_len" - which
693 would make no sense - we assume that we need to swap them. */
694 if (hdr->version_major == 2 &&
695 (hdr->version_minor < 3 ||
696 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
699 temp = rechdr->orig_len;
700 rechdr->orig_len = rechdr->incl_len;
701 rechdr->incl_len = temp;
707 * Thread function that reads from a pipe and pushes the data
708 * to the main application thread.
711 * XXX Right now we use async queues for basic signaling. The main thread
712 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
713 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
714 * Iff the read is successful cap_pipe_read pushes an item onto
715 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
716 * the queues themselves (yet).
718 * We might want to move some of the cap_pipe_dispatch logic here so that
719 * we can let cap_pipe_read run independently, queuing up multiple reads
720 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
722 static void *cap_pipe_read(void *ld_ptr) {
723 loop_data *ld = (loop_data *)ld_ptr;
732 while (ld->cap_pipe_err == PIPOK) {
733 g_async_queue_pop(cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
734 g_mutex_lock(cap_pipe_read_mtx);
736 while (bytes_read < (int) ld->cap_pipe_bytes_to_read) {
738 /* If we try to use read() on a named pipe on Windows with partial
739 * data it appears to return EOF.
741 res = ReadFile(ld->cap_pipe_h, ld->cap_pipe_buf+bytes_read,
742 ld->cap_pipe_bytes_to_read - bytes_read,
747 last_err = GetLastError();
748 if (last_err == ERROR_MORE_DATA) {
750 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
751 ld->cap_pipe_err = PIPEOF;
755 ld->cap_pipe_err = PIPERR;
758 } else if (b == 0 && ld->cap_pipe_bytes_to_read > 0) {
759 ld->cap_pipe_err = PIPEOF;
764 b = read(ld->cap_pipe_fd, ld->cap_pipe_buf+bytes_read,
765 ld->cap_pipe_bytes_to_read - bytes_read);
768 ld->cap_pipe_err = PIPEOF;
772 ld->cap_pipe_err = PIPERR;
781 ld->cap_pipe_bytes_read = bytes_read;
782 if (ld->cap_pipe_bytes_read >= ld->cap_pipe_bytes_to_read) {
783 g_async_queue_push(cap_pipe_done_q, ld->cap_pipe_buf); /* Any non-NULL value will do */
785 g_mutex_unlock(cap_pipe_read_mtx);
789 #endif /* USE_THREADS */
791 /* Provide select() functionality for a single file descriptor
792 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
794 * Returns the same values as select. If an error is returned,
795 * the string cap_pipe_err_str should be used instead of errno.
798 cap_pipe_select(int pipe_fd) {
800 struct timeval timeout, *pto;
803 cap_pipe_err_str = "Unknown error";
806 FD_SET(pipe_fd, &rfds);
809 timeout.tv_usec = CAP_READ_TIMEOUT * 1000;
812 sel_ret = select(pipe_fd+1, &rfds, NULL, NULL, pto);
814 cap_pipe_err_str = strerror(errno);
819 /* Mimic pcap_open_live() for pipe captures
820 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
822 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
823 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
825 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
826 char *errmsg, int errmsgl)
829 struct stat pipe_stat;
832 unsigned int bytes_read;
843 ld->cap_pipe_fd = -1;
845 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
847 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
850 * XXX (T)Wireshark blocks until we return
852 if (strcmp(pipename, "-") == 0) {
854 fd = 0; /* read from stdin */
856 ld->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
860 if (ws_stat(pipename, &pipe_stat) < 0) {
861 if (errno == ENOENT || errno == ENOTDIR)
862 ld->cap_pipe_err = PIPNEXIST;
864 g_snprintf(errmsg, errmsgl,
865 "The capture session could not be initiated "
866 "due to error on pipe: %s", strerror(errno));
867 ld->cap_pipe_err = PIPERR;
871 if (! S_ISFIFO(pipe_stat.st_mode)) {
872 if (S_ISCHR(pipe_stat.st_mode)) {
874 * Assume the user specified an interface on a system where
875 * interfaces are in /dev. Pretend we haven't seen it.
877 ld->cap_pipe_err = PIPNEXIST;
880 g_snprintf(errmsg, errmsgl,
881 "The capture session could not be initiated because\n"
882 "\"%s\" is neither an interface nor a pipe", pipename);
883 ld->cap_pipe_err = PIPERR;
887 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
889 g_snprintf(errmsg, errmsgl,
890 "The capture session could not be initiated "
891 "due to error on pipe open: %s", strerror(errno));
892 ld->cap_pipe_err = PIPERR;
896 #define PIPE_STR "\\pipe\\"
897 /* Under Windows, named pipes _must_ have the form
898 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
900 pncopy = g_strdup(pipename);
901 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
902 pos = strchr(pncopy + 3, '\\');
903 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
910 g_snprintf(errmsg, errmsgl,
911 "The capture session could not be initiated because\n"
912 "\"%s\" is neither an interface nor a pipe", pipename);
913 ld->cap_pipe_err = PIPNEXIST;
917 /* Wait for the pipe to appear */
919 ld->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
920 OPEN_EXISTING, 0, NULL);
922 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE)
925 if (GetLastError() != ERROR_PIPE_BUSY) {
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\" could not be started "
930 "due to error on pipe open: %s (error %d)",
931 pipename, utf_16to8(err_str), GetLastError());
933 ld->cap_pipe_err = PIPERR;
937 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
938 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
939 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
940 g_snprintf(errmsg, errmsgl,
941 "The capture session on \"%s\" timed out during "
942 "pipe open: %s (error %d)",
943 pipename, utf_16to8(err_str), GetLastError());
945 ld->cap_pipe_err = PIPERR;
953 ld->from_cap_pipe = TRUE;
956 /* read the pcap header */
958 while (bytes_read < sizeof magic) {
959 sel_ret = cap_pipe_select(fd);
961 g_snprintf(errmsg, errmsgl,
962 "Unexpected error from select: %s", strerror(errno));
964 } else if (sel_ret > 0) {
965 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
968 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
970 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
977 #else /* USE_THREADS */
978 g_thread_create(&cap_pipe_read, ld, FALSE, NULL);
980 ld->cap_pipe_buf = (char *) &magic;
981 ld->cap_pipe_bytes_read = 0;
982 ld->cap_pipe_bytes_to_read = sizeof(magic);
983 /* We don't have to worry about cap_pipe_read_mtx here */
984 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
985 g_async_queue_pop(cap_pipe_done_q);
986 if (ld->cap_pipe_bytes_read <= 0) {
987 if (ld->cap_pipe_bytes_read == 0)
988 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
990 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
994 #endif /* USE_THREADS */
998 /* Host that wrote it has our byte order, and was running
999 a program using either standard or ss990417 libpcap. */
1000 ld->cap_pipe_byte_swapped = FALSE;
1001 ld->cap_pipe_modified = FALSE;
1003 case PCAP_MODIFIED_MAGIC:
1004 /* Host that wrote it has our byte order, but was running
1005 a program using either ss990915 or ss991029 libpcap. */
1006 ld->cap_pipe_byte_swapped = FALSE;
1007 ld->cap_pipe_modified = TRUE;
1009 case PCAP_SWAPPED_MAGIC:
1010 /* Host that wrote it has a byte order opposite to ours,
1011 and was running a program using either standard or
1012 ss990417 libpcap. */
1013 ld->cap_pipe_byte_swapped = TRUE;
1014 ld->cap_pipe_modified = FALSE;
1016 case PCAP_SWAPPED_MODIFIED_MAGIC:
1017 /* Host that wrote it out has a byte order opposite to
1018 ours, and was running a program using either ss990915
1019 or ss991029 libpcap. */
1020 ld->cap_pipe_byte_swapped = TRUE;
1021 ld->cap_pipe_modified = TRUE;
1024 /* Not a "libpcap" type we know about. */
1025 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
1030 /* Read the rest of the header */
1032 while (bytes_read < sizeof(struct pcap_hdr)) {
1033 sel_ret = cap_pipe_select(fd);
1035 g_snprintf(errmsg, errmsgl,
1036 "Unexpected error from select: %s", strerror(errno));
1038 } else if (sel_ret > 0) {
1039 b = read(fd, ((char *)hdr)+bytes_read,
1040 sizeof(struct pcap_hdr) - bytes_read);
1043 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1045 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
1052 #else /* USE_THREADS */
1053 ld->cap_pipe_buf = (char *) hdr;
1054 ld->cap_pipe_bytes_read = 0;
1055 ld->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1056 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1057 g_async_queue_pop(cap_pipe_done_q);
1058 if (ld->cap_pipe_bytes_read <= 0) {
1059 if (ld->cap_pipe_bytes_read == 0)
1060 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1062 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
1066 #endif /* USE_THREADS */
1068 if (ld->cap_pipe_byte_swapped) {
1069 /* Byte-swap the header fields about which we care. */
1070 hdr->version_major = BSWAP16(hdr->version_major);
1071 hdr->version_minor = BSWAP16(hdr->version_minor);
1072 hdr->snaplen = BSWAP32(hdr->snaplen);
1073 hdr->network = BSWAP32(hdr->network);
1075 ld->linktype = hdr->network;
1077 if (hdr->version_major < 2) {
1078 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1082 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1083 ld->cap_pipe_err = PIPOK;
1085 ld->cap_pipe_fd = fd;
1090 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1091 ld->cap_pipe_err = PIPERR;
1094 ld->cap_pipe_fd = -1;
1101 /* We read one record from the pipe, take care of byte order in the record
1102 * header, write the record to the capture file, and update capture statistics. */
1104 cap_pipe_dispatch(loop_data *ld, guchar *data, char *errmsg, int errmsgl)
1106 struct pcap_pkthdr phdr;
1107 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1119 #ifdef LOG_CAPTURE_VERBOSE
1120 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1123 switch (ld->cap_pipe_state) {
1125 case STATE_EXPECT_REC_HDR:
1127 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1130 ld->cap_pipe_state = STATE_READ_REC_HDR;
1131 ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
1132 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1133 ld->cap_pipe_bytes_read = 0;
1136 ld->cap_pipe_buf = (char *) &ld->cap_pipe_rechdr;
1137 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1138 g_mutex_unlock(cap_pipe_read_mtx);
1143 case STATE_READ_REC_HDR:
1145 b = read(ld->cap_pipe_fd, ((char *)&ld->cap_pipe_rechdr)+ld->cap_pipe_bytes_read,
1146 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1149 result = PD_PIPE_EOF;
1151 result = PD_PIPE_ERR;
1154 ld->cap_pipe_bytes_read += b;
1155 #else /* USE_THREADS */
1156 g_get_current_time(&wait_time);
1157 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1158 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1159 if (ld->cap_pipe_err == PIPEOF) {
1160 result = PD_PIPE_EOF;
1162 } else if (ld->cap_pipe_err == PIPERR) {
1163 result = PD_PIPE_ERR;
1169 #endif /* USE_THREADS */
1170 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1172 result = PD_REC_HDR_READ;
1175 case STATE_EXPECT_DATA:
1177 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1180 ld->cap_pipe_state = STATE_READ_DATA;
1181 ld->cap_pipe_bytes_to_read = ld->cap_pipe_rechdr.hdr.incl_len;
1182 ld->cap_pipe_bytes_read = 0;
1185 ld->cap_pipe_buf = (char *) data;
1186 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1187 g_mutex_unlock(cap_pipe_read_mtx);
1192 case STATE_READ_DATA:
1194 b = read(ld->cap_pipe_fd, data+ld->cap_pipe_bytes_read,
1195 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1198 result = PD_PIPE_EOF;
1200 result = PD_PIPE_ERR;
1203 ld->cap_pipe_bytes_read += b;
1204 #else /* USE_THREADS */
1205 g_get_current_time(&wait_time);
1206 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1207 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1208 if (ld->cap_pipe_err == PIPEOF) {
1209 result = PD_PIPE_EOF;
1211 } else if (ld->cap_pipe_err == PIPERR) {
1212 result = PD_PIPE_ERR;
1218 #endif /* USE_THREADS */
1219 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1221 result = PD_DATA_READ;
1225 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
1228 } /* switch (ld->cap_pipe_state) */
1231 * We've now read as much data as we were expecting, so process it.
1235 case PD_REC_HDR_READ:
1236 /* We've read the header. Take care of byte order. */
1237 cap_pipe_adjust_header(ld->cap_pipe_byte_swapped, &ld->cap_pipe_hdr,
1238 &ld->cap_pipe_rechdr.hdr);
1239 if (ld->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1240 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
1241 ld->packet_count+1, ld->cap_pipe_rechdr.hdr.incl_len);
1244 ld->cap_pipe_state = STATE_EXPECT_DATA;
1248 /* Fill in a "struct pcap_pkthdr", and process the packet. */
1249 phdr.ts.tv_sec = ld->cap_pipe_rechdr.hdr.ts_sec;
1250 phdr.ts.tv_usec = ld->cap_pipe_rechdr.hdr.ts_usec;
1251 phdr.caplen = ld->cap_pipe_rechdr.hdr.incl_len;
1252 phdr.len = ld->cap_pipe_rechdr.hdr.orig_len;
1254 capture_loop_packet_cb((u_char *)ld, &phdr, data);
1256 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1260 ld->cap_pipe_err = PIPEOF;
1265 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1266 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1267 g_snprintf(errmsg, errmsgl,
1268 "Error reading from pipe: %s (error %d)",
1269 utf_16to8(err_str), GetLastError());
1272 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
1280 ld->cap_pipe_err = PIPERR;
1281 /* Return here rather than inside the switch to prevent GCC warning */
1286 /** Open the capture input file (pcap or capture pipe).
1287 * Returns TRUE if it succeeds, FALSE otherwise. */
1289 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
1290 char *errmsg, size_t errmsg_len,
1291 char *secondary_errmsg, size_t secondary_errmsg_len)
1293 gchar open_err_str[PCAP_ERRBUF_SIZE];
1294 gchar *sync_msg_str;
1295 static const char ppamsg[] = "can't find PPA for ";
1296 const char *set_linktype_err_str;
1297 const char *libpcap_warn;
1299 gchar *sync_secondary_msg_str;
1301 WORD wVersionRequested;
1304 #ifdef HAVE_PCAP_REMOTE
1305 struct pcap_rmtauth auth;
1309 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
1312 /* XXX - opening Winsock on tshark? */
1314 /* Initialize Windows Socket if we are in a WIN32 OS
1315 This needs to be done before querying the interface for network/netmask */
1317 /* XXX - do we really require 1.1 or earlier?
1318 Are there any versions that support only 2.0 or higher? */
1319 wVersionRequested = MAKEWORD(1, 1);
1320 err = WSAStartup(wVersionRequested, &wsaData);
1324 case WSASYSNOTREADY:
1325 g_snprintf(errmsg, (gulong) errmsg_len,
1326 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
1329 case WSAVERNOTSUPPORTED:
1330 g_snprintf(errmsg, (gulong) errmsg_len,
1331 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
1332 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
1335 case WSAEINPROGRESS:
1336 g_snprintf(errmsg, (gulong) errmsg_len,
1337 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
1341 g_snprintf(errmsg, (gulong) errmsg_len,
1342 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
1346 g_snprintf(errmsg, (gulong) errmsg_len,
1347 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
1351 g_snprintf(errmsg, (gulong) errmsg_len,
1352 "Couldn't initialize Windows Sockets: error %d", err);
1355 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
1360 /* Open the network interface to capture from it.
1361 Some versions of libpcap may put warnings into the error buffer
1362 if they succeed; to tell if that's happened, we have to clear
1363 the error buffer, and check if it's still a null string. */
1364 open_err_str[0] = '\0';
1365 #ifdef HAVE_PCAP_OPEN
1366 auth.type = capture_opts->auth_type == CAPTURE_AUTH_PWD ?
1367 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
1368 auth.username = capture_opts->auth_username;
1369 auth.password = capture_opts->auth_password;
1371 ld->pcap_h = pcap_open(capture_opts->iface,
1372 capture_opts->has_snaplen ? capture_opts->snaplen :
1373 WTAP_MAX_PACKET_SIZE,
1375 (capture_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
1376 (capture_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
1377 (capture_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
1378 CAP_READ_TIMEOUT, &auth, open_err_str);
1380 ld->pcap_h = pcap_open_live(capture_opts->iface,
1381 capture_opts->has_snaplen ? capture_opts->snaplen :
1382 WTAP_MAX_PACKET_SIZE,
1383 capture_opts->promisc_mode, CAP_READ_TIMEOUT,
1387 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
1388 /* to remove any suid privileges. */
1389 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
1390 /* (euid/egid have already previously been set to ruid/rgid. */
1391 /* (See comment in main() for details) */
1393 relinquish_special_privs_perm();
1395 relinquish_all_capabilities();
1398 if (ld->pcap_h != NULL) {
1399 /* we've opened "iface" as a network device */
1401 /* try to set the capture buffer size */
1402 if (capture_opts->buffer_size > 1 &&
1403 pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
1404 sync_secondary_msg_str = g_strdup_printf(
1405 "The capture buffer size of %luMB seems to be too high for your machine,\n"
1406 "the default of 1MB will be used.\n"
1408 "Nonetheless, the capture is started.\n",
1409 capture_opts->buffer_size);
1410 report_capture_error("Couldn't set the capture buffer size!",
1411 sync_secondary_msg_str);
1412 g_free(sync_secondary_msg_str);
1416 #if defined(HAVE_PCAP_REMOTE) && defined(HAVE_PCAP_SETSAMPLING)
1417 if (capture_opts->sampling_method != CAPTURE_SAMP_NONE)
1419 struct pcap_samp *samp;
1421 if ((samp = pcap_setsampling(ld->pcap_h)) != NULL)
1423 switch (capture_opts->sampling_method)
1425 case CAPTURE_SAMP_BY_COUNT:
1426 samp->method = PCAP_SAMP_1_EVERY_N;
1429 case CAPTURE_SAMP_BY_TIMER:
1430 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
1434 sync_msg_str = g_strdup_printf(
1435 "Unknown sampling method %d specified,\n"
1436 "continue without packet sampling",
1437 capture_opts->sampling_method);
1438 report_capture_error("Couldn't set the capture "
1439 "sampling", sync_msg_str);
1440 g_free(sync_msg_str);
1442 samp->value = capture_opts->sampling_param;
1446 report_capture_error("Couldn't set the capture sampling",
1447 "Cannot get packet sampling data structure");
1453 /* setting the data link type only works on real interfaces */
1454 if (capture_opts->linktype != -1) {
1455 set_linktype_err_str = set_pcap_linktype(ld->pcap_h, capture_opts->iface,
1456 capture_opts->linktype);
1457 if (set_linktype_err_str != NULL) {
1458 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
1459 set_linktype_err_str);
1460 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
1464 ld->linktype = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
1466 /* We couldn't open "iface" as a network device. */
1467 /* Try to open it as a pipe */
1468 cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, (int) errmsg_len);
1471 if (ld->cap_pipe_fd == -1) {
1473 if (ld->cap_pipe_h == INVALID_HANDLE_VALUE) {
1476 if (ld->cap_pipe_err == PIPNEXIST) {
1477 /* Pipe doesn't exist, so output message for interface */
1479 /* If we got a "can't find PPA for X" message, warn the user (who
1480 is running (T)Wireshark on HP-UX) that they don't have a version
1481 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1482 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1483 PPA for X" rather than "can't find PPA for X"). */
1484 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1487 "You are running (T)Wireshark with a version of the libpcap library\n"
1488 "that doesn't handle HP-UX network devices well; this means that\n"
1489 "(T)Wireshark may not be able to capture packets.\n"
1491 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1492 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1493 "packaged binary form from the Software Porting And Archive Centre\n"
1494 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1495 "at the URL lists a number of mirror sites.";
1498 g_snprintf(errmsg, (gulong) errmsg_len,
1499 "The capture session could not be initiated (%s).", open_err_str);
1501 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
1502 "Please check to make sure you have sufficient permissions, and that you have "
1503 "the proper interface or pipe specified.%s", libpcap_warn);
1505 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
1507 "Please check that \"%s\" is the proper interface.\n"
1510 "Help can be found at:\n"
1512 " http://wiki.wireshark.org/WinPcap\n"
1513 " http://wiki.wireshark.org/CaptureSetup\n",
1514 capture_opts->iface);
1518 * Else pipe (or file) does exist and cap_pipe_open_live() has
1523 /* cap_pipe_open_live() succeeded; don't want
1524 error message from pcap_open_live() */
1525 open_err_str[0] = '\0';
1528 /* XXX - will this work for tshark? */
1529 #ifdef MUST_DO_SELECT
1530 if (!ld->from_cap_pipe) {
1531 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
1532 ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
1534 ld->pcap_fd = pcap_fileno(ld->pcap_h);
1539 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1540 returned a warning; print it, but keep capturing. */
1541 if (open_err_str[0] != '\0') {
1542 sync_msg_str = g_strdup_printf("%s.", open_err_str);
1543 report_capture_error(sync_msg_str, "");
1544 g_free(sync_msg_str);
1551 /* close the capture input file (pcap or capture pipe) */
1552 static void capture_loop_close_input(loop_data *ld) {
1554 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
1556 /* if open, close the capture pipe "input file" */
1558 if (ld->cap_pipe_fd >= 0) {
1559 g_assert(ld->from_cap_pipe);
1560 ws_close(ld->cap_pipe_fd);
1561 ld->cap_pipe_fd = 0;
1564 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE) {
1565 CloseHandle(ld->cap_pipe_h);
1566 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
1570 /* if open, close the pcap "input file" */
1571 if(ld->pcap_h != NULL) {
1572 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)ld->pcap_h);
1573 g_assert(!ld->from_cap_pipe);
1574 pcap_close(ld->pcap_h);
1581 /* Shut down windows sockets */
1587 /* init the capture filter */
1588 static initfilter_status_t
1589 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe, gchar * iface, gchar * cfilter) {
1590 bpf_u_int32 netnum, netmask;
1591 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
1592 struct bpf_program fcode;
1595 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
1597 /* capture filters only work on real interfaces */
1598 if (cfilter && !from_cap_pipe) {
1599 /* A capture filter was specified; set it up. */
1600 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1602 * Well, we can't get the netmask for this interface; it's used
1603 * only for filters that check for broadcast IP addresses, so
1604 * we just punt and use 0. It might be nice to warn the user,
1605 * but that's a pain in a GUI application, as it'd involve popping
1606 * up a message box, and it's not clear how often this would make
1607 * a difference (only filters that check for IP broadcast addresses
1611 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
1614 if (pcap_compile(pcap_h, &fcode, cfilter, 1, netmask) < 0) {
1615 /* Treat this specially - our caller might try to compile this
1616 as a display filter and, if that succeeds, warn the user that
1617 the display and capture filter syntaxes are different. */
1618 return INITFILTER_BAD_FILTER;
1620 if (pcap_setfilter(pcap_h, &fcode) < 0) {
1621 #ifdef HAVE_PCAP_FREECODE
1622 pcap_freecode(&fcode);
1624 return INITFILTER_OTHER_ERROR;
1626 #ifdef HAVE_PCAP_FREECODE
1627 pcap_freecode(&fcode);
1631 return INITFILTER_NO_ERROR;
1635 /* set up to write to the already-opened capture output file/files */
1637 capture_loop_init_output(capture_options *capture_opts, int save_file_fd, loop_data *ld, char *errmsg, int errmsg_len) {
1641 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
1644 if (ld->from_cap_pipe) {
1645 ld->file_snaplen = ld->cap_pipe_hdr.snaplen;
1648 ld->file_snaplen = pcap_snapshot(ld->pcap_h);
1651 /* Set up to write to the capture file. */
1652 if (capture_opts->multi_files_on) {
1653 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
1655 ld->pdh = libpcap_fdopen(save_file_fd, &err);
1658 gboolean successful;
1660 ld->bytes_written = 0;
1661 if (capture_opts->use_pcapng) {
1664 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
1665 successful = libpcap_write_session_header_block(ld->pdh, appname, &ld->bytes_written, &err) &&
1666 libpcap_write_interface_description_block(ld->pdh, capture_opts->iface, capture_opts->cfilter, ld->linktype, ld->file_snaplen, &ld->bytes_written, &err);
1668 successful = libpcap_write_file_header(ld->pdh, ld->linktype, ld->file_snaplen,
1669 &ld->bytes_written, &err);
1677 if (ld->pdh == NULL) {
1678 /* We couldn't set up to write to the capture file. */
1679 /* XXX - use cf_open_error_message from tshark instead? */
1682 case WTAP_ERR_CANT_OPEN:
1683 g_snprintf(errmsg, errmsg_len, "The file to which the capture would be saved"
1684 " couldn't be created for some unknown reason.");
1687 case WTAP_ERR_SHORT_WRITE:
1688 g_snprintf(errmsg, errmsg_len, "A full header couldn't be written to the file"
1689 " to which the capture would be saved.");
1694 g_snprintf(errmsg, errmsg_len,
1695 "The file to which the capture would be"
1696 " saved (\"%s\") could not be opened: Error %d.",
1697 capture_opts->save_file, err);
1699 g_snprintf(errmsg, errmsg_len,
1700 "The file to which the capture would be"
1701 " saved (\"%s\") could not be opened: %s.",
1702 capture_opts->save_file, strerror(err));
1714 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
1716 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
1718 if (capture_opts->multi_files_on) {
1719 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
1721 if (capture_opts->use_pcapng) {
1722 libpcap_write_interface_statistics_block(ld->pdh, 0, ld->pcap_h, &ld->bytes_written, err_close);
1724 return libpcap_dump_close(ld->pdh, err_close);
1728 /* dispatch incoming packets (pcap or capture pipe)
1730 * Waits for incoming packets to be available, and calls pcap_dispatch()
1731 * to cause them to be processed.
1733 * Returns the number of packets which were processed.
1735 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
1736 * packet-batching behaviour does not cause packets to get held back
1740 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
1741 char *errmsg, int errmsg_len)
1744 gint packet_count_before;
1745 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1750 packet_count_before = ld->packet_count;
1751 if (ld->from_cap_pipe) {
1752 /* dispatch from capture pipe */
1753 #ifdef LOG_CAPTURE_VERBOSE
1754 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
1757 sel_ret = cap_pipe_select(ld->cap_pipe_fd);
1760 if (sel_ret < 0 && errno != EINTR) {
1761 g_snprintf(errmsg, errmsg_len,
1762 "Unexpected error from select: %s", strerror(errno));
1763 report_capture_error(errmsg, please_report);
1768 * "select()" says we can read from the pipe without blocking
1770 #endif /* USE_THREADS */
1771 inpkts = cap_pipe_dispatch(ld, pcap_data, errmsg, errmsg_len);
1781 /* dispatch from pcap */
1782 #ifdef MUST_DO_SELECT
1784 * If we have "pcap_get_selectable_fd()", we use it to get the
1785 * descriptor on which to select; if that's -1, it means there
1786 * is no descriptor on which you can do a "select()" (perhaps
1787 * because you're capturing on a special device, and that device's
1788 * driver unfortunately doesn't support "select()", in which case
1789 * we don't do the select - which means it might not be possible
1790 * to stop a capture until a packet arrives. If that's unacceptable,
1791 * plead with whoever supplies the software for that device to add
1792 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
1793 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
1794 * later, so it can use pcap_breakloop().
1796 #ifdef LOG_CAPTURE_VERBOSE
1797 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
1799 if (ld->pcap_fd != -1) {
1800 sel_ret = cap_pipe_select(ld->pcap_fd);
1803 * "select()" says we can read from it without blocking; go for
1806 * We don't have pcap_breakloop(), so we only process one packet
1807 * per pcap_dispatch() call, to allow a signal to stop the
1808 * processing immediately, rather than processing all packets
1809 * in a batch before quitting.
1811 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb,
1815 /* Error, rather than pcap_breakloop(). */
1816 ld->pcap_err = TRUE;
1818 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1821 if (sel_ret < 0 && errno != EINTR) {
1822 g_snprintf(errmsg, errmsg_len,
1823 "Unexpected error from select: %s", strerror(errno));
1824 report_capture_error(errmsg, please_report);
1830 #endif /* MUST_DO_SELECT */
1832 /* dispatch from pcap without select */
1834 #ifdef LOG_CAPTURE_VERBOSE
1835 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
1839 * On Windows, we don't support asynchronously telling a process to
1840 * stop capturing; instead, we check for an indication on a pipe
1841 * after processing packets. We therefore process only one packet
1842 * at a time, so that we can check the pipe after every packet.
1844 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb, (u_char *) ld);
1846 inpkts = pcap_dispatch(ld->pcap_h, -1, capture_loop_packet_cb, (u_char *) ld);
1850 /* Error, rather than pcap_breakloop(). */
1851 ld->pcap_err = TRUE;
1853 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1855 #else /* pcap_next_ex */
1856 #ifdef LOG_CAPTURE_VERBOSE
1857 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
1859 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
1862 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
1863 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
1864 * This should be fixed in the WinPcap 4.0 alpha release.
1866 * For reference, an example remote interface:
1867 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
1870 /* emulate dispatch from pcap */
1873 struct pcap_pkthdr *pkt_header;
1878 (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1)
1879 capture_loop_packet_cb( (u_char *) ld, pkt_header, pkt_data);
1882 ld->pcap_err = TRUE;
1886 #endif /* pcap_next_ex */
1890 #ifdef LOG_CAPTURE_VERBOSE
1891 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
1894 return ld->packet_count - packet_count_before;
1898 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
1899 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
1901 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
1902 char *errmsg, int errmsg_len) {
1905 gchar *capfile_name;
1906 gboolean is_tempfile;
1911 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
1912 (capture_opts->save_file) ? capture_opts->save_file : "");
1914 if (capture_opts->save_file != NULL) {
1915 /* We return to the caller while the capture is in progress.
1916 * Therefore we need to take a copy of save_file in
1917 * case the caller destroys it after we return.
1919 capfile_name = g_strdup(capture_opts->save_file);
1921 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
1922 if (capture_opts->multi_files_on) {
1923 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
1924 g_snprintf(errmsg, errmsg_len,
1925 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
1926 g_free(capfile_name);
1929 if (strcmp(capfile_name, "-") == 0) {
1930 /* write to stdout */
1933 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
1934 _setmode(1, O_BINARY);
1937 } /* if (...output_to_pipe ... */
1940 if (capture_opts->multi_files_on) {
1941 /* ringbuffer is enabled */
1942 *save_file_fd = ringbuf_init(capfile_name,
1943 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
1945 /* we need the ringbuf name */
1946 if(*save_file_fd != -1) {
1947 g_free(capfile_name);
1948 capfile_name = g_strdup(ringbuf_current_filename());
1951 /* Try to open/create the specified file for use as a capture buffer. */
1952 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
1956 is_tempfile = FALSE;
1958 /* Choose a random name for the temporary capture buffer */
1959 *save_file_fd = create_tempfile(&tmpname, "wireshark");
1960 capfile_name = g_strdup(tmpname);
1964 /* did we fail to open the output file? */
1965 if (*save_file_fd == -1) {
1967 g_snprintf(errmsg, errmsg_len,
1968 "The temporary file to which the capture would be saved (\"%s\") "
1969 "could not be opened: %s.", capfile_name, strerror(errno));
1971 if (capture_opts->multi_files_on) {
1972 ringbuf_error_cleanup();
1975 g_snprintf(errmsg, errmsg_len,
1976 "The file to which the capture would be saved (\"%s\") "
1977 "could not be opened: %s.", capfile_name,
1980 g_free(capfile_name);
1984 if(capture_opts->save_file != NULL) {
1985 g_free(capture_opts->save_file);
1987 capture_opts->save_file = capfile_name;
1988 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
1989 "g_free(capfile_name)". */
1991 ret = fchown(*save_file_fd, capture_opts->owner, capture_opts->group);
1999 #define TIME_GET() GetTickCount()
2001 #define TIME_GET() time(NULL)
2004 /* Do the low-level work of a capture.
2005 Returns TRUE if it succeeds, FALSE otherwise. */
2007 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
2009 time_t upd_time, cur_time;
2013 gint inpkts_to_sync_pipe = 0; /* packets not already send out to the sync_pipe */
2014 condition *cnd_file_duration = NULL;
2015 condition *cnd_autostop_files = NULL;
2016 condition *cnd_autostop_size = NULL;
2017 condition *cnd_autostop_duration = NULL;
2018 guint32 autostop_files = 0;
2021 gboolean cfilter_error = FALSE;
2022 #define MSG_MAX_LENGTH 4096
2023 char errmsg[MSG_MAX_LENGTH+1];
2024 char secondary_errmsg[MSG_MAX_LENGTH+1];
2025 int save_file_fd = -1;
2028 *secondary_errmsg = '\0';
2030 /* init the loop data */
2031 global_ld.go = TRUE;
2032 global_ld.packet_count = 0;
2033 if (capture_opts->has_autostop_packets)
2034 global_ld.packet_max = capture_opts->autostop_packets;
2036 global_ld.packet_max = 0; /* no limit */
2037 global_ld.err = 0; /* no error seen yet */
2038 global_ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
2039 global_ld.pcap_err = FALSE;
2040 global_ld.from_cap_pipe = FALSE;
2041 global_ld.pdh = NULL;
2043 global_ld.cap_pipe_fd = -1;
2045 global_ld.cap_pipe_h = INVALID_HANDLE_VALUE;
2047 #ifdef MUST_DO_SELECT
2048 global_ld.pcap_fd = 0;
2051 /* We haven't yet gotten the capture statistics. */
2052 *stats_known = FALSE;
2054 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
2055 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
2057 /* open the "input file" from network interface or capture pipe */
2058 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
2059 secondary_errmsg, sizeof(secondary_errmsg))) {
2063 /* init the input filter from the network interface (capture pipe will do nothing) */
2064 switch (capture_loop_init_filter(global_ld.pcap_h, global_ld.from_cap_pipe,
2065 capture_opts->iface,
2066 capture_opts->cfilter)) {
2068 case INITFILTER_NO_ERROR:
2071 case INITFILTER_BAD_FILTER:
2072 cfilter_error = TRUE;
2073 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(global_ld.pcap_h));
2076 case INITFILTER_OTHER_ERROR:
2077 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
2078 pcap_geterr(global_ld.pcap_h));
2079 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
2083 /* If we're supposed to write to a capture file, open it for output
2084 (temporary/specified name/ringbuffer) */
2085 if (capture_opts->saving_to_file) {
2086 if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
2090 /* set up to write to the already-opened capture output file/files */
2091 if (!capture_loop_init_output(capture_opts, save_file_fd, &global_ld,
2092 errmsg, sizeof(errmsg))) {
2096 /* XXX - capture SIGTERM and close the capture, in case we're on a
2097 Linux 2.0[.x] system and you have to explicitly close the capture
2098 stream in order to turn promiscuous mode off? We need to do that
2099 in other places as well - and I don't think that works all the
2100 time in any case, due to libpcap bugs. */
2102 /* Well, we should be able to start capturing.
2104 Sync out the capture file, so the header makes it to the file system,
2105 and send a "capture started successfully and capture file created"
2106 message to our parent so that they'll open the capture file and
2107 update its windows to indicate that we have a live capture in
2109 libpcap_dump_flush(global_ld.pdh, NULL);
2110 report_new_capture_file(capture_opts->save_file);
2113 /* initialize capture stop (and alike) conditions */
2114 init_capture_stop_conditions();
2115 /* create stop conditions */
2116 if (capture_opts->has_autostop_filesize)
2118 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
2119 if (capture_opts->has_autostop_duration)
2120 cnd_autostop_duration =
2121 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
2123 if (capture_opts->multi_files_on) {
2124 if (capture_opts->has_file_duration)
2126 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
2128 if (capture_opts->has_autostop_files)
2129 cnd_autostop_files =
2130 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
2133 /* init the time values */
2134 start_time = TIME_GET();
2135 upd_time = TIME_GET();
2137 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
2139 /* WOW, everything is prepared! */
2140 /* please fasten your seat belts, we will enter now the actual capture loop */
2141 while (global_ld.go) {
2142 /* dispatch incoming packets */
2143 inpkts = capture_loop_dispatch(capture_opts, &global_ld, errmsg,
2147 /* any news from our parent (signal pipe)? -> just stop the capture */
2148 if (!signal_pipe_check_running()) {
2149 global_ld.go = FALSE;
2154 inpkts_to_sync_pipe += inpkts;
2156 /* check capture size condition */
2157 if (cnd_autostop_size != NULL &&
2158 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)){
2159 /* Capture size limit reached, do we have another file? */
2160 if (capture_opts->multi_files_on) {
2161 if (cnd_autostop_files != NULL &&
2162 cnd_eval(cnd_autostop_files, ++autostop_files)) {
2163 /* no files left: stop here */
2164 global_ld.go = FALSE;
2168 /* Switch to the next ringbuffer file */
2169 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2170 &save_file_fd, &global_ld.err)) {
2171 gboolean successful;
2173 /* File switch succeeded: reset the conditions */
2174 global_ld.bytes_written = 0;
2175 if (capture_opts->use_pcapng) {
2178 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2179 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2180 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);
2182 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2183 &global_ld.bytes_written, &global_ld.err);
2186 fclose(global_ld.pdh);
2187 global_ld.pdh = NULL;
2188 global_ld.go = FALSE;
2191 cnd_reset(cnd_autostop_size);
2192 if (cnd_file_duration) {
2193 cnd_reset(cnd_file_duration);
2195 libpcap_dump_flush(global_ld.pdh, NULL);
2196 report_packet_count(inpkts_to_sync_pipe);
2197 inpkts_to_sync_pipe = 0;
2198 report_new_capture_file(capture_opts->save_file);
2200 /* File switch failed: stop here */
2201 global_ld.go = FALSE;
2205 /* single file, stop now */
2206 global_ld.go = FALSE;
2209 } /* cnd_autostop_size */
2210 if (capture_opts->output_to_pipe) {
2211 libpcap_dump_flush(global_ld.pdh, NULL);
2215 /* Only update once a second (Win32: 500ms) so as not to overload slow
2216 * displays. This also prevents too much context-switching between the
2217 * dumpcap and wireshark processes */
2218 cur_time = TIME_GET();
2220 if ( (cur_time - upd_time) > 500) {
2222 if (cur_time - upd_time > 0) {
2224 upd_time = cur_time;
2226 /*if (pcap_stats(pch, stats) >= 0) {
2227 *stats_known = TRUE;
2230 /* Let the parent process know. */
2231 if (inpkts_to_sync_pipe) {
2233 libpcap_dump_flush(global_ld.pdh, NULL);
2235 /* Send our parent a message saying we've written out "inpkts_to_sync_pipe"
2236 packets to the capture file. */
2237 report_packet_count(inpkts_to_sync_pipe);
2239 inpkts_to_sync_pipe = 0;
2242 /* check capture duration condition */
2243 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
2244 /* The maximum capture time has elapsed; stop the capture. */
2245 global_ld.go = FALSE;
2249 /* check capture file duration condition */
2250 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
2251 /* duration limit reached, do we have another file? */
2252 if (capture_opts->multi_files_on) {
2253 if (cnd_autostop_files != NULL &&
2254 cnd_eval(cnd_autostop_files, ++autostop_files)) {
2255 /* no files left: stop here */
2256 global_ld.go = FALSE;
2260 /* Switch to the next ringbuffer file */
2261 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2262 &save_file_fd, &global_ld.err)) {
2263 gboolean successful;
2265 /* file switch succeeded: reset the conditions */
2266 global_ld.bytes_written = 0;
2267 if (capture_opts->use_pcapng) {
2270 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2271 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2272 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);
2274 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2275 &global_ld.bytes_written, &global_ld.err);
2278 fclose(global_ld.pdh);
2279 global_ld.pdh = NULL;
2280 global_ld.go = FALSE;
2283 cnd_reset(cnd_file_duration);
2284 if(cnd_autostop_size)
2285 cnd_reset(cnd_autostop_size);
2286 libpcap_dump_flush(global_ld.pdh, NULL);
2287 report_packet_count(inpkts_to_sync_pipe);
2288 inpkts_to_sync_pipe = 0;
2289 report_new_capture_file(capture_opts->save_file);
2291 /* File switch failed: stop here */
2292 global_ld.go = FALSE;
2296 /* single file, stop now */
2297 global_ld.go = FALSE;
2300 } /* cnd_file_duration */
2303 } /* while (global_ld.go) */
2305 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
2307 /* delete stop conditions */
2308 if (cnd_file_duration != NULL)
2309 cnd_delete(cnd_file_duration);
2310 if (cnd_autostop_files != NULL)
2311 cnd_delete(cnd_autostop_files);
2312 if (cnd_autostop_size != NULL)
2313 cnd_delete(cnd_autostop_size);
2314 if (cnd_autostop_duration != NULL)
2315 cnd_delete(cnd_autostop_duration);
2317 /* did we had a pcap (input) error? */
2318 if (global_ld.pcap_err) {
2319 /* On Linux, if an interface goes down while you're capturing on it,
2320 you'll get a "recvfrom: Network is down" error (ENETDOWN).
2321 (At least you will if strerror() doesn't show a local translation
2324 On FreeBSD and OS X, if a network adapter disappears while
2325 you're capturing on it, you'll get a "read: Device not configured"
2326 error (ENXIO). (See previous parenthetical note.)
2328 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
2330 These should *not* be reported to the Wireshark developers. */
2333 cap_err_str = pcap_geterr(global_ld.pcap_h);
2334 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
2335 strcmp(cap_err_str, "read: Device not configured") == 0 ||
2336 strcmp(cap_err_str, "read: I/O error") == 0) {
2337 report_capture_error("The network adapter on which the capture was being done "
2338 "is no longer running; the capture has stopped.",
2341 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
2343 report_capture_error(errmsg, please_report);
2346 else if (global_ld.from_cap_pipe && global_ld.cap_pipe_err == PIPERR)
2347 report_capture_error(errmsg, "");
2349 /* did we had an error while capturing? */
2350 if (global_ld.err == 0) {
2353 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
2354 global_ld.err, FALSE);
2355 report_capture_error(errmsg, please_report);
2359 if (capture_opts->saving_to_file) {
2360 /* close the wiretap (output) file */
2361 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
2365 /* there might be packets not yet notified to the parent */
2366 /* (do this after closing the file, so all packets are already flushed) */
2367 if(inpkts_to_sync_pipe) {
2368 report_packet_count(inpkts_to_sync_pipe);
2369 inpkts_to_sync_pipe = 0;
2372 /* If we've displayed a message about a write error, there's no point
2373 in displaying another message about an error on close. */
2374 if (!close_ok && write_ok) {
2375 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
2377 report_capture_error(errmsg, "");
2381 * XXX We exhibit different behaviour between normal mode and sync mode
2382 * when the pipe is stdin and not already at EOF. If we're a child, the
2383 * parent's stdin isn't closed, so if the user starts another capture,
2384 * cap_pipe_open_live() will very likely not see the expected magic bytes and
2385 * will say "Unrecognized libpcap format". On the other hand, in normal
2386 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
2389 /* get packet drop statistics from pcap */
2390 if(global_ld.pcap_h != NULL) {
2391 g_assert(!global_ld.from_cap_pipe);
2392 /* Get the capture statistics, so we know how many packets were
2394 if (pcap_stats(global_ld.pcap_h, stats) >= 0) {
2395 *stats_known = TRUE;
2396 /* Let the parent process know. */
2397 report_packet_drops(stats->ps_drop);
2399 g_snprintf(errmsg, sizeof(errmsg),
2400 "Can't get packet-drop statistics: %s",
2401 pcap_geterr(global_ld.pcap_h));
2402 report_capture_error(errmsg, please_report);
2406 /* close the input file (pcap or capture pipe) */
2407 capture_loop_close_input(&global_ld);
2409 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
2411 /* ok, if the write and the close were successful. */
2412 return write_ok && close_ok;
2415 if (capture_opts->multi_files_on) {
2416 /* cleanup ringbuffer */
2417 ringbuf_error_cleanup();
2419 /* We can't use the save file, and we have no FILE * for the stream
2420 to close in order to close it, so close the FD directly. */
2421 if(save_file_fd != -1) {
2422 ws_close(save_file_fd);
2425 /* We couldn't even start the capture, so get rid of the capture
2427 if(capture_opts->save_file != NULL) {
2428 ws_unlink(capture_opts->save_file);
2429 g_free(capture_opts->save_file);
2432 capture_opts->save_file = NULL;
2434 report_cfilter_error(capture_opts->cfilter, errmsg);
2436 report_capture_error(errmsg, secondary_errmsg);
2438 /* close the input file (pcap or cap_pipe) */
2439 capture_loop_close_input(&global_ld);
2441 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
2447 static void capture_loop_stop(void)
2449 #ifdef HAVE_PCAP_BREAKLOOP
2450 if(global_ld.pcap_h != NULL)
2451 pcap_breakloop(global_ld.pcap_h);
2453 global_ld.go = FALSE;
2458 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
2459 int err, gboolean is_close)
2464 g_snprintf(errmsg, errmsglen,
2465 "Not all the packets could be written to the file"
2466 " to which the capture was being saved\n"
2467 "(\"%s\") because there is no space left on the file system\n"
2468 "on which that file resides.",
2474 g_snprintf(errmsg, errmsglen,
2475 "Not all the packets could be written to the file"
2476 " to which the capture was being saved\n"
2477 "(\"%s\") because you are too close to, or over,"
2478 " your disk quota\n"
2479 "on the file system on which that file resides.",
2484 case WTAP_ERR_CANT_CLOSE:
2485 g_snprintf(errmsg, errmsglen,
2486 "The file to which the capture was being saved"
2487 " couldn't be closed for some unknown reason.");
2490 case WTAP_ERR_SHORT_WRITE:
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"
2500 g_snprintf(errmsg, errmsglen,
2501 "The file to which the capture was being saved\n"
2502 "(\"%s\") could not be closed: %s.",
2503 fname, wtap_strerror(err));
2505 g_snprintf(errmsg, errmsglen,
2506 "An error occurred while writing to the file"
2507 " to which the capture was being saved\n"
2509 fname, wtap_strerror(err));
2516 /* one packet was captured, process it */
2518 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
2521 loop_data *ld = (void *) user;
2524 /* We may be called multiple times from pcap_dispatch(); if we've set
2525 the "stop capturing" flag, ignore this packet, as we're not
2526 supposed to be saving any more packets. */
2531 gboolean successful;
2532 /* We're supposed to write the packet to a file; do so.
2533 If this fails, set "ld->go" to FALSE, to stop the capture, and set
2534 "ld->err" to the error. */
2535 if (global_capture_opts.use_pcapng) {
2536 successful = libpcap_write_enhanced_packet_block(ld->pdh, phdr, 0, pd, &ld->bytes_written, &err);
2538 successful = libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err);
2545 /* if the user told us to stop after x packets, do we already have enough? */
2546 if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
2555 /* And now our feature presentation... [ fade to music ] */
2557 main(int argc, char *argv[])
2560 gboolean arg_error = FALSE;
2565 struct sigaction action, oldaction;
2568 gboolean start_capture = TRUE;
2569 gboolean stats_known;
2570 struct pcap_stat stats;
2571 GLogLevelFlags log_flags;
2572 gboolean list_interfaces = FALSE;
2573 gboolean list_link_layer_types = FALSE;
2574 gboolean machine_readable = FALSE;
2575 gboolean print_statistics = FALSE;
2576 int status, run_once_args = 0;
2578 #if defined(__APPLE__) && defined(__LP64__)
2579 struct utsname osinfo;
2582 #ifdef HAVE_PCAP_REMOTE
2583 #define OPTSTRING_INIT "a:A:b:c:Df:hi:Lm:MnprSs:uvw:y:Z:"
2585 #define OPTSTRING_INIT "a:b:c:Df:hi:LMnpSs:vw:y:Z:"
2589 #define OPTSTRING_WIN32 "B:"
2591 #define OPTSTRING_WIN32 ""
2594 char optstring[sizeof(OPTSTRING_INIT) + sizeof(OPTSTRING_WIN32) - 1] =
2595 OPTSTRING_INIT OPTSTRING_WIN32;
2597 #ifdef DEBUG_CHILD_DUMPCAP
2598 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
2599 fprintf (stderr, "Unable to open debug log file !\n");
2604 #if defined(__APPLE__) && defined(__LP64__)
2606 * Is this Mac OS X 10.6 or 10.6.1? If so, we need a bug workaround.
2608 if (uname(&osinfo) == 0) {
2610 * Mac OS X 10.x uses Darwin x.0.0. Mac OS X 10.x.y uses Darwin
2611 * x.y.0 (except that 10.6.1 appears to have a uname version
2612 * number of 10.0.0, not 10.1.0 - go figure).
2614 if (strcmp(osinfo.release, "10.0.0") == 0 ||
2615 strcmp(osinfo.release, "10.1.0") == 0)
2616 need_timeout_workaround = 1;
2620 /* Determine if dumpcap is being requested to run in a special */
2621 /* capture_child mode by going thru the command line args to see if */
2622 /* a -Z is present. (-Z is a hidden option). */
2623 /* The primary result of running in capture_child mode is that */
2624 /* all messages sent out on stderr are in a special type/len/string */
2625 /* format to allow message processing by type. */
2626 /* These messages include various 'status' messages which are sent */
2627 /* when an actual capture is in progress. Capture_child mode */
2628 /* would normally be requested by a parent process which invokes */
2629 /* dumpcap and obtains dumpcap stderr output via a pipe to which */
2630 /* dumpcap stderr has been redirected. */
2631 /* Capture_child mode needs to be determined immediately upon */
2632 /* startup so that any messages generated by dumpcap in this mode */
2633 /* (eg: during initialization) will be formatted properly. */
2635 for (i=1; i<argc; i++) {
2636 if (strcmp("-Z", argv[i]) == 0) {
2637 capture_child = TRUE;
2639 /* set output pipe to binary mode, to avoid ugly text conversions */
2640 _setmode(2, O_BINARY);
2645 /* The default_log_handler will use stdout, which makes trouble in */
2646 /* capture child mode, as it uses stdout for it's sync_pipe. */
2647 /* So: the filtering is done in the console_log_handler and not here.*/
2648 /* We set the log handlers right up front to make sure that any log */
2649 /* messages when running as child will be sent back to the parent */
2650 /* with the correct format. */
2654 G_LOG_LEVEL_CRITICAL|
2655 G_LOG_LEVEL_WARNING|
2656 G_LOG_LEVEL_MESSAGE|
2659 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
2661 g_log_set_handler(NULL,
2663 console_log_handler, NULL /* user_data */);
2664 g_log_set_handler(LOG_DOMAIN_MAIN,
2666 console_log_handler, NULL /* user_data */);
2667 g_log_set_handler(LOG_DOMAIN_CAPTURE,
2669 console_log_handler, NULL /* user_data */);
2670 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
2672 console_log_handler, NULL /* user_data */);
2675 /* Load wpcap if possible. Do this before collecting the run-time version information */
2678 /* ... and also load the packet.dll from wpcap */
2679 /* XXX - currently not required, may change later. */
2680 /*wpcap_packet_load();*/
2682 /* Start windows sockets */
2683 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
2685 /* Set handler for Ctrl+C key */
2686 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
2688 /* Prepare to read from a pipe */
2689 if (!g_thread_supported ())
2690 g_thread_init (NULL);
2691 cap_pipe_pending_q = g_async_queue_new();
2692 cap_pipe_done_q = g_async_queue_new();
2693 cap_pipe_read_mtx = g_mutex_new();
2696 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
2698 action.sa_handler = capture_cleanup_handler;
2700 * Arrange that system calls not get restarted, because when
2701 * our signal handler returns we don't want to restart
2702 * a call that was waiting for packets to arrive.
2704 action.sa_flags = 0;
2705 sigemptyset(&action.sa_mask);
2706 sigaction(SIGTERM, &action, NULL);
2707 sigaction(SIGINT, &action, NULL);
2708 sigaction(SIGPIPE, &action, NULL);
2709 sigaction(SIGHUP, NULL, &oldaction);
2710 if (oldaction.sa_handler == SIG_DFL)
2711 sigaction(SIGHUP, &action, NULL);
2714 /* ----------------------------------------------------------------- */
2715 /* Privilege and capability handling */
2717 /* 1. Running not as root or suid root; no special capabilities. */
2720 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
2723 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
2725 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
2726 /* capabilities; Drop all other capabilities; */
2727 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2728 /* else: after pcap_open_live() in capture_loop_open_input() */
2729 /* drop all capabilities (NET_RAW and NET_ADMIN); */
2730 /* (Note: this means that the process, although logged in */
2731 /* as root, does not have various permissions such as the */
2732 /* ability to bypass file access permissions). */
2733 /* XXX: Should we just leave capabilities alone in this case */
2734 /* so that user gets expected effect that root can do */
2737 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
2739 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2740 /* else: after pcap_open_live() in capture_loop_open_input() */
2741 /* drop suid root (set euid=ruid).(ie: keep suid until after */
2742 /* pcap_open_live). */
2744 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
2746 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
2747 /* capabilities; Drop all other capabilities; */
2748 /* Drop suid privileges (euid=ruid); */
2749 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2750 /* else: after pcap_open_live() in capture_loop_open_input() */
2751 /* drop all capabilities (NET_RAW and NET_ADMIN). */
2753 /* XXX: For some Linux versions/distros with capabilities */
2754 /* a 'normal' process with any capabilities cannot be */
2755 /* 'killed' (signaled) from another (same uid) non-privileged */
2757 /* For example: If (non-suid) Wireshark forks a */
2758 /* child suid dumpcap which acts as described here (case 5), */
2759 /* Wireshark will be unable to kill (signal) the child */
2760 /* dumpcap process until the capabilities have been dropped */
2761 /* (after pcap_open_live()). */
2762 /* This behaviour will apparently be changed in the kernel */
2763 /* to allow the kill (signal) in this case. */
2764 /* See the following for details: */
2765 /* http://www.mail-archive.com/ [wrapped] */
2766 /* linux-security-module@vger.kernel.org/msg02913.html */
2768 /* It is therefore conceivable that if dumpcap somehow hangs */
2769 /* in pcap_open_live or before that wireshark will not */
2770 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
2771 /* In this case, exiting wireshark will kill the child */
2772 /* dumpcap process. */
2774 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
2775 /* capabilities; Using libcap. Note: capset cmd (which see) */
2776 /* used to assign capabilities to file. */
2778 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
2779 /* else: after pcap_open_live() in capture_loop_open_input() */
2780 /* drop all capabilities (NET_RAW and NET_ADMIN) */
2782 /* ToDo: -S (stats) should drop privileges/capabilities when no */
2783 /* longer required (similar to capture). */
2785 /* ----------------------------------------------------------------- */
2787 get_credential_info();
2790 /* If 'started with special privileges' (and using libcap) */
2791 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
2792 /* Set euid/egid = ruid/rgid to remove suid privileges */
2793 relinquish_privs_except_capture();
2796 /* Set the initial values in the capture options. This might be overwritten
2797 by the command line parameters. */
2798 capture_opts_init(&global_capture_opts, NULL);
2800 /* Default to capturing the entire packet. */
2801 global_capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
2803 /* We always save to a file - if no file was specified, we save to a
2805 global_capture_opts.saving_to_file = TRUE;
2806 global_capture_opts.has_ring_num_files = TRUE;
2808 /* Now get our args */
2809 while ((opt = getopt(argc, argv, optstring)) != -1) {
2811 case 'h': /* Print help and exit */
2815 case 'v': /* Show version and exit */
2817 GString *comp_info_str;
2818 GString *runtime_info_str;
2819 /* Assemble the compile-time version information string */
2820 comp_info_str = g_string_new("Compiled ");
2821 get_compiled_version_info(comp_info_str, NULL);
2823 /* Assemble the run-time version information string */
2824 runtime_info_str = g_string_new("Running ");
2825 get_runtime_version_info(runtime_info_str, NULL);
2826 show_version(comp_info_str, runtime_info_str);
2827 g_string_free(comp_info_str, TRUE);
2828 g_string_free(runtime_info_str, TRUE);
2832 /*** capture option specific ***/
2833 case 'a': /* autostop criteria */
2834 case 'b': /* Ringbuffer option */
2835 case 'c': /* Capture x packets */
2836 case 'f': /* capture filter */
2837 case 'i': /* Use interface x */
2838 case 'n': /* Use pcapng format */
2839 case 'p': /* Don't capture in promiscuous mode */
2840 case 's': /* Set the snapshot (capture) length */
2841 case 'w': /* Write to capture file x */
2842 case 'y': /* Set the pcap data link type */
2843 #ifdef HAVE_PCAP_REMOTE
2844 case 'u': /* Use UDP for data transfer */
2845 case 'r': /* Capture own RPCAP traffic too */
2846 case 'A': /* Authentication */
2848 #ifdef HAVE_PCAP_SETSAMPLING
2849 case 'm': /* Sampling */
2852 case 'B': /* Buffer size */
2854 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
2859 /*** hidden option: Wireshark child mode (using binary output messages) ***/
2861 capture_child = TRUE;
2863 /* set output pipe to binary mode, to avoid ugly text conversions */
2864 _setmode(2, O_BINARY);
2866 * optarg = the control ID, aka the PPID, currently used for the
2869 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
2870 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
2871 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
2872 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
2874 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
2875 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2876 "Signal pipe: Unable to open %s. Dead parent?",
2884 /*** all non capture option specific ***/
2885 case 'D': /* Print a list of capture devices and exit */
2886 list_interfaces = TRUE;
2889 case 'L': /* Print list of link-layer types and exit */
2890 list_link_layer_types = TRUE;
2893 case 'S': /* Print interface statistics once a second */
2894 print_statistics = TRUE;
2897 case 'M': /* For -D and -L, print machine-readable output */
2898 machine_readable = TRUE;
2901 case '?': /* Bad flag - print usage message */
2902 cmdarg_err("Invalid Option: %s", argv[optind-1]);
2910 /* user specified file name as regular command-line argument */
2911 /* XXX - use it as the capture file name (or something else)? */
2918 * Extra command line arguments were specified; complain.
2919 * XXX - interpret as capture filter, as tcpdump and tshark do?
2921 cmdarg_err("Invalid argument: %s", argv[0]);
2930 if (run_once_args > 1) {
2931 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
2933 } else if (list_link_layer_types) {
2934 /* We're supposed to list the link-layer types for an interface;
2935 did the user also specify a capture file to be read? */
2936 /* No - did they specify a ring buffer option? */
2937 if (global_capture_opts.multi_files_on) {
2938 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
2942 /* No - was the ring buffer option specified and, if so, does it make
2944 if (global_capture_opts.multi_files_on) {
2945 /* Ring buffer works only under certain conditions:
2946 a) ring buffer does not work with temporary files;
2947 b) it makes no sense to enable the ring buffer if the maximum
2948 file size is set to "infinite". */
2949 if (global_capture_opts.save_file == NULL) {
2950 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
2951 global_capture_opts.multi_files_on = FALSE;
2953 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
2954 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
2955 /* XXX - this must be redesigned as the conditions changed */
2956 /* global_capture_opts.multi_files_on = FALSE;*/
2961 if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
2962 /* cmdarg_err() already called .... */
2966 /* Let the user know what interface was chosen. */
2967 /* get_interface_descriptive_name() is not available! */
2968 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", global_capture_opts.iface);
2970 if (list_interfaces) {
2971 status = capture_opts_list_interfaces(machine_readable);
2973 } else if (list_link_layer_types) {
2974 status = capture_opts_list_link_layer_types(&global_capture_opts, machine_readable);
2976 } else if (print_statistics) {
2977 status = print_statistics_loop(machine_readable);
2981 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
2982 capture_opts_trim_ring_num_files(&global_capture_opts);
2984 /* Now start the capture. */
2986 if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
2990 /* capture failed */
2997 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
2998 const char *message, gpointer user_data _U_)
3005 /* ignore log message, if log_level isn't interesting */
3006 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3007 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
3012 /* create a "timestamp" */
3014 today = localtime(&curr);
3016 switch(log_level & G_LOG_LEVEL_MASK) {
3017 case G_LOG_LEVEL_ERROR:
3020 case G_LOG_LEVEL_CRITICAL:
3023 case G_LOG_LEVEL_WARNING:
3026 case G_LOG_LEVEL_MESSAGE:
3029 case G_LOG_LEVEL_INFO:
3032 case G_LOG_LEVEL_DEBUG:
3036 fprintf(stderr, "unknown log_level %u\n", log_level);
3038 g_assert_not_reached();
3041 /* Generate the output message */
3042 if(log_level & G_LOG_LEVEL_MESSAGE) {
3043 /* normal user messages without additional infos */
3044 msg = g_strdup_printf("%s\n", message);
3046 /* info/debug messages with additional infos */
3047 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
3048 today->tm_hour, today->tm_min, today->tm_sec,
3049 log_domain != NULL ? log_domain : "",
3053 /* DEBUG & INFO msgs (if we're debugging today) */
3054 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3055 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3056 #ifdef DEBUG_DUMPCAP
3057 fprintf(stderr, "%s", msg);
3060 #ifdef DEBUG_CHILD_DUMPCAP
3061 fprintf(debug_log, "%s", msg);
3069 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
3070 /* to parent especially formatted if dumpcap running as child. */
3071 if (capture_child) {
3072 sync_pipe_errmsg_to_parent(2, msg, "");
3074 fprintf(stderr, "%s", msg);
3081 /****************************************************************************************************************/
3082 /* indication report routines */
3086 report_packet_count(int packet_count)
3088 char tmp[SP_DECISIZE+1+1];
3089 static int count = 0;
3092 g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
3093 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
3094 pipe_write_block(2, SP_PACKET_COUNT, tmp);
3096 count += packet_count;
3097 fprintf(stderr, "\rPackets: %u ", count);
3098 /* stderr could be line buffered */
3104 report_new_capture_file(const char *filename)
3107 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
3108 pipe_write_block(2, SP_FILE, filename);
3110 fprintf(stderr, "File: %s\n", filename);
3111 /* stderr could be line buffered */
3117 report_cfilter_error(const char *cfilter, const char *errmsg)
3119 if (capture_child) {
3120 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
3121 pipe_write_block(2, SP_BAD_FILTER, errmsg);
3124 "Invalid capture filter: \"%s\"!\n"
3126 "That string isn't a valid capture filter (%s).\n"
3127 "See the User's Guide for a description of the capture filter syntax.\n",
3133 report_capture_error(const char *error_msg, const char *secondary_error_msg)
3136 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3137 "Primary Error: %s", error_msg);
3138 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3139 "Secondary Error: %s", secondary_error_msg);
3140 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
3142 fprintf(stderr, "%s\n%s\n", error_msg, secondary_error_msg);
3147 report_packet_drops(guint32 drops)
3149 char tmp[SP_DECISIZE+1+1];
3151 g_snprintf(tmp, sizeof(tmp), "%u", drops);
3154 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
3155 pipe_write_block(2, SP_DROPS, tmp);
3157 fprintf(stderr, "Packets dropped: %s\n", tmp);
3158 /* stderr could be line buffered */
3164 /****************************************************************************************************************/
3165 /* signal_pipe handling */
3170 signal_pipe_check_running(void)
3172 /* any news from our parent? -> just stop the capture */
3176 /* if we are running standalone, no check required */
3177 if(!capture_child) {
3181 if(!sig_pipe_name || !sig_pipe_handle) {
3182 /* This shouldn't happen */
3183 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3184 "Signal pipe: No name or handle");
3189 * XXX - We should have the process ID of the parent (from the "-Z" flag)
3190 * at this point. Should we check to see if the parent is still alive,
3191 * e.g. by using OpenProcess?
3194 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
3196 if(!result || avail > 0) {
3197 /* peek failed or some bytes really available */
3198 /* (if not piping from stdin this would fail) */
3199 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3200 "Signal pipe: Stop capture: %s", sig_pipe_name);
3201 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3202 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
3203 sig_pipe_handle, result, avail);
3206 /* pipe ok and no bytes available */
3213 * Editor modelines - http://www.wireshark.org/tools/modelines.html
3218 * indent-tabs-mode: nil
3221 * vi: set shiftwidth=4 tabstop=8 expandtab
3222 * :indentSize=4:tabSize=8:noTabs=true: