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 #ifdef HAVE_ARPA_INET_H
52 #include <arpa/inet.h>
55 #if defined(__APPLE__) && defined(__LP64__)
56 #include <sys/utsname.h>
63 #include "wsutil/wsgetopt.h"
71 # include <sys/prctl.h>
72 # include <sys/capability.h>
75 #include "ringbuffer.h"
76 #include "clopts_common.h"
77 #include "console_io.h"
78 #include "cmdarg_err.h"
79 #include "version_info.h"
81 #include "capture-pcap-util.h"
83 #include "capture-wpcap.h"
89 #include "capture-wpcap.h"
90 #include <wsutil/unicode-utils.h>
94 #include <sys/socket.h>
98 #ifdef NEED_INET_V6DEFS_H
99 # include "wsutil/inet_v6defs.h"
102 #include <wsutil/privileges.h>
104 #include "sync_pipe.h"
106 #include "capture_opts.h"
107 #include "capture_ifinfo.h"
108 #include "capture_sync.h"
110 #include "conditions.h"
111 #include "capture_stop_conditions.h"
113 #include "tempfile.h"
115 #include "wsutil/file_util.h"
118 * Get information about libpcap format from "wiretap/libpcap.h".
119 * XXX - can we just use pcap_open_offline() to read the pipe?
121 #include "wiretap/libpcap.h"
123 /**#define DEBUG_DUMPCAP**/
124 /**#define DEBUG_CHILD_DUMPCAP**/
128 #include <conio.h> /* _getch() */
132 #ifdef DEBUG_CHILD_DUMPCAP
133 FILE *debug_log; /* for logging debug messages to */
134 /* a file if DEBUG_CHILD_DUMPCAP */
138 static GAsyncQueue *pcap_queue;
139 static gint64 pcap_queue_bytes;
140 static gint64 pcap_queue_packets;
141 static gint64 pcap_queue_byte_limit = 1024 * 1024;
142 static gint64 pcap_queue_packet_limit = 1000;
144 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
146 static gchar *sig_pipe_name = NULL;
147 static HANDLE sig_pipe_handle = NULL;
148 static gboolean signal_pipe_check_running(void);
152 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
153 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
156 /** Stop a low-level capture (stops the capture child). */
157 static void capture_loop_stop(void);
159 #if !defined (__linux__)
160 #ifndef HAVE_PCAP_BREAKLOOP
162 * We don't have pcap_breakloop(), which is the only way to ensure that
163 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
164 * won't, if the call to read the next packet or batch of packets is
165 * is interrupted by a signal on UN*X, just go back and try again to
168 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
169 * the signal handler, set a flag to stop capturing; however, without
170 * a guarantee of that sort, we can't guarantee that we'll stop capturing
171 * if the read will be retried and won't time out if no packets arrive.
173 * Therefore, on at least some platforms, we work around the lack of
174 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
175 * to wait for packets to arrive, so that we're probably going to be
176 * blocked in the select() when the signal arrives, and can just bail
177 * out of the loop at that point.
179 * However, we don't want to do that on BSD (because "select()" doesn't work
180 * correctly on BPF devices on at least some releases of some flavors of
181 * BSD), and we don't want to do it on Windows (because "select()" is
182 * something for sockets, not for arbitrary handles). (Note that "Windows"
183 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
184 * using WinPcap, not a UNIX libpcap.)
186 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
187 * on BSD times out even if no packets have arrived, so we'll eventually
188 * exit pcap_dispatch() with an indication that no packets have arrived,
189 * and will break out of the capture loop at that point.
191 * On Windows, we can't send a SIGINT to stop capturing, so none of this
192 * applies in any case.
194 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
195 * want to include it if it's not present on this platform, however.
197 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
198 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
200 # define MUST_DO_SELECT
201 # endif /* avoid select */
202 #endif /* HAVE_PCAP_BREAKLOOP */
204 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
205 * in pcap_dispatch(); on the other hand, select() works just fine there.
206 * Hence we use a select for that come what may.
208 #define MUST_DO_SELECT
211 /** init the capture filter */
214 INITFILTER_BAD_FILTER,
215 INITFILTER_OTHER_ERROR
216 } initfilter_status_t;
218 typedef struct _pcap_options {
222 #ifdef MUST_DO_SELECT
223 int pcap_fd; /* pcap file descriptor */
230 /* capture pipe (unix only "input file") */
231 gboolean from_cap_pipe; /* TRUE if we are capturing data from a capture pipe */
232 struct pcap_hdr cap_pipe_hdr; /* Pcap header when capturing from a pipe */
233 struct pcaprec_modified_hdr cap_pipe_rechdr; /* Pcap record header when capturing from a pipe */
235 HANDLE cap_pipe_h; /* The handle of the capture pipe */
237 int cap_pipe_fd; /* the file descriptor of the capture pipe */
239 gboolean cap_pipe_modified; /* TRUE if data in the pipe uses modified pcap headers */
240 gboolean cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
242 char * cap_pipe_buf; /* Pointer to the data buffer we read into */
244 int cap_pipe_bytes_to_read;/* Used by cap_pipe_dispatch */
245 int cap_pipe_bytes_read; /* Used by cap_pipe_dispatch */
247 STATE_EXPECT_REC_HDR,
252 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
254 GMutex *cap_pipe_read_mtx;
255 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
259 typedef struct _loop_data {
261 gboolean go; /* TRUE as long as we're supposed to keep capturing */
262 int err; /* if non-zero, error seen while capturing */
263 gint packet_count; /* Number of packets we have already captured */
264 gint packet_max; /* Number of packets we're supposed to capture - 0 means infinite */
265 gint inpkts_to_sync_pipe; /* Packets not already send out to the sync_pipe */
267 gboolean report_packet_count; /* Set by SIGINFO handler; print packet count */
274 guint32 autostop_files;
277 typedef struct _pcap_queue_element {
278 pcap_options *pcap_opts;
279 struct pcap_pkthdr phdr;
281 } pcap_queue_element;
284 * Standard secondary message for unexpected errors.
286 static const char please_report[] =
287 "Please report this to the Wireshark developers.\n"
288 "(This is not a crash; please do not report it as such.)";
291 * This needs to be static, so that the SIGINT handler can clear the "go"
294 static loop_data global_ld;
298 * Timeout, in milliseconds, for reads from the stream of captured packets
299 * from a capture device.
301 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
302 * 64-bit applications, with sub-second timeouts not to work. The bug is
303 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
305 #if defined(__APPLE__) && defined(__LP64__)
306 static gboolean need_timeout_workaround;
308 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
310 #define CAP_READ_TIMEOUT 250
314 * Timeout, in microseconds, for reads from the stream of captured packets
315 * from a pipe. Pipes don't have the same problem that BPF devices do
316 * in OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
317 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
318 * of the offending versions of Snow Leopard.
320 * On Windows this value is converted to milliseconds and passed to
321 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
322 * will return immediately.
325 #define PIPE_READ_TIMEOUT 100000
327 #define PIPE_READ_TIMEOUT 250000
330 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
333 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
334 const char *message, gpointer user_data _U_);
336 /* capture related options */
337 static capture_options global_capture_opts;
338 static gboolean quiet = FALSE;
339 static gboolean use_threads = FALSE;
341 static void capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
343 static void capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
345 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
346 int err, gboolean is_close);
348 static void WS_MSVC_NORETURN exit_main(int err) G_GNUC_NORETURN;
350 static void report_new_capture_file(const char *filename);
351 static void report_packet_count(int packet_count);
352 static void report_packet_drops(guint32 received, guint32 drops, gchar *name);
353 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
354 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
356 #define MSG_MAX_LENGTH 4096
359 print_usage(gboolean print_ver)
366 "Dumpcap " VERSION "%s\n"
367 "Capture network packets and dump them into a pcapng file.\n"
368 "See http://www.wireshark.org for more information.\n",
369 wireshark_svnversion);
373 fprintf(output, "\nUsage: dumpcap [options] ...\n");
374 fprintf(output, "\n");
375 fprintf(output, "Capture interface:\n");
376 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
377 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
378 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
379 fprintf(output, " -p don't capture in promiscuous mode\n");
380 #ifdef HAVE_PCAP_CREATE
381 fprintf(output, " -I capture in monitor mode, if available\n");
383 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
384 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
386 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
387 fprintf(output, " -D print list of interfaces and exit\n");
388 fprintf(output, " -L print list of link-layer types of iface and exit\n");
389 #ifdef HAVE_BPF_IMAGE
390 fprintf(output, " -d print generated BPF code for capture filter\n");
392 fprintf(output, " -S print statistics for each interface once per second\n");
393 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
394 fprintf(output, "\n");
395 #ifdef HAVE_PCAP_REMOTE
396 fprintf(output, "RPCAP options:\n");
397 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
398 fprintf(output, " -u use UDP for RPCAP data transfer\n");
399 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
400 #ifdef HAVE_PCAP_SETSAMPLING
401 fprintf(output, " -m <sampling type> use packet sampling\n");
402 fprintf(output, " count:NUM - capture one packet of every NUM\n");
403 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
406 fprintf(output, "Stop conditions:\n");
407 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
408 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
409 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
410 fprintf(output, " files:NUM - stop after NUM files\n");
411 /*fprintf(output, "\n");*/
412 fprintf(output, "Output (files):\n");
413 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
414 fprintf(output, " -g enable group read access on the output file(s)\n");
415 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
416 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
417 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
418 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
419 fprintf(output, " -P use libpcap format instead of pcapng\n");
420 fprintf(output, "\n");
421 fprintf(output, "Miscellaneous:\n");
422 fprintf(output, " -t use a separate thread per interface\n");
423 fprintf(output, " -q don't report packet capture counts\n");
424 fprintf(output, " -v print version information and exit\n");
425 fprintf(output, " -h display this help and exit\n");
426 fprintf(output, "\n");
427 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
428 fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcapng\"\n");
429 fprintf(output, "\n");
430 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
434 show_version(GString *comp_info_str, GString *runtime_info_str)
437 "Dumpcap " VERSION "%s\n"
442 "See http://www.wireshark.org for more information.\n",
443 wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
447 * Print to the standard error. This is a command-line tool, so there's
448 * no need to pop up a console.
451 vfprintf_stderr(const char *fmt, va_list ap)
453 vfprintf(stderr, fmt, ap);
457 fprintf_stderr(const char *fmt, ...)
462 vfprintf_stderr(fmt, ap);
467 * Report an error in command-line arguments.
470 cmdarg_err(const char *fmt, ...)
476 /* Generate a 'special format' message back to parent */
478 msg = g_strdup_vprintf(fmt, ap);
479 sync_pipe_errmsg_to_parent(2, msg, "");
484 fprintf(stderr, "dumpcap: ");
485 vfprintf(stderr, fmt, ap);
486 fprintf(stderr, "\n");
492 * Report additional information for an error in command-line arguments.
495 cmdarg_err_cont(const char *fmt, ...)
502 msg = g_strdup_vprintf(fmt, ap);
503 sync_pipe_errmsg_to_parent(2, msg, "");
508 vfprintf(stderr, fmt, ap);
509 fprintf(stderr, "\n");
516 #if 0 /* Set to enable capability debugging */
517 /* see 'man cap_to_text()' for explanation of output */
518 /* '=' means 'all= ' ie: no capabilities */
519 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
521 print_caps(const char *pfx) {
522 cap_t caps = cap_get_proc();
523 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
524 "%s: EUID: %d Capabilities: %s", pfx,
525 geteuid(), cap_to_text(caps, NULL));
528 print_caps(const char *pfx _U_) {
533 relinquish_all_capabilities(void)
535 /* Drop any and all capabilities this process may have. */
536 /* Allowed whether or not process has any privileges. */
537 cap_t caps = cap_init(); /* all capabilities initialized to off */
538 print_caps("Pre-clear");
539 if (cap_set_proc(caps)) {
540 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
542 print_caps("Post-clear");
548 open_capture_device(interface_options *interface_opts,
549 char (*open_err_str)[PCAP_ERRBUF_SIZE])
552 #ifdef HAVE_PCAP_CREATE
555 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
556 struct pcap_rmtauth auth;
559 /* Open the network interface to capture from it.
560 Some versions of libpcap may put warnings into the error buffer
561 if they succeed; to tell if that's happened, we have to clear
562 the error buffer, and check if it's still a null string. */
563 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Entering open_capture_device().");
564 (*open_err_str)[0] = '\0';
565 #if defined(HAVE_PCAP_OPEN) && defined(HAVE_PCAP_REMOTE)
567 * If we're opening a remote device, use pcap_open(); that's currently
568 * the only open routine that supports remote devices.
570 if (strncmp (interface_opts->name, "rpcap://", 8) == 0) {
571 auth.type = interface_opts->auth_type == CAPTURE_AUTH_PWD ?
572 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
573 auth.username = interface_opts->auth_username;
574 auth.password = interface_opts->auth_password;
576 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
577 "Calling pcap_open() using name %s, snaplen %d, promisc_mode %d, datatx_udp %d, nocap_rpcap %d.",
578 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode,
579 interface_opts->datatx_udp, interface_opts->nocap_rpcap);
580 pcap_h = pcap_open(interface_opts->name, interface_opts->snaplen,
582 (interface_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
583 (interface_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
584 (interface_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
585 CAP_READ_TIMEOUT, &auth, *open_err_str);
586 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
587 "pcap_open() returned %p.", (void *)pcap_h);
592 * If we're not opening a remote device, use pcap_create() and
593 * pcap_activate() if we have them, so that we can set the buffer
594 * size, otherwise use pcap_open_live().
596 #ifdef HAVE_PCAP_CREATE
597 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
598 "Calling pcap_create() using %s.", interface_opts->name);
599 pcap_h = pcap_create(interface_opts->name, *open_err_str);
600 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
601 "pcap_create() returned %p.", (void *)pcap_h);
602 if (pcap_h != NULL) {
603 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
604 "Calling pcap_set_snaplen() with snaplen %d.", interface_opts->snaplen);
605 pcap_set_snaplen(pcap_h, interface_opts->snaplen);
606 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
607 "Calling pcap_set_snaplen() with promisc_mode %d.", interface_opts->promisc_mode);
608 pcap_set_promisc(pcap_h, interface_opts->promisc_mode);
609 pcap_set_timeout(pcap_h, CAP_READ_TIMEOUT);
611 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
612 "buffersize %d.", interface_opts->buffer_size);
613 if (interface_opts->buffer_size > 1) {
614 pcap_set_buffer_size(pcap_h, interface_opts->buffer_size * 1024 * 1024);
616 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
617 "monitor_mode %d.", interface_opts->monitor_mode);
618 if (interface_opts->monitor_mode)
619 pcap_set_rfmon(pcap_h, 1);
620 err = pcap_activate(pcap_h);
621 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
622 "pcap_activate() returned %d.", err);
624 /* Failed to activate, set to NULL */
625 if (err == PCAP_ERROR)
626 g_strlcpy(*open_err_str, pcap_geterr(pcap_h), sizeof *open_err_str);
628 g_strlcpy(*open_err_str, pcap_statustostr(err), sizeof *open_err_str);
634 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
635 "pcap_open_live() calling using name %s, snaplen %d, promisc_mode %d.",
636 interface_opts->name, interface_opts->snaplen, interface_opts->promisc_mode);
637 pcap_h = pcap_open_live(interface_opts->name, interface_opts->snaplen,
638 interface_opts->promisc_mode, CAP_READ_TIMEOUT,
640 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
641 "pcap_open_live() returned %p.", (void *)pcap_h);
644 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "open_capture_device %s : %s", pcap_h ? "SUCCESS" : "FAILURE", interface_opts->name);
649 get_capture_device_open_failure_messages(const char *open_err_str,
655 char *errmsg, size_t errmsg_len,
656 char *secondary_errmsg,
657 size_t secondary_errmsg_len)
659 const char *libpcap_warn;
660 static const char ppamsg[] = "can't find PPA for ";
662 /* If we got a "can't find PPA for X" message, warn the user (who
663 is running dumcap on HP-UX) that they don't have a version of
664 libpcap that properly handles HP-UX (libpcap 0.6.x and later
665 versions, which properly handle HP-UX, say "can't find /dev/dlpi
666 PPA for X" rather than "can't find PPA for X"). */
667 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
670 "You are running (T)Wireshark with a version of the libpcap library\n"
671 "that doesn't handle HP-UX network devices well; this means that\n"
672 "(T)Wireshark may not be able to capture packets.\n"
674 "To fix this, you should install libpcap 0.6.2, or a later version\n"
675 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
676 "packaged binary form from the Software Porting And Archive Centre\n"
677 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
678 "at the URL lists a number of mirror sites.";
681 g_snprintf(errmsg, (gulong) errmsg_len,
682 "The capture session could not be initiated (%s).", open_err_str);
685 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
687 "In order to capture packets, WinPcap must be installed; see\n"
689 " http://www.winpcap.org/\n"
693 " http://www.mirrors.wiretapped.net/security/packet-capture/winpcap/\n"
697 " http://winpcap.cs.pu.edu.tw/\n"
699 "for a downloadable version of WinPcap and for instructions on how to install\n"
702 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
704 "Please check that \"%s\" is the proper interface.\n"
707 "Help can be found at:\n"
709 " http://wiki.wireshark.org/WinPcap\n"
710 " http://wiki.wireshark.org/CaptureSetup\n",
714 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
715 "Please check to make sure you have sufficient permissions, and that you have "
716 "the proper interface or pipe specified.%s", libpcap_warn);
720 /* Set the data link type on a pcap. */
722 set_pcap_linktype(pcap_t *pcap_h, int linktype,
723 #ifdef HAVE_PCAP_SET_DATALINK
728 char *errmsg, size_t errmsg_len,
729 char *secondary_errmsg, size_t secondary_errmsg_len)
731 char *set_linktype_err_str;
734 return TRUE; /* just use the default */
735 #ifdef HAVE_PCAP_SET_DATALINK
736 if (pcap_set_datalink(pcap_h, linktype) == 0)
737 return TRUE; /* no error */
738 set_linktype_err_str = pcap_geterr(pcap_h);
740 /* Let them set it to the type it is; reject any other request. */
741 if (get_pcap_linktype(pcap_h, name) == linktype)
742 return TRUE; /* no error */
743 set_linktype_err_str =
744 "That DLT isn't one of the DLTs supported by this device";
746 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
747 set_linktype_err_str);
749 * If the error isn't "XXX is not one of the DLTs supported by this device",
750 * tell the user to tell the Wireshark developers about it.
752 if (strstr(set_linktype_err_str, "is not one of the DLTs supported by this device") == NULL)
753 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
755 secondary_errmsg[0] = '\0';
760 compile_capture_filter(const char *iface, pcap_t *pcap_h,
761 struct bpf_program *fcode, const char *cfilter)
763 bpf_u_int32 netnum, netmask;
764 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
766 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
768 * Well, we can't get the netmask for this interface; it's used
769 * only for filters that check for broadcast IP addresses, so
770 * we just punt and use 0. It might be nice to warn the user,
771 * but that's a pain in a GUI application, as it'd involve popping
772 * up a message box, and it's not clear how often this would make
773 * a difference (only filters that check for IP broadcast addresses
777 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
782 * Sigh. Older versions of libpcap don't properly declare the
783 * third argument to pcap_compile() as a const pointer. Cast
786 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
791 #ifdef HAVE_BPF_IMAGE
793 show_filter_code(capture_options *capture_opts)
795 interface_options interface_opts;
797 gchar open_err_str[PCAP_ERRBUF_SIZE];
798 char errmsg[MSG_MAX_LENGTH+1];
799 char secondary_errmsg[MSG_MAX_LENGTH+1];
800 struct bpf_program fcode;
801 struct bpf_insn *insn;
805 for (j = 0; j < capture_opts->ifaces->len; j++) {
806 interface_opts = g_array_index(capture_opts->ifaces, interface_options, j);
807 pcap_h = open_capture_device(&interface_opts, &open_err_str);
808 if (pcap_h == NULL) {
809 /* Open failed; get messages */
810 get_capture_device_open_failure_messages(open_err_str,
812 errmsg, sizeof errmsg,
814 sizeof secondary_errmsg);
815 /* And report them */
816 report_capture_error(errmsg, secondary_errmsg);
820 /* Set the link-layer type. */
821 if (!set_pcap_linktype(pcap_h, interface_opts.linktype, interface_opts.name,
822 errmsg, sizeof errmsg,
823 secondary_errmsg, sizeof secondary_errmsg)) {
825 report_capture_error(errmsg, secondary_errmsg);
829 /* OK, try to compile the capture filter. */
830 if (!compile_capture_filter(interface_opts.name, pcap_h, &fcode,
831 interface_opts.cfilter)) {
833 report_cfilter_error(capture_opts, j, errmsg);
838 /* Now print the filter code. */
839 insn = fcode.bf_insns;
841 for (i = 0; i < fcode.bf_len; insn++, i++)
842 printf("%s\n", bpf_image(insn, i));
844 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
845 /* to remove any suid privileges. */
846 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
847 /* (euid/egid have already previously been set to ruid/rgid. */
848 /* (See comment in main() for details) */
850 relinquish_special_privs_perm();
852 relinquish_all_capabilities();
855 /* Let our parent know we succeeded. */
856 pipe_write_block(2, SP_SUCCESS, NULL);
863 * capture_interface_list() is expected to do the right thing to get
864 * a list of interfaces.
866 * In most of the programs in the Wireshark suite, "the right thing"
867 * is to run dumpcap and ask it for the list, because dumpcap may
868 * be the only program in the suite with enough privileges to get
871 * In dumpcap itself, however, we obviously can't run dumpcap to
872 * ask for the list. Therefore, our capture_interface_list() should
873 * just call get_interface_list().
876 capture_interface_list(int *err, char **err_str)
878 return get_interface_list(err, err_str);
882 * Get the data-link type for a libpcap device.
883 * This works around AIX 5.x's non-standard and incompatible-with-the-
884 * rest-of-the-universe libpcap.
887 get_pcap_linktype(pcap_t *pch, const char *devname
895 const char *ifacename;
898 linktype = pcap_datalink(pch);
902 * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
903 * rather than DLT_ values for link-layer types; the ifType values
904 * for LAN devices are:
911 * and the ifType value for a loopback device is 24.
913 * The AIX names for LAN devices begin with:
920 * and the AIX names for loopback devices begin with "lo".
922 * (The difference between "Ethernet" and "802.3" is presumably
923 * whether packets have an Ethernet header, with a packet type,
924 * or an 802.3 header, with a packet length, followed by an 802.2
925 * header and possibly a SNAP header.)
927 * If the device name matches "linktype" interpreted as an ifType
928 * value, rather than as a DLT_ value, we will assume this is AIX's
929 * non-standard, incompatible libpcap, rather than a standard libpcap,
930 * and will map the link-layer type to the standard DLT_ value for
931 * that link-layer type, as that's what the rest of Wireshark expects.
933 * (This means the capture files won't be readable by a tcpdump
934 * linked with AIX's non-standard libpcap, but so it goes. They
935 * *will* be readable by standard versions of tcpdump, Wireshark,
938 * XXX - if we conclude we're using AIX libpcap, should we also
939 * set a flag to cause us to assume the time stamps are in
940 * seconds-and-nanoseconds form, and to convert them to
941 * seconds-and-microseconds form before processing them and
946 * Find the last component of the device name, which is the
949 ifacename = strchr(devname, '/');
950 if (ifacename == NULL)
953 /* See if it matches any of the LAN device names. */
954 if (strncmp(ifacename, "en", 2) == 0) {
957 * That's the RFC 1573 value for Ethernet; map it to DLT_EN10MB.
961 } else if (strncmp(ifacename, "et", 2) == 0) {
964 * That's the RFC 1573 value for 802.3; map it to DLT_EN10MB.
965 * (libpcap, tcpdump, Wireshark, etc. don't care if it's Ethernet
970 } else if (strncmp(ifacename, "tr", 2) == 0) {
973 * That's the RFC 1573 value for 802.5 (Token Ring); map it to
974 * DLT_IEEE802, which is what's used for Token Ring.
978 } else if (strncmp(ifacename, "fi", 2) == 0) {
979 if (linktype == 15) {
981 * That's the RFC 1573 value for FDDI; map it to DLT_FDDI.
985 } else if (strncmp(ifacename, "lo", 2) == 0) {
986 if (linktype == 24) {
988 * That's the RFC 1573 value for "software loopback" devices; map it
989 * to DLT_NULL, which is what's used for loopback devices on BSD.
999 static data_link_info_t *
1000 create_data_link_info(int dlt)
1002 data_link_info_t *data_link_info;
1005 data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
1006 data_link_info->dlt = dlt;
1007 text = pcap_datalink_val_to_name(dlt);
1009 data_link_info->name = g_strdup(text);
1011 data_link_info->name = g_strdup_printf("DLT %d", dlt);
1012 text = pcap_datalink_val_to_description(dlt);
1014 data_link_info->description = g_strdup(text);
1016 data_link_info->description = NULL;
1017 return data_link_info;
1021 * Get the capabilities of a network device.
1023 static if_capabilities_t *
1024 get_if_capabilities(const char *devname, gboolean monitor_mode
1025 #ifndef HAVE_PCAP_CREATE
1030 if_capabilities_t *caps;
1031 char errbuf[PCAP_ERRBUF_SIZE];
1033 #ifdef HAVE_PCAP_CREATE
1037 #ifdef HAVE_PCAP_LIST_DATALINKS
1041 data_link_info_t *data_link_info;
1044 * Allocate the interface capabilities structure.
1046 caps = g_malloc(sizeof *caps);
1048 #ifdef HAVE_PCAP_OPEN
1049 pch = pcap_open(devname, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1050 caps->can_set_rfmon = FALSE;
1052 if (err_str != NULL)
1053 *err_str = g_strdup(errbuf);
1057 #elif defined(HAVE_PCAP_CREATE)
1058 pch = pcap_create(devname, errbuf);
1060 if (err_str != NULL)
1061 *err_str = g_strdup(errbuf);
1065 status = pcap_can_set_rfmon(pch);
1068 if (status == PCAP_ERROR)
1069 *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
1072 *err_str = g_strdup(pcap_statustostr(status));
1078 caps->can_set_rfmon = FALSE;
1079 else if (status == 1) {
1080 caps->can_set_rfmon = TRUE;
1082 pcap_set_rfmon(pch, 1);
1084 if (err_str != NULL) {
1085 *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
1093 status = pcap_activate(pch);
1095 /* Error. We ignore warnings (status > 0). */
1096 if (err_str != NULL) {
1097 if (status == PCAP_ERROR)
1098 *err_str = g_strdup_printf("pcap_activate() failed: %s",
1101 *err_str = g_strdup(pcap_statustostr(status));
1108 pch = pcap_open_live(devname, MIN_PACKET_SIZE, 0, 0, errbuf);
1109 caps->can_set_rfmon = FALSE;
1111 if (err_str != NULL)
1112 *err_str = g_strdup(errbuf);
1117 deflt = get_pcap_linktype(pch, devname);
1118 #ifdef HAVE_PCAP_LIST_DATALINKS
1119 nlt = pcap_list_datalinks(pch, &linktypes);
1120 if (nlt == 0 || linktypes == NULL) {
1122 if (err_str != NULL)
1123 *err_str = NULL; /* an empty list doesn't mean an error */
1126 caps->data_link_types = NULL;
1127 for (i = 0; i < nlt; i++) {
1128 data_link_info = create_data_link_info(linktypes[i]);
1131 * XXX - for 802.11, make the most detailed 802.11
1132 * version the default, rather than the one the
1133 * device has as the default?
1135 if (linktypes[i] == deflt)
1136 caps->data_link_types = g_list_prepend(caps->data_link_types,
1139 caps->data_link_types = g_list_append(caps->data_link_types,
1142 #ifdef HAVE_PCAP_FREE_DATALINKS
1143 pcap_free_datalinks(linktypes);
1146 * In Windows, there's no guarantee that if you have a library
1147 * built with one version of the MSVC++ run-time library, and
1148 * it returns a pointer to allocated data, you can free that
1149 * data from a program linked with another version of the
1150 * MSVC++ run-time library.
1152 * This is not an issue on UN*X.
1154 * See the mail threads starting at
1156 * http://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
1160 * http://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
1163 #define xx_free free /* hack so checkAPIs doesn't complain */
1166 #endif /* HAVE_PCAP_FREE_DATALINKS */
1167 #else /* HAVE_PCAP_LIST_DATALINKS */
1169 data_link_info = create_data_link_info(deflt);
1170 caps->data_link_types = g_list_append(caps->data_link_types,
1172 #endif /* HAVE_PCAP_LIST_DATALINKS */
1176 if (err_str != NULL)
1181 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
1183 print_machine_readable_interfaces(GList *if_list)
1190 char addr_str[ADDRSTRLEN];
1192 if (capture_child) {
1193 /* Let our parent know we succeeded. */
1194 pipe_write_block(2, SP_SUCCESS, NULL);
1197 i = 1; /* Interface id number */
1198 for (if_entry = g_list_first(if_list); if_entry != NULL;
1199 if_entry = g_list_next(if_entry)) {
1200 if_info = (if_info_t *)if_entry->data;
1201 printf("%d. %s", i++, if_info->name);
1204 * Print the contents of the if_entry struct in a parseable format.
1205 * Each if_entry element is tab-separated. Addresses are comma-
1208 /* XXX - Make sure our description doesn't contain a tab */
1209 if (if_info->description != NULL)
1210 printf("\t%s\t", if_info->description);
1214 for(addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
1215 addr = g_slist_next(addr)) {
1216 if (addr != g_slist_nth(if_info->addrs, 0))
1219 if_addr = (if_addr_t *)addr->data;
1220 switch(if_addr->ifat_type) {
1222 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
1224 printf("%s", addr_str);
1226 printf("<unknown IPv4>");
1230 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
1231 addr_str, ADDRSTRLEN)) {
1232 printf("%s", addr_str);
1234 printf("<unknown IPv6>");
1238 printf("<type unknown %u>", if_addr->ifat_type);
1242 if (if_info->loopback)
1243 printf("\tloopback");
1245 printf("\tnetwork");
1252 * If you change the machine-readable output format of this function,
1253 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
1256 print_machine_readable_if_capabilities(if_capabilities_t *caps)
1259 data_link_info_t *data_link_info;
1260 const gchar *desc_str;
1262 if (capture_child) {
1263 /* Let our parent know we succeeded. */
1264 pipe_write_block(2, SP_SUCCESS, NULL);
1267 if (caps->can_set_rfmon)
1271 for (lt_entry = caps->data_link_types; lt_entry != NULL;
1272 lt_entry = g_list_next(lt_entry)) {
1273 data_link_info = (data_link_info_t *)lt_entry->data;
1274 if (data_link_info->description != NULL)
1275 desc_str = data_link_info->description;
1277 desc_str = "(not supported)";
1278 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
1288 /* Print the number of packets captured for each interface until we're killed. */
1290 print_statistics_loop(gboolean machine_readable)
1292 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1298 char errbuf[PCAP_ERRBUF_SIZE];
1299 struct pcap_stat ps;
1301 if_list = get_interface_list(&err, &err_str);
1302 if (if_list == NULL) {
1304 case CANT_GET_INTERFACE_LIST:
1305 case DONT_HAVE_PCAP:
1306 cmdarg_err("%s", err_str);
1310 case NO_INTERFACES_FOUND:
1311 cmdarg_err("There are no interfaces on which a capture can be done");
1317 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1318 if_info = (if_info_t *)if_entry->data;
1319 #ifdef HAVE_PCAP_OPEN
1320 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1322 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1326 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
1327 if_stat->name = g_strdup(if_info->name);
1329 stat_list = g_list_append(stat_list, if_stat);
1334 cmdarg_err("There are no interfaces on which a capture can be done");
1338 if (capture_child) {
1339 /* Let our parent know we succeeded. */
1340 pipe_write_block(2, SP_SUCCESS, NULL);
1343 if (!machine_readable) {
1344 printf("%-15s %10s %10s\n", "Interface", "Received",
1348 global_ld.go = TRUE;
1349 while (global_ld.go) {
1350 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1351 if_stat = (if_stat_t *)stat_entry->data;
1352 pcap_stats(if_stat->pch, &ps);
1354 if (!machine_readable) {
1355 printf("%-15s %10u %10u\n", if_stat->name,
1356 ps.ps_recv, ps.ps_drop);
1358 printf("%s\t%u\t%u\n", if_stat->name,
1359 ps.ps_recv, ps.ps_drop);
1370 /* XXX - Not reached. Should we look for 'q' in stdin? */
1371 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1372 if_stat = (if_stat_t *)stat_entry->data;
1373 pcap_close(if_stat->pch);
1374 g_free(if_stat->name);
1377 g_list_free(stat_list);
1378 free_interface_list(if_list);
1386 capture_cleanup_handler(DWORD dwCtrlType)
1388 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1389 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1390 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1391 like SIGTERM at least when the machine's shutting down.
1393 For now, if we're running as a command rather than a capture child,
1394 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1395 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1396 in that way on UN*X.
1398 If we're not running as a capture child, we might be running as
1399 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1400 user logs out. (XXX - can we explicitly check whether we're
1401 running as a service?) */
1403 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1404 "Console: Control signal");
1405 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1406 "Console: Control signal, CtrlType: %u", dwCtrlType);
1408 /* Keep capture running if we're a service and a user logs off */
1409 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1410 capture_loop_stop();
1418 capture_cleanup_handler(int signum _U_)
1420 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1421 SIGTERM. We assume that if the user wanted it to keep running
1422 after they logged out, they'd have nohupped it. */
1424 /* Note: don't call g_log() in the signal handler: if we happened to be in
1425 * g_log() in process context when the signal came in, g_log will detect
1426 * the "recursion" and abort.
1429 capture_loop_stop();
1435 report_capture_count(gboolean reportit)
1437 /* Don't print this if we're a capture child. */
1438 if (!capture_child && reportit) {
1439 fprintf(stderr, "\rPackets captured: %u\n", global_ld.packet_count);
1440 /* stderr could be line buffered */
1448 report_counts_for_siginfo(void)
1450 report_capture_count(quiet);
1451 infoprint = FALSE; /* we just reported it */
1455 report_counts_siginfo(int signum _U_)
1457 int sav_errno = errno;
1459 /* If we've been told to delay printing, just set a flag asking
1460 that we print counts (if we're supposed to), otherwise print
1461 the count of packets captured (if we're supposed to). */
1465 report_counts_for_siginfo();
1468 #endif /* SIGINFO */
1471 exit_main(int status)
1474 /* Shutdown windows sockets */
1477 /* can be helpful for debugging */
1478 #ifdef DEBUG_DUMPCAP
1479 printf("Press any key\n");
1490 * If we were linked with libcap (not libpcap), make sure we have
1491 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1492 * (See comment in main() for details)
1495 relinquish_privs_except_capture(void)
1497 /* If 'started_with_special_privs' (ie: suid) then enable for
1498 * ourself the NET_ADMIN and NET_RAW capabilities and then
1499 * drop our suid privileges.
1501 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1502 * stuff we don't need (and shouldn't have).
1503 * CAP_NET_RAW: Packet capture (raw sockets).
1506 if (started_with_special_privs()) {
1507 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1508 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1510 cap_t caps = cap_init(); /* all capabilities initialized to off */
1512 print_caps("Pre drop, pre set");
1514 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1515 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1518 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1519 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1521 if (cap_set_proc(caps)) {
1522 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1524 print_caps("Pre drop, post set");
1526 relinquish_special_privs_perm();
1528 print_caps("Post drop, pre set");
1529 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1530 if (cap_set_proc(caps)) {
1531 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1533 print_caps("Post drop, post set");
1539 #endif /* HAVE_LIBCAP */
1541 /* Take care of byte order in the libpcap headers read from pipes.
1542 * (function taken from wiretap/libpcap.c) */
1544 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1547 /* Byte-swap the record header fields. */
1548 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
1549 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
1550 rechdr->incl_len = BSWAP32(rechdr->incl_len);
1551 rechdr->orig_len = BSWAP32(rechdr->orig_len);
1554 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1555 swapped, in order to match the BPF header layout.
1557 Unfortunately, some files were, according to a comment in the "libpcap"
1558 source, written with version 2.3 in their headers but without the
1559 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1560 would make no sense - we assume that we need to swap them. */
1561 if (hdr->version_major == 2 &&
1562 (hdr->version_minor < 3 ||
1563 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1566 temp = rechdr->orig_len;
1567 rechdr->orig_len = rechdr->incl_len;
1568 rechdr->incl_len = temp;
1574 * Thread function that reads from a pipe and pushes the data
1575 * to the main application thread.
1578 * XXX Right now we use async queues for basic signaling. The main thread
1579 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1580 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1581 * Iff the read is successful cap_pipe_read pushes an item onto
1582 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1583 * the queues themselves (yet).
1585 * We might want to move some of the cap_pipe_dispatch logic here so that
1586 * we can let cap_pipe_read run independently, queuing up multiple reads
1587 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1589 static void *cap_pipe_read(void *arg)
1591 pcap_options *pcap_opts;
1600 pcap_opts = (pcap_options *)arg;
1601 while (pcap_opts->cap_pipe_err == PIPOK) {
1602 g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1603 g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1605 while (bytes_read < (int) pcap_opts->cap_pipe_bytes_to_read) {
1607 /* If we try to use read() on a named pipe on Windows with partial
1608 * data it appears to return EOF.
1610 res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1611 pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1616 last_err = GetLastError();
1617 if (last_err == ERROR_MORE_DATA) {
1619 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1620 pcap_opts->cap_pipe_err = PIPEOF;
1624 pcap_opts->cap_pipe_err = PIPERR;
1627 } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1628 pcap_opts->cap_pipe_err = PIPEOF;
1633 b = read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1634 pcap_opts->cap_pipe_bytes_to_read - bytes_read);
1637 pcap_opts->cap_pipe_err = PIPEOF;
1641 pcap_opts->cap_pipe_err = PIPERR;
1650 pcap_opts->cap_pipe_bytes_read = bytes_read;
1651 if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1652 g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1654 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1660 #if !defined(_WIN32) || defined(MUST_DO_SELECT)
1661 /* Provide select() functionality for a single file descriptor
1662 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1664 * Returns the same values as select.
1667 cap_pipe_select(int pipe_fd)
1670 struct timeval timeout;
1673 FD_SET(pipe_fd, &rfds);
1675 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1676 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1678 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1683 /* Mimic pcap_open_live() for pipe captures
1685 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1686 * open it, and read the header.
1688 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1689 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1691 cap_pipe_open_live(char *pipename,
1692 pcap_options *pcap_opts,
1693 struct pcap_hdr *hdr,
1694 char *errmsg, int errmsgl)
1697 ws_statb64 pipe_stat;
1698 struct sockaddr_un sa;
1709 unsigned int bytes_read;
1714 pcap_opts->cap_pipe_fd = -1;
1716 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
1718 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1721 * XXX - this blocks until a pcap per-file header has been written to
1722 * the pipe, so it could block indefinitely.
1724 if (strcmp(pipename, "-") == 0) {
1726 fd = 0; /* read from stdin */
1728 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1732 if (ws_stat64(pipename, &pipe_stat) < 0) {
1733 if (errno == ENOENT || errno == ENOTDIR)
1734 pcap_opts->cap_pipe_err = PIPNEXIST;
1736 g_snprintf(errmsg, errmsgl,
1737 "The capture session could not be initiated "
1738 "due to error getting information on pipe/socket: %s", g_strerror(errno));
1739 pcap_opts->cap_pipe_err = PIPERR;
1743 if (S_ISFIFO(pipe_stat.st_mode)) {
1744 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1746 g_snprintf(errmsg, errmsgl,
1747 "The capture session could not be initiated "
1748 "due to error on pipe open: %s", g_strerror(errno));
1749 pcap_opts->cap_pipe_err = PIPERR;
1752 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1753 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1755 g_snprintf(errmsg, errmsgl,
1756 "The capture session could not be initiated "
1757 "due to error on socket create: %s", g_strerror(errno));
1758 pcap_opts->cap_pipe_err = PIPERR;
1761 sa.sun_family = AF_UNIX;
1763 * The Single UNIX Specification says:
1765 * The size of sun_path has intentionally been left undefined.
1766 * This is because different implementations use different sizes.
1767 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1768 * of 104. Since most implementations originate from BSD versions,
1769 * the size is typically in the range 92 to 108.
1771 * Applications should not assume a particular length for sun_path
1772 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1776 * The <sys/un.h> header shall define the sockaddr_un structure,
1777 * which shall include at least the following members:
1779 * sa_family_t sun_family Address family.
1780 * char sun_path[] Socket pathname.
1782 * so we assume that it's an array, with a specified size,
1783 * and that the size reflects the maximum path length.
1785 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1786 /* Path name too long */
1787 g_snprintf(errmsg, errmsgl,
1788 "The capture session coud not be initiated "
1789 "due to error on socket connect: Path name too long");
1790 pcap_opts->cap_pipe_err = PIPERR;
1793 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1795 g_snprintf(errmsg, errmsgl,
1796 "The capture session coud not be initiated "
1797 "due to error on socket connect: %s", g_strerror(errno));
1798 pcap_opts->cap_pipe_err = PIPERR;
1802 if (S_ISCHR(pipe_stat.st_mode)) {
1804 * Assume the user specified an interface on a system where
1805 * interfaces are in /dev. Pretend we haven't seen it.
1807 pcap_opts->cap_pipe_err = PIPNEXIST;
1810 g_snprintf(errmsg, errmsgl,
1811 "The capture session could not be initiated because\n"
1812 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
1813 pcap_opts->cap_pipe_err = PIPERR;
1818 #define PIPE_STR "\\pipe\\"
1819 /* Under Windows, named pipes _must_ have the form
1820 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1822 pncopy = g_strdup(pipename);
1823 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1824 pos = strchr(pncopy + 3, '\\');
1825 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1832 g_snprintf(errmsg, errmsgl,
1833 "The capture session could not be initiated because\n"
1834 "\"%s\" is neither an interface nor a pipe", pipename);
1835 pcap_opts->cap_pipe_err = PIPNEXIST;
1839 /* Wait for the pipe to appear */
1841 pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1842 OPEN_EXISTING, 0, NULL);
1844 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
1847 if (GetLastError() != ERROR_PIPE_BUSY) {
1848 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1849 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1850 g_snprintf(errmsg, errmsgl,
1851 "The capture session on \"%s\" could not be started "
1852 "due to error on pipe open: %s (error %d)",
1853 pipename, utf_16to8(err_str), GetLastError());
1855 pcap_opts->cap_pipe_err = PIPERR;
1859 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1860 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1861 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1862 g_snprintf(errmsg, errmsgl,
1863 "The capture session on \"%s\" timed out during "
1864 "pipe open: %s (error %d)",
1865 pipename, utf_16to8(err_str), GetLastError());
1867 pcap_opts->cap_pipe_err = PIPERR;
1874 pcap_opts->from_cap_pipe = TRUE;
1877 /* read the pcap header */
1879 while (bytes_read < sizeof magic) {
1880 sel_ret = cap_pipe_select(fd);
1882 g_snprintf(errmsg, errmsgl,
1883 "Unexpected error from select: %s", g_strerror(errno));
1885 } else if (sel_ret > 0) {
1886 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
1889 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1891 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1899 g_thread_create(&cap_pipe_read, pcap_opts, FALSE, NULL);
1901 pcap_opts->cap_pipe_buf = (char *) &magic;
1902 pcap_opts->cap_pipe_bytes_read = 0;
1903 pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
1904 /* We don't have to worry about cap_pipe_read_mtx here */
1905 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
1906 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
1907 if (pcap_opts->cap_pipe_bytes_read <= 0) {
1908 if (pcap_opts->cap_pipe_bytes_read == 0)
1909 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1911 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1920 /* Host that wrote it has our byte order, and was running
1921 a program using either standard or ss990417 libpcap. */
1922 pcap_opts->cap_pipe_byte_swapped = FALSE;
1923 pcap_opts->cap_pipe_modified = FALSE;
1925 case PCAP_MODIFIED_MAGIC:
1926 /* Host that wrote it has our byte order, but was running
1927 a program using either ss990915 or ss991029 libpcap. */
1928 pcap_opts->cap_pipe_byte_swapped = FALSE;
1929 pcap_opts->cap_pipe_modified = TRUE;
1931 case PCAP_SWAPPED_MAGIC:
1932 /* Host that wrote it has a byte order opposite to ours,
1933 and was running a program using either standard or
1934 ss990417 libpcap. */
1935 pcap_opts->cap_pipe_byte_swapped = TRUE;
1936 pcap_opts->cap_pipe_modified = FALSE;
1938 case PCAP_SWAPPED_MODIFIED_MAGIC:
1939 /* Host that wrote it out has a byte order opposite to
1940 ours, and was running a program using either ss990915
1941 or ss991029 libpcap. */
1942 pcap_opts->cap_pipe_byte_swapped = TRUE;
1943 pcap_opts->cap_pipe_modified = TRUE;
1946 /* Not a "libpcap" type we know about. */
1947 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
1952 /* Read the rest of the header */
1954 while (bytes_read < sizeof(struct pcap_hdr)) {
1955 sel_ret = cap_pipe_select(fd);
1957 g_snprintf(errmsg, errmsgl,
1958 "Unexpected error from select: %s", g_strerror(errno));
1960 } else if (sel_ret > 0) {
1961 b = read(fd, ((char *)hdr)+bytes_read,
1962 sizeof(struct pcap_hdr) - bytes_read);
1965 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1967 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
1975 pcap_opts->cap_pipe_buf = (char *) hdr;
1976 pcap_opts->cap_pipe_bytes_read = 0;
1977 pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1978 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
1979 g_async_queue_pop(pcap_opts->cap_pipe_done_q);
1980 if (pcap_opts->cap_pipe_bytes_read <= 0) {
1981 if (pcap_opts->cap_pipe_bytes_read == 0)
1982 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1984 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
1990 if (pcap_opts->cap_pipe_byte_swapped) {
1991 /* Byte-swap the header fields about which we care. */
1992 hdr->version_major = BSWAP16(hdr->version_major);
1993 hdr->version_minor = BSWAP16(hdr->version_minor);
1994 hdr->snaplen = BSWAP32(hdr->snaplen);
1995 hdr->network = BSWAP32(hdr->network);
1997 pcap_opts->linktype = hdr->network;
1999 if (hdr->version_major < 2) {
2000 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
2004 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2005 pcap_opts->cap_pipe_err = PIPOK;
2007 pcap_opts->cap_pipe_fd = fd;
2012 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
2013 pcap_opts->cap_pipe_err = PIPERR;
2016 pcap_opts->cap_pipe_fd = -1;
2023 /* We read one record from the pipe, take care of byte order in the record
2024 * header, write the record to the capture file, and update capture statistics. */
2026 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
2028 struct pcap_pkthdr phdr;
2029 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2041 #ifdef LOG_CAPTURE_VERBOSE
2042 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
2045 switch (pcap_opts->cap_pipe_state) {
2047 case STATE_EXPECT_REC_HDR:
2049 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2052 pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
2053 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
2054 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2055 pcap_opts->cap_pipe_bytes_read = 0;
2058 pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
2059 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2060 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2065 case STATE_READ_REC_HDR:
2067 b = read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
2068 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read);
2071 result = PD_PIPE_EOF;
2073 result = PD_PIPE_ERR;
2076 pcap_opts->cap_pipe_bytes_read += b;
2078 g_get_current_time(&wait_time);
2079 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2080 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2081 if (pcap_opts->cap_pipe_err == PIPEOF) {
2082 result = PD_PIPE_EOF;
2084 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2085 result = PD_PIPE_ERR;
2092 if ((pcap_opts->cap_pipe_bytes_read) < pcap_opts->cap_pipe_bytes_to_read)
2094 result = PD_REC_HDR_READ;
2097 case STATE_EXPECT_DATA:
2099 if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2102 pcap_opts->cap_pipe_state = STATE_READ_DATA;
2103 pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2104 pcap_opts->cap_pipe_bytes_read = 0;
2107 pcap_opts->cap_pipe_buf = (char *) data;
2108 g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2109 g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2114 case STATE_READ_DATA:
2116 b = read(pcap_opts->cap_pipe_fd, data+pcap_opts->cap_pipe_bytes_read,
2117 pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read);
2120 result = PD_PIPE_EOF;
2122 result = PD_PIPE_ERR;
2125 pcap_opts->cap_pipe_bytes_read += b;
2127 g_get_current_time(&wait_time);
2128 g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2129 q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2130 if (pcap_opts->cap_pipe_err == PIPEOF) {
2131 result = PD_PIPE_EOF;
2133 } else if (pcap_opts->cap_pipe_err == PIPERR) {
2134 result = PD_PIPE_ERR;
2141 if ((pcap_opts->cap_pipe_bytes_read) < pcap_opts->cap_pipe_bytes_to_read)
2143 result = PD_DATA_READ;
2147 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2150 } /* switch (ld->cap_pipe_state) */
2153 * We've now read as much data as we were expecting, so process it.
2157 case PD_REC_HDR_READ:
2158 /* We've read the header. Take care of byte order. */
2159 cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
2160 &pcap_opts->cap_pipe_rechdr.hdr);
2161 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2162 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2163 ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
2167 if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2168 pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2171 /* no data to read? fall through */
2174 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2175 phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2176 phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2177 phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2178 phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2181 capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2183 capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2185 pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2189 pcap_opts->cap_pipe_err = PIPEOF;
2194 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
2195 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2196 g_snprintf(errmsg, errmsgl,
2197 "Error reading from pipe: %s (error %d)",
2198 utf_16to8(err_str), GetLastError());
2201 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2209 pcap_opts->cap_pipe_err = PIPERR;
2210 /* Return here rather than inside the switch to prevent GCC warning */
2215 /** Open the capture input file (pcap or capture pipe).
2216 * Returns TRUE if it succeeds, FALSE otherwise. */
2218 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2219 char *errmsg, size_t errmsg_len,
2220 char *secondary_errmsg, size_t secondary_errmsg_len)
2222 gchar open_err_str[PCAP_ERRBUF_SIZE];
2223 gchar *sync_msg_str;
2224 interface_options interface_opts;
2225 pcap_options *pcap_opts;
2229 gchar *sync_secondary_msg_str;
2230 WORD wVersionRequested;
2234 /* XXX - opening Winsock on tshark? */
2236 /* Initialize Windows Socket if we are in a WIN32 OS
2237 This needs to be done before querying the interface for network/netmask */
2239 /* XXX - do we really require 1.1 or earlier?
2240 Are there any versions that support only 2.0 or higher? */
2241 wVersionRequested = MAKEWORD(1, 1);
2242 err = WSAStartup(wVersionRequested, &wsaData);
2246 case WSASYSNOTREADY:
2247 g_snprintf(errmsg, (gulong) errmsg_len,
2248 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2251 case WSAVERNOTSUPPORTED:
2252 g_snprintf(errmsg, (gulong) errmsg_len,
2253 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2254 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2257 case WSAEINPROGRESS:
2258 g_snprintf(errmsg, (gulong) errmsg_len,
2259 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2263 g_snprintf(errmsg, (gulong) errmsg_len,
2264 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2268 g_snprintf(errmsg, (gulong) errmsg_len,
2269 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2273 g_snprintf(errmsg, (gulong) errmsg_len,
2274 "Couldn't initialize Windows Sockets: error %d", err);
2277 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2281 if ((use_threads == FALSE) &&
2282 (capture_opts->ifaces->len > 1)) {
2283 g_snprintf(errmsg, (gulong) errmsg_len,
2284 "Using threads is required for capturing on mulitple interfaces!");
2288 for (i = 0; i < capture_opts->ifaces->len; i++) {
2289 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2290 pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2291 if (pcap_opts == NULL) {
2292 g_snprintf(errmsg, (gulong) errmsg_len,
2293 "Could not allocate memory.");
2296 pcap_opts->received = 0;
2297 pcap_opts->dropped = 0;
2298 pcap_opts->pcap_h = NULL;
2299 #ifdef MUST_DO_SELECT
2300 pcap_opts->pcap_fd = -1;
2302 pcap_opts->pcap_err = FALSE;
2303 pcap_opts->interface_id = i;
2304 pcap_opts->tid = NULL;
2305 pcap_opts->snaplen = 0;
2306 pcap_opts->linktype = -1;
2307 pcap_opts->from_cap_pipe = FALSE;
2308 memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2309 memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2311 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2313 pcap_opts->cap_pipe_fd = -1;
2315 pcap_opts->cap_pipe_modified = FALSE;
2316 pcap_opts->cap_pipe_byte_swapped = FALSE;
2318 pcap_opts->cap_pipe_buf = NULL;
2320 pcap_opts->cap_pipe_bytes_to_read = 0;
2321 pcap_opts->cap_pipe_bytes_read = 0;
2322 pcap_opts->cap_pipe_state = 0;
2323 pcap_opts->cap_pipe_err = PIPOK;
2325 #if GLIB_CHECK_VERSION(2,31,0)
2326 pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2327 g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2329 pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2331 pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2332 pcap_opts->cap_pipe_done_q = g_async_queue_new();
2334 g_array_append_val(ld->pcaps, pcap_opts);
2336 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2337 pcap_opts->pcap_h = open_capture_device(&interface_opts, &open_err_str);
2339 if (pcap_opts->pcap_h != NULL) {
2340 /* we've opened "iface" as a network device */
2342 /* try to set the capture buffer size */
2343 if (interface_opts.buffer_size > 1 &&
2344 pcap_setbuff(pcap_opts->pcap_h, interface_opts.buffer_size * 1024 * 1024) != 0) {
2345 sync_secondary_msg_str = g_strdup_printf(
2346 "The capture buffer size of %dMB seems to be too high for your machine,\n"
2347 "the default of 1MB will be used.\n"
2349 "Nonetheless, the capture is started.\n",
2350 interface_opts.buffer_size);
2351 report_capture_error("Couldn't set the capture buffer size!",
2352 sync_secondary_msg_str);
2353 g_free(sync_secondary_msg_str);
2357 #if defined(HAVE_PCAP_SETSAMPLING)
2358 if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2359 struct pcap_samp *samp;
2361 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2362 switch (interface_opts.sampling_method) {
2363 case CAPTURE_SAMP_BY_COUNT:
2364 samp->method = PCAP_SAMP_1_EVERY_N;
2367 case CAPTURE_SAMP_BY_TIMER:
2368 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2372 sync_msg_str = g_strdup_printf(
2373 "Unknown sampling method %d specified,\n"
2374 "continue without packet sampling",
2375 interface_opts.sampling_method);
2376 report_capture_error("Couldn't set the capture "
2377 "sampling", sync_msg_str);
2378 g_free(sync_msg_str);
2380 samp->value = interface_opts.sampling_param;
2382 report_capture_error("Couldn't set the capture sampling",
2383 "Cannot get packet sampling data structure");
2388 /* setting the data link type only works on real interfaces */
2389 if (!set_pcap_linktype(pcap_opts->pcap_h, interface_opts.linktype, interface_opts.name,
2391 secondary_errmsg, secondary_errmsg_len)) {
2394 pcap_opts->linktype = get_pcap_linktype(pcap_opts->pcap_h, interface_opts.name);
2396 /* We couldn't open "iface" as a network device. */
2397 /* Try to open it as a pipe */
2398 cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2401 if (pcap_opts->cap_pipe_fd == -1) {
2403 if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2405 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2406 /* Pipe doesn't exist, so output message for interface */
2407 get_capture_device_open_failure_messages(open_err_str,
2408 interface_opts.name,
2412 secondary_errmsg_len);
2415 * Else pipe (or file) does exist and cap_pipe_open_live() has
2420 /* cap_pipe_open_live() succeeded; don't want
2421 error message from pcap_open_live() */
2422 open_err_str[0] = '\0';
2426 /* XXX - will this work for tshark? */
2427 #ifdef MUST_DO_SELECT
2428 if (!pcap_opts->from_cap_pipe) {
2429 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2430 pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2432 pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2437 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2438 returned a warning; print it, but keep capturing. */
2439 if (open_err_str[0] != '\0') {
2440 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2441 report_capture_error(sync_msg_str, "");
2442 g_free(sync_msg_str);
2444 capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2445 g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2448 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
2449 /* to remove any suid privileges. */
2450 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
2451 /* (euid/egid have already previously been set to ruid/rgid. */
2452 /* (See comment in main() for details) */
2454 relinquish_special_privs_perm();
2456 relinquish_all_capabilities();
2461 /* close the capture input file (pcap or capture pipe) */
2462 static void capture_loop_close_input(loop_data *ld)
2465 pcap_options *pcap_opts;
2467 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2469 for (i = 0; i < ld->pcaps->len; i++) {
2470 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2471 /* if open, close the capture pipe "input file" */
2473 if (pcap_opts->cap_pipe_fd >= 0) {
2474 g_assert(pcap_opts->from_cap_pipe);
2475 ws_close(pcap_opts->cap_pipe_fd);
2476 pcap_opts->cap_pipe_fd = -1;
2479 if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2480 CloseHandle(pcap_opts->cap_pipe_h);
2481 pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2484 /* if open, close the pcap "input file" */
2485 if (pcap_opts->pcap_h != NULL) {
2486 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2487 pcap_close(pcap_opts->pcap_h);
2488 pcap_opts->pcap_h = NULL;
2495 /* Shut down windows sockets */
2501 /* init the capture filter */
2502 static initfilter_status_t
2503 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2504 const gchar * name, const gchar * cfilter)
2506 struct bpf_program fcode;
2508 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2510 /* capture filters only work on real interfaces */
2511 if (cfilter && !from_cap_pipe) {
2512 /* A capture filter was specified; set it up. */
2513 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2514 /* Treat this specially - our caller might try to compile this
2515 as a display filter and, if that succeeds, warn the user that
2516 the display and capture filter syntaxes are different. */
2517 return INITFILTER_BAD_FILTER;
2519 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2520 #ifdef HAVE_PCAP_FREECODE
2521 pcap_freecode(&fcode);
2523 return INITFILTER_OTHER_ERROR;
2525 #ifdef HAVE_PCAP_FREECODE
2526 pcap_freecode(&fcode);
2530 return INITFILTER_NO_ERROR;
2534 /* set up to write to the already-opened capture output file/files */
2536 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2540 pcap_options *pcap_opts;
2541 interface_options interface_opts;
2542 gboolean successful;
2544 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2546 if ((capture_opts->use_pcapng == FALSE) &&
2547 (capture_opts->ifaces->len > 1)) {
2548 g_snprintf(errmsg, errmsg_len,
2549 "Using PCAPNG is required for capturing on mulitple interfaces! Use the -n option.");
2553 /* Set up to write to the capture file. */
2554 if (capture_opts->multi_files_on) {
2555 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2557 ld->pdh = libpcap_fdopen(ld->save_file_fd, &err);
2560 if (capture_opts->use_pcapng) {
2563 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2564 successful = libpcap_write_session_header_block(ld->pdh, appname, &ld->bytes_written, &err);
2565 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2566 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2567 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2568 if (pcap_opts->from_cap_pipe) {
2569 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2571 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2573 successful = libpcap_write_interface_description_block(ld->pdh,
2574 interface_opts.name,
2575 interface_opts.cfilter?interface_opts.cfilter:"",
2576 pcap_opts->linktype,
2582 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
2583 if (pcap_opts->from_cap_pipe) {
2584 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2586 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2588 successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
2589 &ld->bytes_written, &err);
2597 if (ld->pdh == NULL) {
2598 /* We couldn't set up to write to the capture file. */
2599 /* XXX - use cf_open_error_message from tshark instead? */
2604 g_snprintf(errmsg, errmsg_len,
2605 "The file to which the capture would be"
2606 " saved (\"%s\") could not be opened: Error %d.",
2607 capture_opts->save_file, err);
2609 g_snprintf(errmsg, errmsg_len,
2610 "The file to which the capture would be"
2611 " saved (\"%s\") could not be opened: %s.",
2612 capture_opts->save_file, g_strerror(err));
2624 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2628 pcap_options *pcap_opts;
2630 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2632 if (capture_opts->multi_files_on) {
2633 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2635 if (capture_opts->use_pcapng) {
2636 for (i = 0; i < global_ld.pcaps->len; i++) {
2637 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2638 if (!pcap_opts->from_cap_pipe) {
2639 libpcap_write_interface_statistics_block(ld->pdh, i, pcap_opts->pcap_h, &ld->bytes_written, err_close);
2643 return libpcap_dump_close(ld->pdh, err_close);
2647 /* dispatch incoming packets (pcap or capture pipe)
2649 * Waits for incoming packets to be available, and calls pcap_dispatch()
2650 * to cause them to be processed.
2652 * Returns the number of packets which were processed.
2654 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2655 * packet-batching behaviour does not cause packets to get held back
2659 capture_loop_dispatch(loop_data *ld,
2660 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
2663 gint packet_count_before;
2664 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
2669 packet_count_before = ld->packet_count;
2670 if (pcap_opts->from_cap_pipe) {
2671 /* dispatch from capture pipe */
2672 #ifdef LOG_CAPTURE_VERBOSE
2673 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2676 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
2678 if (sel_ret < 0 && errno != EINTR) {
2679 g_snprintf(errmsg, errmsg_len,
2680 "Unexpected error from select: %s", g_strerror(errno));
2681 report_capture_error(errmsg, please_report);
2686 * "select()" says we can read from the pipe without blocking
2689 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
2699 /* dispatch from pcap */
2700 #ifdef MUST_DO_SELECT
2702 * If we have "pcap_get_selectable_fd()", we use it to get the
2703 * descriptor on which to select; if that's -1, it means there
2704 * is no descriptor on which you can do a "select()" (perhaps
2705 * because you're capturing on a special device, and that device's
2706 * driver unfortunately doesn't support "select()", in which case
2707 * we don't do the select - which means it might not be possible
2708 * to stop a capture until a packet arrives. If that's unacceptable,
2709 * plead with whoever supplies the software for that device to add
2710 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2711 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2712 * later, so it can use pcap_breakloop().
2714 #ifdef LOG_CAPTURE_VERBOSE
2715 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2717 if (pcap_opts->pcap_fd != -1) {
2718 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
2721 * "select()" says we can read from it without blocking; go for
2724 * We don't have pcap_breakloop(), so we only process one packet
2725 * per pcap_dispatch() call, to allow a signal to stop the
2726 * processing immediately, rather than processing all packets
2727 * in a batch before quitting.
2730 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2732 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2736 /* Error, rather than pcap_breakloop(). */
2737 pcap_opts->pcap_err = TRUE;
2739 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2742 if (sel_ret < 0 && errno != EINTR) {
2743 g_snprintf(errmsg, errmsg_len,
2744 "Unexpected error from select: %s", g_strerror(errno));
2745 report_capture_error(errmsg, please_report);
2751 #endif /* MUST_DO_SELECT */
2753 /* dispatch from pcap without select */
2755 #ifdef LOG_CAPTURE_VERBOSE
2756 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2760 * On Windows, we don't support asynchronously telling a process to
2761 * stop capturing; instead, we check for an indication on a pipe
2762 * after processing packets. We therefore process only one packet
2763 * at a time, so that we can check the pipe after every packet.
2766 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2768 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2772 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2774 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2779 /* Error, rather than pcap_breakloop(). */
2780 pcap_opts->pcap_err = TRUE;
2782 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2784 #else /* pcap_next_ex */
2785 #ifdef LOG_CAPTURE_VERBOSE
2786 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2788 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2791 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2792 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
2793 * This should be fixed in the WinPcap 4.0 alpha release.
2795 * For reference, an example remote interface:
2796 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2799 /* emulate dispatch from pcap */
2802 struct pcap_pkthdr *pkt_header;
2807 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
2809 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
2811 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
2816 pcap_opts->pcap_err = TRUE;
2820 #endif /* pcap_next_ex */
2824 #ifdef LOG_CAPTURE_VERBOSE
2825 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2828 return ld->packet_count - packet_count_before;
2832 /* Isolate the Universally Unique Identifier from the interface. Basically, we
2833 * want to grab only the characters between the '{' and '}' delimiters.
2835 * Returns a GString that must be freed with g_string_free(). */
2837 isolate_uuid(const char *iface)
2842 ptr = strchr(iface, '{');
2844 return g_string_new(iface);
2845 gstr = g_string_new(ptr + 1);
2847 ptr = strchr(gstr->str, '}');
2851 gstr = g_string_truncate(gstr, ptr - gstr->str);
2856 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2857 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2859 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2860 char *errmsg, int errmsg_len)
2863 gchar *capfile_name;
2865 gboolean is_tempfile;
2867 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2868 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
2870 if (capture_opts->save_file != NULL) {
2871 /* We return to the caller while the capture is in progress.
2872 * Therefore we need to take a copy of save_file in
2873 * case the caller destroys it after we return.
2875 capfile_name = g_strdup(capture_opts->save_file);
2877 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2878 if (capture_opts->multi_files_on) {
2879 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2880 g_snprintf(errmsg, errmsg_len,
2881 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2882 g_free(capfile_name);
2885 if (strcmp(capfile_name, "-") == 0) {
2886 /* write to stdout */
2889 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
2890 _setmode(1, O_BINARY);
2893 } /* if (...output_to_pipe ... */
2896 if (capture_opts->multi_files_on) {
2897 /* ringbuffer is enabled */
2898 *save_file_fd = ringbuf_init(capfile_name,
2899 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
2900 capture_opts->group_read_access);
2902 /* we need the ringbuf name */
2903 if(*save_file_fd != -1) {
2904 g_free(capfile_name);
2905 capfile_name = g_strdup(ringbuf_current_filename());
2908 /* Try to open/create the specified file for use as a capture buffer. */
2909 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
2910 (capture_opts->group_read_access) ? 0640 : 0600);
2913 is_tempfile = FALSE;
2915 /* Choose a random name for the temporary capture buffer */
2916 if (global_capture_opts.ifaces->len > 1) {
2917 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
2922 iface = isolate_uuid(g_array_index(global_capture_opts.ifaces, interface_options, 0).name);
2923 basename = g_path_get_basename(iface->str);
2924 g_string_free(iface, TRUE);
2926 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).name);
2928 prefix = g_strconcat("wireshark_", basename, NULL);
2931 *save_file_fd = create_tempfile(&tmpname, prefix);
2933 capfile_name = g_strdup(tmpname);
2937 /* did we fail to open the output file? */
2938 if (*save_file_fd == -1) {
2940 g_snprintf(errmsg, errmsg_len,
2941 "The temporary file to which the capture would be saved (\"%s\") "
2942 "could not be opened: %s.", capfile_name, g_strerror(errno));
2944 if (capture_opts->multi_files_on) {
2945 ringbuf_error_cleanup();
2948 g_snprintf(errmsg, errmsg_len,
2949 "The file to which the capture would be saved (\"%s\") "
2950 "could not be opened: %s.", capfile_name,
2953 g_free(capfile_name);
2957 if(capture_opts->save_file != NULL) {
2958 g_free(capture_opts->save_file);
2960 capture_opts->save_file = capfile_name;
2961 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2962 "g_free(capfile_name)". */
2968 /* Do the work of handling either the file size or file duration capture
2969 conditions being reached, and switching files or stopping. */
2971 do_file_switch_or_stop(capture_options *capture_opts,
2972 condition *cnd_autostop_files,
2973 condition *cnd_autostop_size,
2974 condition *cnd_file_duration)
2977 pcap_options *pcap_opts;
2978 interface_options interface_opts;
2979 gboolean successful;
2981 if (capture_opts->multi_files_on) {
2982 if (cnd_autostop_files != NULL &&
2983 cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
2984 /* no files left: stop here */
2985 global_ld.go = FALSE;
2989 /* Switch to the next ringbuffer file */
2990 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2991 &global_ld.save_file_fd, &global_ld.err)) {
2993 /* File switch succeeded: reset the conditions */
2994 global_ld.bytes_written = 0;
2995 if (capture_opts->use_pcapng) {
2998 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2999 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &(global_ld.bytes_written), &global_ld.err);
3000 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3001 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3002 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3003 successful = libpcap_write_interface_description_block(global_ld.pdh,
3004 interface_opts.name,
3005 interface_opts.cfilter?interface_opts.cfilter:"",
3006 pcap_opts->linktype,
3008 &(global_ld.bytes_written),
3012 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3013 successful = libpcap_write_file_header(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
3014 &global_ld.bytes_written, &global_ld.err);
3017 fclose(global_ld.pdh);
3018 global_ld.pdh = NULL;
3019 global_ld.go = FALSE;
3022 if (cnd_autostop_size)
3023 cnd_reset(cnd_autostop_size);
3024 if (cnd_file_duration)
3025 cnd_reset(cnd_file_duration);
3026 libpcap_dump_flush(global_ld.pdh, NULL);
3028 report_packet_count(global_ld.inpkts_to_sync_pipe);
3029 global_ld.inpkts_to_sync_pipe = 0;
3030 report_new_capture_file(capture_opts->save_file);
3032 /* File switch failed: stop here */
3033 global_ld.go = FALSE;
3037 /* single file, stop now */
3038 global_ld.go = FALSE;
3045 pcap_read_handler(void* arg)
3047 pcap_options *pcap_opts;
3048 char errmsg[MSG_MAX_LENGTH+1];
3050 pcap_opts = (pcap_options *)arg;
3052 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3053 pcap_opts->interface_id);
3055 while (global_ld.go) {
3056 /* dispatch incoming packets */
3057 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3059 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3060 pcap_opts->interface_id);
3061 g_thread_exit(NULL);
3065 /* Do the low-level work of a capture.
3066 Returns TRUE if it succeeds, FALSE otherwise. */
3068 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3071 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3073 struct timeval upd_time, cur_time;
3077 condition *cnd_file_duration = NULL;
3078 condition *cnd_autostop_files = NULL;
3079 condition *cnd_autostop_size = NULL;
3080 condition *cnd_autostop_duration = NULL;
3083 gboolean cfilter_error = FALSE;
3084 char errmsg[MSG_MAX_LENGTH+1];
3085 char secondary_errmsg[MSG_MAX_LENGTH+1];
3086 pcap_options *pcap_opts;
3087 interface_options interface_opts;
3088 guint i, error_index = 0;
3091 *secondary_errmsg = '\0';
3093 /* init the loop data */
3094 global_ld.go = TRUE;
3095 global_ld.packet_count = 0;
3097 global_ld.report_packet_count = FALSE;
3099 if (capture_opts->has_autostop_packets)
3100 global_ld.packet_max = capture_opts->autostop_packets;
3102 global_ld.packet_max = 0; /* no limit */
3103 global_ld.inpkts_to_sync_pipe = 0;
3104 global_ld.err = 0; /* no error seen yet */
3105 global_ld.pdh = NULL;
3106 global_ld.autostop_files = 0;
3107 global_ld.save_file_fd = -1;
3109 /* We haven't yet gotten the capture statistics. */
3110 *stats_known = FALSE;
3112 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3113 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3115 /* open the "input file" from network interface or capture pipe */
3116 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3117 secondary_errmsg, sizeof(secondary_errmsg))) {
3120 for (i = 0; i < capture_opts->ifaces->len; i++) {
3121 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3122 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3123 /* init the input filter from the network interface (capture pipe will do nothing) */
3125 * When remote capturing WinPCap crashes when the capture filter
3126 * is NULL. This might be a bug in WPCap. Therefore we provide an emtpy
3129 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3130 interface_opts.name,
3131 interface_opts.cfilter?interface_opts.cfilter:"")) {
3133 case INITFILTER_NO_ERROR:
3136 case INITFILTER_BAD_FILTER:
3137 cfilter_error = TRUE;
3139 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3142 case INITFILTER_OTHER_ERROR:
3143 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3144 pcap_geterr(pcap_opts->pcap_h));
3145 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3150 /* If we're supposed to write to a capture file, open it for output
3151 (temporary/specified name/ringbuffer) */
3152 if (capture_opts->saving_to_file) {
3153 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3154 errmsg, sizeof(errmsg))) {
3158 /* set up to write to the already-opened capture output file/files */
3159 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3164 /* XXX - capture SIGTERM and close the capture, in case we're on a
3165 Linux 2.0[.x] system and you have to explicitly close the capture
3166 stream in order to turn promiscuous mode off? We need to do that
3167 in other places as well - and I don't think that works all the
3168 time in any case, due to libpcap bugs. */
3170 /* Well, we should be able to start capturing.
3172 Sync out the capture file, so the header makes it to the file system,
3173 and send a "capture started successfully and capture file created"
3174 message to our parent so that they'll open the capture file and
3175 update its windows to indicate that we have a live capture in
3177 libpcap_dump_flush(global_ld.pdh, NULL);
3178 report_new_capture_file(capture_opts->save_file);
3181 /* initialize capture stop (and alike) conditions */
3182 init_capture_stop_conditions();
3183 /* create stop conditions */
3184 if (capture_opts->has_autostop_filesize)
3186 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
3187 if (capture_opts->has_autostop_duration)
3188 cnd_autostop_duration =
3189 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3191 if (capture_opts->multi_files_on) {
3192 if (capture_opts->has_file_duration)
3194 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3196 if (capture_opts->has_autostop_files)
3197 cnd_autostop_files =
3198 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
3201 /* init the time values */
3203 upd_time = GetTickCount();
3205 gettimeofday(&upd_time, NULL);
3208 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
3210 /* WOW, everything is prepared! */
3211 /* please fasten your seat belts, we will enter now the actual capture loop */
3213 pcap_queue = g_async_queue_new();
3214 pcap_queue_bytes = 0;
3215 pcap_queue_packets = 0;
3216 for (i = 0; i < global_ld.pcaps->len; i++) {
3217 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3218 #if GLIB_CHECK_VERSION(2,31,0)
3219 /* XXX - Add an interface name here? */
3220 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3222 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3226 while (global_ld.go) {
3227 /* dispatch incoming packets */
3229 GTimeVal write_thread_time;
3230 pcap_queue_element *queue_element;
3232 g_get_current_time(&write_thread_time);
3233 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3234 g_async_queue_lock(pcap_queue);
3235 queue_element = g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3236 if (queue_element) {
3237 pcap_queue_bytes -= queue_element->phdr.caplen;
3238 pcap_queue_packets -= 1;
3240 g_async_queue_unlock(pcap_queue);
3241 if (queue_element) {
3242 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3243 "Dequeued a packet of length %d captured on interface %d.",
3244 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3246 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3247 &queue_element->phdr,
3249 g_free(queue_element->pd);
3250 g_free(queue_element);
3256 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3257 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3258 sizeof(errmsg), pcap_opts);
3261 /* Were we asked to print packet counts by the SIGINFO handler? */
3262 if (global_ld.report_packet_count) {
3263 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3264 plurality(global_ld.packet_count, "", "s"));
3265 global_ld.report_packet_count = FALSE;
3270 /* any news from our parent (signal pipe)? -> just stop the capture */
3271 if (!signal_pipe_check_running()) {
3272 global_ld.go = FALSE;
3277 global_ld.inpkts_to_sync_pipe += inpkts;
3279 /* check capture size condition */
3280 if (cnd_autostop_size != NULL &&
3281 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)) {
3282 /* Capture size limit reached, do we have another file? */
3283 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3284 cnd_autostop_size, cnd_file_duration))
3286 } /* cnd_autostop_size */
3287 if (capture_opts->output_to_pipe) {
3288 libpcap_dump_flush(global_ld.pdh, NULL);
3292 /* Only update once every 500ms so as not to overload slow displays.
3293 * This also prevents too much context-switching between the dumpcap
3294 * and wireshark processes.
3296 #define DUMPCAP_UPD_TIME 500
3299 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3300 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3302 gettimeofday(&cur_time, NULL);
3303 if ((cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3304 (upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3307 upd_time = cur_time;
3310 if (pcap_stats(pch, stats) >= 0) {
3311 *stats_known = TRUE;
3314 /* Let the parent process know. */
3315 if (global_ld.inpkts_to_sync_pipe) {
3317 libpcap_dump_flush(global_ld.pdh, NULL);
3319 /* Send our parent a message saying we've written out
3320 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3322 report_packet_count(global_ld.inpkts_to_sync_pipe);
3324 global_ld.inpkts_to_sync_pipe = 0;
3327 /* check capture duration condition */
3328 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3329 /* The maximum capture time has elapsed; stop the capture. */
3330 global_ld.go = FALSE;
3334 /* check capture file duration condition */
3335 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3336 /* duration limit reached, do we have another file? */
3337 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3338 cnd_autostop_size, cnd_file_duration))
3340 } /* cnd_file_duration */
3344 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3346 pcap_queue_element *queue_element;
3348 for (i = 0; i < global_ld.pcaps->len; i++) {
3349 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3350 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3351 pcap_opts->interface_id);
3352 g_thread_join(pcap_opts->tid);
3353 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3354 pcap_opts->interface_id);
3357 g_async_queue_lock(pcap_queue);
3358 queue_element = g_async_queue_try_pop_unlocked(pcap_queue);
3359 if (queue_element) {
3360 pcap_queue_bytes -= queue_element->phdr.caplen;
3361 pcap_queue_packets -= 1;
3363 g_async_queue_unlock(pcap_queue);
3364 if (queue_element == NULL) {
3367 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3368 "Dequeued a packet of length %d captured on interface %d.",
3369 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3370 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3371 &queue_element->phdr,
3373 g_free(queue_element->pd);
3374 g_free(queue_element);
3375 global_ld.inpkts_to_sync_pipe += 1;
3376 if (capture_opts->output_to_pipe) {
3377 libpcap_dump_flush(global_ld.pdh, NULL);
3383 /* delete stop conditions */
3384 if (cnd_file_duration != NULL)
3385 cnd_delete(cnd_file_duration);
3386 if (cnd_autostop_files != NULL)
3387 cnd_delete(cnd_autostop_files);
3388 if (cnd_autostop_size != NULL)
3389 cnd_delete(cnd_autostop_size);
3390 if (cnd_autostop_duration != NULL)
3391 cnd_delete(cnd_autostop_duration);
3393 /* did we have a pcap (input) error? */
3394 for (i = 0; i < capture_opts->ifaces->len; i++) {
3395 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3396 if (pcap_opts->pcap_err) {
3397 /* On Linux, if an interface goes down while you're capturing on it,
3398 you'll get a "recvfrom: Network is down" or
3399 "The interface went down" error (ENETDOWN).
3400 (At least you will if g_strerror() doesn't show a local translation
3403 On FreeBSD and OS X, if a network adapter disappears while
3404 you're capturing on it, you'll get a "read: Device not configured"
3405 error (ENXIO). (See previous parenthetical note.)
3407 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3409 These should *not* be reported to the Wireshark developers. */
3412 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3413 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3414 strcmp(cap_err_str, "The interface went down") == 0 ||
3415 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3416 strcmp(cap_err_str, "read: I/O error") == 0 ||
3417 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3418 report_capture_error("The network adapter on which the capture was being done "
3419 "is no longer running; the capture has stopped.",
3422 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3424 report_capture_error(errmsg, please_report);
3427 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3428 report_capture_error(errmsg, "");
3432 /* did we have an output error while capturing? */
3433 if (global_ld.err == 0) {
3436 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3437 global_ld.err, FALSE);
3438 report_capture_error(errmsg, please_report);
3442 if (capture_opts->saving_to_file) {
3443 /* close the output file */
3444 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3448 /* there might be packets not yet notified to the parent */
3449 /* (do this after closing the file, so all packets are already flushed) */
3450 if(global_ld.inpkts_to_sync_pipe) {
3452 report_packet_count(global_ld.inpkts_to_sync_pipe);
3453 global_ld.inpkts_to_sync_pipe = 0;
3456 /* If we've displayed a message about a write error, there's no point
3457 in displaying another message about an error on close. */
3458 if (!close_ok && write_ok) {
3459 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3461 report_capture_error(errmsg, "");
3465 * XXX We exhibit different behaviour between normal mode and sync mode
3466 * when the pipe is stdin and not already at EOF. If we're a child, the
3467 * parent's stdin isn't closed, so if the user starts another capture,
3468 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3469 * will say "Unrecognized libpcap format". On the other hand, in normal
3470 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3473 report_capture_count(TRUE);
3475 /* get packet drop statistics from pcap */
3476 for (i = 0; i < capture_opts->ifaces->len; i++) {
3480 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3481 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3482 received = pcap_opts->received;
3483 dropped = pcap_opts->dropped;
3484 if (pcap_opts->pcap_h != NULL) {
3485 g_assert(!pcap_opts->from_cap_pipe);
3486 /* Get the capture statistics, so we know how many packets were dropped. */
3487 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3488 *stats_known = TRUE;
3489 /* Let the parent process know. */
3490 dropped += stats->ps_drop;
3492 g_snprintf(errmsg, sizeof(errmsg),
3493 "Can't get packet-drop statistics: %s",
3494 pcap_geterr(pcap_opts->pcap_h));
3495 report_capture_error(errmsg, please_report);
3498 report_packet_drops(received, dropped, interface_opts.name);
3501 /* close the input file (pcap or capture pipe) */
3502 capture_loop_close_input(&global_ld);
3504 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
3506 /* ok, if the write and the close were successful. */
3507 return write_ok && close_ok;
3510 if (capture_opts->multi_files_on) {
3511 /* cleanup ringbuffer */
3512 ringbuf_error_cleanup();
3514 /* We can't use the save file, and we have no FILE * for the stream
3515 to close in order to close it, so close the FD directly. */
3516 if (global_ld.save_file_fd != -1) {
3517 ws_close(global_ld.save_file_fd);
3520 /* We couldn't even start the capture, so get rid of the capture
3522 if (capture_opts->save_file != NULL) {
3523 ws_unlink(capture_opts->save_file);
3524 g_free(capture_opts->save_file);
3527 capture_opts->save_file = NULL;
3529 report_cfilter_error(capture_opts, error_index, errmsg);
3531 report_capture_error(errmsg, secondary_errmsg);
3533 /* close the input file (pcap or cap_pipe) */
3534 capture_loop_close_input(&global_ld);
3536 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3542 static void capture_loop_stop(void)
3544 #ifdef HAVE_PCAP_BREAKLOOP
3546 pcap_options *pcap_opts;
3548 for (i = 0; i < global_ld.pcaps->len; i++) {
3549 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3550 if (pcap_opts->pcap_h != NULL)
3551 pcap_breakloop(pcap_opts->pcap_h);
3554 global_ld.go = FALSE;
3559 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3560 int err, gboolean is_close)
3565 g_snprintf(errmsg, errmsglen,
3566 "Not all the packets could be written to the file"
3567 " to which the capture was being saved\n"
3568 "(\"%s\") because there is no space left on the file system\n"
3569 "on which that file resides.",
3575 g_snprintf(errmsg, errmsglen,
3576 "Not all the packets could be written to the file"
3577 " to which the capture was being saved\n"
3578 "(\"%s\") because you are too close to, or over,"
3579 " your disk quota\n"
3580 "on the file system on which that file resides.",
3587 g_snprintf(errmsg, errmsglen,
3588 "The file to which the capture was being saved\n"
3589 "(\"%s\") could not be closed: %s.",
3590 fname, g_strerror(err));
3592 g_snprintf(errmsg, errmsglen,
3593 "An error occurred while writing to the file"
3594 " to which the capture was being saved\n"
3596 fname, g_strerror(err));
3603 /* one packet was captured, process it */
3605 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3608 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3611 /* We may be called multiple times from pcap_dispatch(); if we've set
3612 the "stop capturing" flag, ignore this packet, as we're not
3613 supposed to be saving any more packets. */
3617 if (global_ld.pdh) {
3618 gboolean successful;
3620 /* We're supposed to write the packet to a file; do so.
3621 If this fails, set "ld->go" to FALSE, to stop the capture, and set
3622 "ld->err" to the error. */
3623 if (global_capture_opts.use_pcapng) {
3624 successful = libpcap_write_enhanced_packet_block(global_ld.pdh, phdr, pcap_opts->interface_id, pd, &global_ld.bytes_written, &err);
3626 successful = libpcap_write_packet(global_ld.pdh, phdr, pd, &global_ld.bytes_written, &err);
3629 global_ld.go = FALSE;
3630 global_ld.err = err;
3632 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3633 "Wrote a packet of length %d captured on interface %u.",
3634 phdr->caplen, pcap_opts->interface_id);
3635 global_ld.packet_count++;
3636 pcap_opts->received++;
3637 /* if the user told us to stop after x packets, do we already have enough? */
3638 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
3639 global_ld.go = FALSE;
3645 /* one packet was captured, queue it */
3647 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3650 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3651 pcap_queue_element *queue_element;
3652 gboolean limit_reached;
3654 /* We may be called multiple times from pcap_dispatch(); if we've set
3655 the "stop capturing" flag, ignore this packet, as we're not
3656 supposed to be saving any more packets. */
3660 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
3661 if (queue_element == NULL) {
3662 pcap_opts->dropped++;
3665 queue_element->pcap_opts = pcap_opts;
3666 queue_element->phdr = *phdr;
3667 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
3668 if (queue_element->pd == NULL) {
3669 pcap_opts->dropped++;
3670 g_free(queue_element);
3673 memcpy(queue_element->pd, pd, phdr->caplen);
3674 g_async_queue_lock(pcap_queue);
3675 if (((pcap_queue_byte_limit > 0) && (pcap_queue_bytes < pcap_queue_byte_limit)) &&
3676 ((pcap_queue_packet_limit > 0) && (pcap_queue_packets < pcap_queue_packet_limit))) {
3677 limit_reached = FALSE;
3678 g_async_queue_push_unlocked(pcap_queue, queue_element);
3679 pcap_queue_bytes += phdr->caplen;
3680 pcap_queue_packets += 1;
3682 limit_reached = TRUE;
3684 g_async_queue_unlock(pcap_queue);
3685 if (limit_reached) {
3686 pcap_opts->dropped++;
3687 g_free(queue_element->pd);
3688 g_free(queue_element);
3689 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3690 "Dropped a packet of length %d captured on interface %u.",
3691 phdr->caplen, pcap_opts->interface_id);
3693 pcap_opts->received++;
3694 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3695 "Queued a packet of length %d captured on interface %u.",
3696 phdr->caplen, pcap_opts->interface_id);
3698 /* I don't want to hold the mutex over the debug output. So the
3699 output may be wrong */
3700 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3701 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
3702 pcap_queue_bytes, pcap_queue_packets);
3705 /* And now our feature presentation... [ fade to music ] */
3707 main(int argc, char *argv[])
3710 gboolean arg_error = FALSE;
3715 struct sigaction action, oldaction;
3718 gboolean start_capture = TRUE;
3719 gboolean stats_known;
3720 struct pcap_stat stats;
3721 GLogLevelFlags log_flags;
3722 gboolean list_interfaces = FALSE;
3723 gboolean list_link_layer_types = FALSE;
3724 #ifdef HAVE_BPF_IMAGE
3725 gboolean print_bpf_code = FALSE;
3727 gboolean machine_readable = FALSE;
3728 gboolean print_statistics = FALSE;
3729 int status, run_once_args = 0;
3732 #if defined(__APPLE__) && defined(__LP64__)
3733 struct utsname osinfo;
3738 arg_list_utf_16to8(argc, argv);
3743 * Initialize our DLL search path. MUST be called before LoadLibrary
3746 ws_init_dll_search_path();
3749 #ifdef HAVE_PCAP_REMOTE
3750 #define OPTSTRING_A "A:"
3751 #define OPTSTRING_r "r"
3752 #define OPTSTRING_u "u"
3754 #define OPTSTRING_A ""
3755 #define OPTSTRING_r ""
3756 #define OPTSTRING_u ""
3759 #ifdef HAVE_PCAP_SETSAMPLING
3760 #define OPTSTRING_m "m:"
3762 #define OPTSTRING_m ""
3765 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
3766 #define OPTSTRING_B "B:"
3768 #define OPTSTRING_B ""
3769 #endif /* _WIN32 or HAVE_PCAP_CREATE */
3771 #ifdef HAVE_PCAP_CREATE
3772 #define OPTSTRING_I "I"
3774 #define OPTSTRING_I ""
3777 #ifdef HAVE_BPF_IMAGE
3778 #define OPTSTRING_d "d"
3780 #define OPTSTRING_d ""
3783 #define OPTSTRING "a:" OPTSTRING_A "b:" OPTSTRING_B "c:" OPTSTRING_d "Df:ghi:" OPTSTRING_I "L" OPTSTRING_m "MnpPq" OPTSTRING_r "Ss:t" OPTSTRING_u "vw:y:Z:"
3785 #ifdef DEBUG_CHILD_DUMPCAP
3786 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
3787 fprintf (stderr, "Unable to open debug log file !\n");
3792 #if defined(__APPLE__) && defined(__LP64__)
3794 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
3795 * a bug workaround - timeouts less than 1 second don't work with libpcap
3796 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
3797 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
3798 * The problem is extremely unlikely to be reintroduced in a future
3801 if (uname(&osinfo) == 0) {
3803 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
3804 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
3805 * number of 10.0.0, not 10.1.0 - go figure).
3807 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
3808 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
3809 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
3810 need_timeout_workaround = TRUE;
3815 * Determine if dumpcap is being requested to run in a special
3816 * capture_child mode by going thru the command line args to see if
3817 * a -Z is present. (-Z is a hidden option).
3819 * The primary result of running in capture_child mode is that
3820 * all messages sent out on stderr are in a special type/len/string
3821 * format to allow message processing by type. These messages include
3822 * error messages if dumpcap fails to start the operation it was
3823 * requested to do, as well as various "status" messages which are sent
3824 * when an actual capture is in progress, and a "success" message sent
3825 * if dumpcap was requested to perform an operation other than a
3828 * Capture_child mode would normally be requested by a parent process
3829 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
3830 * to which dumpcap stderr has been redirected. It might also have
3831 * another pipe to obtain dumpcap stdout output; for operations other
3832 * than a capture, that information is formatted specially for easier
3833 * parsing by the parent process.
3835 * Capture_child mode needs to be determined immediately upon
3836 * startup so that any messages generated by dumpcap in this mode
3837 * (eg: during initialization) will be formatted properly.
3840 for (i=1; i<argc; i++) {
3841 if (strcmp("-Z", argv[i]) == 0) {
3842 capture_child = TRUE;
3843 machine_readable = TRUE; /* request machine-readable output */
3845 /* set output pipe to binary mode, to avoid ugly text conversions */
3846 _setmode(2, O_BINARY);
3851 /* The default_log_handler will use stdout, which makes trouble in */
3852 /* capture child mode, as it uses stdout for it's sync_pipe. */
3853 /* So: the filtering is done in the console_log_handler and not here.*/
3854 /* We set the log handlers right up front to make sure that any log */
3855 /* messages when running as child will be sent back to the parent */
3856 /* with the correct format. */
3860 G_LOG_LEVEL_CRITICAL|
3861 G_LOG_LEVEL_WARNING|
3862 G_LOG_LEVEL_MESSAGE|
3865 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
3867 g_log_set_handler(NULL,
3869 console_log_handler, NULL /* user_data */);
3870 g_log_set_handler(LOG_DOMAIN_MAIN,
3872 console_log_handler, NULL /* user_data */);
3873 g_log_set_handler(LOG_DOMAIN_CAPTURE,
3875 console_log_handler, NULL /* user_data */);
3876 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
3878 console_log_handler, NULL /* user_data */);
3880 /* Initialize the pcaps list */
3881 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
3883 #if !GLIB_CHECK_VERSION(2,31,0)
3884 /* Initialize the thread system */
3885 g_thread_init(NULL);
3889 /* Load wpcap if possible. Do this before collecting the run-time version information */
3892 /* ... and also load the packet.dll from wpcap */
3893 /* XXX - currently not required, may change later. */
3894 /*wpcap_packet_load();*/
3896 /* Start windows sockets */
3897 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
3899 /* Set handler for Ctrl+C key */
3900 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
3902 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
3904 action.sa_handler = capture_cleanup_handler;
3906 * Arrange that system calls not get restarted, because when
3907 * our signal handler returns we don't want to restart
3908 * a call that was waiting for packets to arrive.
3910 action.sa_flags = 0;
3911 sigemptyset(&action.sa_mask);
3912 sigaction(SIGTERM, &action, NULL);
3913 sigaction(SIGINT, &action, NULL);
3914 sigaction(SIGPIPE, &action, NULL);
3915 sigaction(SIGHUP, NULL, &oldaction);
3916 if (oldaction.sa_handler == SIG_DFL)
3917 sigaction(SIGHUP, &action, NULL);
3920 /* Catch SIGINFO and, if we get it and we're capturing in
3921 quiet mode, report the number of packets we've captured. */
3922 action.sa_handler = report_counts_siginfo;
3923 action.sa_flags = SA_RESTART;
3924 sigemptyset(&action.sa_mask);
3925 sigaction(SIGINFO, &action, NULL);
3926 #endif /* SIGINFO */
3929 /* ----------------------------------------------------------------- */
3930 /* Privilege and capability handling */
3932 /* 1. Running not as root or suid root; no special capabilities. */
3935 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
3938 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
3940 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
3941 /* capabilities; Drop all other capabilities; */
3942 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3943 /* else: after pcap_open_live() in capture_loop_open_input() */
3944 /* drop all capabilities (NET_RAW and NET_ADMIN); */
3945 /* (Note: this means that the process, although logged in */
3946 /* as root, does not have various permissions such as the */
3947 /* ability to bypass file access permissions). */
3948 /* XXX: Should we just leave capabilities alone in this case */
3949 /* so that user gets expected effect that root can do */
3952 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
3954 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3955 /* else: after pcap_open_live() in capture_loop_open_input() */
3956 /* drop suid root (set euid=ruid).(ie: keep suid until after */
3957 /* pcap_open_live). */
3959 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
3961 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
3962 /* capabilities; Drop all other capabilities; */
3963 /* Drop suid privileges (euid=ruid); */
3964 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3965 /* else: after pcap_open_live() in capture_loop_open_input() */
3966 /* drop all capabilities (NET_RAW and NET_ADMIN). */
3968 /* XXX: For some Linux versions/distros with capabilities */
3969 /* a 'normal' process with any capabilities cannot be */
3970 /* 'killed' (signaled) from another (same uid) non-privileged */
3972 /* For example: If (non-suid) Wireshark forks a */
3973 /* child suid dumpcap which acts as described here (case 5), */
3974 /* Wireshark will be unable to kill (signal) the child */
3975 /* dumpcap process until the capabilities have been dropped */
3976 /* (after pcap_open_live()). */
3977 /* This behaviour will apparently be changed in the kernel */
3978 /* to allow the kill (signal) in this case. */
3979 /* See the following for details: */
3980 /* http://www.mail-archive.com/ [wrapped] */
3981 /* linux-security-module@vger.kernel.org/msg02913.html */
3983 /* It is therefore conceivable that if dumpcap somehow hangs */
3984 /* in pcap_open_live or before that wireshark will not */
3985 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
3986 /* In this case, exiting wireshark will kill the child */
3987 /* dumpcap process. */
3989 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
3990 /* capabilities; Using libcap. Note: capset cmd (which see) */
3991 /* used to assign capabilities to file. */
3993 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3994 /* else: after pcap_open_live() in capture_loop_open_input() */
3995 /* drop all capabilities (NET_RAW and NET_ADMIN) */
3997 /* ToDo: -S (stats) should drop privileges/capabilities when no */
3998 /* longer required (similar to capture). */
4000 /* ----------------------------------------------------------------- */
4002 init_process_policies();
4005 /* If 'started with special privileges' (and using libcap) */
4006 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4007 /* Set euid/egid = ruid/rgid to remove suid privileges */
4008 relinquish_privs_except_capture();
4011 /* Set the initial values in the capture options. This might be overwritten
4012 by the command line parameters. */
4013 capture_opts_init(&global_capture_opts, NULL);
4015 /* We always save to a file - if no file was specified, we save to a
4017 global_capture_opts.saving_to_file = TRUE;
4018 global_capture_opts.has_ring_num_files = TRUE;
4020 /* Now get our args */
4021 while ((opt = getopt(argc, argv, OPTSTRING)) != -1) {
4023 case 'h': /* Print help and exit */
4027 case 'v': /* Show version and exit */
4029 GString *comp_info_str;
4030 GString *runtime_info_str;
4031 /* Assemble the compile-time version information string */
4032 comp_info_str = g_string_new("Compiled ");
4033 get_compiled_version_info(comp_info_str, NULL, NULL);
4035 /* Assemble the run-time version information string */
4036 runtime_info_str = g_string_new("Running ");
4037 get_runtime_version_info(runtime_info_str, NULL);
4038 show_version(comp_info_str, runtime_info_str);
4039 g_string_free(comp_info_str, TRUE);
4040 g_string_free(runtime_info_str, TRUE);
4044 /*** capture option specific ***/
4045 case 'a': /* autostop criteria */
4046 case 'b': /* Ringbuffer option */
4047 case 'c': /* Capture x packets */
4048 case 'f': /* capture filter */
4049 case 'i': /* Use interface x */
4050 case 'n': /* Use pcapng format */
4051 case 'p': /* Don't capture in promiscuous mode */
4052 case 'P': /* Use pcap format */
4053 case 's': /* Set the snapshot (capture) length */
4054 case 'w': /* Write to capture file x */
4055 case 'g': /* enable group read accesson file(s) */
4056 case 'y': /* Set the pcap data link type */
4057 #ifdef HAVE_PCAP_REMOTE
4058 case 'u': /* Use UDP for data transfer */
4059 case 'r': /* Capture own RPCAP traffic too */
4060 case 'A': /* Authentication */
4062 #ifdef HAVE_PCAP_SETSAMPLING
4063 case 'm': /* Sampling */
4065 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4066 case 'B': /* Buffer size */
4067 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4068 #ifdef HAVE_PCAP_CREATE
4069 case 'I': /* Monitor mode */
4071 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4076 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4078 capture_child = TRUE;
4080 /* set output pipe to binary mode, to avoid ugly text conversions */
4081 _setmode(2, O_BINARY);
4083 * optarg = the control ID, aka the PPID, currently used for the
4086 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4087 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4088 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4089 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4091 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4092 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4093 "Signal pipe: Unable to open %s. Dead parent?",
4101 case 'q': /* Quiet */
4107 /*** all non capture option specific ***/
4108 case 'D': /* Print a list of capture devices and exit */
4109 list_interfaces = TRUE;
4112 case 'L': /* Print list of link-layer types and exit */
4113 list_link_layer_types = TRUE;
4116 #ifdef HAVE_BPF_IMAGE
4117 case 'd': /* Print BPF code for capture filter and exit */
4118 print_bpf_code = TRUE;
4122 case 'S': /* Print interface statistics once a second */
4123 print_statistics = TRUE;
4126 case 'M': /* For -D, -L, and -S, print machine-readable output */
4127 machine_readable = TRUE;
4130 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4132 case '?': /* Bad flag - print usage message */
4141 /* user specified file name as regular command-line argument */
4142 /* XXX - use it as the capture file name (or something else)? */
4148 * Extra command line arguments were specified; complain.
4149 * XXX - interpret as capture filter, as tcpdump and tshark do?
4151 cmdarg_err("Invalid argument: %s", argv[0]);
4161 if (run_once_args > 1) {
4162 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
4164 } else if (run_once_args == 1) {
4165 /* We're supposed to print some information, rather than
4166 to capture traffic; did they specify a ring buffer option? */
4167 if (global_capture_opts.multi_files_on) {
4168 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4172 /* We're supposed to capture traffic; */
4173 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4174 if (global_capture_opts.ifaces->len > 1) {
4176 global_capture_opts.use_pcapng = TRUE;
4178 /* Was the ring buffer option specified and, if so, does it make sense? */
4179 if (global_capture_opts.multi_files_on) {
4180 /* Ring buffer works only under certain conditions:
4181 a) ring buffer does not work with temporary files;
4182 b) it makes no sense to enable the ring buffer if the maximum
4183 file size is set to "infinite". */
4184 if (global_capture_opts.save_file == NULL) {
4185 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4186 global_capture_opts.multi_files_on = FALSE;
4188 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4189 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4191 /* XXX - this must be redesigned as the conditions changed */
4192 global_capture_opts.multi_files_on = FALSE;
4199 * "-D" requires no interface to be selected; it's supposed to list
4202 if (list_interfaces) {
4203 /* Get the list of interfaces */
4208 if_list = capture_interface_list(&err, &err_str);
4209 if (if_list == NULL) {
4211 case CANT_GET_INTERFACE_LIST:
4212 case DONT_HAVE_PCAP:
4213 cmdarg_err("%s", err_str);
4218 case NO_INTERFACES_FOUND:
4220 * If we're being run by another program, just give them
4221 * an empty list of interfaces, don't report this as
4222 * an error; that lets them decide whether to report
4223 * this as an error or not.
4225 if (!machine_readable) {
4226 cmdarg_err("There are no interfaces on which a capture can be done");
4233 if (machine_readable) /* tab-separated values to stdout */
4234 print_machine_readable_interfaces(if_list);
4236 capture_opts_print_interfaces(if_list);
4237 free_interface_list(if_list);
4242 * "-S" requires no interface to be selected; it gives statistics
4243 * for all interfaces.
4245 if (print_statistics) {
4246 status = print_statistics_loop(machine_readable);
4251 * "-L", "-d", and capturing act on a particular interface, so we have to
4252 * have an interface; if none was specified, pick a default.
4254 if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
4255 /* cmdarg_err() already called .... */
4259 /* Let the user know what interfaces were chosen. */
4260 /* get_interface_descriptive_name() is not available! */
4261 if (capture_child) {
4262 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4263 interface_options interface_opts;
4265 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4266 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4267 interface_opts.name);
4270 str = g_string_new("");
4272 if (global_capture_opts.ifaces->len < 2) {
4274 if (global_capture_opts.ifaces->len < 4) {
4276 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4277 interface_options interface_opts;
4279 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4281 if (global_capture_opts.ifaces->len > 2) {
4282 g_string_append_printf(str, ",");
4284 g_string_append_printf(str, " ");
4285 if (j == global_capture_opts.ifaces->len - 1) {
4286 g_string_append_printf(str, "and ");
4289 g_string_append_printf(str, "%s", interface_opts.name);
4292 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4294 fprintf(stderr, "Capturing on %s\n", str->str);
4295 g_string_free(str, TRUE);
4298 if (list_link_layer_types) {
4299 /* Get the list of link-layer types for the capture device. */
4300 if_capabilities_t *caps;
4304 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
4305 interface_options interface_opts;
4307 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, i);
4308 caps = get_if_capabilities(interface_opts.name,
4309 interface_opts.monitor_mode, &err_str);
4311 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4312 "Please check to make sure you have sufficient permissions, and that\n"
4313 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4317 if (caps->data_link_types == NULL) {
4318 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4321 if (machine_readable) /* tab-separated values to stdout */
4322 /* XXX: We need to change the format and adopt consumers */
4323 print_machine_readable_if_capabilities(caps);
4325 /* XXX: We might want to print also the interface name */
4326 capture_opts_print_if_capabilities(caps, interface_opts.name,
4327 interface_opts.monitor_mode);
4328 free_if_capabilities(caps);
4333 /* We're supposed to do a capture, or print the BPF code for a filter.
4334 Process the snapshot length, as that affects the generated BPF code. */
4335 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4337 #ifdef HAVE_BPF_IMAGE
4338 if (print_bpf_code) {
4339 show_filter_code(&global_capture_opts);
4344 /* We're supposed to do a capture. Process the ring buffer arguments. */
4345 capture_opts_trim_ring_num_files(&global_capture_opts);
4347 /* Now start the capture. */
4349 if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4353 /* capture failed */
4356 return 0; /* never here, make compiler happy */
4361 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4362 const char *message, gpointer user_data _U_)
4369 /* ignore log message, if log_level isn't interesting */
4370 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4371 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4376 /* create a "timestamp" */
4378 today = localtime(&curr);
4380 switch(log_level & G_LOG_LEVEL_MASK) {
4381 case G_LOG_LEVEL_ERROR:
4384 case G_LOG_LEVEL_CRITICAL:
4387 case G_LOG_LEVEL_WARNING:
4390 case G_LOG_LEVEL_MESSAGE:
4393 case G_LOG_LEVEL_INFO:
4396 case G_LOG_LEVEL_DEBUG:
4400 fprintf(stderr, "unknown log_level %u\n", log_level);
4402 g_assert_not_reached();
4405 /* Generate the output message */
4406 if(log_level & G_LOG_LEVEL_MESSAGE) {
4407 /* normal user messages without additional infos */
4408 msg = g_strdup_printf("%s\n", message);
4410 /* info/debug messages with additional infos */
4411 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4412 today->tm_hour, today->tm_min, today->tm_sec,
4413 log_domain != NULL ? log_domain : "",
4417 /* DEBUG & INFO msgs (if we're debugging today) */
4418 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4419 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4420 #ifdef DEBUG_DUMPCAP
4421 fprintf(stderr, "%s", msg);
4424 #ifdef DEBUG_CHILD_DUMPCAP
4425 fprintf(debug_log, "%s", msg);
4433 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4434 /* to parent especially formatted if dumpcap running as child. */
4435 if (capture_child) {
4436 sync_pipe_errmsg_to_parent(2, msg, "");
4438 fprintf(stderr, "%s", msg);
4445 /****************************************************************************************************************/
4446 /* indication report routines */
4450 report_packet_count(int packet_count)
4452 char tmp[SP_DECISIZE+1+1];
4453 static int count = 0;
4456 g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
4457 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
4458 pipe_write_block(2, SP_PACKET_COUNT, tmp);
4460 count += packet_count;
4461 fprintf(stderr, "\rPackets: %u ", count);
4462 /* stderr could be line buffered */
4468 report_new_capture_file(const char *filename)
4471 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
4472 pipe_write_block(2, SP_FILE, filename);
4476 * Prevent a SIGINFO handler from writing to the standard error
4477 * while we're doing so; instead, have it just set a flag telling
4478 * us to print that information when we're done.
4481 #endif /* SIGINFO */
4482 fprintf(stderr, "File: %s\n", filename);
4483 /* stderr could be line buffered */
4488 * Allow SIGINFO handlers to write.
4493 * If a SIGINFO handler asked us to write out capture counts, do so.
4496 report_counts_for_siginfo();
4497 #endif /* SIGINFO */
4502 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
4504 interface_options interface_opts;
4505 char tmp[MSG_MAX_LENGTH+1+6];
4507 if (i < capture_opts->ifaces->len) {
4508 if (capture_child) {
4509 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
4510 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
4511 pipe_write_block(2, SP_BAD_FILTER, tmp);
4514 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
4515 * the error message below.
4517 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
4519 "Invalid capture filter: \"%s\" for interface %s!\n"
4521 "That string isn't a valid capture filter (%s).\n"
4522 "See the User's Guide for a description of the capture filter syntax.",
4523 interface_opts.cfilter, interface_opts.name, errmsg);
4529 report_capture_error(const char *error_msg, const char *secondary_error_msg)
4532 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4533 "Primary Error: %s", error_msg);
4534 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4535 "Secondary Error: %s", secondary_error_msg);
4536 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
4538 cmdarg_err("%s", error_msg);
4539 if (secondary_error_msg[0] != '\0')
4540 cmdarg_err_cont("%s", secondary_error_msg);
4545 report_packet_drops(guint32 received, guint32 drops, gchar *name)
4547 char tmp[SP_DECISIZE+1+1];
4549 g_snprintf(tmp, sizeof(tmp), "%u", drops);
4552 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4553 "Packets received/dropped on interface %s: %u/%u",
4554 name, received, drops);
4555 /* XXX: Need to provide interface id, changes to consumers required. */
4556 pipe_write_block(2, SP_DROPS, tmp);
4559 "Packets received/dropped on interface %s: %u/%u (%.1f%%)\n",
4560 name, received, drops,
4561 received ? 100.0 * received / (received + drops) : 0.0);
4562 /* stderr could be line buffered */
4568 /****************************************************************************************************************/
4569 /* signal_pipe handling */
4574 signal_pipe_check_running(void)
4576 /* any news from our parent? -> just stop the capture */
4580 /* if we are running standalone, no check required */
4581 if(!capture_child) {
4585 if(!sig_pipe_name || !sig_pipe_handle) {
4586 /* This shouldn't happen */
4587 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4588 "Signal pipe: No name or handle");
4593 * XXX - We should have the process ID of the parent (from the "-Z" flag)
4594 * at this point. Should we check to see if the parent is still alive,
4595 * e.g. by using OpenProcess?
4598 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
4600 if(!result || avail > 0) {
4601 /* peek failed or some bytes really available */
4602 /* (if not piping from stdin this would fail) */
4603 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4604 "Signal pipe: Stop capture: %s", sig_pipe_name);
4605 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4606 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
4607 sig_pipe_handle, result, avail);
4610 /* pipe ok and no bytes available */
4617 * Editor modelines - http://www.wireshark.org/tools/modelines.html
4622 * indent-tabs-mode: nil
4625 * vi: set shiftwidth=4 tabstop=8 expandtab:
4626 * :indentSize=4:tabSize=8:noTabs=true: