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 g_string_free(os_info_str, TRUE);
2579 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2580 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2581 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2582 if (pcap_opts->from_cap_pipe) {
2583 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2585 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2587 successful = libpcap_write_interface_description_block(ld->pdh,
2588 interface_opts.name,
2589 interface_opts.cfilter?interface_opts.cfilter:"",
2590 pcap_opts->linktype,
2596 pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
2597 if (pcap_opts->from_cap_pipe) {
2598 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2600 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2602 successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
2603 &ld->bytes_written, &err);
2611 if (ld->pdh == NULL) {
2612 /* We couldn't set up to write to the capture file. */
2613 /* XXX - use cf_open_error_message from tshark instead? */
2618 g_snprintf(errmsg, errmsg_len,
2619 "The file to which the capture would be"
2620 " saved (\"%s\") could not be opened: Error %d.",
2621 capture_opts->save_file, err);
2623 g_snprintf(errmsg, errmsg_len,
2624 "The file to which the capture would be"
2625 " saved (\"%s\") could not be opened: %s.",
2626 capture_opts->save_file, g_strerror(err));
2638 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2642 pcap_options *pcap_opts;
2644 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2646 if (capture_opts->multi_files_on) {
2647 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2649 if (capture_opts->use_pcapng) {
2650 for (i = 0; i < global_ld.pcaps->len; i++) {
2651 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2652 if (!pcap_opts->from_cap_pipe) {
2653 libpcap_write_interface_statistics_block(ld->pdh, i, pcap_opts->pcap_h, &ld->bytes_written, err_close);
2657 return libpcap_dump_close(ld->pdh, err_close);
2661 /* dispatch incoming packets (pcap or capture pipe)
2663 * Waits for incoming packets to be available, and calls pcap_dispatch()
2664 * to cause them to be processed.
2666 * Returns the number of packets which were processed.
2668 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2669 * packet-batching behaviour does not cause packets to get held back
2673 capture_loop_dispatch(loop_data *ld,
2674 char *errmsg, int errmsg_len, pcap_options *pcap_opts)
2677 gint packet_count_before;
2678 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
2683 packet_count_before = ld->packet_count;
2684 if (pcap_opts->from_cap_pipe) {
2685 /* dispatch from capture pipe */
2686 #ifdef LOG_CAPTURE_VERBOSE
2687 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2690 sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
2692 if (sel_ret < 0 && errno != EINTR) {
2693 g_snprintf(errmsg, errmsg_len,
2694 "Unexpected error from select: %s", g_strerror(errno));
2695 report_capture_error(errmsg, please_report);
2700 * "select()" says we can read from the pipe without blocking
2703 inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
2713 /* dispatch from pcap */
2714 #ifdef MUST_DO_SELECT
2716 * If we have "pcap_get_selectable_fd()", we use it to get the
2717 * descriptor on which to select; if that's -1, it means there
2718 * is no descriptor on which you can do a "select()" (perhaps
2719 * because you're capturing on a special device, and that device's
2720 * driver unfortunately doesn't support "select()", in which case
2721 * we don't do the select - which means it might not be possible
2722 * to stop a capture until a packet arrives. If that's unacceptable,
2723 * plead with whoever supplies the software for that device to add
2724 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2725 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2726 * later, so it can use pcap_breakloop().
2728 #ifdef LOG_CAPTURE_VERBOSE
2729 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2731 if (pcap_opts->pcap_fd != -1) {
2732 sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
2735 * "select()" says we can read from it without blocking; go for
2738 * We don't have pcap_breakloop(), so we only process one packet
2739 * per pcap_dispatch() call, to allow a signal to stop the
2740 * processing immediately, rather than processing all packets
2741 * in a batch before quitting.
2744 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2746 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2750 /* Error, rather than pcap_breakloop(). */
2751 pcap_opts->pcap_err = TRUE;
2753 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2756 if (sel_ret < 0 && errno != EINTR) {
2757 g_snprintf(errmsg, errmsg_len,
2758 "Unexpected error from select: %s", g_strerror(errno));
2759 report_capture_error(errmsg, please_report);
2765 #endif /* MUST_DO_SELECT */
2767 /* dispatch from pcap without select */
2769 #ifdef LOG_CAPTURE_VERBOSE
2770 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2774 * On Windows, we don't support asynchronously telling a process to
2775 * stop capturing; instead, we check for an indication on a pipe
2776 * after processing packets. We therefore process only one packet
2777 * at a time, so that we can check the pipe after every packet.
2780 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2782 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
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);
2793 /* Error, rather than pcap_breakloop(). */
2794 pcap_opts->pcap_err = TRUE;
2796 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2798 #else /* pcap_next_ex */
2799 #ifdef LOG_CAPTURE_VERBOSE
2800 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2802 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2805 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2806 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
2807 * This should be fixed in the WinPcap 4.0 alpha release.
2809 * For reference, an example remote interface:
2810 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2813 /* emulate dispatch from pcap */
2816 struct pcap_pkthdr *pkt_header;
2821 (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
2823 capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
2825 capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
2830 pcap_opts->pcap_err = TRUE;
2834 #endif /* pcap_next_ex */
2838 #ifdef LOG_CAPTURE_VERBOSE
2839 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2842 return ld->packet_count - packet_count_before;
2846 /* Isolate the Universally Unique Identifier from the interface. Basically, we
2847 * want to grab only the characters between the '{' and '}' delimiters.
2849 * Returns a GString that must be freed with g_string_free(). */
2851 isolate_uuid(const char *iface)
2856 ptr = strchr(iface, '{');
2858 return g_string_new(iface);
2859 gstr = g_string_new(ptr + 1);
2861 ptr = strchr(gstr->str, '}');
2865 gstr = g_string_truncate(gstr, ptr - gstr->str);
2870 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2871 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2873 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2874 char *errmsg, int errmsg_len)
2877 gchar *capfile_name;
2879 gboolean is_tempfile;
2881 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2882 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
2884 if (capture_opts->save_file != NULL) {
2885 /* We return to the caller while the capture is in progress.
2886 * Therefore we need to take a copy of save_file in
2887 * case the caller destroys it after we return.
2889 capfile_name = g_strdup(capture_opts->save_file);
2891 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2892 if (capture_opts->multi_files_on) {
2893 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2894 g_snprintf(errmsg, errmsg_len,
2895 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2896 g_free(capfile_name);
2899 if (strcmp(capfile_name, "-") == 0) {
2900 /* write to stdout */
2903 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
2904 _setmode(1, O_BINARY);
2907 } /* if (...output_to_pipe ... */
2910 if (capture_opts->multi_files_on) {
2911 /* ringbuffer is enabled */
2912 *save_file_fd = ringbuf_init(capfile_name,
2913 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
2914 capture_opts->group_read_access);
2916 /* we need the ringbuf name */
2917 if(*save_file_fd != -1) {
2918 g_free(capfile_name);
2919 capfile_name = g_strdup(ringbuf_current_filename());
2922 /* Try to open/create the specified file for use as a capture buffer. */
2923 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
2924 (capture_opts->group_read_access) ? 0640 : 0600);
2927 is_tempfile = FALSE;
2929 /* Choose a random name for the temporary capture buffer */
2930 if (global_capture_opts.ifaces->len > 1) {
2931 prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
2936 iface = isolate_uuid(g_array_index(global_capture_opts.ifaces, interface_options, 0).name);
2937 basename = g_path_get_basename(iface->str);
2938 g_string_free(iface, TRUE);
2940 basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).name);
2942 prefix = g_strconcat("wireshark_", basename, NULL);
2945 *save_file_fd = create_tempfile(&tmpname, prefix);
2947 capfile_name = g_strdup(tmpname);
2951 /* did we fail to open the output file? */
2952 if (*save_file_fd == -1) {
2954 g_snprintf(errmsg, errmsg_len,
2955 "The temporary file to which the capture would be saved (\"%s\") "
2956 "could not be opened: %s.", capfile_name, g_strerror(errno));
2958 if (capture_opts->multi_files_on) {
2959 ringbuf_error_cleanup();
2962 g_snprintf(errmsg, errmsg_len,
2963 "The file to which the capture would be saved (\"%s\") "
2964 "could not be opened: %s.", capfile_name,
2967 g_free(capfile_name);
2971 if(capture_opts->save_file != NULL) {
2972 g_free(capture_opts->save_file);
2974 capture_opts->save_file = capfile_name;
2975 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2976 "g_free(capfile_name)". */
2982 /* Do the work of handling either the file size or file duration capture
2983 conditions being reached, and switching files or stopping. */
2985 do_file_switch_or_stop(capture_options *capture_opts,
2986 condition *cnd_autostop_files,
2987 condition *cnd_autostop_size,
2988 condition *cnd_file_duration)
2991 pcap_options *pcap_opts;
2992 interface_options interface_opts;
2993 gboolean successful;
2995 if (capture_opts->multi_files_on) {
2996 if (cnd_autostop_files != NULL &&
2997 cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
2998 /* no files left: stop here */
2999 global_ld.go = FALSE;
3003 /* Switch to the next ringbuffer file */
3004 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3005 &global_ld.save_file_fd, &global_ld.err)) {
3007 /* File switch succeeded: reset the conditions */
3008 global_ld.bytes_written = 0;
3009 if (capture_opts->use_pcapng) {
3011 GString *os_info_str;
3013 os_info_str = g_string_new("");
3014 get_os_version_info(os_info_str);
3016 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
3017 successful = libpcap_write_session_header_block(global_ld.pdh,
3020 os_info_str->str, /* OS */
3022 -1, /* section_length */
3023 &(global_ld.bytes_written),
3026 g_string_free(os_info_str, TRUE);
3028 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3029 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3030 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3031 successful = libpcap_write_interface_description_block(global_ld.pdh,
3032 interface_opts.name,
3033 interface_opts.cfilter?interface_opts.cfilter:"",
3034 pcap_opts->linktype,
3036 &(global_ld.bytes_written),
3040 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3041 successful = libpcap_write_file_header(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
3042 &global_ld.bytes_written, &global_ld.err);
3045 fclose(global_ld.pdh);
3046 global_ld.pdh = NULL;
3047 global_ld.go = FALSE;
3050 if (cnd_autostop_size)
3051 cnd_reset(cnd_autostop_size);
3052 if (cnd_file_duration)
3053 cnd_reset(cnd_file_duration);
3054 libpcap_dump_flush(global_ld.pdh, NULL);
3056 report_packet_count(global_ld.inpkts_to_sync_pipe);
3057 global_ld.inpkts_to_sync_pipe = 0;
3058 report_new_capture_file(capture_opts->save_file);
3060 /* File switch failed: stop here */
3061 global_ld.go = FALSE;
3065 /* single file, stop now */
3066 global_ld.go = FALSE;
3073 pcap_read_handler(void* arg)
3075 pcap_options *pcap_opts;
3076 char errmsg[MSG_MAX_LENGTH+1];
3078 pcap_opts = (pcap_options *)arg;
3080 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3081 pcap_opts->interface_id);
3083 while (global_ld.go) {
3084 /* dispatch incoming packets */
3085 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3087 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3088 pcap_opts->interface_id);
3089 g_thread_exit(NULL);
3093 /* Do the low-level work of a capture.
3094 Returns TRUE if it succeeds, FALSE otherwise. */
3096 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3099 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3101 struct timeval upd_time, cur_time;
3105 condition *cnd_file_duration = NULL;
3106 condition *cnd_autostop_files = NULL;
3107 condition *cnd_autostop_size = NULL;
3108 condition *cnd_autostop_duration = NULL;
3111 gboolean cfilter_error = FALSE;
3112 char errmsg[MSG_MAX_LENGTH+1];
3113 char secondary_errmsg[MSG_MAX_LENGTH+1];
3114 pcap_options *pcap_opts;
3115 interface_options interface_opts;
3116 guint i, error_index = 0;
3119 *secondary_errmsg = '\0';
3121 /* init the loop data */
3122 global_ld.go = TRUE;
3123 global_ld.packet_count = 0;
3125 global_ld.report_packet_count = FALSE;
3127 if (capture_opts->has_autostop_packets)
3128 global_ld.packet_max = capture_opts->autostop_packets;
3130 global_ld.packet_max = 0; /* no limit */
3131 global_ld.inpkts_to_sync_pipe = 0;
3132 global_ld.err = 0; /* no error seen yet */
3133 global_ld.pdh = NULL;
3134 global_ld.autostop_files = 0;
3135 global_ld.save_file_fd = -1;
3137 /* We haven't yet gotten the capture statistics. */
3138 *stats_known = FALSE;
3140 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3141 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3143 /* open the "input file" from network interface or capture pipe */
3144 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3145 secondary_errmsg, sizeof(secondary_errmsg))) {
3148 for (i = 0; i < capture_opts->ifaces->len; i++) {
3149 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3150 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3151 /* init the input filter from the network interface (capture pipe will do nothing) */
3153 * When remote capturing WinPCap crashes when the capture filter
3154 * is NULL. This might be a bug in WPCap. Therefore we provide an emtpy
3157 switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3158 interface_opts.name,
3159 interface_opts.cfilter?interface_opts.cfilter:"")) {
3161 case INITFILTER_NO_ERROR:
3164 case INITFILTER_BAD_FILTER:
3165 cfilter_error = TRUE;
3167 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3170 case INITFILTER_OTHER_ERROR:
3171 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3172 pcap_geterr(pcap_opts->pcap_h));
3173 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3178 /* If we're supposed to write to a capture file, open it for output
3179 (temporary/specified name/ringbuffer) */
3180 if (capture_opts->saving_to_file) {
3181 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3182 errmsg, sizeof(errmsg))) {
3186 /* set up to write to the already-opened capture output file/files */
3187 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3192 /* XXX - capture SIGTERM and close the capture, in case we're on a
3193 Linux 2.0[.x] system and you have to explicitly close the capture
3194 stream in order to turn promiscuous mode off? We need to do that
3195 in other places as well - and I don't think that works all the
3196 time in any case, due to libpcap bugs. */
3198 /* Well, we should be able to start capturing.
3200 Sync out the capture file, so the header makes it to the file system,
3201 and send a "capture started successfully and capture file created"
3202 message to our parent so that they'll open the capture file and
3203 update its windows to indicate that we have a live capture in
3205 libpcap_dump_flush(global_ld.pdh, NULL);
3206 report_new_capture_file(capture_opts->save_file);
3209 /* initialize capture stop (and alike) conditions */
3210 init_capture_stop_conditions();
3211 /* create stop conditions */
3212 if (capture_opts->has_autostop_filesize)
3214 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
3215 if (capture_opts->has_autostop_duration)
3216 cnd_autostop_duration =
3217 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3219 if (capture_opts->multi_files_on) {
3220 if (capture_opts->has_file_duration)
3222 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3224 if (capture_opts->has_autostop_files)
3225 cnd_autostop_files =
3226 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
3229 /* init the time values */
3231 upd_time = GetTickCount();
3233 gettimeofday(&upd_time, NULL);
3236 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
3238 /* WOW, everything is prepared! */
3239 /* please fasten your seat belts, we will enter now the actual capture loop */
3241 pcap_queue = g_async_queue_new();
3242 pcap_queue_bytes = 0;
3243 pcap_queue_packets = 0;
3244 for (i = 0; i < global_ld.pcaps->len; i++) {
3245 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3246 #if GLIB_CHECK_VERSION(2,31,0)
3247 /* XXX - Add an interface name here? */
3248 pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3250 pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3254 while (global_ld.go) {
3255 /* dispatch incoming packets */
3257 GTimeVal write_thread_time;
3258 pcap_queue_element *queue_element;
3260 g_get_current_time(&write_thread_time);
3261 g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3262 g_async_queue_lock(pcap_queue);
3263 queue_element = g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3264 if (queue_element) {
3265 pcap_queue_bytes -= queue_element->phdr.caplen;
3266 pcap_queue_packets -= 1;
3268 g_async_queue_unlock(pcap_queue);
3269 if (queue_element) {
3270 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3271 "Dequeued a packet of length %d captured on interface %d.",
3272 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3274 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3275 &queue_element->phdr,
3277 g_free(queue_element->pd);
3278 g_free(queue_element);
3284 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3285 inpkts = capture_loop_dispatch(&global_ld, errmsg,
3286 sizeof(errmsg), pcap_opts);
3289 /* Were we asked to print packet counts by the SIGINFO handler? */
3290 if (global_ld.report_packet_count) {
3291 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3292 plurality(global_ld.packet_count, "", "s"));
3293 global_ld.report_packet_count = FALSE;
3298 /* any news from our parent (signal pipe)? -> just stop the capture */
3299 if (!signal_pipe_check_running()) {
3300 global_ld.go = FALSE;
3305 global_ld.inpkts_to_sync_pipe += inpkts;
3307 /* check capture size condition */
3308 if (cnd_autostop_size != NULL &&
3309 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)) {
3310 /* Capture size limit reached, do we have another file? */
3311 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3312 cnd_autostop_size, cnd_file_duration))
3314 } /* cnd_autostop_size */
3315 if (capture_opts->output_to_pipe) {
3316 libpcap_dump_flush(global_ld.pdh, NULL);
3320 /* Only update once every 500ms so as not to overload slow displays.
3321 * This also prevents too much context-switching between the dumpcap
3322 * and wireshark processes.
3324 #define DUMPCAP_UPD_TIME 500
3327 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
3328 if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3330 gettimeofday(&cur_time, NULL);
3331 if ((cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3332 (upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3335 upd_time = cur_time;
3338 if (pcap_stats(pch, stats) >= 0) {
3339 *stats_known = TRUE;
3342 /* Let the parent process know. */
3343 if (global_ld.inpkts_to_sync_pipe) {
3345 libpcap_dump_flush(global_ld.pdh, NULL);
3347 /* Send our parent a message saying we've written out
3348 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3350 report_packet_count(global_ld.inpkts_to_sync_pipe);
3352 global_ld.inpkts_to_sync_pipe = 0;
3355 /* check capture duration condition */
3356 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3357 /* The maximum capture time has elapsed; stop the capture. */
3358 global_ld.go = FALSE;
3362 /* check capture file duration condition */
3363 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3364 /* duration limit reached, do we have another file? */
3365 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3366 cnd_autostop_size, cnd_file_duration))
3368 } /* cnd_file_duration */
3372 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3374 pcap_queue_element *queue_element;
3376 for (i = 0; i < global_ld.pcaps->len; i++) {
3377 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3378 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3379 pcap_opts->interface_id);
3380 g_thread_join(pcap_opts->tid);
3381 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3382 pcap_opts->interface_id);
3385 g_async_queue_lock(pcap_queue);
3386 queue_element = g_async_queue_try_pop_unlocked(pcap_queue);
3387 if (queue_element) {
3388 pcap_queue_bytes -= queue_element->phdr.caplen;
3389 pcap_queue_packets -= 1;
3391 g_async_queue_unlock(pcap_queue);
3392 if (queue_element == NULL) {
3395 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3396 "Dequeued a packet of length %d captured on interface %d.",
3397 queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3398 capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3399 &queue_element->phdr,
3401 g_free(queue_element->pd);
3402 g_free(queue_element);
3403 global_ld.inpkts_to_sync_pipe += 1;
3404 if (capture_opts->output_to_pipe) {
3405 libpcap_dump_flush(global_ld.pdh, NULL);
3411 /* delete stop conditions */
3412 if (cnd_file_duration != NULL)
3413 cnd_delete(cnd_file_duration);
3414 if (cnd_autostop_files != NULL)
3415 cnd_delete(cnd_autostop_files);
3416 if (cnd_autostop_size != NULL)
3417 cnd_delete(cnd_autostop_size);
3418 if (cnd_autostop_duration != NULL)
3419 cnd_delete(cnd_autostop_duration);
3421 /* did we have a pcap (input) error? */
3422 for (i = 0; i < capture_opts->ifaces->len; i++) {
3423 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3424 if (pcap_opts->pcap_err) {
3425 /* On Linux, if an interface goes down while you're capturing on it,
3426 you'll get a "recvfrom: Network is down" or
3427 "The interface went down" error (ENETDOWN).
3428 (At least you will if g_strerror() doesn't show a local translation
3431 On FreeBSD and OS X, if a network adapter disappears while
3432 you're capturing on it, you'll get a "read: Device not configured"
3433 error (ENXIO). (See previous parenthetical note.)
3435 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3437 These should *not* be reported to the Wireshark developers. */
3440 cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3441 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3442 strcmp(cap_err_str, "The interface went down") == 0 ||
3443 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3444 strcmp(cap_err_str, "read: I/O error") == 0 ||
3445 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3446 report_capture_error("The network adapter on which the capture was being done "
3447 "is no longer running; the capture has stopped.",
3450 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3452 report_capture_error(errmsg, please_report);
3455 } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3456 report_capture_error(errmsg, "");
3460 /* did we have an output error while capturing? */
3461 if (global_ld.err == 0) {
3464 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3465 global_ld.err, FALSE);
3466 report_capture_error(errmsg, please_report);
3470 if (capture_opts->saving_to_file) {
3471 /* close the output file */
3472 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3476 /* there might be packets not yet notified to the parent */
3477 /* (do this after closing the file, so all packets are already flushed) */
3478 if(global_ld.inpkts_to_sync_pipe) {
3480 report_packet_count(global_ld.inpkts_to_sync_pipe);
3481 global_ld.inpkts_to_sync_pipe = 0;
3484 /* If we've displayed a message about a write error, there's no point
3485 in displaying another message about an error on close. */
3486 if (!close_ok && write_ok) {
3487 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3489 report_capture_error(errmsg, "");
3493 * XXX We exhibit different behaviour between normal mode and sync mode
3494 * when the pipe is stdin and not already at EOF. If we're a child, the
3495 * parent's stdin isn't closed, so if the user starts another capture,
3496 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3497 * will say "Unrecognized libpcap format". On the other hand, in normal
3498 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3501 report_capture_count(TRUE);
3503 /* get packet drop statistics from pcap */
3504 for (i = 0; i < capture_opts->ifaces->len; i++) {
3508 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3509 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3510 received = pcap_opts->received;
3511 dropped = pcap_opts->dropped;
3512 if (pcap_opts->pcap_h != NULL) {
3513 g_assert(!pcap_opts->from_cap_pipe);
3514 /* Get the capture statistics, so we know how many packets were dropped. */
3515 if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3516 *stats_known = TRUE;
3517 /* Let the parent process know. */
3518 dropped += stats->ps_drop;
3520 g_snprintf(errmsg, sizeof(errmsg),
3521 "Can't get packet-drop statistics: %s",
3522 pcap_geterr(pcap_opts->pcap_h));
3523 report_capture_error(errmsg, please_report);
3526 report_packet_drops(received, dropped, interface_opts.name);
3529 /* close the input file (pcap or capture pipe) */
3530 capture_loop_close_input(&global_ld);
3532 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
3534 /* ok, if the write and the close were successful. */
3535 return write_ok && close_ok;
3538 if (capture_opts->multi_files_on) {
3539 /* cleanup ringbuffer */
3540 ringbuf_error_cleanup();
3542 /* We can't use the save file, and we have no FILE * for the stream
3543 to close in order to close it, so close the FD directly. */
3544 if (global_ld.save_file_fd != -1) {
3545 ws_close(global_ld.save_file_fd);
3548 /* We couldn't even start the capture, so get rid of the capture
3550 if (capture_opts->save_file != NULL) {
3551 ws_unlink(capture_opts->save_file);
3552 g_free(capture_opts->save_file);
3555 capture_opts->save_file = NULL;
3557 report_cfilter_error(capture_opts, error_index, errmsg);
3559 report_capture_error(errmsg, secondary_errmsg);
3561 /* close the input file (pcap or cap_pipe) */
3562 capture_loop_close_input(&global_ld);
3564 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3570 static void capture_loop_stop(void)
3572 #ifdef HAVE_PCAP_BREAKLOOP
3574 pcap_options *pcap_opts;
3576 for (i = 0; i < global_ld.pcaps->len; i++) {
3577 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3578 if (pcap_opts->pcap_h != NULL)
3579 pcap_breakloop(pcap_opts->pcap_h);
3582 global_ld.go = FALSE;
3587 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3588 int err, gboolean is_close)
3593 g_snprintf(errmsg, errmsglen,
3594 "Not all the packets could be written to the file"
3595 " to which the capture was being saved\n"
3596 "(\"%s\") because there is no space left on the file system\n"
3597 "on which that file resides.",
3603 g_snprintf(errmsg, errmsglen,
3604 "Not all the packets could be written to the file"
3605 " to which the capture was being saved\n"
3606 "(\"%s\") because you are too close to, or over,"
3607 " your disk quota\n"
3608 "on the file system on which that file resides.",
3615 g_snprintf(errmsg, errmsglen,
3616 "The file to which the capture was being saved\n"
3617 "(\"%s\") could not be closed: %s.",
3618 fname, g_strerror(err));
3620 g_snprintf(errmsg, errmsglen,
3621 "An error occurred while writing to the file"
3622 " to which the capture was being saved\n"
3624 fname, g_strerror(err));
3631 /* one packet was captured, process it */
3633 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3636 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3639 /* We may be called multiple times from pcap_dispatch(); if we've set
3640 the "stop capturing" flag, ignore this packet, as we're not
3641 supposed to be saving any more packets. */
3645 if (global_ld.pdh) {
3646 gboolean successful;
3648 /* We're supposed to write the packet to a file; do so.
3649 If this fails, set "ld->go" to FALSE, to stop the capture, and set
3650 "ld->err" to the error. */
3651 if (global_capture_opts.use_pcapng) {
3652 successful = libpcap_write_enhanced_packet_block(global_ld.pdh, phdr, pcap_opts->interface_id, pd, &global_ld.bytes_written, &err);
3654 successful = libpcap_write_packet(global_ld.pdh, phdr, pd, &global_ld.bytes_written, &err);
3657 global_ld.go = FALSE;
3658 global_ld.err = err;
3660 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3661 "Wrote a packet of length %d captured on interface %u.",
3662 phdr->caplen, pcap_opts->interface_id);
3663 global_ld.packet_count++;
3664 pcap_opts->received++;
3665 /* if the user told us to stop after x packets, do we already have enough? */
3666 if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
3667 global_ld.go = FALSE;
3673 /* one packet was captured, queue it */
3675 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3678 pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3679 pcap_queue_element *queue_element;
3680 gboolean limit_reached;
3682 /* We may be called multiple times from pcap_dispatch(); if we've set
3683 the "stop capturing" flag, ignore this packet, as we're not
3684 supposed to be saving any more packets. */
3688 queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
3689 if (queue_element == NULL) {
3690 pcap_opts->dropped++;
3693 queue_element->pcap_opts = pcap_opts;
3694 queue_element->phdr = *phdr;
3695 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
3696 if (queue_element->pd == NULL) {
3697 pcap_opts->dropped++;
3698 g_free(queue_element);
3701 memcpy(queue_element->pd, pd, phdr->caplen);
3702 g_async_queue_lock(pcap_queue);
3703 if (((pcap_queue_byte_limit > 0) && (pcap_queue_bytes < pcap_queue_byte_limit)) &&
3704 ((pcap_queue_packet_limit > 0) && (pcap_queue_packets < pcap_queue_packet_limit))) {
3705 limit_reached = FALSE;
3706 g_async_queue_push_unlocked(pcap_queue, queue_element);
3707 pcap_queue_bytes += phdr->caplen;
3708 pcap_queue_packets += 1;
3710 limit_reached = TRUE;
3712 g_async_queue_unlock(pcap_queue);
3713 if (limit_reached) {
3714 pcap_opts->dropped++;
3715 g_free(queue_element->pd);
3716 g_free(queue_element);
3717 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3718 "Dropped a packet of length %d captured on interface %u.",
3719 phdr->caplen, pcap_opts->interface_id);
3721 pcap_opts->received++;
3722 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3723 "Queued a packet of length %d captured on interface %u.",
3724 phdr->caplen, pcap_opts->interface_id);
3726 /* I don't want to hold the mutex over the debug output. So the
3727 output may be wrong */
3728 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3729 "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
3730 pcap_queue_bytes, pcap_queue_packets);
3733 /* And now our feature presentation... [ fade to music ] */
3735 main(int argc, char *argv[])
3738 gboolean arg_error = FALSE;
3743 struct sigaction action, oldaction;
3746 gboolean start_capture = TRUE;
3747 gboolean stats_known;
3748 struct pcap_stat stats;
3749 GLogLevelFlags log_flags;
3750 gboolean list_interfaces = FALSE;
3751 gboolean list_link_layer_types = FALSE;
3752 #ifdef HAVE_BPF_IMAGE
3753 gboolean print_bpf_code = FALSE;
3755 gboolean machine_readable = FALSE;
3756 gboolean print_statistics = FALSE;
3757 int status, run_once_args = 0;
3760 #if defined(__APPLE__) && defined(__LP64__)
3761 struct utsname osinfo;
3766 arg_list_utf_16to8(argc, argv);
3771 * Initialize our DLL search path. MUST be called before LoadLibrary
3774 ws_init_dll_search_path();
3777 #ifdef HAVE_PCAP_REMOTE
3778 #define OPTSTRING_A "A:"
3779 #define OPTSTRING_r "r"
3780 #define OPTSTRING_u "u"
3782 #define OPTSTRING_A ""
3783 #define OPTSTRING_r ""
3784 #define OPTSTRING_u ""
3787 #ifdef HAVE_PCAP_SETSAMPLING
3788 #define OPTSTRING_m "m:"
3790 #define OPTSTRING_m ""
3793 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
3794 #define OPTSTRING_B "B:"
3796 #define OPTSTRING_B ""
3797 #endif /* _WIN32 or HAVE_PCAP_CREATE */
3799 #ifdef HAVE_PCAP_CREATE
3800 #define OPTSTRING_I "I"
3802 #define OPTSTRING_I ""
3805 #ifdef HAVE_BPF_IMAGE
3806 #define OPTSTRING_d "d"
3808 #define OPTSTRING_d ""
3811 #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:"
3813 #ifdef DEBUG_CHILD_DUMPCAP
3814 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
3815 fprintf (stderr, "Unable to open debug log file !\n");
3820 #if defined(__APPLE__) && defined(__LP64__)
3822 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
3823 * a bug workaround - timeouts less than 1 second don't work with libpcap
3824 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
3825 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
3826 * The problem is extremely unlikely to be reintroduced in a future
3829 if (uname(&osinfo) == 0) {
3831 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
3832 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
3833 * number of 10.0.0, not 10.1.0 - go figure).
3835 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
3836 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
3837 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
3838 need_timeout_workaround = TRUE;
3843 * Determine if dumpcap is being requested to run in a special
3844 * capture_child mode by going thru the command line args to see if
3845 * a -Z is present. (-Z is a hidden option).
3847 * The primary result of running in capture_child mode is that
3848 * all messages sent out on stderr are in a special type/len/string
3849 * format to allow message processing by type. These messages include
3850 * error messages if dumpcap fails to start the operation it was
3851 * requested to do, as well as various "status" messages which are sent
3852 * when an actual capture is in progress, and a "success" message sent
3853 * if dumpcap was requested to perform an operation other than a
3856 * Capture_child mode would normally be requested by a parent process
3857 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
3858 * to which dumpcap stderr has been redirected. It might also have
3859 * another pipe to obtain dumpcap stdout output; for operations other
3860 * than a capture, that information is formatted specially for easier
3861 * parsing by the parent process.
3863 * Capture_child mode needs to be determined immediately upon
3864 * startup so that any messages generated by dumpcap in this mode
3865 * (eg: during initialization) will be formatted properly.
3868 for (i=1; i<argc; i++) {
3869 if (strcmp("-Z", argv[i]) == 0) {
3870 capture_child = TRUE;
3871 machine_readable = TRUE; /* request machine-readable output */
3873 /* set output pipe to binary mode, to avoid ugly text conversions */
3874 _setmode(2, O_BINARY);
3879 /* The default_log_handler will use stdout, which makes trouble in */
3880 /* capture child mode, as it uses stdout for it's sync_pipe. */
3881 /* So: the filtering is done in the console_log_handler and not here.*/
3882 /* We set the log handlers right up front to make sure that any log */
3883 /* messages when running as child will be sent back to the parent */
3884 /* with the correct format. */
3888 G_LOG_LEVEL_CRITICAL|
3889 G_LOG_LEVEL_WARNING|
3890 G_LOG_LEVEL_MESSAGE|
3893 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
3895 g_log_set_handler(NULL,
3897 console_log_handler, NULL /* user_data */);
3898 g_log_set_handler(LOG_DOMAIN_MAIN,
3900 console_log_handler, NULL /* user_data */);
3901 g_log_set_handler(LOG_DOMAIN_CAPTURE,
3903 console_log_handler, NULL /* user_data */);
3904 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
3906 console_log_handler, NULL /* user_data */);
3908 /* Initialize the pcaps list */
3909 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
3911 #if !GLIB_CHECK_VERSION(2,31,0)
3912 /* Initialize the thread system */
3913 g_thread_init(NULL);
3917 /* Load wpcap if possible. Do this before collecting the run-time version information */
3920 /* ... and also load the packet.dll from wpcap */
3921 /* XXX - currently not required, may change later. */
3922 /*wpcap_packet_load();*/
3924 /* Start windows sockets */
3925 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
3927 /* Set handler for Ctrl+C key */
3928 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
3930 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
3932 action.sa_handler = capture_cleanup_handler;
3934 * Arrange that system calls not get restarted, because when
3935 * our signal handler returns we don't want to restart
3936 * a call that was waiting for packets to arrive.
3938 action.sa_flags = 0;
3939 sigemptyset(&action.sa_mask);
3940 sigaction(SIGTERM, &action, NULL);
3941 sigaction(SIGINT, &action, NULL);
3942 sigaction(SIGPIPE, &action, NULL);
3943 sigaction(SIGHUP, NULL, &oldaction);
3944 if (oldaction.sa_handler == SIG_DFL)
3945 sigaction(SIGHUP, &action, NULL);
3948 /* Catch SIGINFO and, if we get it and we're capturing in
3949 quiet mode, report the number of packets we've captured. */
3950 action.sa_handler = report_counts_siginfo;
3951 action.sa_flags = SA_RESTART;
3952 sigemptyset(&action.sa_mask);
3953 sigaction(SIGINFO, &action, NULL);
3954 #endif /* SIGINFO */
3957 /* ----------------------------------------------------------------- */
3958 /* Privilege and capability handling */
3960 /* 1. Running not as root or suid root; no special capabilities. */
3963 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
3966 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
3968 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
3969 /* capabilities; Drop all other capabilities; */
3970 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3971 /* else: after pcap_open_live() in capture_loop_open_input() */
3972 /* drop all capabilities (NET_RAW and NET_ADMIN); */
3973 /* (Note: this means that the process, although logged in */
3974 /* as root, does not have various permissions such as the */
3975 /* ability to bypass file access permissions). */
3976 /* XXX: Should we just leave capabilities alone in this case */
3977 /* so that user gets expected effect that root can do */
3980 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
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 suid root (set euid=ruid).(ie: keep suid until after */
3985 /* pcap_open_live). */
3987 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
3989 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
3990 /* capabilities; Drop all other capabilities; */
3991 /* Drop suid privileges (euid=ruid); */
3992 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3993 /* else: after pcap_open_live() in capture_loop_open_input() */
3994 /* drop all capabilities (NET_RAW and NET_ADMIN). */
3996 /* XXX: For some Linux versions/distros with capabilities */
3997 /* a 'normal' process with any capabilities cannot be */
3998 /* 'killed' (signaled) from another (same uid) non-privileged */
4000 /* For example: If (non-suid) Wireshark forks a */
4001 /* child suid dumpcap which acts as described here (case 5), */
4002 /* Wireshark will be unable to kill (signal) the child */
4003 /* dumpcap process until the capabilities have been dropped */
4004 /* (after pcap_open_live()). */
4005 /* This behaviour will apparently be changed in the kernel */
4006 /* to allow the kill (signal) in this case. */
4007 /* See the following for details: */
4008 /* http://www.mail-archive.com/ [wrapped] */
4009 /* linux-security-module@vger.kernel.org/msg02913.html */
4011 /* It is therefore conceivable that if dumpcap somehow hangs */
4012 /* in pcap_open_live or before that wireshark will not */
4013 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
4014 /* In this case, exiting wireshark will kill the child */
4015 /* dumpcap process. */
4017 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
4018 /* capabilities; Using libcap. Note: capset cmd (which see) */
4019 /* used to assign capabilities to file. */
4021 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
4022 /* else: after pcap_open_live() in capture_loop_open_input() */
4023 /* drop all capabilities (NET_RAW and NET_ADMIN) */
4025 /* ToDo: -S (stats) should drop privileges/capabilities when no */
4026 /* longer required (similar to capture). */
4028 /* ----------------------------------------------------------------- */
4030 init_process_policies();
4033 /* If 'started with special privileges' (and using libcap) */
4034 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
4035 /* Set euid/egid = ruid/rgid to remove suid privileges */
4036 relinquish_privs_except_capture();
4039 /* Set the initial values in the capture options. This might be overwritten
4040 by the command line parameters. */
4041 capture_opts_init(&global_capture_opts, NULL);
4043 /* We always save to a file - if no file was specified, we save to a
4045 global_capture_opts.saving_to_file = TRUE;
4046 global_capture_opts.has_ring_num_files = TRUE;
4048 /* Now get our args */
4049 while ((opt = getopt(argc, argv, OPTSTRING)) != -1) {
4051 case 'h': /* Print help and exit */
4055 case 'v': /* Show version and exit */
4057 GString *comp_info_str;
4058 GString *runtime_info_str;
4059 /* Assemble the compile-time version information string */
4060 comp_info_str = g_string_new("Compiled ");
4061 get_compiled_version_info(comp_info_str, NULL, NULL);
4063 /* Assemble the run-time version information string */
4064 runtime_info_str = g_string_new("Running ");
4065 get_runtime_version_info(runtime_info_str, NULL);
4066 show_version(comp_info_str, runtime_info_str);
4067 g_string_free(comp_info_str, TRUE);
4068 g_string_free(runtime_info_str, TRUE);
4072 /*** capture option specific ***/
4073 case 'a': /* autostop criteria */
4074 case 'b': /* Ringbuffer option */
4075 case 'c': /* Capture x packets */
4076 case 'f': /* capture filter */
4077 case 'i': /* Use interface x */
4078 case 'n': /* Use pcapng format */
4079 case 'p': /* Don't capture in promiscuous mode */
4080 case 'P': /* Use pcap format */
4081 case 's': /* Set the snapshot (capture) length */
4082 case 'w': /* Write to capture file x */
4083 case 'g': /* enable group read accesson file(s) */
4084 case 'y': /* Set the pcap data link type */
4085 #ifdef HAVE_PCAP_REMOTE
4086 case 'u': /* Use UDP for data transfer */
4087 case 'r': /* Capture own RPCAP traffic too */
4088 case 'A': /* Authentication */
4090 #ifdef HAVE_PCAP_SETSAMPLING
4091 case 'm': /* Sampling */
4093 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4094 case 'B': /* Buffer size */
4095 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4096 #ifdef HAVE_PCAP_CREATE
4097 case 'I': /* Monitor mode */
4099 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4104 /*** hidden option: Wireshark child mode (using binary output messages) ***/
4106 capture_child = TRUE;
4108 /* set output pipe to binary mode, to avoid ugly text conversions */
4109 _setmode(2, O_BINARY);
4111 * optarg = the control ID, aka the PPID, currently used for the
4114 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4115 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4116 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4117 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4119 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4120 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4121 "Signal pipe: Unable to open %s. Dead parent?",
4129 case 'q': /* Quiet */
4135 /*** all non capture option specific ***/
4136 case 'D': /* Print a list of capture devices and exit */
4137 list_interfaces = TRUE;
4140 case 'L': /* Print list of link-layer types and exit */
4141 list_link_layer_types = TRUE;
4144 #ifdef HAVE_BPF_IMAGE
4145 case 'd': /* Print BPF code for capture filter and exit */
4146 print_bpf_code = TRUE;
4150 case 'S': /* Print interface statistics once a second */
4151 print_statistics = TRUE;
4154 case 'M': /* For -D, -L, and -S, print machine-readable output */
4155 machine_readable = TRUE;
4158 cmdarg_err("Invalid Option: %s", argv[optind-1]);
4160 case '?': /* Bad flag - print usage message */
4169 /* user specified file name as regular command-line argument */
4170 /* XXX - use it as the capture file name (or something else)? */
4176 * Extra command line arguments were specified; complain.
4177 * XXX - interpret as capture filter, as tcpdump and tshark do?
4179 cmdarg_err("Invalid argument: %s", argv[0]);
4189 if (run_once_args > 1) {
4190 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
4192 } else if (run_once_args == 1) {
4193 /* We're supposed to print some information, rather than
4194 to capture traffic; did they specify a ring buffer option? */
4195 if (global_capture_opts.multi_files_on) {
4196 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4200 /* We're supposed to capture traffic; */
4201 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4202 if (global_capture_opts.ifaces->len > 1) {
4204 global_capture_opts.use_pcapng = TRUE;
4206 /* Was the ring buffer option specified and, if so, does it make sense? */
4207 if (global_capture_opts.multi_files_on) {
4208 /* Ring buffer works only under certain conditions:
4209 a) ring buffer does not work with temporary files;
4210 b) it makes no sense to enable the ring buffer if the maximum
4211 file size is set to "infinite". */
4212 if (global_capture_opts.save_file == NULL) {
4213 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4214 global_capture_opts.multi_files_on = FALSE;
4216 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4217 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4219 /* XXX - this must be redesigned as the conditions changed */
4220 global_capture_opts.multi_files_on = FALSE;
4227 * "-D" requires no interface to be selected; it's supposed to list
4230 if (list_interfaces) {
4231 /* Get the list of interfaces */
4236 if_list = capture_interface_list(&err, &err_str);
4237 if (if_list == NULL) {
4239 case CANT_GET_INTERFACE_LIST:
4240 case DONT_HAVE_PCAP:
4241 cmdarg_err("%s", err_str);
4246 case NO_INTERFACES_FOUND:
4248 * If we're being run by another program, just give them
4249 * an empty list of interfaces, don't report this as
4250 * an error; that lets them decide whether to report
4251 * this as an error or not.
4253 if (!machine_readable) {
4254 cmdarg_err("There are no interfaces on which a capture can be done");
4261 if (machine_readable) /* tab-separated values to stdout */
4262 print_machine_readable_interfaces(if_list);
4264 capture_opts_print_interfaces(if_list);
4265 free_interface_list(if_list);
4270 * "-S" requires no interface to be selected; it gives statistics
4271 * for all interfaces.
4273 if (print_statistics) {
4274 status = print_statistics_loop(machine_readable);
4279 * "-L", "-d", and capturing act on a particular interface, so we have to
4280 * have an interface; if none was specified, pick a default.
4282 if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
4283 /* cmdarg_err() already called .... */
4287 /* Let the user know what interfaces were chosen. */
4288 /* get_interface_descriptive_name() is not available! */
4289 if (capture_child) {
4290 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4291 interface_options interface_opts;
4293 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4294 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4295 interface_opts.name);
4298 str = g_string_new("");
4300 if (global_capture_opts.ifaces->len < 2) {
4302 if (global_capture_opts.ifaces->len < 4) {
4304 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4305 interface_options interface_opts;
4307 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4309 if (global_capture_opts.ifaces->len > 2) {
4310 g_string_append_printf(str, ",");
4312 g_string_append_printf(str, " ");
4313 if (j == global_capture_opts.ifaces->len - 1) {
4314 g_string_append_printf(str, "and ");
4317 g_string_append_printf(str, "%s", interface_opts.name);
4320 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4322 fprintf(stderr, "Capturing on %s\n", str->str);
4323 g_string_free(str, TRUE);
4326 if (list_link_layer_types) {
4327 /* Get the list of link-layer types for the capture device. */
4328 if_capabilities_t *caps;
4332 for (i = 0; i < global_capture_opts.ifaces->len; i++) {
4333 interface_options interface_opts;
4335 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, i);
4336 caps = get_if_capabilities(interface_opts.name,
4337 interface_opts.monitor_mode, &err_str);
4339 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4340 "Please check to make sure you have sufficient permissions, and that\n"
4341 "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4345 if (caps->data_link_types == NULL) {
4346 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4349 if (machine_readable) /* tab-separated values to stdout */
4350 /* XXX: We need to change the format and adopt consumers */
4351 print_machine_readable_if_capabilities(caps);
4353 /* XXX: We might want to print also the interface name */
4354 capture_opts_print_if_capabilities(caps, interface_opts.name,
4355 interface_opts.monitor_mode);
4356 free_if_capabilities(caps);
4361 /* We're supposed to do a capture, or print the BPF code for a filter.
4362 Process the snapshot length, as that affects the generated BPF code. */
4363 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4365 #ifdef HAVE_BPF_IMAGE
4366 if (print_bpf_code) {
4367 show_filter_code(&global_capture_opts);
4372 /* We're supposed to do a capture. Process the ring buffer arguments. */
4373 capture_opts_trim_ring_num_files(&global_capture_opts);
4375 /* Now start the capture. */
4377 if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4381 /* capture failed */
4384 return 0; /* never here, make compiler happy */
4389 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4390 const char *message, gpointer user_data _U_)
4397 /* ignore log message, if log_level isn't interesting */
4398 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4399 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4404 /* create a "timestamp" */
4406 today = localtime(&curr);
4408 switch(log_level & G_LOG_LEVEL_MASK) {
4409 case G_LOG_LEVEL_ERROR:
4412 case G_LOG_LEVEL_CRITICAL:
4415 case G_LOG_LEVEL_WARNING:
4418 case G_LOG_LEVEL_MESSAGE:
4421 case G_LOG_LEVEL_INFO:
4424 case G_LOG_LEVEL_DEBUG:
4428 fprintf(stderr, "unknown log_level %u\n", log_level);
4430 g_assert_not_reached();
4433 /* Generate the output message */
4434 if(log_level & G_LOG_LEVEL_MESSAGE) {
4435 /* normal user messages without additional infos */
4436 msg = g_strdup_printf("%s\n", message);
4438 /* info/debug messages with additional infos */
4439 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4440 today->tm_hour, today->tm_min, today->tm_sec,
4441 log_domain != NULL ? log_domain : "",
4445 /* DEBUG & INFO msgs (if we're debugging today) */
4446 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4447 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4448 #ifdef DEBUG_DUMPCAP
4449 fprintf(stderr, "%s", msg);
4452 #ifdef DEBUG_CHILD_DUMPCAP
4453 fprintf(debug_log, "%s", msg);
4461 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
4462 /* to parent especially formatted if dumpcap running as child. */
4463 if (capture_child) {
4464 sync_pipe_errmsg_to_parent(2, msg, "");
4466 fprintf(stderr, "%s", msg);
4473 /****************************************************************************************************************/
4474 /* indication report routines */
4478 report_packet_count(int packet_count)
4480 char tmp[SP_DECISIZE+1+1];
4481 static int count = 0;
4484 g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
4485 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
4486 pipe_write_block(2, SP_PACKET_COUNT, tmp);
4488 count += packet_count;
4489 fprintf(stderr, "\rPackets: %u ", count);
4490 /* stderr could be line buffered */
4496 report_new_capture_file(const char *filename)
4499 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
4500 pipe_write_block(2, SP_FILE, filename);
4504 * Prevent a SIGINFO handler from writing to the standard error
4505 * while we're doing so; instead, have it just set a flag telling
4506 * us to print that information when we're done.
4509 #endif /* SIGINFO */
4510 fprintf(stderr, "File: %s\n", filename);
4511 /* stderr could be line buffered */
4516 * Allow SIGINFO handlers to write.
4521 * If a SIGINFO handler asked us to write out capture counts, do so.
4524 report_counts_for_siginfo();
4525 #endif /* SIGINFO */
4530 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
4532 interface_options interface_opts;
4533 char tmp[MSG_MAX_LENGTH+1+6];
4535 if (i < capture_opts->ifaces->len) {
4536 if (capture_child) {
4537 g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
4538 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
4539 pipe_write_block(2, SP_BAD_FILTER, tmp);
4542 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
4543 * the error message below.
4545 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
4547 "Invalid capture filter: \"%s\" for interface %s!\n"
4549 "That string isn't a valid capture filter (%s).\n"
4550 "See the User's Guide for a description of the capture filter syntax.",
4551 interface_opts.cfilter, interface_opts.name, errmsg);
4557 report_capture_error(const char *error_msg, const char *secondary_error_msg)
4560 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4561 "Primary Error: %s", error_msg);
4562 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4563 "Secondary Error: %s", secondary_error_msg);
4564 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
4566 cmdarg_err("%s", error_msg);
4567 if (secondary_error_msg[0] != '\0')
4568 cmdarg_err_cont("%s", secondary_error_msg);
4573 report_packet_drops(guint32 received, guint32 drops, gchar *name)
4575 char tmp[SP_DECISIZE+1+1];
4577 g_snprintf(tmp, sizeof(tmp), "%u", drops);
4580 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4581 "Packets received/dropped on interface %s: %u/%u",
4582 name, received, drops);
4583 /* XXX: Need to provide interface id, changes to consumers required. */
4584 pipe_write_block(2, SP_DROPS, tmp);
4587 "Packets received/dropped on interface %s: %u/%u (%.1f%%)\n",
4588 name, received, drops,
4589 received ? 100.0 * received / (received + drops) : 0.0);
4590 /* stderr could be line buffered */
4596 /****************************************************************************************************************/
4597 /* signal_pipe handling */
4602 signal_pipe_check_running(void)
4604 /* any news from our parent? -> just stop the capture */
4608 /* if we are running standalone, no check required */
4609 if(!capture_child) {
4613 if(!sig_pipe_name || !sig_pipe_handle) {
4614 /* This shouldn't happen */
4615 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4616 "Signal pipe: No name or handle");
4621 * XXX - We should have the process ID of the parent (from the "-Z" flag)
4622 * at this point. Should we check to see if the parent is still alive,
4623 * e.g. by using OpenProcess?
4626 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
4628 if(!result || avail > 0) {
4629 /* peek failed or some bytes really available */
4630 /* (if not piping from stdin this would fail) */
4631 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4632 "Signal pipe: Stop capture: %s", sig_pipe_name);
4633 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4634 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
4635 sig_pipe_handle, result, avail);
4638 /* pipe ok and no bytes available */
4645 * Editor modelines - http://www.wireshark.org/tools/modelines.html
4650 * indent-tabs-mode: nil
4653 * vi: set shiftwidth=4 tabstop=8 expandtab:
4654 * :indentSize=4:tabSize=8:noTabs=true: