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>
65 #include "wsutil/wsgetopt.h"
73 # include <sys/prctl.h>
74 # include <sys/capability.h>
77 #include "ringbuffer.h"
78 #include "clopts_common.h"
79 #include "console_io.h"
80 #include "cmdarg_err.h"
81 #include "version_info.h"
83 #include "capture-pcap-util.h"
88 #include "capture-wpcap.h"
89 #include <wsutil/unicode-utils.h>
93 #include <sys/socket.h>
97 #ifdef NEED_INET_V6DEFS_H
98 # include "wsutil/inet_v6defs.h"
101 #include <wsutil/privileges.h>
103 #include "sync_pipe.h"
105 #include "capture_opts.h"
106 #include "capture_ifinfo.h"
107 #include "capture_sync.h"
109 #include "conditions.h"
110 #include "capture_stop_conditions.h"
112 #include "tempfile.h"
114 #include "wsutil/file_util.h"
117 * Get information about libpcap format from "wiretap/libpcap.h".
118 * XXX - can we just use pcap_open_offline() to read the pipe?
120 #include "wiretap/libpcap.h"
122 /**#define DEBUG_DUMPCAP**/
123 /**#define DEBUG_CHILD_DUMPCAP**/
125 #ifdef DEBUG_CHILD_DUMPCAP
126 FILE *debug_log; /* for logging debug messages to */
127 /* a file if DEBUG_CHILD_DUMPCAP */
135 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
137 static gchar *sig_pipe_name = NULL;
138 static HANDLE sig_pipe_handle = NULL;
139 static gboolean signal_pipe_check_running(void);
143 static GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
144 static GMutex *cap_pipe_read_mtx;
148 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
149 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
152 /** Stop a low-level capture (stops the capture child). */
153 static void capture_loop_stop(void);
155 #if !defined (__linux__)
156 #ifndef HAVE_PCAP_BREAKLOOP
158 * We don't have pcap_breakloop(), which is the only way to ensure that
159 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
160 * won't, if the call to read the next packet or batch of packets is
161 * is interrupted by a signal on UN*X, just go back and try again to
164 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
165 * the signal handler, set a flag to stop capturing; however, without
166 * a guarantee of that sort, we can't guarantee that we'll stop capturing
167 * if the read will be retried and won't time out if no packets arrive.
169 * Therefore, on at least some platforms, we work around the lack of
170 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
171 * to wait for packets to arrive, so that we're probably going to be
172 * blocked in the select() when the signal arrives, and can just bail
173 * out of the loop at that point.
175 * However, we don't want to that on BSD (because "select()" doesn't work
176 * correctly on BPF devices on at least some releases of some flavors of
177 * BSD), and we don't want to do it on Windows (because "select()" is
178 * something for sockets, not for arbitrary handles). (Note that "Windows"
179 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
180 * using WinPcap, not a UNIX libpcap.)
182 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
183 * on BSD times out even if no packets have arrived, so we'll eventually
184 * exit pcap_dispatch() with an indication that no packets have arrived,
185 * and will break out of the capture loop at that point.
187 * On Windows, we can't send a SIGINT to stop capturing, so none of this
188 * applies in any case.
190 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
191 * want to include it if it's not present on this platform, however.
193 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
194 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
196 # define MUST_DO_SELECT
197 # endif /* avoid select */
198 #endif /* HAVE_PCAP_BREAKLOOP */
200 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
201 * in pcap_dispatch(); on the other hand, select() works just fine there.
202 * Hence we use a select for that come what may.
204 #define MUST_DO_SELECT
207 /** init the capture filter */
210 INITFILTER_BAD_FILTER,
211 INITFILTER_OTHER_ERROR
212 } initfilter_status_t;
214 typedef struct _loop_data {
216 gboolean go; /* TRUE as long as we're supposed to keep capturing */
217 int err; /* if non-zero, error seen while capturing */
218 gint packet_count; /* Number of packets we have already captured */
219 gint packet_max; /* Number of packets we're supposed to capture - 0 means infinite */
220 gint inpkts_to_sync_pipe; /* Packets not already send out to the sync_pipe */
222 gboolean report_packet_count; /* Set by SIGINFO handler; print packet count */
225 /* pcap "input file" */
226 pcap_t *pcap_h; /* pcap handle */
227 gboolean pcap_err; /* TRUE if error from pcap */
228 #ifdef MUST_DO_SELECT
229 int pcap_fd; /* pcap file descriptor */
232 /* capture pipe (unix only "input file") */
233 gboolean from_cap_pipe; /* TRUE if we are capturing data from a capture pipe */
234 struct pcap_hdr cap_pipe_hdr; /* Pcap header when capturing from a pipe */
235 struct pcaprec_modified_hdr cap_pipe_rechdr; /* Pcap record header when capturing from a pipe */
237 HANDLE cap_pipe_h; /* The handle of the capture pipe */
239 int cap_pipe_fd; /* the file descriptor of the capture pipe */
241 gboolean cap_pipe_modified; /* TRUE if data in the pipe uses modified pcap headers */
242 gboolean cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
244 char * cap_pipe_buf; /* Pointer to the data buffer we read into */
245 #endif /* USE_THREADS */
246 int cap_pipe_bytes_to_read;/* Used by cap_pipe_dispatch */
247 int cap_pipe_bytes_read; /* Used by cap_pipe_dispatch */
249 STATE_EXPECT_REC_HDR,
254 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
263 guint32 autostop_files;
267 * Standard secondary message for unexpected errors.
269 static const char please_report[] =
270 "Please report this to the Wireshark developers.\n"
271 "(This is not a crash; please do not report it as such.)";
274 * This needs to be static, so that the SIGINT handler can clear the "go"
277 static loop_data global_ld;
281 * Timeout, in milliseconds, for reads from the stream of captured packets.
283 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
284 * 64-bit applications, with sub-second timeouts not to work. The bug is
287 #if defined(__APPLE__) && defined(__LP64__)
288 static gboolean need_timeout_workaround;
290 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
292 #define CAP_READ_TIMEOUT 250
296 * Timeout, in microseconds, for threaded reads from a pipe.
298 #define THREAD_READ_TIMEOUT 100
299 static const char *cap_pipe_err_str;
302 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
303 const char *message, gpointer user_data _U_);
305 /* capture related options */
306 static capture_options global_capture_opts;
307 static gboolean quiet;
309 static void capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
311 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
312 int err, gboolean is_close);
314 static void exit_main(int err) G_GNUC_NORETURN;
316 static void report_new_capture_file(const char *filename);
317 static void report_packet_count(int packet_count);
318 static void report_packet_drops(guint32 drops);
319 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
320 static void report_cfilter_error(const char *cfilter, const char *errmsg);
322 #define MSG_MAX_LENGTH 4096
325 print_usage(gboolean print_ver) {
333 "Dumpcap " VERSION "%s\n"
334 "Capture network packets and dump them into a libpcap file.\n"
335 "See http://www.wireshark.org for more information.\n",
336 wireshark_svnversion);
340 fprintf(output, "\nUsage: dumpcap [options] ...\n");
341 fprintf(output, "\n");
342 fprintf(output, "Capture interface:\n");
343 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
344 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
345 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
346 fprintf(output, " -p don't capture in promiscuous mode\n");
347 #ifdef HAVE_PCAP_CREATE
348 fprintf(output, " -I capture in monitor mode, if available\n");
350 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
351 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
353 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
354 fprintf(output, " -D print list of interfaces and exit\n");
355 fprintf(output, " -L print list of link-layer types of iface and exit\n");
356 #ifdef HAVE_BPF_IMAGE
357 fprintf(output, " -d print generated BPF code for capture filter\n");
359 fprintf(output, " -S print statistics for each interface once every second\n");
360 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
361 fprintf(output, "\n");
362 #ifdef HAVE_PCAP_REMOTE
363 fprintf(output, "\nRPCAP options:\n");
364 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
365 fprintf(output, " -u use UDP for RPCAP data transfer\n");
366 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
367 #ifdef HAVE_PCAP_SETSAMPLING
368 fprintf(output, " -m <sampling type> use packet sampling\n");
369 fprintf(output, " count:NUM - capture one packet of every NUM\n");
370 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
373 fprintf(output, "Stop conditions:\n");
374 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
375 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
376 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
377 fprintf(output, " files:NUM - stop after NUM files\n");
378 /*fprintf(output, "\n");*/
379 fprintf(output, "Output (files):\n");
380 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
381 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
382 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
383 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
384 fprintf(output, " -n use pcapng format instead of pcap\n");
385 /*fprintf(output, "\n");*/
386 fprintf(output, "Miscellaneous:\n");
387 fprintf(output, " -q don't report packet capture counts\n");
388 fprintf(output, " -v print version information and exit\n");
389 fprintf(output, " -h display this help and exit\n");
390 fprintf(output, "\n");
391 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcap\n");
392 fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcap\"\n");
393 fprintf(output, "\n");
394 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
398 show_version(GString *comp_info_str, GString *runtime_info_str)
402 "Dumpcap " VERSION "%s\n"
407 "See http://www.wireshark.org for more information.\n",
408 wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
412 * Print to the standard error. This is a command-line tool, so there's
413 * no need to pop up a console.
416 vfprintf_stderr(const char *fmt, va_list ap)
418 vfprintf(stderr, fmt, ap);
422 fprintf_stderr(const char *fmt, ...)
427 vfprintf_stderr(fmt, ap);
432 * Report an error in command-line arguments.
435 cmdarg_err(const char *fmt, ...)
441 /* Generate a 'special format' message back to parent */
443 msg = g_strdup_vprintf(fmt, ap);
444 sync_pipe_errmsg_to_parent(2, msg, "");
449 fprintf(stderr, "dumpcap: ");
450 vfprintf(stderr, fmt, ap);
451 fprintf(stderr, "\n");
457 * Report additional information for an error in command-line arguments.
460 cmdarg_err_cont(const char *fmt, ...)
467 msg = g_strdup_vprintf(fmt, ap);
468 sync_pipe_errmsg_to_parent(2, msg, "");
473 vfprintf(stderr, fmt, ap);
474 fprintf(stderr, "\n");
481 #if 0 /* Set to enable capability debugging */
482 /* see 'man cap_to_text()' for explanation of output */
483 /* '=' means 'all= ' ie: no capabilities */
484 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
486 print_caps(const char *pfx) {
487 cap_t caps = cap_get_proc();
488 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
489 "%s: EUID: %d Capabilities: %s", pfx,
490 geteuid(), cap_to_text(caps, NULL));
493 print_caps(const char *pfx _U_) {
498 relinquish_all_capabilities(void)
500 /* Drop any and all capabilities this process may have. */
501 /* Allowed whether or not process has any privileges. */
502 cap_t caps = cap_init(); /* all capabilities initialized to off */
503 print_caps("Pre-clear");
504 if (cap_set_proc(caps)) {
505 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
507 print_caps("Post-clear");
513 open_capture_device(capture_options *capture_opts,
514 char (*open_err_str)[PCAP_ERRBUF_SIZE])
517 #ifdef HAVE_PCAP_CREATE
520 #ifdef HAVE_PCAP_REMOTE
521 struct pcap_rmtauth auth;
524 /* Open the network interface to capture from it.
525 Some versions of libpcap may put warnings into the error buffer
526 if they succeed; to tell if that's happened, we have to clear
527 the error buffer, and check if it's still a null string. */
528 (*open_err_str)[0] = '\0';
529 #ifdef HAVE_PCAP_OPEN
531 * If we're opening a remote device, use pcap_open(); that's currently
532 * the only open routine that supports remote devices.
534 if (strncmp (capture_opts->iface, "rpcap://", 8) == 0) {
535 auth.type = capture_opts->auth_type == CAPTURE_AUTH_PWD ?
536 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
537 auth.username = capture_opts->auth_username;
538 auth.password = capture_opts->auth_password;
540 pcap_h = pcap_open(capture_opts->iface,
541 capture_opts->has_snaplen ? capture_opts->snaplen :
542 WTAP_MAX_PACKET_SIZE,
544 (capture_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
545 (capture_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
546 (capture_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
547 CAP_READ_TIMEOUT, &auth, *open_err_str);
549 #endif /* HAVE_PCAP_OPEN */
552 * If we're not opening a remote device, use pcap_create() and
553 * pcap_activate() if we have them, so that we can set the buffer
554 * size, otherwise use pcap_open_live().
556 #ifdef HAVE_PCAP_CREATE
557 pcap_h = pcap_create(capture_opts->iface, *open_err_str);
558 if (pcap_h != NULL) {
559 pcap_set_snaplen(pcap_h, capture_opts->has_snaplen ? capture_opts->snaplen : WTAP_MAX_PACKET_SIZE);
560 pcap_set_promisc(pcap_h, capture_opts->promisc_mode);
561 pcap_set_timeout(pcap_h, CAP_READ_TIMEOUT);
563 if (capture_opts->buffer_size > 1) {
564 pcap_set_buffer_size(pcap_h, capture_opts->buffer_size * 1024 * 1024);
566 if (capture_opts->monitor_mode)
567 pcap_set_rfmon(pcap_h, 1);
568 err = pcap_activate(pcap_h);
570 /* Failed to activate, set to NULL */
571 if (err == PCAP_ERROR)
572 g_strlcpy(*open_err_str, pcap_geterr(pcap_h), sizeof *open_err_str);
574 g_strlcpy(*open_err_str, pcap_statustostr(err), sizeof *open_err_str);
580 pcap_h = pcap_open_live(capture_opts->iface,
581 capture_opts->has_snaplen ? capture_opts->snaplen :
582 WTAP_MAX_PACKET_SIZE,
583 capture_opts->promisc_mode, CAP_READ_TIMEOUT,
588 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
589 /* to remove any suid privileges. */
590 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
591 /* (euid/egid have already previously been set to ruid/rgid. */
592 /* (See comment in main() for details) */
594 relinquish_special_privs_perm();
596 relinquish_all_capabilities();
603 get_capture_device_open_failure_messages(const char *open_err_str,
609 char *errmsg, size_t errmsg_len,
610 char *secondary_errmsg,
611 size_t secondary_errmsg_len)
613 const char *libpcap_warn;
614 static const char ppamsg[] = "can't find PPA for ";
616 /* If we got a "can't find PPA for X" message, warn the user (who
617 is running dumcap on HP-UX) that they don't have a version of
618 libpcap that properly handles HP-UX (libpcap 0.6.x and later
619 versions, which properly handle HP-UX, say "can't find /dev/dlpi
620 PPA for X" rather than "can't find PPA for X"). */
621 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
624 "You are running (T)Wireshark with a version of the libpcap library\n"
625 "that doesn't handle HP-UX network devices well; this means that\n"
626 "(T)Wireshark may not be able to capture packets.\n"
628 "To fix this, you should install libpcap 0.6.2, or a later version\n"
629 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
630 "packaged binary form from the Software Porting And Archive Centre\n"
631 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
632 "at the URL lists a number of mirror sites.";
635 g_snprintf(errmsg, (gulong) errmsg_len,
636 "The capture session could not be initiated (%s).", open_err_str);
638 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
639 "Please check to make sure you have sufficient permissions, and that you have "
640 "the proper interface or pipe specified.%s", libpcap_warn);
642 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
644 "Please check that \"%s\" is the proper interface.\n"
647 "Help can be found at:\n"
649 " http://wiki.wireshark.org/WinPcap\n"
650 " http://wiki.wireshark.org/CaptureSetup\n",
655 /* Set the data link type on a pcap. */
657 set_pcap_linktype(pcap_t *pcap_h, capture_options *capture_opts,
658 char *errmsg, size_t errmsg_len,
659 char *secondary_errmsg, size_t secondary_errmsg_len)
661 char *set_linktype_err_str;
663 if (capture_opts->linktype == -1)
664 return TRUE; /* just use the default */
665 #ifdef HAVE_PCAP_SET_DATALINK
666 if (pcap_set_datalink(pcap_h, capture_opts->linktype) == 0)
667 return TRUE; /* no error */
668 set_linktype_err_str = pcap_geterr(pcap_h);
670 /* Let them set it to the type it is; reject any other request. */
671 if (get_pcap_linktype(pcap_h, capture_opts->iface) == capture_opts->linktype)
672 return TRUE; /* no error */
673 set_linktype_err_str =
674 "That DLT isn't one of the DLTs supported by this device";
676 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
677 set_linktype_err_str);
679 * If the error isn't "XXX is not one of the DLTs supported by this device",
680 * tell the user to tell the Wireshark developers about it.
682 if (strstr(set_linktype_err_str, "is not one of the DLTs supported by this device") == NULL)
683 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
685 secondary_errmsg[0] = '\0';
690 compile_capture_filter(const char *iface, pcap_t *pcap_h,
691 struct bpf_program *fcode, char *cfilter)
693 bpf_u_int32 netnum, netmask;
694 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
696 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
698 * Well, we can't get the netmask for this interface; it's used
699 * only for filters that check for broadcast IP addresses, so
700 * we just punt and use 0. It might be nice to warn the user,
701 * but that's a pain in a GUI application, as it'd involve popping
702 * up a message box, and it's not clear how often this would make
703 * a difference (only filters that check for IP broadcast addresses
707 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
710 if (pcap_compile(pcap_h, fcode, cfilter, 1, netmask) < 0)
715 #ifdef HAVE_BPF_IMAGE
717 show_filter_code(capture_options *capture_opts)
720 gchar open_err_str[PCAP_ERRBUF_SIZE];
721 char errmsg[MSG_MAX_LENGTH+1];
722 char secondary_errmsg[MSG_MAX_LENGTH+1];
723 struct bpf_program fcode;
724 struct bpf_insn *insn;
727 pcap_h = open_capture_device(capture_opts, &open_err_str);
728 if (pcap_h == NULL) {
729 /* Open failed; get messages */
730 get_capture_device_open_failure_messages(open_err_str,
732 errmsg, sizeof errmsg,
734 sizeof secondary_errmsg);
735 /* And report them */
736 report_capture_error(errmsg, secondary_errmsg);
740 /* Set the link-layer type. */
741 if (!set_pcap_linktype(pcap_h, capture_opts, errmsg, sizeof errmsg,
742 secondary_errmsg, sizeof secondary_errmsg)) {
744 report_capture_error(errmsg, secondary_errmsg);
748 /* OK, try to compile the capture filter. */
749 if (!compile_capture_filter(capture_opts->iface, pcap_h, &fcode,
750 capture_opts->cfilter)) {
752 report_cfilter_error(capture_opts->cfilter, errmsg);
758 /* Let our parent know we succeeded. */
759 pipe_write_block(2, SP_SUCCESS, NULL);
762 /* Now print the filter code. */
763 insn = fcode.bf_insns;
765 for (i = 0; i < fcode.bf_len; insn++, i++)
766 printf("%s\n", bpf_image(insn, i));
772 * capture_interface_list() is expected to do the right thing to get
773 * a list of interfaces.
775 * In most of the programs in the Wireshark suite, "the right thing"
776 * is to run dumpcap and ask it for the list, because dumpcap may
777 * be the only program in the suite with enough privileges to get
780 * In dumpcap itself, however, we obviously can't run dumpcap to
781 * ask for the list. Therefore, our capture_interface_list() should
782 * just call get_interface_list().
785 capture_interface_list(int *err, char **err_str)
787 return get_interface_list(err, err_str);
791 * Get the data-link type for a libpcap device.
792 * This works around AIX 5.x's non-standard and incompatible-with-the-
793 * rest-of-the-universe libpcap.
796 get_pcap_linktype(pcap_t *pch, const char *devname
804 const char *ifacename;
807 linktype = pcap_datalink(pch);
811 * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
812 * rather than DLT_ values for link-layer types; the ifType values
813 * for LAN devices are:
820 * and the ifType value for a loopback device is 24.
822 * The AIX names for LAN devices begin with:
829 * and the AIX names for loopback devices begin with "lo".
831 * (The difference between "Ethernet" and "802.3" is presumably
832 * whether packets have an Ethernet header, with a packet type,
833 * or an 802.3 header, with a packet length, followed by an 802.2
834 * header and possibly a SNAP header.)
836 * If the device name matches "linktype" interpreted as an ifType
837 * value, rather than as a DLT_ value, we will assume this is AIX's
838 * non-standard, incompatible libpcap, rather than a standard libpcap,
839 * and will map the link-layer type to the standard DLT_ value for
840 * that link-layer type, as that's what the rest of Wireshark expects.
842 * (This means the capture files won't be readable by a tcpdump
843 * linked with AIX's non-standard libpcap, but so it goes. They
844 * *will* be readable by standard versions of tcpdump, Wireshark,
847 * XXX - if we conclude we're using AIX libpcap, should we also
848 * set a flag to cause us to assume the time stamps are in
849 * seconds-and-nanoseconds form, and to convert them to
850 * seconds-and-microseconds form before processing them and
855 * Find the last component of the device name, which is the
858 ifacename = strchr(devname, '/');
859 if (ifacename == NULL)
862 /* See if it matches any of the LAN device names. */
863 if (strncmp(ifacename, "en", 2) == 0) {
866 * That's the RFC 1573 value for Ethernet; map it to DLT_EN10MB.
870 } else if (strncmp(ifacename, "et", 2) == 0) {
873 * That's the RFC 1573 value for 802.3; map it to DLT_EN10MB.
874 * (libpcap, tcpdump, Wireshark, etc. don't care if it's Ethernet
879 } else if (strncmp(ifacename, "tr", 2) == 0) {
882 * That's the RFC 1573 value for 802.5 (Token Ring); map it to
883 * DLT_IEEE802, which is what's used for Token Ring.
887 } else if (strncmp(ifacename, "fi", 2) == 0) {
888 if (linktype == 15) {
890 * That's the RFC 1573 value for FDDI; map it to DLT_FDDI.
894 } else if (strncmp(ifacename, "lo", 2) == 0) {
895 if (linktype == 24) {
897 * That's the RFC 1573 value for "software loopback" devices; map it
898 * to DLT_NULL, which is what's used for loopback devices on BSD.
908 static data_link_info_t *
909 create_data_link_info(int dlt)
911 data_link_info_t *data_link_info;
914 data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
915 data_link_info->dlt = dlt;
916 text = pcap_datalink_val_to_name(dlt);
918 data_link_info->name = g_strdup(text);
920 data_link_info->name = g_strdup_printf("DLT %d", dlt);
921 text = pcap_datalink_val_to_description(dlt);
923 data_link_info->description = g_strdup(text);
925 data_link_info->description = NULL;
926 return data_link_info;
930 * Get the capabilities of a network device.
932 static if_capabilities_t *
933 get_if_capabilities(const char *devname, gboolean monitor_mode
934 #ifndef HAVE_PCAP_CREATE
939 if_capabilities_t *caps;
940 char errbuf[PCAP_ERRBUF_SIZE];
942 #ifdef HAVE_PCAP_CREATE
946 #ifdef HAVE_PCAP_LIST_DATALINKS
950 data_link_info_t *data_link_info;
953 * Allocate the interface capabilities structure.
955 caps = g_malloc(sizeof *caps);
957 #ifdef HAVE_PCAP_OPEN
958 pch = pcap_open(devname, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
959 caps->can_set_rfmon = FALSE;
962 *err_str = g_strdup(errbuf);
966 #elif defined(HAVE_PCAP_CREATE)
967 pch = pcap_create(devname, errbuf);
970 *err_str = g_strdup(errbuf);
974 status = pcap_can_set_rfmon(pch);
977 if (status == PCAP_ERROR)
978 *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
981 *err_str = g_strdup(pcap_statustostr(status));
987 caps->can_set_rfmon = FALSE;
988 else if (status == 1) {
989 caps->can_set_rfmon = TRUE;
991 pcap_set_rfmon(pch, 1);
993 if (err_str != NULL) {
994 *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
1002 status = pcap_activate(pch);
1004 /* Error. We ignore warnings (status > 0). */
1005 if (err_str != NULL) {
1006 if (status == PCAP_ERROR)
1007 *err_str = g_strdup_printf("pcap_activate() failed: %s",
1010 *err_str = g_strdup(pcap_statustostr(status));
1017 pch = pcap_open_live(devname, MIN_PACKET_SIZE, 0, 0, errbuf);
1018 caps->can_set_rfmon = FALSE;
1020 if (err_str != NULL)
1021 *err_str = g_strdup(errbuf);
1026 deflt = get_pcap_linktype(pch, devname);
1027 #ifdef HAVE_PCAP_LIST_DATALINKS
1028 nlt = pcap_list_datalinks(pch, &linktypes);
1029 if (nlt == 0 || linktypes == NULL) {
1031 if (err_str != NULL)
1032 *err_str = NULL; /* an empty list doesn't mean an error */
1035 caps->data_link_types = NULL;
1036 for (i = 0; i < nlt; i++) {
1037 data_link_info = create_data_link_info(linktypes[i]);
1040 * XXX - for 802.11, make the most detailed 802.11
1041 * version the default, rather than the one the
1042 * device has as the default?
1044 if (linktypes[i] == deflt)
1045 caps->data_link_types = g_list_prepend(caps->data_link_types,
1048 caps->data_link_types = g_list_append(caps->data_link_types,
1051 #ifdef HAVE_PCAP_FREE_DATALINKS
1052 pcap_free_datalinks(linktypes);
1055 * In Windows, there's no guarantee that if you have a library
1056 * built with one version of the MSVC++ run-time library, and
1057 * it returns a pointer to allocated data, you can free that
1058 * data from a program linked with another version of the
1059 * MSVC++ run-time library.
1061 * This is not an issue on UN*X.
1063 * See the mail threads starting at
1065 * http://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
1069 * http://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
1072 #define xx_free free /* hack so checkAPIs doesn't complain */
1075 #endif /* HAVE_PCAP_FREE_DATALINKS */
1076 #else /* HAVE_PCAP_LIST_DATALINKS */
1078 data_link_info = create_data_link_info(deflt);
1079 caps->data_link_types = g_list_append(caps->data_link_types,
1081 #endif /* HAVE_PCAP_LIST_DATALINKS */
1085 if (err_str != NULL)
1090 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
1092 print_machine_readable_interfaces(GList *if_list)
1099 char addr_str[ADDRSTRLEN];
1101 if (capture_child) {
1102 /* Let our parent know we succeeded. */
1103 pipe_write_block(2, SP_SUCCESS, NULL);
1106 i = 1; /* Interface id number */
1107 for (if_entry = g_list_first(if_list); if_entry != NULL;
1108 if_entry = g_list_next(if_entry)) {
1109 if_info = (if_info_t *)if_entry->data;
1110 printf("%d. %s", i++, if_info->name);
1113 * Print the contents of the if_entry struct in a parseable format.
1114 * Each if_entry element is tab-separated. Addresses are comma-
1117 /* XXX - Make sure our description doesn't contain a tab */
1118 if (if_info->description != NULL)
1119 printf("\t%s\t", if_info->description);
1123 for(addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
1124 addr = g_slist_next(addr)) {
1125 if (addr != g_slist_nth(if_info->addrs, 0))
1128 if_addr = (if_addr_t *)addr->data;
1129 switch(if_addr->ifat_type) {
1131 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
1133 printf("%s", addr_str);
1135 printf("<unknown IPv4>");
1139 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
1140 addr_str, ADDRSTRLEN)) {
1141 printf("%s", addr_str);
1143 printf("<unknown IPv6>");
1147 printf("<type unknown %u>", if_addr->ifat_type);
1151 if (if_info->loopback)
1152 printf("\tloopback");
1154 printf("\tnetwork");
1161 * If you change the machine-readable output format of this function,
1162 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
1165 print_machine_readable_if_capabilities(if_capabilities_t *caps)
1168 data_link_info_t *data_link_info;
1169 const gchar *desc_str;
1171 if (capture_child) {
1172 /* Let our parent know we succeeded. */
1173 pipe_write_block(2, SP_SUCCESS, NULL);
1176 if (caps->can_set_rfmon)
1180 for (lt_entry = caps->data_link_types; lt_entry != NULL;
1181 lt_entry = g_list_next(lt_entry)) {
1182 data_link_info = (data_link_info_t *)lt_entry->data;
1183 if (data_link_info->description != NULL)
1184 desc_str = data_link_info->description;
1186 desc_str = "(not supported)";
1187 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
1197 /* Print the number of packets captured for each interface until we're killed. */
1199 print_statistics_loop(gboolean machine_readable)
1201 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1207 char errbuf[PCAP_ERRBUF_SIZE];
1208 struct pcap_stat ps;
1210 if_list = get_interface_list(&err, &err_str);
1211 if (if_list == NULL) {
1213 case CANT_GET_INTERFACE_LIST:
1214 cmdarg_err("%s", err_str);
1218 case NO_INTERFACES_FOUND:
1219 cmdarg_err("There are no interfaces on which a capture can be done");
1225 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1226 if_info = (if_info_t *)if_entry->data;
1227 #ifdef HAVE_PCAP_OPEN
1228 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1230 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1234 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
1235 if_stat->name = g_strdup(if_info->name);
1237 stat_list = g_list_append(stat_list, if_stat);
1242 cmdarg_err("There are no interfaces on which a capture can be done");
1246 if (capture_child) {
1247 /* Let our parent know we succeeded. */
1248 pipe_write_block(2, SP_SUCCESS, NULL);
1251 if (!machine_readable) {
1252 printf("%-15s %10s %10s\n", "Interface", "Received",
1256 global_ld.go = TRUE;
1257 while (global_ld.go) {
1258 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1259 if_stat = (if_stat_t *)stat_entry->data;
1260 pcap_stats(if_stat->pch, &ps);
1262 if (!machine_readable) {
1263 printf("%-15s %10u %10u\n", if_stat->name,
1264 ps.ps_recv, ps.ps_drop);
1266 printf("%s\t%u\t%u\n", if_stat->name,
1267 ps.ps_recv, ps.ps_drop);
1272 if (! global_ld.from_cap_pipe)
1279 /* XXX - Not reached. Should we look for 'q' in stdin? */
1280 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1281 if_stat = (if_stat_t *)stat_entry->data;
1282 pcap_close(if_stat->pch);
1283 g_free(if_stat->name);
1286 g_list_free(stat_list);
1287 free_interface_list(if_list);
1295 capture_cleanup_handler(DWORD dwCtrlType)
1297 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1298 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1299 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1300 like SIGTERM at least when the machine's shutting down.
1302 For now, if we're running as a command rather than a capture child,
1303 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1304 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1305 in that way on UN*X.
1307 If we're not running as a capture child, we might be running as
1308 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1309 user logs out. (XXX - can we explicitly check whether we're
1310 running as a service?) */
1312 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1313 "Console: Control signal");
1314 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1315 "Console: Control signal, CtrlType: %u", dwCtrlType);
1317 /* Keep capture running if we're a service and a user logs off */
1318 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1319 capture_loop_stop();
1327 capture_cleanup_handler(int signum _U_)
1329 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1330 SIGTERM. We assume that if the user wanted it to keep running
1331 after they logged out, they'd have nohupped it. */
1333 /* Note: don't call g_log() in the signal handler: if we happened to be in
1334 * g_log() in process context when the signal came in, g_log will detect
1335 * the "recursion" and abort.
1338 capture_loop_stop();
1347 /* Don't print this if we're a capture child. */
1348 if (!capture_child) {
1350 /* Report the count only if we aren't printing a packet count
1351 as packets arrive. */
1352 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
1353 plurality(global_ld.packet_count, "", "s"));
1356 infoprint = FALSE; /* we just reported it */
1360 report_counts_siginfo(int signum _U_)
1362 int sav_errno = errno;
1364 /* If we've been told to delay printing, just set a flag asking
1365 that we print counts (if we're supposed to), otherwise print
1366 the count of packets captured (if we're supposed to). */
1373 #endif /* SIGINFO */
1375 static void exit_main(int status)
1378 /* Shutdown windows sockets */
1381 /* can be helpful for debugging */
1382 #ifdef DEBUG_DUMPCAP
1383 printf("Press any key\n");
1394 * If we were linked with libcap (not libpcap), make sure we have
1395 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1396 * (See comment in main() for details)
1399 relinquish_privs_except_capture(void)
1401 /* If 'started_with_special_privs' (ie: suid) then enable for
1402 * ourself the NET_ADMIN and NET_RAW capabilities and then
1403 * drop our suid privileges.
1405 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1406 * stuff we don't need (and shouldn't have).
1407 * CAP_NET_RAW: Packet capture (raw sockets).
1410 if (started_with_special_privs()) {
1411 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1412 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1414 cap_t caps = cap_init(); /* all capabilities initialized to off */
1416 print_caps("Pre drop, pre set");
1418 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1419 cmdarg_err("prctl() fail return: %s", strerror(errno));
1422 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1423 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1425 if (cap_set_proc(caps)) {
1426 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
1428 print_caps("Pre drop, post set");
1430 relinquish_special_privs_perm();
1432 print_caps("Post drop, pre set");
1433 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1434 if (cap_set_proc(caps)) {
1435 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
1437 print_caps("Post drop, post set");
1443 #endif /* HAVE_LIBCAP */
1445 /* Take care of byte order in the libpcap headers read from pipes.
1446 * (function taken from wiretap/libpcap.c) */
1448 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1451 /* Byte-swap the record header fields. */
1452 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
1453 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
1454 rechdr->incl_len = BSWAP32(rechdr->incl_len);
1455 rechdr->orig_len = BSWAP32(rechdr->orig_len);
1458 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1459 swapped, in order to match the BPF header layout.
1461 Unfortunately, some files were, according to a comment in the "libpcap"
1462 source, written with version 2.3 in their headers but without the
1463 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1464 would make no sense - we assume that we need to swap them. */
1465 if (hdr->version_major == 2 &&
1466 (hdr->version_minor < 3 ||
1467 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1470 temp = rechdr->orig_len;
1471 rechdr->orig_len = rechdr->incl_len;
1472 rechdr->incl_len = temp;
1478 * Thread function that reads from a pipe and pushes the data
1479 * to the main application thread.
1482 * XXX Right now we use async queues for basic signaling. The main thread
1483 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1484 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1485 * Iff the read is successful cap_pipe_read pushes an item onto
1486 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1487 * the queues themselves (yet).
1489 * We might want to move some of the cap_pipe_dispatch logic here so that
1490 * we can let cap_pipe_read run independently, queuing up multiple reads
1491 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1493 static void *cap_pipe_read(void *ld_ptr) {
1494 loop_data *ld = (loop_data *)ld_ptr;
1503 while (ld->cap_pipe_err == PIPOK) {
1504 g_async_queue_pop(cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1505 g_mutex_lock(cap_pipe_read_mtx);
1507 while (bytes_read < (int) ld->cap_pipe_bytes_to_read) {
1509 /* If we try to use read() on a named pipe on Windows with partial
1510 * data it appears to return EOF.
1512 res = ReadFile(ld->cap_pipe_h, ld->cap_pipe_buf+bytes_read,
1513 ld->cap_pipe_bytes_to_read - bytes_read,
1518 last_err = GetLastError();
1519 if (last_err == ERROR_MORE_DATA) {
1521 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1522 ld->cap_pipe_err = PIPEOF;
1526 ld->cap_pipe_err = PIPERR;
1529 } else if (b == 0 && ld->cap_pipe_bytes_to_read > 0) {
1530 ld->cap_pipe_err = PIPEOF;
1535 b = read(ld->cap_pipe_fd, ld->cap_pipe_buf+bytes_read,
1536 ld->cap_pipe_bytes_to_read - bytes_read);
1539 ld->cap_pipe_err = PIPEOF;
1543 ld->cap_pipe_err = PIPERR;
1552 ld->cap_pipe_bytes_read = bytes_read;
1553 if (ld->cap_pipe_bytes_read >= ld->cap_pipe_bytes_to_read) {
1554 g_async_queue_push(cap_pipe_done_q, ld->cap_pipe_buf); /* Any non-NULL value will do */
1556 g_mutex_unlock(cap_pipe_read_mtx);
1560 #endif /* USE_THREADS */
1562 /* Provide select() functionality for a single file descriptor
1563 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1565 * Returns the same values as select. If an error is returned,
1566 * the string cap_pipe_err_str should be used instead of errno.
1569 cap_pipe_select(int pipe_fd) {
1571 struct timeval timeout, *pto;
1574 cap_pipe_err_str = "Unknown error";
1577 FD_SET(pipe_fd, &rfds);
1580 timeout.tv_usec = CAP_READ_TIMEOUT * 1000;
1583 sel_ret = select(pipe_fd+1, &rfds, NULL, NULL, pto);
1585 cap_pipe_err_str = strerror(errno);
1590 /* Mimic pcap_open_live() for pipe captures
1592 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1593 * open it, and read the header.
1595 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1596 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1598 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
1599 char *errmsg, int errmsgl)
1602 struct stat pipe_stat;
1603 struct sockaddr_un sa;
1606 unsigned int bytes_read;
1617 ld->cap_pipe_fd = -1;
1619 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
1621 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1624 * XXX - this blocks until a pcap per-file header has been written to
1625 * the pipe, so it could block indefinitely.
1627 if (strcmp(pipename, "-") == 0) {
1629 fd = 0; /* read from stdin */
1631 ld->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1635 if (ws_stat(pipename, &pipe_stat) < 0) {
1636 if (errno == ENOENT || errno == ENOTDIR)
1637 ld->cap_pipe_err = PIPNEXIST;
1639 g_snprintf(errmsg, errmsgl,
1640 "The capture session could not be initiated "
1641 "due to error getting information on pipe/socket: %s", strerror(errno));
1642 ld->cap_pipe_err = PIPERR;
1646 if (S_ISFIFO(pipe_stat.st_mode)) {
1647 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1649 g_snprintf(errmsg, errmsgl,
1650 "The capture session could not be initiated "
1651 "due to error on pipe open: %s", strerror(errno));
1652 ld->cap_pipe_err = PIPERR;
1655 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1656 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1658 g_snprintf(errmsg, errmsgl,
1659 "The capture session could not be initiated "
1660 "due to error on socket create: %s", strerror(errno));
1661 ld->cap_pipe_err = PIPERR;
1664 sa.sun_family = AF_UNIX;
1666 * The Single UNIX Specification says:
1668 * The size of sun_path has intentionally been left undefined.
1669 * This is because different implementations use different sizes.
1670 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1671 * of 104. Since most implementations originate from BSD versions,
1672 * the size is typically in the range 92 to 108.
1674 * Applications should not assume a particular length for sun_path
1675 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1679 * The <sys/un.h> header shall define the sockaddr_un structure,
1680 * which shall include at least the following members:
1682 * sa_family_t sun_family Address family.
1683 * char sun_path[] Socket pathname.
1685 * so we assume that it's an array, with a specified size,
1686 * and that the size reflects the maximum path length.
1688 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1689 /* Path name too long */
1690 g_snprintf(errmsg, errmsgl,
1691 "The capture session coud not be initiated "
1692 "due to error on socket connect: Path name too long");
1693 ld->cap_pipe_err = PIPERR;
1696 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1698 g_snprintf(errmsg, errmsgl,
1699 "The capture session coud not be initiated "
1700 "due to error on socket connect: %s", strerror(errno));
1701 ld->cap_pipe_err = PIPERR;
1705 if (S_ISCHR(pipe_stat.st_mode)) {
1707 * Assume the user specified an interface on a system where
1708 * interfaces are in /dev. Pretend we haven't seen it.
1710 ld->cap_pipe_err = PIPNEXIST;
1713 g_snprintf(errmsg, errmsgl,
1714 "The capture session could not be initiated because\n"
1715 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
1716 ld->cap_pipe_err = PIPERR;
1721 #define PIPE_STR "\\pipe\\"
1722 /* Under Windows, named pipes _must_ have the form
1723 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1725 pncopy = g_strdup(pipename);
1726 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1727 pos = strchr(pncopy + 3, '\\');
1728 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1735 g_snprintf(errmsg, errmsgl,
1736 "The capture session could not be initiated because\n"
1737 "\"%s\" is neither an interface nor a pipe", pipename);
1738 ld->cap_pipe_err = PIPNEXIST;
1742 /* Wait for the pipe to appear */
1744 ld->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1745 OPEN_EXISTING, 0, NULL);
1747 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE)
1750 if (GetLastError() != ERROR_PIPE_BUSY) {
1751 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1752 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1753 g_snprintf(errmsg, errmsgl,
1754 "The capture session on \"%s\" could not be started "
1755 "due to error on pipe open: %s (error %d)",
1756 pipename, utf_16to8(err_str), GetLastError());
1758 ld->cap_pipe_err = PIPERR;
1762 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1763 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1764 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1765 g_snprintf(errmsg, errmsgl,
1766 "The capture session on \"%s\" timed out during "
1767 "pipe open: %s (error %d)",
1768 pipename, utf_16to8(err_str), GetLastError());
1770 ld->cap_pipe_err = PIPERR;
1777 ld->from_cap_pipe = TRUE;
1780 /* read the pcap header */
1782 while (bytes_read < sizeof magic) {
1783 sel_ret = cap_pipe_select(fd);
1785 g_snprintf(errmsg, errmsgl,
1786 "Unexpected error from select: %s", strerror(errno));
1788 } else if (sel_ret > 0) {
1789 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
1792 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1794 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1801 #else /* USE_THREADS */
1802 g_thread_create(&cap_pipe_read, ld, FALSE, NULL);
1804 ld->cap_pipe_buf = (char *) &magic;
1805 ld->cap_pipe_bytes_read = 0;
1806 ld->cap_pipe_bytes_to_read = sizeof(magic);
1807 /* We don't have to worry about cap_pipe_read_mtx here */
1808 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1809 g_async_queue_pop(cap_pipe_done_q);
1810 if (ld->cap_pipe_bytes_read <= 0) {
1811 if (ld->cap_pipe_bytes_read == 0)
1812 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1814 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1819 #endif /* USE_THREADS */
1823 /* Host that wrote it has our byte order, and was running
1824 a program using either standard or ss990417 libpcap. */
1825 ld->cap_pipe_byte_swapped = FALSE;
1826 ld->cap_pipe_modified = FALSE;
1828 case PCAP_MODIFIED_MAGIC:
1829 /* Host that wrote it has our byte order, but was running
1830 a program using either ss990915 or ss991029 libpcap. */
1831 ld->cap_pipe_byte_swapped = FALSE;
1832 ld->cap_pipe_modified = TRUE;
1834 case PCAP_SWAPPED_MAGIC:
1835 /* Host that wrote it has a byte order opposite to ours,
1836 and was running a program using either standard or
1837 ss990417 libpcap. */
1838 ld->cap_pipe_byte_swapped = TRUE;
1839 ld->cap_pipe_modified = FALSE;
1841 case PCAP_SWAPPED_MODIFIED_MAGIC:
1842 /* Host that wrote it out has a byte order opposite to
1843 ours, and was running a program using either ss990915
1844 or ss991029 libpcap. */
1845 ld->cap_pipe_byte_swapped = TRUE;
1846 ld->cap_pipe_modified = TRUE;
1849 /* Not a "libpcap" type we know about. */
1850 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
1855 /* Read the rest of the header */
1857 while (bytes_read < sizeof(struct pcap_hdr)) {
1858 sel_ret = cap_pipe_select(fd);
1860 g_snprintf(errmsg, errmsgl,
1861 "Unexpected error from select: %s", strerror(errno));
1863 } else if (sel_ret > 0) {
1864 b = read(fd, ((char *)hdr)+bytes_read,
1865 sizeof(struct pcap_hdr) - bytes_read);
1868 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1870 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
1877 #else /* USE_THREADS */
1878 ld->cap_pipe_buf = (char *) hdr;
1879 ld->cap_pipe_bytes_read = 0;
1880 ld->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1881 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1882 g_async_queue_pop(cap_pipe_done_q);
1883 if (ld->cap_pipe_bytes_read <= 0) {
1884 if (ld->cap_pipe_bytes_read == 0)
1885 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1887 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
1891 #endif /* USE_THREADS */
1893 if (ld->cap_pipe_byte_swapped) {
1894 /* Byte-swap the header fields about which we care. */
1895 hdr->version_major = BSWAP16(hdr->version_major);
1896 hdr->version_minor = BSWAP16(hdr->version_minor);
1897 hdr->snaplen = BSWAP32(hdr->snaplen);
1898 hdr->network = BSWAP32(hdr->network);
1900 ld->linktype = hdr->network;
1902 if (hdr->version_major < 2) {
1903 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1907 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1908 ld->cap_pipe_err = PIPOK;
1910 ld->cap_pipe_fd = fd;
1915 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1916 ld->cap_pipe_err = PIPERR;
1919 ld->cap_pipe_fd = -1;
1926 /* We read one record from the pipe, take care of byte order in the record
1927 * header, write the record to the capture file, and update capture statistics. */
1929 cap_pipe_dispatch(loop_data *ld, guchar *data, char *errmsg, int errmsgl)
1931 struct pcap_pkthdr phdr;
1932 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1944 #ifdef LOG_CAPTURE_VERBOSE
1945 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1948 switch (ld->cap_pipe_state) {
1950 case STATE_EXPECT_REC_HDR:
1952 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1955 ld->cap_pipe_state = STATE_READ_REC_HDR;
1956 ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
1957 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1958 ld->cap_pipe_bytes_read = 0;
1961 ld->cap_pipe_buf = (char *) &ld->cap_pipe_rechdr;
1962 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1963 g_mutex_unlock(cap_pipe_read_mtx);
1968 case STATE_READ_REC_HDR:
1970 b = read(ld->cap_pipe_fd, ((char *)&ld->cap_pipe_rechdr)+ld->cap_pipe_bytes_read,
1971 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1974 result = PD_PIPE_EOF;
1976 result = PD_PIPE_ERR;
1979 ld->cap_pipe_bytes_read += b;
1980 #else /* USE_THREADS */
1981 g_get_current_time(&wait_time);
1982 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1983 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1984 if (ld->cap_pipe_err == PIPEOF) {
1985 result = PD_PIPE_EOF;
1987 } else if (ld->cap_pipe_err == PIPERR) {
1988 result = PD_PIPE_ERR;
1994 #endif /* USE_THREADS */
1995 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1997 result = PD_REC_HDR_READ;
2000 case STATE_EXPECT_DATA:
2002 if (g_mutex_trylock(cap_pipe_read_mtx)) {
2005 ld->cap_pipe_state = STATE_READ_DATA;
2006 ld->cap_pipe_bytes_to_read = ld->cap_pipe_rechdr.hdr.incl_len;
2007 ld->cap_pipe_bytes_read = 0;
2010 ld->cap_pipe_buf = (char *) data;
2011 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
2012 g_mutex_unlock(cap_pipe_read_mtx);
2017 case STATE_READ_DATA:
2019 b = read(ld->cap_pipe_fd, data+ld->cap_pipe_bytes_read,
2020 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
2023 result = PD_PIPE_EOF;
2025 result = PD_PIPE_ERR;
2028 ld->cap_pipe_bytes_read += b;
2029 #else /* USE_THREADS */
2030 g_get_current_time(&wait_time);
2031 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
2032 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
2033 if (ld->cap_pipe_err == PIPEOF) {
2034 result = PD_PIPE_EOF;
2036 } else if (ld->cap_pipe_err == PIPERR) {
2037 result = PD_PIPE_ERR;
2043 #endif /* USE_THREADS */
2044 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
2046 result = PD_DATA_READ;
2050 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2053 } /* switch (ld->cap_pipe_state) */
2056 * We've now read as much data as we were expecting, so process it.
2060 case PD_REC_HDR_READ:
2061 /* We've read the header. Take care of byte order. */
2062 cap_pipe_adjust_header(ld->cap_pipe_byte_swapped, &ld->cap_pipe_hdr,
2063 &ld->cap_pipe_rechdr.hdr);
2064 if (ld->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2065 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2066 ld->packet_count+1, ld->cap_pipe_rechdr.hdr.incl_len);
2069 ld->cap_pipe_state = STATE_EXPECT_DATA;
2073 /* Fill in a "struct pcap_pkthdr", and process the packet. */
2074 phdr.ts.tv_sec = ld->cap_pipe_rechdr.hdr.ts_sec;
2075 phdr.ts.tv_usec = ld->cap_pipe_rechdr.hdr.ts_usec;
2076 phdr.caplen = ld->cap_pipe_rechdr.hdr.incl_len;
2077 phdr.len = ld->cap_pipe_rechdr.hdr.orig_len;
2079 capture_loop_packet_cb((u_char *)ld, &phdr, data);
2081 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
2085 ld->cap_pipe_err = PIPEOF;
2090 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
2091 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2092 g_snprintf(errmsg, errmsgl,
2093 "Error reading from pipe: %s (error %d)",
2094 utf_16to8(err_str), GetLastError());
2097 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2105 ld->cap_pipe_err = PIPERR;
2106 /* Return here rather than inside the switch to prevent GCC warning */
2111 /** Open the capture input file (pcap or capture pipe).
2112 * Returns TRUE if it succeeds, FALSE otherwise. */
2114 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2115 char *errmsg, size_t errmsg_len,
2116 char *secondary_errmsg, size_t secondary_errmsg_len)
2118 gchar open_err_str[PCAP_ERRBUF_SIZE];
2119 gchar *sync_msg_str;
2122 gchar *sync_secondary_msg_str;
2123 WORD wVersionRequested;
2127 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
2130 /* XXX - opening Winsock on tshark? */
2132 /* Initialize Windows Socket if we are in a WIN32 OS
2133 This needs to be done before querying the interface for network/netmask */
2135 /* XXX - do we really require 1.1 or earlier?
2136 Are there any versions that support only 2.0 or higher? */
2137 wVersionRequested = MAKEWORD(1, 1);
2138 err = WSAStartup(wVersionRequested, &wsaData);
2142 case WSASYSNOTREADY:
2143 g_snprintf(errmsg, (gulong) errmsg_len,
2144 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2147 case WSAVERNOTSUPPORTED:
2148 g_snprintf(errmsg, (gulong) errmsg_len,
2149 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2150 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2153 case WSAEINPROGRESS:
2154 g_snprintf(errmsg, (gulong) errmsg_len,
2155 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2159 g_snprintf(errmsg, (gulong) errmsg_len,
2160 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2164 g_snprintf(errmsg, (gulong) errmsg_len,
2165 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2169 g_snprintf(errmsg, (gulong) errmsg_len,
2170 "Couldn't initialize Windows Sockets: error %d", err);
2173 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2178 ld->pcap_h = open_capture_device(capture_opts, &open_err_str);
2180 if (ld->pcap_h != NULL) {
2181 /* we've opened "iface" as a network device */
2183 /* try to set the capture buffer size */
2184 if (capture_opts->buffer_size > 1 &&
2185 pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
2186 sync_secondary_msg_str = g_strdup_printf(
2187 "The capture buffer size of %dMB seems to be too high for your machine,\n"
2188 "the default of 1MB will be used.\n"
2190 "Nonetheless, the capture is started.\n",
2191 capture_opts->buffer_size);
2192 report_capture_error("Couldn't set the capture buffer size!",
2193 sync_secondary_msg_str);
2194 g_free(sync_secondary_msg_str);
2198 #if defined(HAVE_PCAP_REMOTE) && defined(HAVE_PCAP_SETSAMPLING)
2199 if ((capture_opts->sampling_method != CAPTURE_SAMP_NONE) &&
2200 (strncmp (capture_opts->iface, "rpcap://", 8) == 0))
2202 struct pcap_samp *samp;
2204 if ((samp = pcap_setsampling(ld->pcap_h)) != NULL)
2206 switch (capture_opts->sampling_method)
2208 case CAPTURE_SAMP_BY_COUNT:
2209 samp->method = PCAP_SAMP_1_EVERY_N;
2212 case CAPTURE_SAMP_BY_TIMER:
2213 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2217 sync_msg_str = g_strdup_printf(
2218 "Unknown sampling method %d specified,\n"
2219 "continue without packet sampling",
2220 capture_opts->sampling_method);
2221 report_capture_error("Couldn't set the capture "
2222 "sampling", sync_msg_str);
2223 g_free(sync_msg_str);
2225 samp->value = capture_opts->sampling_param;
2229 report_capture_error("Couldn't set the capture sampling",
2230 "Cannot get packet sampling data structure");
2236 /* setting the data link type only works on real interfaces */
2237 if (!set_pcap_linktype(ld->pcap_h, capture_opts, errmsg, errmsg_len,
2238 secondary_errmsg, secondary_errmsg_len))
2240 ld->linktype = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
2242 /* We couldn't open "iface" as a network device. */
2243 /* Try to open it as a pipe */
2244 cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, (int) errmsg_len);
2247 if (ld->cap_pipe_fd == -1) {
2249 if (ld->cap_pipe_h == INVALID_HANDLE_VALUE) {
2252 if (ld->cap_pipe_err == PIPNEXIST) {
2253 /* Pipe doesn't exist, so output message for interface */
2254 get_capture_device_open_failure_messages(open_err_str,
2255 capture_opts->iface,
2259 secondary_errmsg_len);
2262 * Else pipe (or file) does exist and cap_pipe_open_live() has
2267 /* cap_pipe_open_live() succeeded; don't want
2268 error message from pcap_open_live() */
2269 open_err_str[0] = '\0';
2272 /* XXX - will this work for tshark? */
2273 #ifdef MUST_DO_SELECT
2274 if (!ld->from_cap_pipe) {
2275 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2276 ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
2278 ld->pcap_fd = pcap_fileno(ld->pcap_h);
2283 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
2284 returned a warning; print it, but keep capturing. */
2285 if (open_err_str[0] != '\0') {
2286 sync_msg_str = g_strdup_printf("%s.", open_err_str);
2287 report_capture_error(sync_msg_str, "");
2288 g_free(sync_msg_str);
2294 /* close the capture input file (pcap or capture pipe) */
2295 static void capture_loop_close_input(loop_data *ld) {
2297 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2299 /* if open, close the capture pipe "input file" */
2301 if (ld->cap_pipe_fd >= 0) {
2302 g_assert(ld->from_cap_pipe);
2303 ws_close(ld->cap_pipe_fd);
2304 ld->cap_pipe_fd = 0;
2307 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE) {
2308 CloseHandle(ld->cap_pipe_h);
2309 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
2313 /* if open, close the pcap "input file" */
2314 if(ld->pcap_h != NULL) {
2315 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)ld->pcap_h);
2316 g_assert(!ld->from_cap_pipe);
2317 pcap_close(ld->pcap_h);
2324 /* Shut down windows sockets */
2330 /* init the capture filter */
2331 static initfilter_status_t
2332 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2333 gchar * iface, gchar * cfilter)
2335 struct bpf_program fcode;
2337 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2339 /* capture filters only work on real interfaces */
2340 if (cfilter && !from_cap_pipe) {
2341 /* A capture filter was specified; set it up. */
2342 if (!compile_capture_filter(iface, pcap_h, &fcode, cfilter)) {
2343 /* Treat this specially - our caller might try to compile this
2344 as a display filter and, if that succeeds, warn the user that
2345 the display and capture filter syntaxes are different. */
2346 return INITFILTER_BAD_FILTER;
2348 if (pcap_setfilter(pcap_h, &fcode) < 0) {
2349 #ifdef HAVE_PCAP_FREECODE
2350 pcap_freecode(&fcode);
2352 return INITFILTER_OTHER_ERROR;
2354 #ifdef HAVE_PCAP_FREECODE
2355 pcap_freecode(&fcode);
2359 return INITFILTER_NO_ERROR;
2363 /* set up to write to the already-opened capture output file/files */
2365 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len) {
2369 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2372 if (ld->from_cap_pipe) {
2373 ld->file_snaplen = ld->cap_pipe_hdr.snaplen;
2376 ld->file_snaplen = pcap_snapshot(ld->pcap_h);
2379 /* Set up to write to the capture file. */
2380 if (capture_opts->multi_files_on) {
2381 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2383 ld->pdh = libpcap_fdopen(ld->save_file_fd, &err);
2386 gboolean successful;
2388 ld->bytes_written = 0;
2389 if (capture_opts->use_pcapng) {
2392 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2393 successful = libpcap_write_session_header_block(ld->pdh, appname, &ld->bytes_written, &err) &&
2394 libpcap_write_interface_description_block(ld->pdh, capture_opts->iface, capture_opts->cfilter, ld->linktype, ld->file_snaplen, &ld->bytes_written, &err);
2396 successful = libpcap_write_file_header(ld->pdh, ld->linktype, ld->file_snaplen,
2397 &ld->bytes_written, &err);
2405 if (ld->pdh == NULL) {
2406 /* We couldn't set up to write to the capture file. */
2407 /* XXX - use cf_open_error_message from tshark instead? */
2410 case WTAP_ERR_CANT_OPEN:
2411 g_snprintf(errmsg, errmsg_len, "The file to which the capture would be saved"
2412 " couldn't be created for some unknown reason.");
2415 case WTAP_ERR_SHORT_WRITE:
2416 g_snprintf(errmsg, errmsg_len, "A full header couldn't be written to the file"
2417 " to which the capture would be saved.");
2422 g_snprintf(errmsg, errmsg_len,
2423 "The file to which the capture would be"
2424 " saved (\"%s\") could not be opened: Error %d.",
2425 capture_opts->save_file, err);
2427 g_snprintf(errmsg, errmsg_len,
2428 "The file to which the capture would be"
2429 " saved (\"%s\") could not be opened: %s.",
2430 capture_opts->save_file, strerror(err));
2442 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
2444 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2446 if (capture_opts->multi_files_on) {
2447 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2449 if (capture_opts->use_pcapng) {
2450 libpcap_write_interface_statistics_block(ld->pdh, 0, ld->pcap_h, &ld->bytes_written, err_close);
2452 return libpcap_dump_close(ld->pdh, err_close);
2456 /* dispatch incoming packets (pcap or capture pipe)
2458 * Waits for incoming packets to be available, and calls pcap_dispatch()
2459 * to cause them to be processed.
2461 * Returns the number of packets which were processed.
2463 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2464 * packet-batching behaviour does not cause packets to get held back
2468 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
2469 char *errmsg, int errmsg_len)
2472 gint packet_count_before;
2473 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
2478 packet_count_before = ld->packet_count;
2479 if (ld->from_cap_pipe) {
2480 /* dispatch from capture pipe */
2481 #ifdef LOG_CAPTURE_VERBOSE
2482 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2485 sel_ret = cap_pipe_select(ld->cap_pipe_fd);
2488 if (sel_ret < 0 && errno != EINTR) {
2489 g_snprintf(errmsg, errmsg_len,
2490 "Unexpected error from select: %s", strerror(errno));
2491 report_capture_error(errmsg, please_report);
2496 * "select()" says we can read from the pipe without blocking
2498 #endif /* USE_THREADS */
2499 inpkts = cap_pipe_dispatch(ld, pcap_data, errmsg, errmsg_len);
2509 /* dispatch from pcap */
2510 #ifdef MUST_DO_SELECT
2512 * If we have "pcap_get_selectable_fd()", we use it to get the
2513 * descriptor on which to select; if that's -1, it means there
2514 * is no descriptor on which you can do a "select()" (perhaps
2515 * because you're capturing on a special device, and that device's
2516 * driver unfortunately doesn't support "select()", in which case
2517 * we don't do the select - which means it might not be possible
2518 * to stop a capture until a packet arrives. If that's unacceptable,
2519 * plead with whoever supplies the software for that device to add
2520 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2521 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2522 * later, so it can use pcap_breakloop().
2524 #ifdef LOG_CAPTURE_VERBOSE
2525 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2527 if (ld->pcap_fd != -1) {
2528 sel_ret = cap_pipe_select(ld->pcap_fd);
2531 * "select()" says we can read from it without blocking; go for
2534 * We don't have pcap_breakloop(), so we only process one packet
2535 * per pcap_dispatch() call, to allow a signal to stop the
2536 * processing immediately, rather than processing all packets
2537 * in a batch before quitting.
2539 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb,
2543 /* Error, rather than pcap_breakloop(). */
2544 ld->pcap_err = TRUE;
2546 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2549 if (sel_ret < 0 && errno != EINTR) {
2550 g_snprintf(errmsg, errmsg_len,
2551 "Unexpected error from select: %s", strerror(errno));
2552 report_capture_error(errmsg, please_report);
2558 #endif /* MUST_DO_SELECT */
2560 /* dispatch from pcap without select */
2562 #ifdef LOG_CAPTURE_VERBOSE
2563 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2567 * On Windows, we don't support asynchronously telling a process to
2568 * stop capturing; instead, we check for an indication on a pipe
2569 * after processing packets. We therefore process only one packet
2570 * at a time, so that we can check the pipe after every packet.
2572 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb, (u_char *) ld);
2574 inpkts = pcap_dispatch(ld->pcap_h, -1, capture_loop_packet_cb, (u_char *) ld);
2578 /* Error, rather than pcap_breakloop(). */
2579 ld->pcap_err = TRUE;
2581 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2583 #else /* pcap_next_ex */
2584 #ifdef LOG_CAPTURE_VERBOSE
2585 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2587 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2590 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2591 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
2592 * This should be fixed in the WinPcap 4.0 alpha release.
2594 * For reference, an example remote interface:
2595 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2598 /* emulate dispatch from pcap */
2601 struct pcap_pkthdr *pkt_header;
2606 (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1)
2607 capture_loop_packet_cb( (u_char *) ld, pkt_header, pkt_data);
2610 ld->pcap_err = TRUE;
2614 #endif /* pcap_next_ex */
2618 #ifdef LOG_CAPTURE_VERBOSE
2619 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2622 return ld->packet_count - packet_count_before;
2626 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2627 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2629 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2630 char *errmsg, int errmsg_len) {
2633 gchar *capfile_name;
2634 gboolean is_tempfile;
2639 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2640 (capture_opts->save_file) ? capture_opts->save_file : "");
2642 if (capture_opts->save_file != NULL) {
2643 /* We return to the caller while the capture is in progress.
2644 * Therefore we need to take a copy of save_file in
2645 * case the caller destroys it after we return.
2647 capfile_name = g_strdup(capture_opts->save_file);
2649 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2650 if (capture_opts->multi_files_on) {
2651 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2652 g_snprintf(errmsg, errmsg_len,
2653 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2654 g_free(capfile_name);
2657 if (strcmp(capfile_name, "-") == 0) {
2658 /* write to stdout */
2661 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
2662 _setmode(1, O_BINARY);
2665 } /* if (...output_to_pipe ... */
2668 if (capture_opts->multi_files_on) {
2669 /* ringbuffer is enabled */
2670 *save_file_fd = ringbuf_init(capfile_name,
2671 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
2673 /* we need the ringbuf name */
2674 if(*save_file_fd != -1) {
2675 g_free(capfile_name);
2676 capfile_name = g_strdup(ringbuf_current_filename());
2679 /* Try to open/create the specified file for use as a capture buffer. */
2680 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
2684 is_tempfile = FALSE;
2686 /* Choose a random name for the temporary capture buffer */
2687 *save_file_fd = create_tempfile(&tmpname, "wireshark");
2688 capfile_name = g_strdup(tmpname);
2692 /* did we fail to open the output file? */
2693 if (*save_file_fd == -1) {
2695 g_snprintf(errmsg, errmsg_len,
2696 "The temporary file to which the capture would be saved (\"%s\") "
2697 "could not be opened: %s.", capfile_name, strerror(errno));
2699 if (capture_opts->multi_files_on) {
2700 ringbuf_error_cleanup();
2703 g_snprintf(errmsg, errmsg_len,
2704 "The file to which the capture would be saved (\"%s\") "
2705 "could not be opened: %s.", capfile_name,
2708 g_free(capfile_name);
2712 if(capture_opts->save_file != NULL) {
2713 g_free(capture_opts->save_file);
2715 capture_opts->save_file = capfile_name;
2716 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2717 "g_free(capfile_name)". */
2719 ret = fchown(*save_file_fd, capture_opts->owner, capture_opts->group);
2727 #define TIME_GET() GetTickCount()
2729 #define TIME_GET() time(NULL)
2732 /* Do the work of handling either the file size or file duration capture
2733 conditions being reached, and switching files or stopping. */
2735 do_file_switch_or_stop(capture_options *capture_opts,
2736 condition *cnd_autostop_files,
2737 condition *cnd_autostop_size,
2738 condition *cnd_file_duration)
2740 if (capture_opts->multi_files_on) {
2741 if (cnd_autostop_files != NULL &&
2742 cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
2743 /* no files left: stop here */
2744 global_ld.go = FALSE;
2748 /* Switch to the next ringbuffer file */
2749 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2750 &global_ld.save_file_fd, &global_ld.err)) {
2751 gboolean successful;
2753 /* File switch succeeded: reset the conditions */
2754 global_ld.bytes_written = 0;
2755 if (capture_opts->use_pcapng) {
2758 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2759 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2760 libpcap_write_interface_description_block(global_ld.pdh, capture_opts->iface, capture_opts->cfilter, global_ld.linktype, global_ld.file_snaplen, &global_ld.bytes_written, &global_ld.err);
2762 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2763 &global_ld.bytes_written, &global_ld.err);
2766 fclose(global_ld.pdh);
2767 global_ld.pdh = NULL;
2768 global_ld.go = FALSE;
2771 if(cnd_autostop_size)
2772 cnd_reset(cnd_autostop_size);
2773 if(cnd_file_duration)
2774 cnd_reset(cnd_file_duration);
2775 libpcap_dump_flush(global_ld.pdh, NULL);
2777 report_packet_count(global_ld.inpkts_to_sync_pipe);
2778 global_ld.inpkts_to_sync_pipe = 0;
2779 report_new_capture_file(capture_opts->save_file);
2781 /* File switch failed: stop here */
2782 global_ld.go = FALSE;
2786 /* single file, stop now */
2787 global_ld.go = FALSE;
2793 /* Do the low-level work of a capture.
2794 Returns TRUE if it succeeds, FALSE otherwise. */
2796 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
2798 time_t upd_time, cur_time;
2802 condition *cnd_file_duration = NULL;
2803 condition *cnd_autostop_files = NULL;
2804 condition *cnd_autostop_size = NULL;
2805 condition *cnd_autostop_duration = NULL;
2808 gboolean cfilter_error = FALSE;
2809 char errmsg[MSG_MAX_LENGTH+1];
2810 char secondary_errmsg[MSG_MAX_LENGTH+1];
2813 *secondary_errmsg = '\0';
2815 /* init the loop data */
2816 global_ld.go = TRUE;
2817 global_ld.packet_count = 0;
2819 global_ld.report_packet_count = FALSE;
2821 if (capture_opts->has_autostop_packets)
2822 global_ld.packet_max = capture_opts->autostop_packets;
2824 global_ld.packet_max = 0; /* no limit */
2825 global_ld.inpkts_to_sync_pipe = 0;
2826 global_ld.err = 0; /* no error seen yet */
2827 global_ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
2828 global_ld.pcap_err = FALSE;
2829 global_ld.from_cap_pipe = FALSE;
2830 global_ld.pdh = NULL;
2832 global_ld.cap_pipe_fd = -1;
2834 global_ld.cap_pipe_h = INVALID_HANDLE_VALUE;
2836 #ifdef MUST_DO_SELECT
2837 global_ld.pcap_fd = 0;
2839 global_ld.autostop_files = 0;
2840 global_ld.save_file_fd = -1;
2842 /* We haven't yet gotten the capture statistics. */
2843 *stats_known = FALSE;
2845 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
2846 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
2848 /* open the "input file" from network interface or capture pipe */
2849 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
2850 secondary_errmsg, sizeof(secondary_errmsg))) {
2854 /* init the input filter from the network interface (capture pipe will do nothing) */
2855 switch (capture_loop_init_filter(global_ld.pcap_h, global_ld.from_cap_pipe,
2856 capture_opts->iface,
2857 capture_opts->cfilter)) {
2859 case INITFILTER_NO_ERROR:
2862 case INITFILTER_BAD_FILTER:
2863 cfilter_error = TRUE;
2864 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(global_ld.pcap_h));
2867 case INITFILTER_OTHER_ERROR:
2868 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
2869 pcap_geterr(global_ld.pcap_h));
2870 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
2874 /* If we're supposed to write to a capture file, open it for output
2875 (temporary/specified name/ringbuffer) */
2876 if (capture_opts->saving_to_file) {
2877 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
2878 errmsg, sizeof(errmsg))) {
2882 /* set up to write to the already-opened capture output file/files */
2883 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
2888 /* XXX - capture SIGTERM and close the capture, in case we're on a
2889 Linux 2.0[.x] system and you have to explicitly close the capture
2890 stream in order to turn promiscuous mode off? We need to do that
2891 in other places as well - and I don't think that works all the
2892 time in any case, due to libpcap bugs. */
2894 /* Well, we should be able to start capturing.
2896 Sync out the capture file, so the header makes it to the file system,
2897 and send a "capture started successfully and capture file created"
2898 message to our parent so that they'll open the capture file and
2899 update its windows to indicate that we have a live capture in
2901 libpcap_dump_flush(global_ld.pdh, NULL);
2902 report_new_capture_file(capture_opts->save_file);
2905 /* initialize capture stop (and alike) conditions */
2906 init_capture_stop_conditions();
2907 /* create stop conditions */
2908 if (capture_opts->has_autostop_filesize)
2910 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
2911 if (capture_opts->has_autostop_duration)
2912 cnd_autostop_duration =
2913 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
2915 if (capture_opts->multi_files_on) {
2916 if (capture_opts->has_file_duration)
2918 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
2920 if (capture_opts->has_autostop_files)
2921 cnd_autostop_files =
2922 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
2925 /* init the time values */
2926 start_time = TIME_GET();
2927 upd_time = TIME_GET();
2929 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
2931 /* WOW, everything is prepared! */
2932 /* please fasten your seat belts, we will enter now the actual capture loop */
2933 while (global_ld.go) {
2934 /* dispatch incoming packets */
2935 inpkts = capture_loop_dispatch(capture_opts, &global_ld, errmsg,
2939 /* Were we asked to print packet counts by the SIGINFO handler? */
2940 if (global_ld.report_packet_count) {
2941 fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
2942 plurality(global_ld.packet_count, "", "s"));
2943 global_ld.report_packet_count = FALSE;
2948 /* any news from our parent (signal pipe)? -> just stop the capture */
2949 if (!signal_pipe_check_running()) {
2950 global_ld.go = FALSE;
2955 global_ld.inpkts_to_sync_pipe += inpkts;
2957 /* check capture size condition */
2958 if (cnd_autostop_size != NULL &&
2959 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)) {
2960 /* Capture size limit reached, do we have another file? */
2961 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
2962 cnd_autostop_size, cnd_file_duration))
2964 } /* cnd_autostop_size */
2965 if (capture_opts->output_to_pipe) {
2966 libpcap_dump_flush(global_ld.pdh, NULL);
2970 /* Only update once a second (Win32: 500ms) so as not to overload slow
2971 * displays. This also prevents too much context-switching between the
2972 * dumpcap and wireshark processes */
2973 cur_time = TIME_GET();
2975 if ( (cur_time - upd_time) > 500) {
2977 if (cur_time - upd_time > 0) {
2979 upd_time = cur_time;
2981 /*if (pcap_stats(pch, stats) >= 0) {
2982 *stats_known = TRUE;
2985 /* Let the parent process know. */
2986 if (global_ld.inpkts_to_sync_pipe) {
2988 libpcap_dump_flush(global_ld.pdh, NULL);
2990 /* Send our parent a message saying we've written out
2991 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
2993 report_packet_count(global_ld.inpkts_to_sync_pipe);
2995 global_ld.inpkts_to_sync_pipe = 0;
2998 /* check capture duration condition */
2999 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3000 /* The maximum capture time has elapsed; stop the capture. */
3001 global_ld.go = FALSE;
3005 /* check capture file duration condition */
3006 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3007 /* duration limit reached, do we have another file? */
3008 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3009 cnd_autostop_size, cnd_file_duration))
3011 } /* cnd_file_duration */
3014 } /* while (global_ld.go) */
3016 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3018 /* delete stop conditions */
3019 if (cnd_file_duration != NULL)
3020 cnd_delete(cnd_file_duration);
3021 if (cnd_autostop_files != NULL)
3022 cnd_delete(cnd_autostop_files);
3023 if (cnd_autostop_size != NULL)
3024 cnd_delete(cnd_autostop_size);
3025 if (cnd_autostop_duration != NULL)
3026 cnd_delete(cnd_autostop_duration);
3028 /* did we had a pcap (input) error? */
3029 if (global_ld.pcap_err) {
3030 /* On Linux, if an interface goes down while you're capturing on it,
3031 you'll get a "recvfrom: Network is down" error (ENETDOWN).
3032 (At least you will if strerror() doesn't show a local translation
3035 On FreeBSD and OS X, if a network adapter disappears while
3036 you're capturing on it, you'll get a "read: Device not configured"
3037 error (ENXIO). (See previous parenthetical note.)
3039 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3041 These should *not* be reported to the Wireshark developers. */
3044 cap_err_str = pcap_geterr(global_ld.pcap_h);
3045 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3046 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3047 strcmp(cap_err_str, "read: I/O error") == 0) {
3048 report_capture_error("The network adapter on which the capture was being done "
3049 "is no longer running; the capture has stopped.",
3052 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3054 report_capture_error(errmsg, please_report);
3057 else if (global_ld.from_cap_pipe && global_ld.cap_pipe_err == PIPERR)
3058 report_capture_error(errmsg, "");
3060 /* did we had an error while capturing? */
3061 if (global_ld.err == 0) {
3064 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3065 global_ld.err, FALSE);
3066 report_capture_error(errmsg, please_report);
3070 if (capture_opts->saving_to_file) {
3071 /* close the wiretap (output) file */
3072 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3076 /* there might be packets not yet notified to the parent */
3077 /* (do this after closing the file, so all packets are already flushed) */
3078 if(global_ld.inpkts_to_sync_pipe) {
3080 report_packet_count(global_ld.inpkts_to_sync_pipe);
3081 global_ld.inpkts_to_sync_pipe = 0;
3084 /* If we've displayed a message about a write error, there's no point
3085 in displaying another message about an error on close. */
3086 if (!close_ok && write_ok) {
3087 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3089 report_capture_error(errmsg, "");
3093 * XXX We exhibit different behaviour between normal mode and sync mode
3094 * when the pipe is stdin and not already at EOF. If we're a child, the
3095 * parent's stdin isn't closed, so if the user starts another capture,
3096 * cap_pipe_open_live() will very likely not see the expected magic bytes and
3097 * will say "Unrecognized libpcap format". On the other hand, in normal
3098 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3101 /* get packet drop statistics from pcap */
3102 if(global_ld.pcap_h != NULL) {
3103 g_assert(!global_ld.from_cap_pipe);
3104 /* Get the capture statistics, so we know how many packets were
3106 if (pcap_stats(global_ld.pcap_h, stats) >= 0) {
3107 *stats_known = TRUE;
3108 /* Let the parent process know. */
3109 report_packet_drops(stats->ps_drop);
3111 g_snprintf(errmsg, sizeof(errmsg),
3112 "Can't get packet-drop statistics: %s",
3113 pcap_geterr(global_ld.pcap_h));
3114 report_capture_error(errmsg, please_report);
3118 /* close the input file (pcap or capture pipe) */
3119 capture_loop_close_input(&global_ld);
3121 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
3123 /* ok, if the write and the close were successful. */
3124 return write_ok && close_ok;
3127 if (capture_opts->multi_files_on) {
3128 /* cleanup ringbuffer */
3129 ringbuf_error_cleanup();
3131 /* We can't use the save file, and we have no FILE * for the stream
3132 to close in order to close it, so close the FD directly. */
3133 if(global_ld.save_file_fd != -1) {
3134 ws_close(global_ld.save_file_fd);
3137 /* We couldn't even start the capture, so get rid of the capture
3139 if(capture_opts->save_file != NULL) {
3140 ws_unlink(capture_opts->save_file);
3141 g_free(capture_opts->save_file);
3144 capture_opts->save_file = NULL;
3146 report_cfilter_error(capture_opts->cfilter, errmsg);
3148 report_capture_error(errmsg, secondary_errmsg);
3150 /* close the input file (pcap or cap_pipe) */
3151 capture_loop_close_input(&global_ld);
3153 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3159 static void capture_loop_stop(void)
3161 #ifdef HAVE_PCAP_BREAKLOOP
3162 if(global_ld.pcap_h != NULL)
3163 pcap_breakloop(global_ld.pcap_h);
3165 global_ld.go = FALSE;
3170 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3171 int err, gboolean is_close)
3176 g_snprintf(errmsg, errmsglen,
3177 "Not all the packets could be written to the file"
3178 " to which the capture was being saved\n"
3179 "(\"%s\") because there is no space left on the file system\n"
3180 "on which that file resides.",
3186 g_snprintf(errmsg, errmsglen,
3187 "Not all the packets could be written to the file"
3188 " to which the capture was being saved\n"
3189 "(\"%s\") because you are too close to, or over,"
3190 " your disk quota\n"
3191 "on the file system on which that file resides.",
3196 case WTAP_ERR_CANT_CLOSE:
3197 g_snprintf(errmsg, errmsglen,
3198 "The file to which the capture was being saved"
3199 " couldn't be closed for some unknown reason.");
3202 case WTAP_ERR_SHORT_WRITE:
3203 g_snprintf(errmsg, errmsglen,
3204 "Not all the packets could be written to the file"
3205 " to which the capture was being saved\n"
3212 g_snprintf(errmsg, errmsglen,
3213 "The file to which the capture was being saved\n"
3214 "(\"%s\") could not be closed: %s.",
3215 fname, wtap_strerror(err));
3217 g_snprintf(errmsg, errmsglen,
3218 "An error occurred while writing to the file"
3219 " to which the capture was being saved\n"
3221 fname, wtap_strerror(err));
3228 /* one packet was captured, process it */
3230 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
3233 loop_data *ld = (loop_data *) (void *) user;
3236 /* We may be called multiple times from pcap_dispatch(); if we've set
3237 the "stop capturing" flag, ignore this packet, as we're not
3238 supposed to be saving any more packets. */
3243 gboolean successful;
3244 /* We're supposed to write the packet to a file; do so.
3245 If this fails, set "ld->go" to FALSE, to stop the capture, and set
3246 "ld->err" to the error. */
3247 if (global_capture_opts.use_pcapng) {
3248 successful = libpcap_write_enhanced_packet_block(ld->pdh, phdr, 0, pd, &ld->bytes_written, &err);
3250 successful = libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err);
3257 /* if the user told us to stop after x packets, do we already have enough? */
3258 if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
3267 /* And now our feature presentation... [ fade to music ] */
3269 main(int argc, char *argv[])
3272 gboolean arg_error = FALSE;
3276 typedef BOOL (*SetDllDirectoryHandler)(LPCTSTR);
3277 SetDllDirectoryHandler PSetDllDirectory;
3279 struct sigaction action, oldaction;
3282 gboolean start_capture = TRUE;
3283 gboolean stats_known;
3284 struct pcap_stat stats;
3285 GLogLevelFlags log_flags;
3286 gboolean list_interfaces = FALSE;
3287 gboolean list_link_layer_types = FALSE;
3288 #ifdef HAVE_BPF_IMAGE
3289 gboolean print_bpf_code = FALSE;
3291 gboolean machine_readable = FALSE;
3292 gboolean print_statistics = FALSE;
3293 int status, run_once_args = 0;
3295 #if defined(__APPLE__) && defined(__LP64__)
3296 struct utsname osinfo;
3299 if (PSetDllDirectory = (SetDllDirectoryHandler) GetProcAddress(GetModuleHandle(_T("kernel32.dll")), "SetDllDirectoryW")) {
3300 PSetDllDirectory(_T(""));
3301 /* XXX - Exit on failure? */
3304 #ifdef HAVE_PCAP_REMOTE
3305 #define OPTSTRING_A "A:"
3306 #define OPTSTRING_r "r"
3307 #define OPTSTRING_u "u"
3309 #define OPTSTRING_A ""
3310 #define OPTSTRING_r ""
3311 #define OPTSTRING_u ""
3314 #ifdef HAVE_PCAP_SETSAMPLING
3315 #define OPTSTRING_m "m:"
3317 #define OPTSTRING_m ""
3320 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
3321 #define OPTSTRING_B "B:"
3323 #define OPTSTRING_B ""
3324 #endif /* _WIN32 or HAVE_PCAP_CREATE */
3326 #ifdef HAVE_PCAP_CREATE
3327 #define OPTSTRING_I "I"
3329 #define OPTSTRING_I ""
3332 #ifdef HAVE_BPF_IMAGE
3333 #define OPTSTRING_d "d"
3335 #define OPTSTRING_d ""
3338 #define OPTSTRING "a:" OPTSTRING_A "b:" OPTSTRING_B "c:" OPTSTRING_d "Df:hi:" OPTSTRING_I "L" OPTSTRING_m "Mnpq" OPTSTRING_r "Ss:" OPTSTRING_u "vw:y:Z:"
3340 #ifdef DEBUG_CHILD_DUMPCAP
3341 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
3342 fprintf (stderr, "Unable to open debug log file !\n");
3347 #if defined(__APPLE__) && defined(__LP64__)
3349 * Is this Mac OS X 10.6.x, other than 10.6.2? If so, we need a bug
3350 * workaround - timeouts less than 1 second don't work with libpcap
3351 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
3352 * and re-introduced in 10.6.3. We don't know whether it'll be fixed
3353 * again in a later 10.6.x release; we'll assume that it'll be fixed
3354 * in any future major releases.)
3356 if (uname(&osinfo) == 0) {
3358 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
3359 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
3360 * number of 10.0.0, not 10.1.0 - go figure).
3362 if (strncmp(osinfo.release, "10.", 3) == 0) {
3364 * OK, it's Snow Leopard - which version?
3366 if (strcmp(osinfo.release, "10.2.0") != 0) {
3368 need_timeout_workaround = TRUE;
3375 * Determine if dumpcap is being requested to run in a special
3376 * capture_child mode by going thru the command line args to see if
3377 * a -Z is present. (-Z is a hidden option).
3379 * The primary result of running in capture_child mode is that
3380 * all messages sent out on stderr are in a special type/len/string
3381 * format to allow message processing by type. These messages include
3382 * error messages if dumpcap fails to start the operation it was
3383 * requested to do, as well as various "status" messages which are sent
3384 * when an actual capture is in progress, and a "success" message sent
3385 * if dumpcap was requested to perform an operation other than a
3388 * Capture_child mode would normally be requested by a parent process
3389 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
3390 * to which dumpcap stderr has been redirected. It might also have
3391 * another pipe to obtain dumpcap stdout output; for operations other
3392 * than a capture, that information is formatted specially for easier
3393 * parsing by the parent process.
3395 * Capture_child mode needs to be determined immediately upon
3396 * startup so that any messages generated by dumpcap in this mode
3397 * (eg: during initialization) will be formatted properly.
3400 for (i=1; i<argc; i++) {
3401 if (strcmp("-Z", argv[i]) == 0) {
3402 capture_child = TRUE;
3403 machine_readable = TRUE; /* request machine-readable output */
3405 /* set output pipe to binary mode, to avoid ugly text conversions */
3406 _setmode(2, O_BINARY);
3411 /* The default_log_handler will use stdout, which makes trouble in */
3412 /* capture child mode, as it uses stdout for it's sync_pipe. */
3413 /* So: the filtering is done in the console_log_handler and not here.*/
3414 /* We set the log handlers right up front to make sure that any log */
3415 /* messages when running as child will be sent back to the parent */
3416 /* with the correct format. */
3420 G_LOG_LEVEL_CRITICAL|
3421 G_LOG_LEVEL_WARNING|
3422 G_LOG_LEVEL_MESSAGE|
3425 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
3427 g_log_set_handler(NULL,
3429 console_log_handler, NULL /* user_data */);
3430 g_log_set_handler(LOG_DOMAIN_MAIN,
3432 console_log_handler, NULL /* user_data */);
3433 g_log_set_handler(LOG_DOMAIN_CAPTURE,
3435 console_log_handler, NULL /* user_data */);
3436 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
3438 console_log_handler, NULL /* user_data */);
3441 /* Load wpcap if possible. Do this before collecting the run-time version information */
3444 /* ... and also load the packet.dll from wpcap */
3445 /* XXX - currently not required, may change later. */
3446 /*wpcap_packet_load();*/
3448 /* Start windows sockets */
3449 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
3451 /* Set handler for Ctrl+C key */
3452 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
3454 /* Prepare to read from a pipe */
3455 if (!g_thread_supported ())
3456 g_thread_init (NULL);
3457 cap_pipe_pending_q = g_async_queue_new();
3458 cap_pipe_done_q = g_async_queue_new();
3459 cap_pipe_read_mtx = g_mutex_new();
3462 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
3464 action.sa_handler = capture_cleanup_handler;
3466 * Arrange that system calls not get restarted, because when
3467 * our signal handler returns we don't want to restart
3468 * a call that was waiting for packets to arrive.
3470 action.sa_flags = 0;
3471 sigemptyset(&action.sa_mask);
3472 sigaction(SIGTERM, &action, NULL);
3473 sigaction(SIGINT, &action, NULL);
3474 sigaction(SIGPIPE, &action, NULL);
3475 sigaction(SIGHUP, NULL, &oldaction);
3476 if (oldaction.sa_handler == SIG_DFL)
3477 sigaction(SIGHUP, &action, NULL);
3480 /* Catch SIGINFO and, if we get it and we're capturing in
3481 quiet mode, report the number of packets we've captured. */
3482 action.sa_handler = report_counts_siginfo;
3483 action.sa_flags = SA_RESTART;
3484 sigemptyset(&action.sa_mask);
3485 sigaction(SIGINFO, &action, NULL);
3486 #endif /* SIGINFO */
3489 /* ----------------------------------------------------------------- */
3490 /* Privilege and capability handling */
3492 /* 1. Running not as root or suid root; no special capabilities. */
3495 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
3498 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
3500 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
3501 /* capabilities; Drop all other capabilities; */
3502 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3503 /* else: after pcap_open_live() in capture_loop_open_input() */
3504 /* drop all capabilities (NET_RAW and NET_ADMIN); */
3505 /* (Note: this means that the process, although logged in */
3506 /* as root, does not have various permissions such as the */
3507 /* ability to bypass file access permissions). */
3508 /* XXX: Should we just leave capabilities alone in this case */
3509 /* so that user gets expected effect that root can do */
3512 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
3514 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3515 /* else: after pcap_open_live() in capture_loop_open_input() */
3516 /* drop suid root (set euid=ruid).(ie: keep suid until after */
3517 /* pcap_open_live). */
3519 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
3521 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
3522 /* capabilities; Drop all other capabilities; */
3523 /* Drop suid privileges (euid=ruid); */
3524 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3525 /* else: after pcap_open_live() in capture_loop_open_input() */
3526 /* drop all capabilities (NET_RAW and NET_ADMIN). */
3528 /* XXX: For some Linux versions/distros with capabilities */
3529 /* a 'normal' process with any capabilities cannot be */
3530 /* 'killed' (signaled) from another (same uid) non-privileged */
3532 /* For example: If (non-suid) Wireshark forks a */
3533 /* child suid dumpcap which acts as described here (case 5), */
3534 /* Wireshark will be unable to kill (signal) the child */
3535 /* dumpcap process until the capabilities have been dropped */
3536 /* (after pcap_open_live()). */
3537 /* This behaviour will apparently be changed in the kernel */
3538 /* to allow the kill (signal) in this case. */
3539 /* See the following for details: */
3540 /* http://www.mail-archive.com/ [wrapped] */
3541 /* linux-security-module@vger.kernel.org/msg02913.html */
3543 /* It is therefore conceivable that if dumpcap somehow hangs */
3544 /* in pcap_open_live or before that wireshark will not */
3545 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
3546 /* In this case, exiting wireshark will kill the child */
3547 /* dumpcap process. */
3549 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
3550 /* capabilities; Using libcap. Note: capset cmd (which see) */
3551 /* used to assign capabilities to file. */
3553 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3554 /* else: after pcap_open_live() in capture_loop_open_input() */
3555 /* drop all capabilities (NET_RAW and NET_ADMIN) */
3557 /* ToDo: -S (stats) should drop privileges/capabilities when no */
3558 /* longer required (similar to capture). */
3560 /* ----------------------------------------------------------------- */
3562 get_credential_info();
3565 /* If 'started with special privileges' (and using libcap) */
3566 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
3567 /* Set euid/egid = ruid/rgid to remove suid privileges */
3568 relinquish_privs_except_capture();
3571 /* Set the initial values in the capture options. This might be overwritten
3572 by the command line parameters. */
3573 capture_opts_init(&global_capture_opts, NULL);
3575 /* Default to capturing the entire packet. */
3576 global_capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
3578 /* We always save to a file - if no file was specified, we save to a
3580 global_capture_opts.saving_to_file = TRUE;
3581 global_capture_opts.has_ring_num_files = TRUE;
3583 /* Now get our args */
3584 while ((opt = getopt(argc, argv, OPTSTRING)) != -1) {
3586 case 'h': /* Print help and exit */
3590 case 'v': /* Show version and exit */
3592 GString *comp_info_str;
3593 GString *runtime_info_str;
3594 /* Assemble the compile-time version information string */
3595 comp_info_str = g_string_new("Compiled ");
3596 get_compiled_version_info(comp_info_str, NULL);
3598 /* Assemble the run-time version information string */
3599 runtime_info_str = g_string_new("Running ");
3600 get_runtime_version_info(runtime_info_str, NULL);
3601 show_version(comp_info_str, runtime_info_str);
3602 g_string_free(comp_info_str, TRUE);
3603 g_string_free(runtime_info_str, TRUE);
3607 /*** capture option specific ***/
3608 case 'a': /* autostop criteria */
3609 case 'b': /* Ringbuffer option */
3610 case 'c': /* Capture x packets */
3611 case 'f': /* capture filter */
3612 case 'i': /* Use interface x */
3613 case 'n': /* Use pcapng format */
3614 case 'p': /* Don't capture in promiscuous mode */
3615 case 's': /* Set the snapshot (capture) length */
3616 case 'w': /* Write to capture file x */
3617 case 'y': /* Set the pcap data link type */
3618 #ifdef HAVE_PCAP_REMOTE
3619 case 'u': /* Use UDP for data transfer */
3620 case 'r': /* Capture own RPCAP traffic too */
3621 case 'A': /* Authentication */
3623 #ifdef HAVE_PCAP_SETSAMPLING
3624 case 'm': /* Sampling */
3626 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
3627 case 'B': /* Buffer size */
3628 #endif /* _WIN32 or HAVE_PCAP_CREATE */
3629 #ifdef HAVE_PCAP_CREATE
3630 case 'I': /* Monitor mode */
3632 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
3637 /*** hidden option: Wireshark child mode (using binary output messages) ***/
3639 capture_child = TRUE;
3641 /* set output pipe to binary mode, to avoid ugly text conversions */
3642 _setmode(2, O_BINARY);
3644 * optarg = the control ID, aka the PPID, currently used for the
3647 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
3648 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
3649 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
3650 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
3652 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
3653 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3654 "Signal pipe: Unable to open %s. Dead parent?",
3662 case 'q': /* Quiet */
3666 /*** all non capture option specific ***/
3667 case 'D': /* Print a list of capture devices and exit */
3668 list_interfaces = TRUE;
3671 case 'L': /* Print list of link-layer types and exit */
3672 list_link_layer_types = TRUE;
3675 #ifdef HAVE_BPF_IMAGE
3676 case 'd': /* Print BPF code for capture filter and exit */
3677 print_bpf_code = TRUE;
3681 case 'S': /* Print interface statistics once a second */
3682 print_statistics = TRUE;
3685 case 'M': /* For -D, -L, and -S, print machine-readable output */
3686 machine_readable = TRUE;
3689 case '?': /* Bad flag - print usage message */
3690 cmdarg_err("Invalid Option: %s", argv[optind-1]);
3698 /* user specified file name as regular command-line argument */
3699 /* XXX - use it as the capture file name (or something else)? */
3706 * Extra command line arguments were specified; complain.
3707 * XXX - interpret as capture filter, as tcpdump and tshark do?
3709 cmdarg_err("Invalid argument: %s", argv[0]);
3718 if (run_once_args > 1) {
3719 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
3721 } else if (run_once_args == 1) {
3722 /* We're supposed to print some information, rather than
3723 to capture traffic; did they specify a ring buffer option? */
3724 if (global_capture_opts.multi_files_on) {
3725 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
3729 /* We're supposed to capture traffic; was the ring buffer option
3730 specified and, if so, does it make sense? */
3731 if (global_capture_opts.multi_files_on) {
3732 /* Ring buffer works only under certain conditions:
3733 a) ring buffer does not work with temporary files;
3734 b) it makes no sense to enable the ring buffer if the maximum
3735 file size is set to "infinite". */
3736 if (global_capture_opts.save_file == NULL) {
3737 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
3738 global_capture_opts.multi_files_on = FALSE;
3740 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
3741 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
3742 /* XXX - this must be redesigned as the conditions changed */
3743 /* global_capture_opts.multi_files_on = FALSE;*/
3749 * "-D" requires no interface to be selected; it's supposed to list
3752 if (list_interfaces) {
3753 /* Get the list of interfaces */
3758 if_list = capture_interface_list(&err, &err_str);
3759 if (if_list == NULL) {
3761 case CANT_GET_INTERFACE_LIST:
3762 cmdarg_err("%s", err_str);
3767 case NO_INTERFACES_FOUND:
3769 * If we're being run by another program, just give them
3770 * an empty list of interfaces, don't report this as
3771 * an error; that lets them decide whether to report
3772 * this as an error or not.
3774 if (!machine_readable) {
3775 cmdarg_err("There are no interfaces on which a capture can be done");
3782 if (machine_readable) /* tab-separated values to stdout */
3783 print_machine_readable_interfaces(if_list);
3785 capture_opts_print_interfaces(if_list);
3786 free_interface_list(if_list);
3791 * "-S" requires no interface to be selected; it gives statistics
3792 * for all interfaces.
3794 if (print_statistics) {
3795 status = print_statistics_loop(machine_readable);
3800 * "-L", "-d", and capturing act on a particular interface, so we have to
3801 * have an interface; if none was specified, pick a default.
3803 if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
3804 /* cmdarg_err() already called .... */
3808 /* Let the user know what interface was chosen. */
3809 /* get_interface_descriptive_name() is not available! */
3810 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", global_capture_opts.iface);
3812 if (list_link_layer_types) {
3813 /* Get the list of link-layer types for the capture device. */
3814 if_capabilities_t *caps;
3817 caps = get_if_capabilities(global_capture_opts.iface,
3818 global_capture_opts.monitor_mode, &err_str);
3820 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
3821 "Please check to make sure you have sufficient permissions, and that\n"
3822 "you have the proper interface or pipe specified.", global_capture_opts.iface, err_str);
3826 if (caps->data_link_types == NULL) {
3827 cmdarg_err("The capture device \"%s\" has no data link types.", global_capture_opts.iface);
3830 if (machine_readable) /* tab-separated values to stdout */
3831 print_machine_readable_if_capabilities(caps);
3833 capture_opts_print_if_capabilities(caps,
3834 global_capture_opts.monitor_mode);
3835 free_if_capabilities(caps);
3839 /* We're supposed to do a capture, or print the BPF code for a filter.
3840 Process the snapshot length, as that affects the generated BPF code. */
3841 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
3843 #ifdef HAVE_BPF_IMAGE
3844 if (print_bpf_code) {
3845 show_filter_code(&global_capture_opts);
3850 /* We're supposed to do a capture. Process the ring buffer arguments. */
3851 capture_opts_trim_ring_num_files(&global_capture_opts);
3853 /* Now start the capture. */
3855 if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
3859 /* capture failed */
3866 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
3867 const char *message, gpointer user_data _U_)
3874 /* ignore log message, if log_level isn't interesting */
3875 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3876 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
3881 /* create a "timestamp" */
3883 today = localtime(&curr);
3885 switch(log_level & G_LOG_LEVEL_MASK) {
3886 case G_LOG_LEVEL_ERROR:
3889 case G_LOG_LEVEL_CRITICAL:
3892 case G_LOG_LEVEL_WARNING:
3895 case G_LOG_LEVEL_MESSAGE:
3898 case G_LOG_LEVEL_INFO:
3901 case G_LOG_LEVEL_DEBUG:
3905 fprintf(stderr, "unknown log_level %u\n", log_level);
3907 g_assert_not_reached();
3910 /* Generate the output message */
3911 if(log_level & G_LOG_LEVEL_MESSAGE) {
3912 /* normal user messages without additional infos */
3913 msg = g_strdup_printf("%s\n", message);
3915 /* info/debug messages with additional infos */
3916 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
3917 today->tm_hour, today->tm_min, today->tm_sec,
3918 log_domain != NULL ? log_domain : "",
3922 /* DEBUG & INFO msgs (if we're debugging today) */
3923 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3924 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3925 #ifdef DEBUG_DUMPCAP
3926 fprintf(stderr, "%s", msg);
3929 #ifdef DEBUG_CHILD_DUMPCAP
3930 fprintf(debug_log, "%s", msg);
3938 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
3939 /* to parent especially formatted if dumpcap running as child. */
3940 if (capture_child) {
3941 sync_pipe_errmsg_to_parent(2, msg, "");
3943 fprintf(stderr, "%s", msg);
3950 /****************************************************************************************************************/
3951 /* indication report routines */
3955 report_packet_count(int packet_count)
3957 char tmp[SP_DECISIZE+1+1];
3958 static int count = 0;
3961 g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
3962 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
3963 pipe_write_block(2, SP_PACKET_COUNT, tmp);
3965 count += packet_count;
3966 fprintf(stderr, "\rPackets: %u ", count);
3967 /* stderr could be line buffered */
3973 report_new_capture_file(const char *filename)
3976 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
3977 pipe_write_block(2, SP_FILE, filename);
3981 * Prevent a SIGINFO handler from writing to the standard error
3982 * while we're doing so; instead, have it just set a flag telling
3983 * us to print that information when we're done.
3986 #endif /* SIGINFO */
3987 fprintf(stderr, "File: %s\n", filename);
3988 /* stderr could be line buffered */
3993 * Allow SIGINFO handlers to write.
3998 * If a SIGINFO handler asked us to write out capture counts, do so.
4002 #endif /* SIGINFO */
4007 report_cfilter_error(const char *cfilter, const char *errmsg)
4009 if (capture_child) {
4010 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
4011 pipe_write_block(2, SP_BAD_FILTER, errmsg);
4014 "Invalid capture filter: \"%s\"!\n"
4016 "That string isn't a valid capture filter (%s).\n"
4017 "See the User's Guide for a description of the capture filter syntax.\n",
4023 report_capture_error(const char *error_msg, const char *secondary_error_msg)
4026 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4027 "Primary Error: %s", error_msg);
4028 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4029 "Secondary Error: %s", secondary_error_msg);
4030 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
4032 fprintf(stderr, "%s\n", error_msg);
4033 if (secondary_error_msg[0] != '\0')
4034 fprintf(stderr, "%s\n", secondary_error_msg);
4039 report_packet_drops(guint32 drops)
4041 char tmp[SP_DECISIZE+1+1];
4043 g_snprintf(tmp, sizeof(tmp), "%u", drops);
4046 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
4047 pipe_write_block(2, SP_DROPS, tmp);
4049 fprintf(stderr, "Packets dropped: %s\n", tmp);
4050 /* stderr could be line buffered */
4056 /****************************************************************************************************************/
4057 /* signal_pipe handling */
4062 signal_pipe_check_running(void)
4064 /* any news from our parent? -> just stop the capture */
4068 /* if we are running standalone, no check required */
4069 if(!capture_child) {
4073 if(!sig_pipe_name || !sig_pipe_handle) {
4074 /* This shouldn't happen */
4075 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4076 "Signal pipe: No name or handle");
4081 * XXX - We should have the process ID of the parent (from the "-Z" flag)
4082 * at this point. Should we check to see if the parent is still alive,
4083 * e.g. by using OpenProcess?
4086 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
4088 if(!result || avail > 0) {
4089 /* peek failed or some bytes really available */
4090 /* (if not piping from stdin this would fail) */
4091 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4092 "Signal pipe: Stop capture: %s", sig_pipe_name);
4093 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4094 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
4095 sig_pipe_handle, result, avail);
4098 /* pipe ok and no bytes available */
4105 * Editor modelines - http://www.wireshark.org/tools/modelines.html
4110 * indent-tabs-mode: nil
4113 * vi: set shiftwidth=4 tabstop=8 expandtab
4114 * :indentSize=4:tabSize=8:noTabs=true: