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) {
2562 GString *os_info_str;
2564 os_info_str = g_string_new("");
2565 get_os_version_info(os_info_str);
2567 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2568 successful = libpcap_write_session_header_block(ld->pdh,
2571 os_info_str->str, /* OS*/
2573 -1, /* section_length */
2577 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2578 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2579 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2580 if (pcap_opts->from_cap_pipe) {
2581 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2583 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2585 successful = libpcap_write_interface_description_block(global_ld.pdh,
2586 NULL, /* OPT_COMMENT 1 */
2587 interface_opts.name, /* IDB_NAME 2 */
2588 NULL, /* IDB_DESCRIPTION 3 */
2589 interface_opts.cfilter?interface_opts.cfilter:"", /* IDB_FILTER 11 */
2590 os_info_str->str, /* IDB_OS 12 */
2591 pcap_opts->linktype,
2593 &(global_ld.bytes_written),
2594 0, /* IDB_IF_SPEED 8 */
2595 0, /* IDB_TSRESOL 9 */
2599 g_string_free(os_info_str, TRUE);
2602 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
2603 if (pcap_opts->from_cap_pipe) {
2604 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2606 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2608 successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
2609 &ld->bytes_written, &err);
2617 if (ld->pdh == NULL) {
2618 /* We couldn't set up to write to the capture file. */
2619 /* XXX - use cf_open_error_message from tshark instead? */
2624 g_snprintf(errmsg, errmsg_len,
2625 "The file to which the capture would be"
2626 " saved (\"%s\") could not be opened: Error %d.",
2627 capture_opts->save_file, err);
2629 g_snprintf(errmsg, errmsg_len,
2630 "The file to which the capture would be"
2631 " saved (\"%s\") could not be opened: %s.",
2632 capture_opts->save_file, g_strerror(err));
2644 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2648 pcap_options *pcap_opts;
2650 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2652 if (capture_opts->multi_files_on) {
2653 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2655 if (capture_opts->use_pcapng) {
2656 for (i = 0; i < global_ld.pcaps->len; i++) {
2657 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2658 if (!pcap_opts->from_cap_pipe) {
2659 libpcap_write_interface_statistics_block(ld->pdh, i, pcap_opts->pcap_h, &ld->bytes_written, err_close);
2663 return libpcap_dump_close(ld->pdh, err_close);
2667 /* dispatch incoming packets (pcap or capture pipe)
2669 * Waits for incoming packets to be available, and calls pcap_dispatch()
2670 * to cause them to be processed.
2672 * Returns the number of packets which were processed.
2674 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2675 * packet-batching behaviour does not cause packets to get held back
2679 capture_loop_dispatch(loop_data *ld,
2680 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
2683 gint packet_count_before;
2684 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
2689 packet_count_before = ld->packet_count;
2690 if (pcap_opts->from_cap_pipe) {
2691 /* dispatch from capture pipe */
2692 #ifdef LOG_CAPTURE_VERBOSE
2693 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2696 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
2698 if (sel_ret < 0 && errno != EINTR) {
2699 g_snprintf(errmsg, errmsg_len,
2700 "Unexpected error from select: %s", g_strerror(errno));
2701 report_capture_error(errmsg, please_report);
2706 * "select()" says we can read from the pipe without blocking
2709 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
2719 /* dispatch from pcap */
2720 #ifdef MUST_DO_SELECT
2722 * If we have "pcap_get_selectable_fd()", we use it to get the
2723 * descriptor on which to select; if that's -1, it means there
2724 * is no descriptor on which you can do a "select()" (perhaps
2725 * because you're capturing on a special device, and that device's
2726 * driver unfortunately doesn't support "select()", in which case
2727 * we don't do the select - which means it might not be possible
2728 * to stop a capture until a packet arrives. If that's unacceptable,
2729 * plead with whoever supplies the software for that device to add
2730 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2731 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2732 * later, so it can use pcap_breakloop().
2734 #ifdef LOG_CAPTURE_VERBOSE
2735 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2737 if (pcap_opts->pcap_fd != -1) {
2738 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
2741 * "select()" says we can read from it without blocking; go for
2744 * We don't have pcap_breakloop(), so we only process one packet
2745 * per pcap_dispatch() call, to allow a signal to stop the
2746 * processing immediately, rather than processing all packets
2747 * in a batch before quitting.
2750 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2752 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2756 /* Error, rather than pcap_breakloop(). */
2757 pcap_opts->pcap_err = TRUE;
2759 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2762 if (sel_ret < 0 && errno != EINTR) {
2763 g_snprintf(errmsg, errmsg_len,
2764 "Unexpected error from select: %s", g_strerror(errno));
2765 report_capture_error(errmsg, please_report);
2771 #endif /* MUST_DO_SELECT */
2773 /* dispatch from pcap without select */
2775 #ifdef LOG_CAPTURE_VERBOSE
2776 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2780 * On Windows, we don't support asynchronously telling a process to
2781 * stop capturing; instead, we check for an indication on a pipe
2782 * after processing packets. We therefore process only one packet
2783 * at a time, so that we can check the pipe after every packet.
2786 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2788 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2792 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2794 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2799 /* Error, rather than pcap_breakloop(). */
2800 pcap_opts->pcap_err = TRUE;
2802 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2804 #else /* pcap_next_ex */
2805 #ifdef LOG_CAPTURE_VERBOSE
2806 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2808 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2811 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2812 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
2813 * This should be fixed in the WinPcap 4.0 alpha release.
2815 * For reference, an example remote interface:
2816 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2819 /* emulate dispatch from pcap */
2822 struct pcap_pkthdr *pkt_header;
2827 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
2829 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
2831 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
2836 pcap_opts->pcap_err = TRUE;
2840 #endif /* pcap_next_ex */
2844 #ifdef LOG_CAPTURE_VERBOSE
2845 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2848 return ld->packet_count - packet_count_before;
2852 /* Isolate the Universally Unique Identifier from the interface. Basically, we
2853 * want to grab only the characters between the '{' and '}' delimiters.
2855 * Returns a GString that must be freed with g_string_free(). */
2857 isolate_uuid(const char *iface)
2862 ptr = strchr(iface, '{');
2864 return g_string_new(iface);
2865 gstr = g_string_new(ptr + 1);
2867 ptr = strchr(gstr->str, '}');
2871 gstr = g_string_truncate(gstr, ptr - gstr->str);
2876 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2877 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2879 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2880 char *errmsg, int errmsg_len)
2883 gchar *capfile_name;
2885 gboolean is_tempfile;
2887 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2888 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
2890 if (capture_opts->save_file != NULL) {
2891 /* We return to the caller while the capture is in progress.
2892 * Therefore we need to take a copy of save_file in
2893 * case the caller destroys it after we return.
2895 capfile_name = g_strdup(capture_opts->save_file);
2897 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2898 if (capture_opts->multi_files_on) {
2899 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2900 g_snprintf(errmsg, errmsg_len,
2901 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2902 g_free(capfile_name);
2905 if (strcmp(capfile_name, "-") == 0) {
2906 /* write to stdout */
2909 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
2910 _setmode(1, O_BINARY);
2913 } /* if (...output_to_pipe ... */
2916 if (capture_opts->multi_files_on) {
2917 /* ringbuffer is enabled */
2918 *save_file_fd = ringbuf_init(capfile_name,
2919 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
2920 capture_opts->group_read_access);
2922 /* we need the ringbuf name */
2923 if(*save_file_fd != -1) {
2924 g_free(capfile_name);
2925 capfile_name = g_strdup(ringbuf_current_filename());
2928 /* Try to open/create the specified file for use as a capture buffer. */
2929 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
2930 (capture_opts->group_read_access) ? 0640 : 0600);
2933 is_tempfile = FALSE;
2935 /* Choose a random name for the temporary capture buffer */
2936 if (global_capture_opts.ifaces->len > 1) {
2937 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
2942 iface = isolate_uuid(g_array_index(global_capture_opts.ifaces, interface_options, 0).name);
2943 basename = g_path_get_basename(iface->str);
2944 g_string_free(iface, TRUE);
2946 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).name);
2948 prefix = g_strconcat("wireshark_", basename, NULL);
2951 *save_file_fd = create_tempfile(&tmpname, prefix);
2953 capfile_name = g_strdup(tmpname);
2957 /* did we fail to open the output file? */
2958 if (*save_file_fd == -1) {
2960 g_snprintf(errmsg, errmsg_len,
2961 "The temporary file to which the capture would be saved (\"%s\") "
2962 "could not be opened: %s.", capfile_name, g_strerror(errno));
2964 if (capture_opts->multi_files_on) {
2965 ringbuf_error_cleanup();
2968 g_snprintf(errmsg, errmsg_len,
2969 "The file to which the capture would be saved (\"%s\") "
2970 "could not be opened: %s.", capfile_name,
2973 g_free(capfile_name);
2977 if(capture_opts->save_file != NULL) {
2978 g_free(capture_opts->save_file);
2980 capture_opts->save_file = capfile_name;
2981 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2982 "g_free(capfile_name)". */
2988 /* Do the work of handling either the file size or file duration capture
2989 conditions being reached, and switching files or stopping. */
2991 do_file_switch_or_stop(capture_options *capture_opts,
2992 condition *cnd_autostop_files,
2993 condition *cnd_autostop_size,
2994 condition *cnd_file_duration)
2997 pcap_options *pcap_opts;
2998 interface_options interface_opts;
2999 gboolean successful;
3001 if (capture_opts->multi_files_on) {
3002 if (cnd_autostop_files != NULL &&
3003 cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
3004 /* no files left: stop here */
3005 global_ld.go = FALSE;
3009 /* Switch to the next ringbuffer file */
3010 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3011 &global_ld.save_file_fd, &global_ld.err)) {
3013 /* File switch succeeded: reset the conditions */
3014 global_ld.bytes_written = 0;
3015 if (capture_opts->use_pcapng) {
3017 GString *os_info_str;
3019 os_info_str = g_string_new("");
3020 get_os_version_info(os_info_str);
3022 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
3023 successful = libpcap_write_session_header_block(global_ld.pdh,
3026 os_info_str->str, /* OS */
3028 -1, /* section_length */
3029 &(global_ld.bytes_written),
3032 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3033 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3034 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3035 successful = libpcap_write_interface_description_block(global_ld.pdh,
3036 NULL, /* OPT_COMMENT 1 */
3037 interface_opts.name, /* IDB_NAME 2 */
3038 NULL, /* IDB_DESCRIPTION 3 */
3039 interface_opts.cfilter?interface_opts.cfilter:"", /* IDB_FILTER 11 */
3040 os_info_str->str, /* IDB_OS 12 */
3041 pcap_opts->linktype,
3043 &(global_ld.bytes_written),
3044 0, /* IDB_IF_SPEED 8 */
3045 0, /* IDB_TSRESOL 9 */
3049 g_string_free(os_info_str, TRUE);
3052 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3053 successful = libpcap_write_file_header(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
3054 &global_ld.bytes_written, &global_ld.err);
3057 fclose(global_ld.pdh);
3058 global_ld.pdh = NULL;
3059 global_ld.go = FALSE;
3062 if (cnd_autostop_size)
3063 cnd_reset(cnd_autostop_size);
3064 if (cnd_file_duration)
3065 cnd_reset(cnd_file_duration);
3066 libpcap_dump_flush(global_ld.pdh, NULL);
3068 report_packet_count(global_ld.inpkts_to_sync_pipe);
3069 global_ld.inpkts_to_sync_pipe = 0;
3070 report_new_capture_file(capture_opts->save_file);
3072 /* File switch failed: stop here */
3073 global_ld.go = FALSE;
3077 /* single file, stop now */
3078 global_ld.go = FALSE;
3085 pcap_read_handler(void* arg)
3087 pcap_options *pcap_opts;
3088 char errmsg[MSG_MAX_LENGTH+1];
3090 pcap_opts = (pcap_options *)arg;
3092 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3093 pcap_opts->interface_id);
3095 while (global_ld.go) {
3096 /* dispatch incoming packets */
3097 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3099 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3100 pcap_opts->interface_id);
3101 g_thread_exit(NULL);
3105 /* Do the low-level work of a capture.
3106 Returns TRUE if it succeeds, FALSE otherwise. */
3108 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3111 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3113 struct timeval upd_time, cur_time;
3117 condition *cnd_file_duration = NULL;
3118 condition *cnd_autostop_files = NULL;
3119 condition *cnd_autostop_size = NULL;
3120 condition *cnd_autostop_duration = NULL;
3123 gboolean cfilter_error = FALSE;
3124 char errmsg[MSG_MAX_LENGTH+1];
3125 char secondary_errmsg[MSG_MAX_LENGTH+1];
3126 pcap_options *pcap_opts;
3127 interface_options interface_opts;
3128 guint i, error_index = 0;
3131 *secondary_errmsg = '\0';
3133 /* init the loop data */
3134 global_ld.go = TRUE;
3135 global_ld.packet_count = 0;
3137 global_ld.report_packet_count = FALSE;
3139 if (capture_opts->has_autostop_packets)
3140 global_ld.packet_max = capture_opts->autostop_packets;
3142 global_ld.packet_max = 0; /* no limit */
3143 global_ld.inpkts_to_sync_pipe = 0;
3144 global_ld.err = 0; /* no error seen yet */
3145 global_ld.pdh = NULL;
3146 global_ld.autostop_files = 0;
3147 global_ld.save_file_fd = -1;
3149 /* We haven't yet gotten the capture statistics. */
3150 *stats_known = FALSE;
3152 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3153 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3155 /* open the "input file" from network interface or capture pipe */
3156 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3157 secondary_errmsg, sizeof(secondary_errmsg))) {
3160 for (i = 0; i < capture_opts->ifaces->len; i++) {
3161 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3162 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3163 /* init the input filter from the network interface (capture pipe will do nothing) */
3165 * When remote capturing WinPCap crashes when the capture filter
3166 * is NULL. This might be a bug in WPCap. Therefore we provide an emtpy
3169 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3170 interface_opts.name,
3171 interface_opts.cfilter?interface_opts.cfilter:"")) {
3173 case INITFILTER_NO_ERROR:
3176 case INITFILTER_BAD_FILTER:
3177 cfilter_error = TRUE;
3179 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3182 case INITFILTER_OTHER_ERROR:
3183 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3184 pcap_geterr(pcap_opts->pcap_h));
3185 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3190 /* If we're supposed to write to a capture file, open it for output
3191 (temporary/specified name/ringbuffer) */
3192 if (capture_opts->saving_to_file) {
3193 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3194 errmsg, sizeof(errmsg))) {
3198 /* set up to write to the already-opened capture output file/files */
3199 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3204 /* XXX - capture SIGTERM and close the capture, in case we're on a
3205 Linux 2.0[.x] system and you have to explicitly close the capture
3206 stream in order to turn promiscuous mode off? We need to do that
3207 in other places as well - and I don't think that works all the
3208 time in any case, due to libpcap bugs. */
3210 /* Well, we should be able to start capturing.
3212 Sync out the capture file, so the header makes it to the file system,
3213 and send a "capture started successfully and capture file created"
3214 message to our parent so that they'll open the capture file and
3215 update its windows to indicate that we have a live capture in
3217 libpcap_dump_flush(global_ld.pdh, NULL);
3218 report_new_capture_file(capture_opts->save_file);
3221 /* initialize capture stop (and alike) conditions */
3222 init_capture_stop_conditions();
3223 /* create stop conditions */
3224 if (capture_opts->has_autostop_filesize)
3226 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
3227 if (capture_opts->has_autostop_duration)
3228 cnd_autostop_duration =
3229 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3231 if (capture_opts->multi_files_on) {
3232 if (capture_opts->has_file_duration)
3234 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3236 if (capture_opts->has_autostop_files)
3237 cnd_autostop_files =
3238 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
3241 /* init the time values */
3243 upd_time = GetTickCount();
3245 gettimeofday(&upd_time, NULL);
3248 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
3250 /* WOW, everything is prepared! */
3251 /* please fasten your seat belts, we will enter now the actual capture loop */
3253 pcap_queue = g_async_queue_new();
3254 pcap_queue_bytes = 0;
3255 pcap_queue_packets = 0;
3256 for (i = 0; i < global_ld.pcaps->len; i++) {
3257 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3258 #if GLIB_CHECK_VERSION(2,31,0)
3259 /* XXX - Add an interface name here? */
3260 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3262 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3266 while (global_ld.go) {
3267 /* dispatch incoming packets */
3269 GTimeVal write_thread_time;
3270 pcap_queue_element *queue_element;
3272 g_get_current_time(&write_thread_time);
3273 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3274 g_async_queue_lock(pcap_queue);
3275 queue_element = g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3276 if (queue_element) {
3277 pcap_queue_bytes -= queue_element->phdr.caplen;
3278 pcap_queue_packets -= 1;
3280 g_async_queue_unlock(pcap_queue);
3281 if (queue_element) {
3282 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3283 "Dequeued a packet of length %d captured on interface %d.",
3284 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3286 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3287 &queue_element->phdr,
3289 g_free(queue_element->pd);
3290 g_free(queue_element);
3296 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3297 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3298 sizeof(errmsg), pcap_opts);
3301 /* Were we asked to print packet counts by the SIGINFO handler? */
3302 if (global_ld.report_packet_count) {
3303 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3304 plurality(global_ld.packet_count, "", "s"));
3305 global_ld.report_packet_count = FALSE;
3310 /* any news from our parent (signal pipe)? -> just stop the capture */
3311 if (!signal_pipe_check_running()) {
3312 global_ld.go = FALSE;
3317 global_ld.inpkts_to_sync_pipe += inpkts;
3319 /* check capture size condition */
3320 if (cnd_autostop_size != NULL &&
3321 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)) {
3322 /* Capture size limit reached, do we have another file? */
3323 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3324 cnd_autostop_size, cnd_file_duration))
3326 } /* cnd_autostop_size */
3327 if (capture_opts->output_to_pipe) {
3328 libpcap_dump_flush(global_ld.pdh, NULL);
3332 /* Only update once every 500ms so as not to overload slow displays.
3333 * This also prevents too much context-switching between the dumpcap
3334 * and wireshark processes.
3336 #define DUMPCAP_UPD_TIME 500
3339 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3340 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3342 gettimeofday(&cur_time, NULL);
3343 if ((cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3344 (upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3347 upd_time = cur_time;
3350 if (pcap_stats(pch, stats) >= 0) {
3351 *stats_known = TRUE;
3354 /* Let the parent process know. */
3355 if (global_ld.inpkts_to_sync_pipe) {
3357 libpcap_dump_flush(global_ld.pdh, NULL);
3359 /* Send our parent a message saying we've written out
3360 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3362 report_packet_count(global_ld.inpkts_to_sync_pipe);
3364 global_ld.inpkts_to_sync_pipe = 0;
3367 /* check capture duration condition */
3368 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3369 /* The maximum capture time has elapsed; stop the capture. */
3370 global_ld.go = FALSE;
3374 /* check capture file duration condition */
3375 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3376 /* duration limit reached, do we have another file? */
3377 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3378 cnd_autostop_size, cnd_file_duration))
3380 } /* cnd_file_duration */
3384 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3386 pcap_queue_element *queue_element;
3388 for (i = 0; i < global_ld.pcaps->len; i++) {
3389 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3390 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3391 pcap_opts->interface_id);
3392 g_thread_join(pcap_opts->tid);
3393 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3394 pcap_opts->interface_id);
3397 g_async_queue_lock(pcap_queue);
3398 queue_element = g_async_queue_try_pop_unlocked(pcap_queue);
3399 if (queue_element) {
3400 pcap_queue_bytes -= queue_element->phdr.caplen;
3401 pcap_queue_packets -= 1;
3403 g_async_queue_unlock(pcap_queue);
3404 if (queue_element == NULL) {
3407 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3408 "Dequeued a packet of length %d captured on interface %d.",
3409 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3410 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3411 &queue_element->phdr,
3413 g_free(queue_element->pd);
3414 g_free(queue_element);
3415 global_ld.inpkts_to_sync_pipe += 1;
3416 if (capture_opts->output_to_pipe) {
3417 libpcap_dump_flush(global_ld.pdh, NULL);
3423 /* delete stop conditions */
3424 if (cnd_file_duration != NULL)
3425 cnd_delete(cnd_file_duration);
3426 if (cnd_autostop_files != NULL)
3427 cnd_delete(cnd_autostop_files);
3428 if (cnd_autostop_size != NULL)
3429 cnd_delete(cnd_autostop_size);
3430 if (cnd_autostop_duration != NULL)
3431 cnd_delete(cnd_autostop_duration);
3433 /* did we have a pcap (input) error? */
3434 for (i = 0; i < capture_opts->ifaces->len; i++) {
3435 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3436 if (pcap_opts->pcap_err) {
3437 /* On Linux, if an interface goes down while you're capturing on it,
3438 you'll get a "recvfrom: Network is down" or
3439 "The interface went down" error (ENETDOWN).
3440 (At least you will if g_strerror() doesn't show a local translation
3443 On FreeBSD and OS X, if a network adapter disappears while
3444 you're capturing on it, you'll get a "read: Device not configured"
3445 error (ENXIO). (See previous parenthetical note.)
3447 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3449 These should *not* be reported to the Wireshark developers. */
3452 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3453 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3454 strcmp(cap_err_str, "The interface went down") == 0 ||
3455 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3456 strcmp(cap_err_str, "read: I/O error") == 0 ||
3457 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3458 report_capture_error("The network adapter on which the capture was being done "
3459 "is no longer running; the capture has stopped.",
3462 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3464 report_capture_error(errmsg, please_report);
3467 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3468 report_capture_error(errmsg, "");
3472 /* did we have an output error while capturing? */
3473 if (global_ld.err == 0) {
3476 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3477 global_ld.err, FALSE);
3478 report_capture_error(errmsg, please_report);
3482 if (capture_opts->saving_to_file) {
3483 /* close the output file */
3484 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3488 /* there might be packets not yet notified to the parent */
3489 /* (do this after closing the file, so all packets are already flushed) */
3490 if(global_ld.inpkts_to_sync_pipe) {
3492 report_packet_count(global_ld.inpkts_to_sync_pipe);
3493 global_ld.inpkts_to_sync_pipe = 0;
3496 /* If we've displayed a message about a write error, there's no point
3497 in displaying another message about an error on close. */
3498 if (!close_ok && write_ok) {
3499 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3501 report_capture_error(errmsg, "");
3505 * XXX We exhibit different behaviour between normal mode and sync mode
3506 * when the pipe is stdin and not already at EOF. If we're a child, the
3507 * parent's stdin isn't closed, so if the user starts another capture,
3508 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3509 * will say "Unrecognized libpcap format". On the other hand, in normal
3510 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3513 report_capture_count(TRUE);
3515 /* get packet drop statistics from pcap */
3516 for (i = 0; i < capture_opts->ifaces->len; i++) {
3520 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3521 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3522 received = pcap_opts->received;
3523 dropped = pcap_opts->dropped;
3524 if (pcap_opts->pcap_h != NULL) {
3525 g_assert(!pcap_opts->from_cap_pipe);
3526 /* Get the capture statistics, so we know how many packets were dropped. */
3527 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3528 *stats_known = TRUE;
3529 /* Let the parent process know. */
3530 dropped += stats->ps_drop;
3532 g_snprintf(errmsg, sizeof(errmsg),
3533 "Can't get packet-drop statistics: %s",
3534 pcap_geterr(pcap_opts->pcap_h));
3535 report_capture_error(errmsg, please_report);
3538 report_packet_drops(received, dropped, interface_opts.name);
3541 /* close the input file (pcap or capture pipe) */
3542 capture_loop_close_input(&global_ld);
3544 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
3546 /* ok, if the write and the close were successful. */
3547 return write_ok && close_ok;
3550 if (capture_opts->multi_files_on) {
3551 /* cleanup ringbuffer */
3552 ringbuf_error_cleanup();
3554 /* We can't use the save file, and we have no FILE * for the stream
3555 to close in order to close it, so close the FD directly. */
3556 if (global_ld.save_file_fd != -1) {
3557 ws_close(global_ld.save_file_fd);
3560 /* We couldn't even start the capture, so get rid of the capture
3562 if (capture_opts->save_file != NULL) {
3563 ws_unlink(capture_opts->save_file);
3564 g_free(capture_opts->save_file);
3567 capture_opts->save_file = NULL;
3569 report_cfilter_error(capture_opts, error_index, errmsg);
3571 report_capture_error(errmsg, secondary_errmsg);
3573 /* close the input file (pcap or cap_pipe) */
3574 capture_loop_close_input(&global_ld);
3576 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3582 static void capture_loop_stop(void)
3584 #ifdef HAVE_PCAP_BREAKLOOP
3586 pcap_options *pcap_opts;
3588 for (i = 0; i < global_ld.pcaps->len; i++) {
3589 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3590 if (pcap_opts->pcap_h != NULL)
3591 pcap_breakloop(pcap_opts->pcap_h);
3594 global_ld.go = FALSE;
3599 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3600 int err, gboolean is_close)
3605 g_snprintf(errmsg, errmsglen,
3606 "Not all the packets could be written to the file"
3607 " to which the capture was being saved\n"
3608 "(\"%s\") because there is no space left on the file system\n"
3609 "on which that file resides.",
3615 g_snprintf(errmsg, errmsglen,
3616 "Not all the packets could be written to the file"
3617 " to which the capture was being saved\n"
3618 "(\"%s\") because you are too close to, or over,"
3619 " your disk quota\n"
3620 "on the file system on which that file resides.",
3627 g_snprintf(errmsg, errmsglen,
3628 "The file to which the capture was being saved\n"
3629 "(\"%s\") could not be closed: %s.",
3630 fname, g_strerror(err));
3632 g_snprintf(errmsg, errmsglen,
3633 "An error occurred while writing to the file"
3634 " to which the capture was being saved\n"
3636 fname, g_strerror(err));
3643 /* one packet was captured, process it */
3645 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3648 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3651 /* We may be called multiple times from pcap_dispatch(); if we've set
3652 the "stop capturing" flag, ignore this packet, as we're not
3653 supposed to be saving any more packets. */
3657 if (global_ld.pdh) {
3658 gboolean successful;
3660 /* We're supposed to write the packet to a file; do so.
3661 If this fails, set "ld->go" to FALSE, to stop the capture, and set
3662 "ld->err" to the error. */
3663 if (global_capture_opts.use_pcapng) {
3664 successful = libpcap_write_enhanced_packet_block(global_ld.pdh, phdr, pcap_opts->interface_id, pd, &global_ld.bytes_written, &err);
3666 successful = libpcap_write_packet(global_ld.pdh, phdr, pd, &global_ld.bytes_written, &err);
3669 global_ld.go = FALSE;
3670 global_ld.err = err;
3672 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3673 "Wrote a packet of length %d captured on interface %u.",
3674 phdr->caplen, pcap_opts->interface_id);
3675 global_ld.packet_count++;
3676 pcap_opts->received++;
3677 /* if the user told us to stop after x packets, do we already have enough? */
3678 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
3679 global_ld.go = FALSE;
3685 /* one packet was captured, queue it */
3687 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3690 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3691 pcap_queue_element *queue_element;
3692 gboolean limit_reached;
3694 /* We may be called multiple times from pcap_dispatch(); if we've set
3695 the "stop capturing" flag, ignore this packet, as we're not
3696 supposed to be saving any more packets. */
3700 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
3701 if (queue_element == NULL) {
3702 pcap_opts->dropped++;
3705 queue_element->pcap_opts = pcap_opts;
3706 queue_element->phdr = *phdr;
3707 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
3708 if (queue_element->pd == NULL) {
3709 pcap_opts->dropped++;
3710 g_free(queue_element);
3713 memcpy(queue_element->pd, pd, phdr->caplen);
3714 g_async_queue_lock(pcap_queue);
3715 if (((pcap_queue_byte_limit > 0) && (pcap_queue_bytes < pcap_queue_byte_limit)) &&
3716 ((pcap_queue_packet_limit > 0) && (pcap_queue_packets < pcap_queue_packet_limit))) {
3717 limit_reached = FALSE;
3718 g_async_queue_push_unlocked(pcap_queue, queue_element);
3719 pcap_queue_bytes += phdr->caplen;
3720 pcap_queue_packets += 1;
3722 limit_reached = TRUE;
3724 g_async_queue_unlock(pcap_queue);
3725 if (limit_reached) {
3726 pcap_opts->dropped++;
3727 g_free(queue_element->pd);
3728 g_free(queue_element);
3729 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3730 "Dropped a packet of length %d captured on interface %u.",
3731 phdr->caplen, pcap_opts->interface_id);
3733 pcap_opts->received++;
3734 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3735 "Queued a packet of length %d captured on interface %u.",
3736 phdr->caplen, pcap_opts->interface_id);
3738 /* I don't want to hold the mutex over the debug output. So the
3739 output may be wrong */
3740 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3741 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
3742 pcap_queue_bytes, pcap_queue_packets);
3745 /* And now our feature presentation... [ fade to music ] */
3747 main(int argc, char *argv[])
3750 gboolean arg_error = FALSE;
3755 struct sigaction action, oldaction;
3758 gboolean start_capture = TRUE;
3759 gboolean stats_known;
3760 struct pcap_stat stats;
3761 GLogLevelFlags log_flags;
3762 gboolean list_interfaces = FALSE;
3763 gboolean list_link_layer_types = FALSE;
3764 #ifdef HAVE_BPF_IMAGE
3765 gboolean print_bpf_code = FALSE;
3767 gboolean machine_readable = FALSE;
3768 gboolean print_statistics = FALSE;
3769 int status, run_once_args = 0;
3772 #if defined(__APPLE__) && defined(__LP64__)
3773 struct utsname osinfo;
3778 arg_list_utf_16to8(argc, argv);
3783 * Initialize our DLL search path. MUST be called before LoadLibrary
3786 ws_init_dll_search_path();
3789 #ifdef HAVE_PCAP_REMOTE
3790 #define OPTSTRING_A "A:"
3791 #define OPTSTRING_r "r"
3792 #define OPTSTRING_u "u"
3794 #define OPTSTRING_A ""
3795 #define OPTSTRING_r ""
3796 #define OPTSTRING_u ""
3799 #ifdef HAVE_PCAP_SETSAMPLING
3800 #define OPTSTRING_m "m:"
3802 #define OPTSTRING_m ""
3805 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
3806 #define OPTSTRING_B "B:"
3808 #define OPTSTRING_B ""
3809 #endif /* _WIN32 or HAVE_PCAP_CREATE */
3811 #ifdef HAVE_PCAP_CREATE
3812 #define OPTSTRING_I "I"
3814 #define OPTSTRING_I ""
3817 #ifdef HAVE_BPF_IMAGE
3818 #define OPTSTRING_d "d"
3820 #define OPTSTRING_d ""
3823 #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:"
3825 #ifdef DEBUG_CHILD_DUMPCAP
3826 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
3827 fprintf (stderr, "Unable to open debug log file !\n");
3832 #if defined(__APPLE__) && defined(__LP64__)
3834 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
3835 * a bug workaround - timeouts less than 1 second don't work with libpcap
3836 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
3837 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
3838 * The problem is extremely unlikely to be reintroduced in a future
3841 if (uname(&osinfo) == 0) {
3843 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
3844 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
3845 * number of 10.0.0, not 10.1.0 - go figure).
3847 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
3848 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
3849 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
3850 need_timeout_workaround = TRUE;
3855 * Determine if dumpcap is being requested to run in a special
3856 * capture_child mode by going thru the command line args to see if
3857 * a -Z is present. (-Z is a hidden option).
3859 * The primary result of running in capture_child mode is that
3860 * all messages sent out on stderr are in a special type/len/string
3861 * format to allow message processing by type. These messages include
3862 * error messages if dumpcap fails to start the operation it was
3863 * requested to do, as well as various "status" messages which are sent
3864 * when an actual capture is in progress, and a "success" message sent
3865 * if dumpcap was requested to perform an operation other than a
3868 * Capture_child mode would normally be requested by a parent process
3869 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
3870 * to which dumpcap stderr has been redirected. It might also have
3871 * another pipe to obtain dumpcap stdout output; for operations other
3872 * than a capture, that information is formatted specially for easier
3873 * parsing by the parent process.
3875 * Capture_child mode needs to be determined immediately upon
3876 * startup so that any messages generated by dumpcap in this mode
3877 * (eg: during initialization) will be formatted properly.
3880 for (i=1; i<argc; i++) {
3881 if (strcmp("-Z", argv[i]) == 0) {
3882 capture_child = TRUE;
3883 machine_readable = TRUE; /* request machine-readable output */
3885 /* set output pipe to binary mode, to avoid ugly text conversions */
3886 _setmode(2, O_BINARY);
3891 /* The default_log_handler will use stdout, which makes trouble in */
3892 /* capture child mode, as it uses stdout for it's sync_pipe. */
3893 /* So: the filtering is done in the console_log_handler and not here.*/
3894 /* We set the log handlers right up front to make sure that any log */
3895 /* messages when running as child will be sent back to the parent */
3896 /* with the correct format. */
3900 G_LOG_LEVEL_CRITICAL|
3901 G_LOG_LEVEL_WARNING|
3902 G_LOG_LEVEL_MESSAGE|
3905 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
3907 g_log_set_handler(NULL,
3909 console_log_handler, NULL /* user_data */);
3910 g_log_set_handler(LOG_DOMAIN_MAIN,
3912 console_log_handler, NULL /* user_data */);
3913 g_log_set_handler(LOG_DOMAIN_CAPTURE,
3915 console_log_handler, NULL /* user_data */);
3916 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
3918 console_log_handler, NULL /* user_data */);
3920 /* Initialize the pcaps list */
3921 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
3923 #if !GLIB_CHECK_VERSION(2,31,0)
3924 /* Initialize the thread system */
3925 g_thread_init(NULL);
3929 /* Load wpcap if possible. Do this before collecting the run-time version information */
3932 /* ... and also load the packet.dll from wpcap */
3933 /* XXX - currently not required, may change later. */
3934 /*wpcap_packet_load();*/
3936 /* Start windows sockets */
3937 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
3939 /* Set handler for Ctrl+C key */
3940 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
3942 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
3944 action.sa_handler = capture_cleanup_handler;
3946 * Arrange that system calls not get restarted, because when
3947 * our signal handler returns we don't want to restart
3948 * a call that was waiting for packets to arrive.
3950 action.sa_flags = 0;
3951 sigemptyset(&action.sa_mask);
3952 sigaction(SIGTERM, &action, NULL);
3953 sigaction(SIGINT, &action, NULL);
3954 sigaction(SIGPIPE, &action, NULL);
3955 sigaction(SIGHUP, NULL, &oldaction);
3956 if (oldaction.sa_handler == SIG_DFL)
3957 sigaction(SIGHUP, &action, NULL);
3960 /* Catch SIGINFO and, if we get it and we're capturing in
3961 quiet mode, report the number of packets we've captured. */
3962 action.sa_handler = report_counts_siginfo;
3963 action.sa_flags = SA_RESTART;
3964 sigemptyset(&action.sa_mask);
3965 sigaction(SIGINFO, &action, NULL);
3966 #endif /* SIGINFO */
3969 /* ----------------------------------------------------------------- */
3970 /* Privilege and capability handling */
3972 /* 1. Running not as root or suid root; no special capabilities. */
3975 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
3978 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
3980 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
3981 /* capabilities; Drop all other capabilities; */
3982 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3983 /* else: after pcap_open_live() in capture_loop_open_input() */
3984 /* drop all capabilities (NET_RAW and NET_ADMIN); */
3985 /* (Note: this means that the process, although logged in */
3986 /* as root, does not have various permissions such as the */
3987 /* ability to bypass file access permissions). */
3988 /* XXX: Should we just leave capabilities alone in this case */
3989 /* so that user gets expected effect that root can do */
3992 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
3994 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3995 /* else: after pcap_open_live() in capture_loop_open_input() */
3996 /* drop suid root (set euid=ruid).(ie: keep suid until after */
3997 /* pcap_open_live). */
3999 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
4001 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
4002 /* capabilities; Drop all other capabilities; */
4003 /* Drop suid privileges (euid=ruid); */
4004 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4005 /* else: after pcap_open_live() in capture_loop_open_input() */
4006 /* drop all capabilities (NET_RAW and NET_ADMIN). */
4008 /* XXX: For some Linux versions/distros with capabilities */
4009 /* a 'normal' process with any capabilities cannot be */
4010 /* 'killed' (signaled) from another (same uid) non-privileged */
4012 /* For example: If (non-suid) Wireshark forks a */
4013 /* child suid dumpcap which acts as described here (case 5), */
4014 /* Wireshark will be unable to kill (signal) the child */
4015 /* dumpcap process until the capabilities have been dropped */
4016 /* (after pcap_open_live()). */
4017 /* This behaviour will apparently be changed in the kernel */
4018 /* to allow the kill (signal) in this case. */
4019 /* See the following for details: */
4020 /* http://www.mail-archive.com/ [wrapped] */
4021 /* linux-security-module@vger.kernel.org/msg02913.html */
4023 /* It is therefore conceivable that if dumpcap somehow hangs */
4024 /* in pcap_open_live or before that wireshark will not */
4025 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4026 /* In this case, exiting wireshark will kill the child */
4027 /* dumpcap process. */
4029 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4030 /* capabilities; Using libcap. Note: capset cmd (which see) */
4031 /* used to assign capabilities to file. */
4033 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4034 /* else: after pcap_open_live() in capture_loop_open_input() */
4035 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4037 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4038 /* longer required (similar to capture). */
4040 /* ----------------------------------------------------------------- */
4042 init_process_policies();
4045 /* If 'started with special privileges' (and using libcap) */
4046 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4047 /* Set euid/egid = ruid/rgid to remove suid privileges */
4048 relinquish_privs_except_capture();
4051 /* Set the initial values in the capture options. This might be overwritten
4052 by the command line parameters. */
4053 capture_opts_init(&global_capture_opts, NULL);
4055 /* We always save to a file - if no file was specified, we save to a
4057 global_capture_opts.saving_to_file = TRUE;
4058 global_capture_opts.has_ring_num_files = TRUE;
4060 /* Now get our args */
4061 while ((opt = getopt(argc, argv, OPTSTRING)) != -1) {
4063 case 'h': /* Print help and exit */
4067 case 'v': /* Show version and exit */
4069 GString *comp_info_str;
4070 GString *runtime_info_str;
4071 /* Assemble the compile-time version information string */
4072 comp_info_str = g_string_new("Compiled ");
4073 get_compiled_version_info(comp_info_str, NULL, NULL);
4075 /* Assemble the run-time version information string */
4076 runtime_info_str = g_string_new("Running ");
4077 get_runtime_version_info(runtime_info_str, NULL);
4078 show_version(comp_info_str, runtime_info_str);
4079 g_string_free(comp_info_str, TRUE);
4080 g_string_free(runtime_info_str, TRUE);
4084 /*** capture option specific ***/
4085 case 'a': /* autostop criteria */
4086 case 'b': /* Ringbuffer option */
4087 case 'c': /* Capture x packets */
4088 case 'f': /* capture filter */
4089 case 'i': /* Use interface x */
4090 case 'n': /* Use pcapng format */
4091 case 'p': /* Don't capture in promiscuous mode */
4092 case 'P': /* Use pcap format */
4093 case 's': /* Set the snapshot (capture) length */
4094 case 'w': /* Write to capture file x */
4095 case 'g': /* enable group read accesson file(s) */
4096 case 'y': /* Set the pcap data link type */
4097 #ifdef HAVE_PCAP_REMOTE
4098 case 'u': /* Use UDP for data transfer */
4099 case 'r': /* Capture own RPCAP traffic too */
4100 case 'A': /* Authentication */
4102 #ifdef HAVE_PCAP_SETSAMPLING
4103 case 'm': /* Sampling */
4105 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4106 case 'B': /* Buffer size */
4107 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4108 #ifdef HAVE_PCAP_CREATE
4109 case 'I': /* Monitor mode */
4111 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4116 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4118 capture_child = TRUE;
4120 /* set output pipe to binary mode, to avoid ugly text conversions */
4121 _setmode(2, O_BINARY);
4123 * optarg = the control ID, aka the PPID, currently used for the
4126 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4127 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4128 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4129 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4131 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4132 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4133 "Signal pipe: Unable to open %s. Dead parent?",
4141 case 'q': /* Quiet */
4147 /*** all non capture option specific ***/
4148 case 'D': /* Print a list of capture devices and exit */
4149 list_interfaces = TRUE;
4152 case 'L': /* Print list of link-layer types and exit */
4153 list_link_layer_types = TRUE;
4156 #ifdef HAVE_BPF_IMAGE
4157 case 'd': /* Print BPF code for capture filter and exit */
4158 print_bpf_code = TRUE;
4162 case 'S': /* Print interface statistics once a second */
4163 print_statistics = TRUE;
4166 case 'M': /* For -D, -L, and -S, print machine-readable output */
4167 machine_readable = TRUE;
4170 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4172 case '?': /* Bad flag - print usage message */
4181 /* user specified file name as regular command-line argument */
4182 /* XXX - use it as the capture file name (or something else)? */
4188 * Extra command line arguments were specified; complain.
4189 * XXX - interpret as capture filter, as tcpdump and tshark do?
4191 cmdarg_err("Invalid argument: %s", argv[0]);
4201 if (run_once_args > 1) {
4202 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
4204 } else if (run_once_args == 1) {
4205 /* We're supposed to print some information, rather than
4206 to capture traffic; did they specify a ring buffer option? */
4207 if (global_capture_opts.multi_files_on) {
4208 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4212 /* We're supposed to capture traffic; */
4213 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4214 if (global_capture_opts.ifaces->len > 1) {
4216 global_capture_opts.use_pcapng = TRUE;
4218 /* Was the ring buffer option specified and, if so, does it make sense? */
4219 if (global_capture_opts.multi_files_on) {
4220 /* Ring buffer works only under certain conditions:
4221 a) ring buffer does not work with temporary files;
4222 b) it makes no sense to enable the ring buffer if the maximum
4223 file size is set to "infinite". */
4224 if (global_capture_opts.save_file == NULL) {
4225 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4226 global_capture_opts.multi_files_on = FALSE;
4228 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4229 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4231 /* XXX - this must be redesigned as the conditions changed */
4232 global_capture_opts.multi_files_on = FALSE;
4239 * "-D" requires no interface to be selected; it's supposed to list
4242 if (list_interfaces) {
4243 /* Get the list of interfaces */
4248 if_list = capture_interface_list(&err, &err_str);
4249 if (if_list == NULL) {
4251 case CANT_GET_INTERFACE_LIST:
4252 case DONT_HAVE_PCAP:
4253 cmdarg_err("%s", err_str);
4258 case NO_INTERFACES_FOUND:
4260 * If we're being run by another program, just give them
4261 * an empty list of interfaces, don't report this as
4262 * an error; that lets them decide whether to report
4263 * this as an error or not.
4265 if (!machine_readable) {
4266 cmdarg_err("There are no interfaces on which a capture can be done");
4273 if (machine_readable) /* tab-separated values to stdout */
4274 print_machine_readable_interfaces(if_list);
4276 capture_opts_print_interfaces(if_list);
4277 free_interface_list(if_list);
4282 * "-S" requires no interface to be selected; it gives statistics
4283 * for all interfaces.
4285 if (print_statistics) {
4286 status = print_statistics_loop(machine_readable);
4291 * "-L", "-d", and capturing act on a particular interface, so we have to
4292 * have an interface; if none was specified, pick a default.
4294 if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
4295 /* cmdarg_err() already called .... */
4299 /* Let the user know what interfaces were chosen. */
4300 /* get_interface_descriptive_name() is not available! */
4301 if (capture_child) {
4302 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4303 interface_options interface_opts;
4305 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4306 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4307 interface_opts.name);
4310 str = g_string_new("");
4312 if (global_capture_opts.ifaces->len < 2) {
4314 if (global_capture_opts.ifaces->len < 4) {
4316 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4317 interface_options interface_opts;
4319 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4321 if (global_capture_opts.ifaces->len > 2) {
4322 g_string_append_printf(str, ",");
4324 g_string_append_printf(str, " ");
4325 if (j == global_capture_opts.ifaces->len - 1) {
4326 g_string_append_printf(str, "and ");
4329 g_string_append_printf(str, "%s", interface_opts.name);
4332 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4334 fprintf(stderr, "Capturing on %s\n", str->str);
4335 g_string_free(str, TRUE);
4338 if (list_link_layer_types) {
4339 /* Get the list of link-layer types for the capture device. */
4340 if_capabilities_t *caps;
4344 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
4345 interface_options interface_opts;
4347 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, i);
4348 caps = get_if_capabilities(interface_opts.name,
4349 interface_opts.monitor_mode, &err_str);
4351 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4352 "Please check to make sure you have sufficient permissions, and that\n"
4353 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4357 if (caps->data_link_types == NULL) {
4358 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4361 if (machine_readable) /* tab-separated values to stdout */
4362 /* XXX: We need to change the format and adopt consumers */
4363 print_machine_readable_if_capabilities(caps);
4365 /* XXX: We might want to print also the interface name */
4366 capture_opts_print_if_capabilities(caps, interface_opts.name,
4367 interface_opts.monitor_mode);
4368 free_if_capabilities(caps);
4373 /* We're supposed to do a capture, or print the BPF code for a filter.
4374 Process the snapshot length, as that affects the generated BPF code. */
4375 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4377 #ifdef HAVE_BPF_IMAGE
4378 if (print_bpf_code) {
4379 show_filter_code(&global_capture_opts);
4384 /* We're supposed to do a capture. Process the ring buffer arguments. */
4385 capture_opts_trim_ring_num_files(&global_capture_opts);
4387 /* Now start the capture. */
4389 if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4393 /* capture failed */
4396 return 0; /* never here, make compiler happy */
4401 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4402 const char *message, gpointer user_data _U_)
4409 /* ignore log message, if log_level isn't interesting */
4410 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4411 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4416 /* create a "timestamp" */
4418 today = localtime(&curr);
4420 switch(log_level & G_LOG_LEVEL_MASK) {
4421 case G_LOG_LEVEL_ERROR:
4424 case G_LOG_LEVEL_CRITICAL:
4427 case G_LOG_LEVEL_WARNING:
4430 case G_LOG_LEVEL_MESSAGE:
4433 case G_LOG_LEVEL_INFO:
4436 case G_LOG_LEVEL_DEBUG:
4440 fprintf(stderr, "unknown log_level %u\n", log_level);
4442 g_assert_not_reached();
4445 /* Generate the output message */
4446 if(log_level & G_LOG_LEVEL_MESSAGE) {
4447 /* normal user messages without additional infos */
4448 msg = g_strdup_printf("%s\n", message);
4450 /* info/debug messages with additional infos */
4451 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4452 today->tm_hour, today->tm_min, today->tm_sec,
4453 log_domain != NULL ? log_domain : "",
4457 /* DEBUG & INFO msgs (if we're debugging today) */
4458 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4459 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4460 #ifdef DEBUG_DUMPCAP
4461 fprintf(stderr, "%s", msg);
4464 #ifdef DEBUG_CHILD_DUMPCAP
4465 fprintf(debug_log, "%s", msg);
4473 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4474 /* to parent especially formatted if dumpcap running as child. */
4475 if (capture_child) {
4476 sync_pipe_errmsg_to_parent(2, msg, "");
4478 fprintf(stderr, "%s", msg);
4485 /****************************************************************************************************************/
4486 /* indication report routines */
4490 report_packet_count(int packet_count)
4492 char tmp[SP_DECISIZE+1+1];
4493 static int count = 0;
4496 g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
4497 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
4498 pipe_write_block(2, SP_PACKET_COUNT, tmp);
4500 count += packet_count;
4501 fprintf(stderr, "\rPackets: %u ", count);
4502 /* stderr could be line buffered */
4508 report_new_capture_file(const char *filename)
4511 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
4512 pipe_write_block(2, SP_FILE, filename);
4516 * Prevent a SIGINFO handler from writing to the standard error
4517 * while we're doing so; instead, have it just set a flag telling
4518 * us to print that information when we're done.
4521 #endif /* SIGINFO */
4522 fprintf(stderr, "File: %s\n", filename);
4523 /* stderr could be line buffered */
4528 * Allow SIGINFO handlers to write.
4533 * If a SIGINFO handler asked us to write out capture counts, do so.
4536 report_counts_for_siginfo();
4537 #endif /* SIGINFO */
4542 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
4544 interface_options interface_opts;
4545 char tmp[MSG_MAX_LENGTH+1+6];
4547 if (i < capture_opts->ifaces->len) {
4548 if (capture_child) {
4549 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
4550 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
4551 pipe_write_block(2, SP_BAD_FILTER, tmp);
4554 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
4555 * the error message below.
4557 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
4559 "Invalid capture filter: \"%s\" for interface %s!\n"
4561 "That string isn't a valid capture filter (%s).\n"
4562 "See the User's Guide for a description of the capture filter syntax.",
4563 interface_opts.cfilter, interface_opts.name, errmsg);
4569 report_capture_error(const char *error_msg, const char *secondary_error_msg)
4572 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4573 "Primary Error: %s", error_msg);
4574 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4575 "Secondary Error: %s", secondary_error_msg);
4576 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
4578 cmdarg_err("%s", error_msg);
4579 if (secondary_error_msg[0] != '\0')
4580 cmdarg_err_cont("%s", secondary_error_msg);
4585 report_packet_drops(guint32 received, guint32 drops, gchar *name)
4587 char tmp[SP_DECISIZE+1+1];
4589 g_snprintf(tmp, sizeof(tmp), "%u", drops);
4592 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4593 "Packets received/dropped on interface %s: %u/%u",
4594 name, received, drops);
4595 /* XXX: Need to provide interface id, changes to consumers required. */
4596 pipe_write_block(2, SP_DROPS, tmp);
4599 "Packets received/dropped on interface %s: %u/%u (%.1f%%)\n",
4600 name, received, drops,
4601 received ? 100.0 * received / (received + drops) : 0.0);
4602 /* stderr could be line buffered */
4608 /****************************************************************************************************************/
4609 /* signal_pipe handling */
4614 signal_pipe_check_running(void)
4616 /* any news from our parent? -> just stop the capture */
4620 /* if we are running standalone, no check required */
4621 if(!capture_child) {
4625 if(!sig_pipe_name || !sig_pipe_handle) {
4626 /* This shouldn't happen */
4627 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4628 "Signal pipe: No name or handle");
4633 * XXX - We should have the process ID of the parent (from the "-Z" flag)
4634 * at this point. Should we check to see if the parent is still alive,
4635 * e.g. by using OpenProcess?
4638 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
4640 if(!result || avail > 0) {
4641 /* peek failed or some bytes really available */
4642 /* (if not piping from stdin this would fail) */
4643 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4644 "Signal pipe: Stop capture: %s", sig_pipe_name);
4645 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4646 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
4647 sig_pipe_handle, result, avail);
4650 /* pipe ok and no bytes available */
4657 * Editor modelines - http://www.wireshark.org/tools/modelines.html
4662 * indent-tabs-mode: nil
4665 * vi: set shiftwidth=4 tabstop=8 expandtab:
4666 * :indentSize=4:tabSize=8:noTabs=true: