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>
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 "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;
147 /** Stop a low-level capture (stops the capture child). */
148 static void capture_loop_stop(void);
150 #if !defined (__linux__)
151 #ifndef HAVE_PCAP_BREAKLOOP
153 * We don't have pcap_breakloop(), which is the only way to ensure that
154 * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
155 * won't, if the call to read the next packet or batch of packets is
156 * is interrupted by a signal on UN*X, just go back and try again to
159 * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
160 * the signal handler, set a flag to stop capturing; however, without
161 * a guarantee of that sort, we can't guarantee that we'll stop capturing
162 * if the read will be retried and won't time out if no packets arrive.
164 * Therefore, on at least some platforms, we work around the lack of
165 * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
166 * to wait for packets to arrive, so that we're probably going to be
167 * blocked in the select() when the signal arrives, and can just bail
168 * out of the loop at that point.
170 * However, we don't want to that on BSD (because "select()" doesn't work
171 * correctly on BPF devices on at least some releases of some flavors of
172 * BSD), and we don't want to do it on Windows (because "select()" is
173 * something for sockets, not for arbitrary handles). (Note that "Windows"
174 * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
175 * using WinPcap, not a UNIX libpcap.)
177 * Fortunately, we don't need to do it on BSD, because the libpcap timeout
178 * on BSD times out even if no packets have arrived, so we'll eventually
179 * exit pcap_dispatch() with an indication that no packets have arrived,
180 * and will break out of the capture loop at that point.
182 * On Windows, we can't send a SIGINT to stop capturing, so none of this
183 * applies in any case.
185 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
186 * want to include it if it's not present on this platform, however.
188 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
189 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
191 # define MUST_DO_SELECT
192 # endif /* avoid select */
193 #endif /* HAVE_PCAP_BREAKLOOP */
195 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
196 * in pcap_dispatch(); on the other hand, select() works just fine there.
197 * Hence we use a select for that come what may.
199 #define MUST_DO_SELECT
202 /** init the capture filter */
205 INITFILTER_BAD_FILTER,
206 INITFILTER_OTHER_ERROR
207 } initfilter_status_t;
209 typedef struct _loop_data {
211 gboolean go; /* TRUE as long as we're supposed to keep capturing */
212 int err; /* if non-zero, error seen while capturing */
213 gint packet_count; /* Number of packets we have already captured */
214 gint packet_max; /* Number of packets we're supposed to capture - 0 means infinite */
216 /* pcap "input file" */
217 pcap_t *pcap_h; /* pcap handle */
218 gboolean pcap_err; /* TRUE if error from pcap */
219 #ifdef MUST_DO_SELECT
220 int pcap_fd; /* pcap file descriptor */
223 /* capture pipe (unix only "input file") */
224 gboolean from_cap_pipe; /* TRUE if we are capturing data from a capture pipe */
225 struct pcap_hdr cap_pipe_hdr; /* Pcap header when capturing from a pipe */
226 struct pcaprec_modified_hdr cap_pipe_rechdr; /* Pcap record header when capturing from a pipe */
228 HANDLE cap_pipe_h; /* The handle of the capture pipe */
230 int cap_pipe_fd; /* the file descriptor of the capture pipe */
232 gboolean cap_pipe_modified; /* TRUE if data in the pipe uses modified pcap headers */
233 gboolean cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
235 char * cap_pipe_buf; /* Pointer to the data buffer we read into */
236 #endif /* USE_THREADS */
237 int cap_pipe_bytes_to_read;/* Used by cap_pipe_dispatch */
238 int cap_pipe_bytes_read; /* Used by cap_pipe_dispatch */
240 STATE_EXPECT_REC_HDR,
245 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
257 * Standard secondary message for unexpected errors.
259 static const char please_report[] =
260 "Please report this to the Wireshark developers.\n"
261 "(This is not a crash; please do not report it as such.)";
264 * This needs to be static, so that the SIGINT handler can clear the "go"
267 static loop_data global_ld;
271 * Timeout, in milliseconds, for reads from the stream of captured packets.
273 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
274 * 64-bit applications, with sub-second timeouts not to work. The bug is
277 #if defined(__APPLE__) && defined(__LP64__)
278 static gboolean need_timeout_workaround;
280 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
282 #define CAP_READ_TIMEOUT 250
286 * Timeout, in microseconds, for threaded reads from a pipe.
288 #define THREAD_READ_TIMEOUT 100
289 static const char *cap_pipe_err_str;
292 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
293 const char *message, gpointer user_data _U_);
295 /* capture related options */
296 static capture_options global_capture_opts;
298 static void capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
300 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
301 int err, gboolean is_close);
303 static void exit_main(int err) G_GNUC_NORETURN;
305 static void report_new_capture_file(const char *filename);
306 static void report_packet_count(int packet_count);
307 static void report_packet_drops(guint32 drops);
308 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
309 static void report_cfilter_error(const char *cfilter, const char *errmsg);
312 print_usage(gboolean print_ver) {
320 "Dumpcap " VERSION "%s\n"
321 "Capture network packets and dump them into a libpcap file.\n"
322 "See http://www.wireshark.org for more information.\n",
323 wireshark_svnversion);
327 fprintf(output, "\nUsage: dumpcap [options] ...\n");
328 fprintf(output, "\n");
329 fprintf(output, "Capture interface:\n");
330 fprintf(output, " -i <interface> name or idx of interface (def: first non-loopback)\n");
331 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
332 fprintf(output, " -s <snaplen> packet snapshot length (def: 65535)\n");
333 fprintf(output, " -p don't capture in promiscuous mode\n");
334 #ifdef HAVE_PCAP_CREATE
335 fprintf(output, " -I capture in monitor mode, if available\n");
337 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
338 fprintf(output, " -B <buffer size> size of kernel buffer (def: 1MB)\n");
340 fprintf(output, " -y <link type> link layer type (def: first appropriate)\n");
341 fprintf(output, " -D print list of interfaces and exit\n");
342 fprintf(output, " -L print list of link-layer types of iface and exit\n");
343 fprintf(output, " -S print statistics for each interface once every second\n");
344 fprintf(output, " -M for -D, -L, and -S produce machine-readable output\n");
345 fprintf(output, "\n");
346 #ifdef HAVE_PCAP_REMOTE
347 fprintf(output, "\nRPCAP options:\n");
348 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
349 fprintf(output, " -u use UDP for RPCAP data transfer\n");
350 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
351 #ifdef HAVE_PCAP_SETSAMPLING
352 fprintf(output, " -m <sampling type> use packet sampling\n");
353 fprintf(output, " count:NUM - capture one packet of every NUM\n");
354 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
357 fprintf(output, "Stop conditions:\n");
358 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
359 fprintf(output, " -a <autostop cond.> ... duration:NUM - stop after NUM seconds\n");
360 fprintf(output, " filesize:NUM - stop this file after NUM KB\n");
361 fprintf(output, " files:NUM - stop after NUM files\n");
362 /*fprintf(output, "\n");*/
363 fprintf(output, "Output (files):\n");
364 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
365 fprintf(output, " -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
366 fprintf(output, " filesize:NUM - switch to next file after NUM KB\n");
367 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
368 fprintf(output, " -n use pcapng format instead of pcap\n");
369 /*fprintf(output, "\n");*/
370 fprintf(output, "Miscellaneous:\n");
371 fprintf(output, " -v print version information and exit\n");
372 fprintf(output, " -h display this help and exit\n");
373 fprintf(output, "\n");
374 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcap\n");
375 fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcap\"\n");
376 fprintf(output, "\n");
377 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
381 show_version(GString *comp_info_str, GString *runtime_info_str)
385 "Dumpcap " VERSION "%s\n"
390 "See http://www.wireshark.org for more information.\n",
391 wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
395 * Print to the standard error. This is a command-line tool, so there's
396 * no need to pop up a console.
399 vfprintf_stderr(const char *fmt, va_list ap)
401 vfprintf(stderr, fmt, ap);
405 fprintf_stderr(const char *fmt, ...)
410 vfprintf_stderr(fmt, ap);
415 * Report an error in command-line arguments.
418 cmdarg_err(const char *fmt, ...)
424 /* Generate a 'special format' message back to parent */
426 msg = g_strdup_vprintf(fmt, ap);
427 sync_pipe_errmsg_to_parent(2, msg, "");
432 fprintf(stderr, "dumpcap: ");
433 vfprintf(stderr, fmt, ap);
434 fprintf(stderr, "\n");
440 * Report additional information for an error in command-line arguments.
443 cmdarg_err_cont(const char *fmt, ...)
450 msg = g_strdup_vprintf(fmt, ap);
451 sync_pipe_errmsg_to_parent(2, msg, "");
456 vfprintf(stderr, fmt, ap);
457 fprintf(stderr, "\n");
463 * capture_interface_list() is expected to do the right thing to get
464 * a list of interfaces.
466 * In most of the programs in the Wireshark suite, "the right thing"
467 * is to run dumpcap and ask it for the list, because dumpcap may
468 * be the only program in the suite with enough privileges to get
471 * In dumpcap itself, however, we obviously can't run dumpcap to
472 * ask for the list. Therefore, our capture_interface_list() should
473 * just call get_interface_list().
476 capture_interface_list(int *err, char **err_str)
478 return get_interface_list(err, err_str);
482 * Get the data-link types available for a libpcap device.
484 static data_link_info_t *
485 create_data_link_info(int dlt)
487 data_link_info_t *data_link_info;
490 data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
491 data_link_info->dlt = dlt;
492 text = pcap_datalink_val_to_name(dlt);
494 data_link_info->name = g_strdup(text);
496 data_link_info->name = g_strdup_printf("DLT %d", dlt);
497 text = pcap_datalink_val_to_description(dlt);
499 data_link_info->description = g_strdup(text);
501 data_link_info->description = NULL;
502 return data_link_info;
506 get_pcap_linktype_list(const char *devname, char **err_str)
508 GList *linktype_list = NULL;
511 char errbuf[PCAP_ERRBUF_SIZE];
512 #ifdef HAVE_PCAP_LIST_DATALINKS
516 data_link_info_t *data_link_info;
518 #ifdef HAVE_PCAP_OPEN
519 pch = pcap_open(devname, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
521 pch = pcap_open_live(devname, MIN_PACKET_SIZE, 0, 0, errbuf);
525 *err_str = g_strdup(errbuf);
528 deflt = get_pcap_linktype(pch, devname);
529 #ifdef HAVE_PCAP_LIST_DATALINKS
530 nlt = pcap_list_datalinks(pch, &linktypes);
531 if (nlt == 0 || linktypes == NULL) {
534 *err_str = NULL; /* an empty list doesn't mean an error */
537 for (i = 0; i < nlt; i++) {
538 data_link_info = create_data_link_info(linktypes[i]);
541 * XXX - for 802.11, make the most detailed 802.11
542 * version the default, rather than the one the
543 * device has as the default?
545 if (linktypes[i] == deflt)
546 linktype_list = g_list_prepend(linktype_list, data_link_info);
548 linktype_list = g_list_append(linktype_list, data_link_info);
550 #ifdef HAVE_PCAP_FREE_DATALINKS
551 pcap_free_datalinks(linktypes);
554 * In Windows, there's no guarantee that if you have a library
555 * built with one version of the MSVC++ run-time library, and
556 * it returns a pointer to allocated data, you can free that
557 * data from a program linked with another version of the
558 * MSVC++ run-time library.
560 * This is not an issue on UN*X.
562 * See the mail threads starting at
564 * http://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
568 * http://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
571 #define xx_free free /* hack so checkAPIs doesn't complain */
574 #endif /* HAVE_PCAP_FREE_DATALINKS */
575 #else /* HAVE_PCAP_LIST_DATALINKS */
577 data_link_info = create_data_link_info(deflt);
578 linktype_list = g_list_append(linktype_list, data_link_info);
579 #endif /* HAVE_PCAP_LIST_DATALINKS */
585 return linktype_list;
588 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
590 print_machine_readable_interfaces(GList *if_list)
597 char addr_str[ADDRSTRLEN];
599 i = 1; /* Interface id number */
600 for (if_entry = g_list_first(if_list); if_entry != NULL;
601 if_entry = g_list_next(if_entry)) {
602 if_info = (if_info_t *)if_entry->data;
603 printf("%d. %s", i++, if_info->name);
606 * Print the contents of the if_entry struct in a parseable format.
607 * Each if_entry element is tab-separated. Addresses are comma-
610 /* XXX - Make sure our description doesn't contain a tab */
611 if (if_info->description != NULL)
612 printf("\t%s\t", if_info->description);
616 for(addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
617 addr = g_slist_next(addr)) {
618 if (addr != g_slist_nth(if_info->addrs, 0))
621 if_addr = (if_addr_t *)addr->data;
622 switch(if_addr->ifat_type) {
624 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
626 printf("%s", addr_str);
628 printf("<unknown IPv4>");
632 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
633 addr_str, ADDRSTRLEN)) {
634 printf("%s", addr_str);
636 printf("<unknown IPv6>");
640 printf("<type unknown %u>", if_addr->ifat_type);
644 if (if_info->loopback)
645 printf("\tloopback");
654 * If you change the machine-readable output format of this function,
655 * you MUST update capture_sync.c:sync_linktype_list_open() accordingly!
658 print_machine_readable_link_layer_types(GList *lt_list)
661 data_link_info_t *data_link_info;
662 const gchar *desc_str;
664 for (lt_entry = lt_list; lt_entry != NULL; lt_entry = g_list_next(lt_entry)) {
665 data_link_info = (data_link_info_t *)lt_entry->data;
666 if (data_link_info->description != NULL)
667 desc_str = data_link_info->description;
669 desc_str = "(not supported)";
670 printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
680 /* Print the number of packets captured for each interface until we're killed. */
682 print_statistics_loop(gboolean machine_readable)
684 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
690 char errbuf[PCAP_ERRBUF_SIZE];
693 if_list = get_interface_list(&err, &err_str);
694 if (if_list == NULL) {
696 case CANT_GET_INTERFACE_LIST:
697 cmdarg_err("%s", err_str);
701 case NO_INTERFACES_FOUND:
702 cmdarg_err("There are no interfaces on which a capture can be done");
708 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
709 if_info = (if_info_t *)if_entry->data;
710 #ifdef HAVE_PCAP_OPEN
711 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
713 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
717 if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
718 if_stat->name = g_strdup(if_info->name);
720 stat_list = g_list_append(stat_list, if_stat);
725 cmdarg_err("There are no interfaces on which a capture can be done");
729 if (!machine_readable) {
730 printf("%-15s %10s %10s\n", "Interface", "Received",
735 while (global_ld.go) {
736 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
737 if_stat = (if_stat_t *)stat_entry->data;
738 pcap_stats(if_stat->pch, &ps);
740 if (!machine_readable) {
741 printf("%-15s %10u %10u\n", if_stat->name,
742 ps.ps_recv, ps.ps_drop);
744 printf("%s\t%u\t%u\n", if_stat->name,
745 ps.ps_recv, ps.ps_drop);
750 if (! global_ld.from_cap_pipe)
757 /* XXX - Not reached. Should we look for 'q' in stdin? */
758 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
759 if_stat = (if_stat_t *)stat_entry->data;
760 pcap_close(if_stat->pch);
761 g_free(if_stat->name);
764 g_list_free(stat_list);
765 free_interface_list(if_list);
773 capture_cleanup_handler(DWORD dwCtrlType)
775 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
776 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
777 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
778 like SIGTERM at least when the machine's shutting down.
780 For now, if we're running as a command rather than a capture child,
781 we handle all but CTRL_LOGOFF_EVENT as indications that we should
782 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
785 If we're not running as a capture child, we might be running as
786 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
787 user logs out. (XXX - can we explicitly check whether we're
788 running as a service?) */
790 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
791 "Console: Control signal");
792 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
793 "Console: Control signal, CtrlType: %u", dwCtrlType);
795 /* Keep capture running if we're a service and a user logs off */
796 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
805 capture_cleanup_handler(int signum _U_)
807 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
808 SIGTERM. We assume that if the user wanted it to keep running
809 after they logged out, they'd have nohupped it. */
811 /* Note: don't call g_log() in the signal handler: if we happened to be in
812 * g_log() in process context when the signal came in, g_log will detect
813 * the "recursion" and abort.
820 static void exit_main(int status)
823 /* Shutdown windows sockets */
826 /* can be helpful for debugging */
828 printf("Press any key\n");
839 * If we were linked with libcap (not libpcap), make sure we have
840 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
841 * (See comment in main() for details)
845 #if 0 /* Set to enable capability debugging */
846 /* see 'man cap_to_text()' for explanation of output */
847 /* '=' means 'all= ' ie: no capabilities */
848 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
850 print_caps(const char *pfx) {
851 cap_t caps = cap_get_proc();
852 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
853 "%s: EUID: %d Capabilities: %s", pfx,
854 geteuid(), cap_to_text(caps, NULL));
857 print_caps(const char *pfx _U_) {
862 relinquish_privs_except_capture(void)
864 /* If 'started_with_special_privs' (ie: suid) then enable for
865 * ourself the NET_ADMIN and NET_RAW capabilities and then
866 * drop our suid privileges.
868 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
869 * stuff we don't need (and shouldn't have).
870 * CAP_NET_RAW: Packet capture (raw sockets).
873 if (started_with_special_privs()) {
874 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
875 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
877 cap_t caps = cap_init(); /* all capabilities initialized to off */
879 print_caps("Pre drop, pre set");
881 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
882 cmdarg_err("prctl() fail return: %s", strerror(errno));
885 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
886 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
888 if (cap_set_proc(caps)) {
889 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
891 print_caps("Pre drop, post set");
893 relinquish_special_privs_perm();
895 print_caps("Post drop, pre set");
896 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
897 if (cap_set_proc(caps)) {
898 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
900 print_caps("Post drop, post set");
908 relinquish_all_capabilities(void)
910 /* Drop any and all capabilities this process may have. */
911 /* Allowed whether or not process has any privileges. */
912 cap_t caps = cap_init(); /* all capabilities initialized to off */
913 print_caps("Pre-clear");
914 if (cap_set_proc(caps)) {
915 cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
917 print_caps("Post-clear");
921 #endif /* HAVE_LIBCAP */
923 /* Set the data link type on a pcap. */
925 set_pcap_linktype(pcap_t *pch, char *devname
926 #ifdef HAVE_PCAP_SET_DATALINK
931 #ifdef HAVE_PCAP_SET_DATALINK
932 if (pcap_set_datalink(pch, dlt) == 0)
933 return NULL; /* no error */
934 return pcap_geterr(pch);
936 /* Let them set it to the type it is; reject any other request. */
937 if (get_pcap_linktype(pch, devname) == dlt)
938 return NULL; /* no error */
939 return "That DLT isn't one of the DLTs supported by this device";
943 /* Take care of byte order in the libpcap headers read from pipes.
944 * (function taken from wiretap/libpcap.c) */
946 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
949 /* Byte-swap the record header fields. */
950 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
951 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
952 rechdr->incl_len = BSWAP32(rechdr->incl_len);
953 rechdr->orig_len = BSWAP32(rechdr->orig_len);
956 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
957 swapped, in order to match the BPF header layout.
959 Unfortunately, some files were, according to a comment in the "libpcap"
960 source, written with version 2.3 in their headers but without the
961 interchanged fields, so if "incl_len" is greater than "orig_len" - which
962 would make no sense - we assume that we need to swap them. */
963 if (hdr->version_major == 2 &&
964 (hdr->version_minor < 3 ||
965 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
968 temp = rechdr->orig_len;
969 rechdr->orig_len = rechdr->incl_len;
970 rechdr->incl_len = temp;
976 * Thread function that reads from a pipe and pushes the data
977 * to the main application thread.
980 * XXX Right now we use async queues for basic signaling. The main thread
981 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
982 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
983 * Iff the read is successful cap_pipe_read pushes an item onto
984 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
985 * the queues themselves (yet).
987 * We might want to move some of the cap_pipe_dispatch logic here so that
988 * we can let cap_pipe_read run independently, queuing up multiple reads
989 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
991 static void *cap_pipe_read(void *ld_ptr) {
992 loop_data *ld = (loop_data *)ld_ptr;
1001 while (ld->cap_pipe_err == PIPOK) {
1002 g_async_queue_pop(cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1003 g_mutex_lock(cap_pipe_read_mtx);
1005 while (bytes_read < (int) ld->cap_pipe_bytes_to_read) {
1007 /* If we try to use read() on a named pipe on Windows with partial
1008 * data it appears to return EOF.
1010 res = ReadFile(ld->cap_pipe_h, ld->cap_pipe_buf+bytes_read,
1011 ld->cap_pipe_bytes_to_read - bytes_read,
1016 last_err = GetLastError();
1017 if (last_err == ERROR_MORE_DATA) {
1019 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1020 ld->cap_pipe_err = PIPEOF;
1024 ld->cap_pipe_err = PIPERR;
1027 } else if (b == 0 && ld->cap_pipe_bytes_to_read > 0) {
1028 ld->cap_pipe_err = PIPEOF;
1033 b = read(ld->cap_pipe_fd, ld->cap_pipe_buf+bytes_read,
1034 ld->cap_pipe_bytes_to_read - bytes_read);
1037 ld->cap_pipe_err = PIPEOF;
1041 ld->cap_pipe_err = PIPERR;
1050 ld->cap_pipe_bytes_read = bytes_read;
1051 if (ld->cap_pipe_bytes_read >= ld->cap_pipe_bytes_to_read) {
1052 g_async_queue_push(cap_pipe_done_q, ld->cap_pipe_buf); /* Any non-NULL value will do */
1054 g_mutex_unlock(cap_pipe_read_mtx);
1058 #endif /* USE_THREADS */
1060 /* Provide select() functionality for a single file descriptor
1061 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1063 * Returns the same values as select. If an error is returned,
1064 * the string cap_pipe_err_str should be used instead of errno.
1067 cap_pipe_select(int pipe_fd) {
1069 struct timeval timeout, *pto;
1072 cap_pipe_err_str = "Unknown error";
1075 FD_SET(pipe_fd, &rfds);
1078 timeout.tv_usec = CAP_READ_TIMEOUT * 1000;
1081 sel_ret = select(pipe_fd+1, &rfds, NULL, NULL, pto);
1083 cap_pipe_err_str = strerror(errno);
1088 /* Mimic pcap_open_live() for pipe captures
1090 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1091 * open it, and read the header.
1093 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1094 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1096 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
1097 char *errmsg, int errmsgl)
1100 struct stat pipe_stat;
1101 struct sockaddr_un sa;
1104 unsigned int bytes_read;
1115 ld->cap_pipe_fd = -1;
1117 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
1119 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1122 * XXX - this blocks until a pcap per-file header has been written to
1123 * the pipe, so it could block indefinitely.
1125 if (strcmp(pipename, "-") == 0) {
1127 fd = 0; /* read from stdin */
1129 ld->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1133 if (ws_stat(pipename, &pipe_stat) < 0) {
1134 if (errno == ENOENT || errno == ENOTDIR)
1135 ld->cap_pipe_err = PIPNEXIST;
1137 g_snprintf(errmsg, errmsgl,
1138 "The capture session could not be initiated "
1139 "due to error getting information on pipe/socket: %s", strerror(errno));
1140 ld->cap_pipe_err = PIPERR;
1144 if (S_ISFIFO(pipe_stat.st_mode)) {
1145 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1147 g_snprintf(errmsg, errmsgl,
1148 "The capture session could not be initiated "
1149 "due to error on pipe open: %s", strerror(errno));
1150 ld->cap_pipe_err = PIPERR;
1153 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1154 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1156 g_snprintf(errmsg, errmsgl,
1157 "The capture session could not be initiated "
1158 "due to error on socket create: %s", strerror(errno));
1159 ld->cap_pipe_err = PIPERR;
1162 sa.sun_family = AF_UNIX;
1164 * The Single UNIX Specification says:
1166 * The size of sun_path has intentionally been left undefined.
1167 * This is because different implementations use different sizes.
1168 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1169 * of 104. Since most implementations originate from BSD versions,
1170 * the size is typically in the range 92 to 108.
1172 * Applications should not assume a particular length for sun_path
1173 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1177 * The <sys/un.h> header shall define the sockaddr_un structure,
1178 * which shall include at least the following members:
1180 * sa_family_t sun_family Address family.
1181 * char sun_path[] Socket pathname.
1183 * so we assume that it's an array, with a specified size,
1184 * and that the size reflects the maximum path length.
1186 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1187 /* Path name too long */
1188 g_snprintf(errmsg, errmsgl,
1189 "The capture session coud not be initiated "
1190 "due to error on socket connect: Path name too long");
1191 ld->cap_pipe_err = PIPERR;
1194 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1196 g_snprintf(errmsg, errmsgl,
1197 "The capture session coud not be initiated "
1198 "due to error on socket connect: %s", strerror(errno));
1199 ld->cap_pipe_err = PIPERR;
1203 if (S_ISCHR(pipe_stat.st_mode)) {
1205 * Assume the user specified an interface on a system where
1206 * interfaces are in /dev. Pretend we haven't seen it.
1208 ld->cap_pipe_err = PIPNEXIST;
1211 g_snprintf(errmsg, errmsgl,
1212 "The capture session could not be initiated because\n"
1213 "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
1214 ld->cap_pipe_err = PIPERR;
1219 #define PIPE_STR "\\pipe\\"
1220 /* Under Windows, named pipes _must_ have the form
1221 * "\\<server>\pipe\<pipename>". <server> may be "." for localhost.
1223 pncopy = g_strdup(pipename);
1224 if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1225 pos = strchr(pncopy + 3, '\\');
1226 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1233 g_snprintf(errmsg, errmsgl,
1234 "The capture session could not be initiated because\n"
1235 "\"%s\" is neither an interface nor a pipe", pipename);
1236 ld->cap_pipe_err = PIPNEXIST;
1240 /* Wait for the pipe to appear */
1242 ld->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1243 OPEN_EXISTING, 0, NULL);
1245 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE)
1248 if (GetLastError() != ERROR_PIPE_BUSY) {
1249 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1250 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1251 g_snprintf(errmsg, errmsgl,
1252 "The capture session on \"%s\" could not be started "
1253 "due to error on pipe open: %s (error %d)",
1254 pipename, utf_16to8(err_str), GetLastError());
1256 ld->cap_pipe_err = PIPERR;
1260 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1261 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1262 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1263 g_snprintf(errmsg, errmsgl,
1264 "The capture session on \"%s\" timed out during "
1265 "pipe open: %s (error %d)",
1266 pipename, utf_16to8(err_str), GetLastError());
1268 ld->cap_pipe_err = PIPERR;
1275 ld->from_cap_pipe = TRUE;
1278 /* read the pcap header */
1280 while (bytes_read < sizeof magic) {
1281 sel_ret = cap_pipe_select(fd);
1283 g_snprintf(errmsg, errmsgl,
1284 "Unexpected error from select: %s", strerror(errno));
1286 } else if (sel_ret > 0) {
1287 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
1290 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1292 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1299 #else /* USE_THREADS */
1300 g_thread_create(&cap_pipe_read, ld, FALSE, NULL);
1302 ld->cap_pipe_buf = (char *) &magic;
1303 ld->cap_pipe_bytes_read = 0;
1304 ld->cap_pipe_bytes_to_read = sizeof(magic);
1305 /* We don't have to worry about cap_pipe_read_mtx here */
1306 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1307 g_async_queue_pop(cap_pipe_done_q);
1308 if (ld->cap_pipe_bytes_read <= 0) {
1309 if (ld->cap_pipe_bytes_read == 0)
1310 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1312 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1317 #endif /* USE_THREADS */
1321 /* Host that wrote it has our byte order, and was running
1322 a program using either standard or ss990417 libpcap. */
1323 ld->cap_pipe_byte_swapped = FALSE;
1324 ld->cap_pipe_modified = FALSE;
1326 case PCAP_MODIFIED_MAGIC:
1327 /* Host that wrote it has our byte order, but was running
1328 a program using either ss990915 or ss991029 libpcap. */
1329 ld->cap_pipe_byte_swapped = FALSE;
1330 ld->cap_pipe_modified = TRUE;
1332 case PCAP_SWAPPED_MAGIC:
1333 /* Host that wrote it has a byte order opposite to ours,
1334 and was running a program using either standard or
1335 ss990417 libpcap. */
1336 ld->cap_pipe_byte_swapped = TRUE;
1337 ld->cap_pipe_modified = FALSE;
1339 case PCAP_SWAPPED_MODIFIED_MAGIC:
1340 /* Host that wrote it out has a byte order opposite to
1341 ours, and was running a program using either ss990915
1342 or ss991029 libpcap. */
1343 ld->cap_pipe_byte_swapped = TRUE;
1344 ld->cap_pipe_modified = TRUE;
1347 /* Not a "libpcap" type we know about. */
1348 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
1353 /* Read the rest of the header */
1355 while (bytes_read < sizeof(struct pcap_hdr)) {
1356 sel_ret = cap_pipe_select(fd);
1358 g_snprintf(errmsg, errmsgl,
1359 "Unexpected error from select: %s", strerror(errno));
1361 } else if (sel_ret > 0) {
1362 b = read(fd, ((char *)hdr)+bytes_read,
1363 sizeof(struct pcap_hdr) - bytes_read);
1366 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1368 g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
1375 #else /* USE_THREADS */
1376 ld->cap_pipe_buf = (char *) hdr;
1377 ld->cap_pipe_bytes_read = 0;
1378 ld->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1379 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1380 g_async_queue_pop(cap_pipe_done_q);
1381 if (ld->cap_pipe_bytes_read <= 0) {
1382 if (ld->cap_pipe_bytes_read == 0)
1383 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1385 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
1389 #endif /* USE_THREADS */
1391 if (ld->cap_pipe_byte_swapped) {
1392 /* Byte-swap the header fields about which we care. */
1393 hdr->version_major = BSWAP16(hdr->version_major);
1394 hdr->version_minor = BSWAP16(hdr->version_minor);
1395 hdr->snaplen = BSWAP32(hdr->snaplen);
1396 hdr->network = BSWAP32(hdr->network);
1398 ld->linktype = hdr->network;
1400 if (hdr->version_major < 2) {
1401 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1405 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1406 ld->cap_pipe_err = PIPOK;
1408 ld->cap_pipe_fd = fd;
1413 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1414 ld->cap_pipe_err = PIPERR;
1417 ld->cap_pipe_fd = -1;
1424 /* We read one record from the pipe, take care of byte order in the record
1425 * header, write the record to the capture file, and update capture statistics. */
1427 cap_pipe_dispatch(loop_data *ld, guchar *data, char *errmsg, int errmsgl)
1429 struct pcap_pkthdr phdr;
1430 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1442 #ifdef LOG_CAPTURE_VERBOSE
1443 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1446 switch (ld->cap_pipe_state) {
1448 case STATE_EXPECT_REC_HDR:
1450 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1453 ld->cap_pipe_state = STATE_READ_REC_HDR;
1454 ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
1455 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1456 ld->cap_pipe_bytes_read = 0;
1459 ld->cap_pipe_buf = (char *) &ld->cap_pipe_rechdr;
1460 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1461 g_mutex_unlock(cap_pipe_read_mtx);
1466 case STATE_READ_REC_HDR:
1468 b = read(ld->cap_pipe_fd, ((char *)&ld->cap_pipe_rechdr)+ld->cap_pipe_bytes_read,
1469 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1472 result = PD_PIPE_EOF;
1474 result = PD_PIPE_ERR;
1477 ld->cap_pipe_bytes_read += b;
1478 #else /* USE_THREADS */
1479 g_get_current_time(&wait_time);
1480 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1481 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1482 if (ld->cap_pipe_err == PIPEOF) {
1483 result = PD_PIPE_EOF;
1485 } else if (ld->cap_pipe_err == PIPERR) {
1486 result = PD_PIPE_ERR;
1492 #endif /* USE_THREADS */
1493 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1495 result = PD_REC_HDR_READ;
1498 case STATE_EXPECT_DATA:
1500 if (g_mutex_trylock(cap_pipe_read_mtx)) {
1503 ld->cap_pipe_state = STATE_READ_DATA;
1504 ld->cap_pipe_bytes_to_read = ld->cap_pipe_rechdr.hdr.incl_len;
1505 ld->cap_pipe_bytes_read = 0;
1508 ld->cap_pipe_buf = (char *) data;
1509 g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1510 g_mutex_unlock(cap_pipe_read_mtx);
1515 case STATE_READ_DATA:
1517 b = read(ld->cap_pipe_fd, data+ld->cap_pipe_bytes_read,
1518 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1521 result = PD_PIPE_EOF;
1523 result = PD_PIPE_ERR;
1526 ld->cap_pipe_bytes_read += b;
1527 #else /* USE_THREADS */
1528 g_get_current_time(&wait_time);
1529 g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1530 q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1531 if (ld->cap_pipe_err == PIPEOF) {
1532 result = PD_PIPE_EOF;
1534 } else if (ld->cap_pipe_err == PIPERR) {
1535 result = PD_PIPE_ERR;
1541 #endif /* USE_THREADS */
1542 if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1544 result = PD_DATA_READ;
1548 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
1551 } /* switch (ld->cap_pipe_state) */
1554 * We've now read as much data as we were expecting, so process it.
1558 case PD_REC_HDR_READ:
1559 /* We've read the header. Take care of byte order. */
1560 cap_pipe_adjust_header(ld->cap_pipe_byte_swapped, &ld->cap_pipe_hdr,
1561 &ld->cap_pipe_rechdr.hdr);
1562 if (ld->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1563 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
1564 ld->packet_count+1, ld->cap_pipe_rechdr.hdr.incl_len);
1567 ld->cap_pipe_state = STATE_EXPECT_DATA;
1571 /* Fill in a "struct pcap_pkthdr", and process the packet. */
1572 phdr.ts.tv_sec = ld->cap_pipe_rechdr.hdr.ts_sec;
1573 phdr.ts.tv_usec = ld->cap_pipe_rechdr.hdr.ts_usec;
1574 phdr.caplen = ld->cap_pipe_rechdr.hdr.incl_len;
1575 phdr.len = ld->cap_pipe_rechdr.hdr.orig_len;
1577 capture_loop_packet_cb((u_char *)ld, &phdr, data);
1579 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1583 ld->cap_pipe_err = PIPEOF;
1588 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1589 NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1590 g_snprintf(errmsg, errmsgl,
1591 "Error reading from pipe: %s (error %d)",
1592 utf_16to8(err_str), GetLastError());
1595 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
1603 ld->cap_pipe_err = PIPERR;
1604 /* Return here rather than inside the switch to prevent GCC warning */
1609 /** Open the capture input file (pcap or capture pipe).
1610 * Returns TRUE if it succeeds, FALSE otherwise. */
1612 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
1613 char *errmsg, size_t errmsg_len,
1614 char *secondary_errmsg, size_t secondary_errmsg_len)
1616 gchar open_err_str[PCAP_ERRBUF_SIZE];
1617 gchar *sync_msg_str;
1618 static const char ppamsg[] = "can't find PPA for ";
1619 const char *set_linktype_err_str;
1620 const char *libpcap_warn;
1622 gchar *sync_secondary_msg_str;
1624 WORD wVersionRequested;
1627 #ifdef HAVE_PCAP_REMOTE
1628 struct pcap_rmtauth auth;
1632 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
1635 /* XXX - opening Winsock on tshark? */
1637 /* Initialize Windows Socket if we are in a WIN32 OS
1638 This needs to be done before querying the interface for network/netmask */
1640 /* XXX - do we really require 1.1 or earlier?
1641 Are there any versions that support only 2.0 or higher? */
1642 wVersionRequested = MAKEWORD(1, 1);
1643 err = WSAStartup(wVersionRequested, &wsaData);
1647 case WSASYSNOTREADY:
1648 g_snprintf(errmsg, (gulong) errmsg_len,
1649 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
1652 case WSAVERNOTSUPPORTED:
1653 g_snprintf(errmsg, (gulong) errmsg_len,
1654 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
1655 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
1658 case WSAEINPROGRESS:
1659 g_snprintf(errmsg, (gulong) errmsg_len,
1660 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
1664 g_snprintf(errmsg, (gulong) errmsg_len,
1665 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
1669 g_snprintf(errmsg, (gulong) errmsg_len,
1670 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
1674 g_snprintf(errmsg, (gulong) errmsg_len,
1675 "Couldn't initialize Windows Sockets: error %d", err);
1678 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
1683 /* Open the network interface to capture from it.
1684 Some versions of libpcap may put warnings into the error buffer
1685 if they succeed; to tell if that's happened, we have to clear
1686 the error buffer, and check if it's still a null string. */
1687 open_err_str[0] = '\0';
1688 #ifdef HAVE_PCAP_OPEN
1689 if (strncmp (capture_opts->iface, "rpcap://", 8) == 0) {
1690 auth.type = capture_opts->auth_type == CAPTURE_AUTH_PWD ?
1691 RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
1692 auth.username = capture_opts->auth_username;
1693 auth.password = capture_opts->auth_password;
1695 ld->pcap_h = pcap_open(capture_opts->iface,
1696 capture_opts->has_snaplen ? capture_opts->snaplen :
1697 WTAP_MAX_PACKET_SIZE,
1699 (capture_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
1700 (capture_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
1701 (capture_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
1702 CAP_READ_TIMEOUT, &auth, open_err_str);
1704 #elif defined(HAVE_PCAP_CREATE)
1706 ld->pcap_h = pcap_create(capture_opts->iface, open_err_str);
1707 if (ld->pcap_h != NULL) {
1708 pcap_set_snaplen(ld->pcap_h, capture_opts->has_snaplen ? capture_opts->snaplen : WTAP_MAX_PACKET_SIZE);
1709 pcap_set_promisc(ld->pcap_h, capture_opts->promisc_mode);
1710 pcap_set_timeout(ld->pcap_h, CAP_READ_TIMEOUT);
1712 if (capture_opts->buffer_size > 1) {
1713 pcap_set_buffer_size(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024);
1715 if (capture_opts->monitor_mode)
1716 pcap_set_rfmon(ld->pcap_h, 1);
1717 if (pcap_activate(ld->pcap_h) != 0) {
1718 /* Failed to activate, set to NULL */
1719 pcap_close(ld->pcap_h);
1725 ld->pcap_h = pcap_open_live(capture_opts->iface,
1726 capture_opts->has_snaplen ? capture_opts->snaplen :
1727 WTAP_MAX_PACKET_SIZE,
1728 capture_opts->promisc_mode, CAP_READ_TIMEOUT,
1732 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
1733 /* to remove any suid privileges. */
1734 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
1735 /* (euid/egid have already previously been set to ruid/rgid. */
1736 /* (See comment in main() for details) */
1738 relinquish_special_privs_perm();
1740 relinquish_all_capabilities();
1743 if (ld->pcap_h != NULL) {
1744 /* we've opened "iface" as a network device */
1746 /* try to set the capture buffer size */
1747 if (capture_opts->buffer_size > 1 &&
1748 pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
1749 sync_secondary_msg_str = g_strdup_printf(
1750 "The capture buffer size of %dMB seems to be too high for your machine,\n"
1751 "the default of 1MB will be used.\n"
1753 "Nonetheless, the capture is started.\n",
1754 capture_opts->buffer_size);
1755 report_capture_error("Couldn't set the capture buffer size!",
1756 sync_secondary_msg_str);
1757 g_free(sync_secondary_msg_str);
1761 #if defined(HAVE_PCAP_REMOTE) && defined(HAVE_PCAP_SETSAMPLING)
1762 if ((capture_opts->sampling_method != CAPTURE_SAMP_NONE) &&
1763 (strncmp (capture_opts->iface, "rpcap://", 8) == 0))
1765 struct pcap_samp *samp;
1767 if ((samp = pcap_setsampling(ld->pcap_h)) != NULL)
1769 switch (capture_opts->sampling_method)
1771 case CAPTURE_SAMP_BY_COUNT:
1772 samp->method = PCAP_SAMP_1_EVERY_N;
1775 case CAPTURE_SAMP_BY_TIMER:
1776 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
1780 sync_msg_str = g_strdup_printf(
1781 "Unknown sampling method %d specified,\n"
1782 "continue without packet sampling",
1783 capture_opts->sampling_method);
1784 report_capture_error("Couldn't set the capture "
1785 "sampling", sync_msg_str);
1786 g_free(sync_msg_str);
1788 samp->value = capture_opts->sampling_param;
1792 report_capture_error("Couldn't set the capture sampling",
1793 "Cannot get packet sampling data structure");
1799 /* setting the data link type only works on real interfaces */
1800 if (capture_opts->linktype != -1) {
1801 set_linktype_err_str = set_pcap_linktype(ld->pcap_h, capture_opts->iface,
1802 capture_opts->linktype);
1803 if (set_linktype_err_str != NULL) {
1804 g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
1805 set_linktype_err_str);
1806 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
1810 ld->linktype = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
1812 /* We couldn't open "iface" as a network device. */
1813 /* Try to open it as a pipe */
1814 cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, (int) errmsg_len);
1817 if (ld->cap_pipe_fd == -1) {
1819 if (ld->cap_pipe_h == INVALID_HANDLE_VALUE) {
1822 if (ld->cap_pipe_err == PIPNEXIST) {
1823 /* Pipe doesn't exist, so output message for interface */
1825 /* If we got a "can't find PPA for X" message, warn the user (who
1826 is running (T)Wireshark on HP-UX) that they don't have a version
1827 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1828 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1829 PPA for X" rather than "can't find PPA for X"). */
1830 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1833 "You are running (T)Wireshark with a version of the libpcap library\n"
1834 "that doesn't handle HP-UX network devices well; this means that\n"
1835 "(T)Wireshark may not be able to capture packets.\n"
1837 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1838 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1839 "packaged binary form from the Software Porting And Archive Centre\n"
1840 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1841 "at the URL lists a number of mirror sites.";
1844 g_snprintf(errmsg, (gulong) errmsg_len,
1845 "The capture session could not be initiated (%s).", open_err_str);
1847 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
1848 "Please check to make sure you have sufficient permissions, and that you have "
1849 "the proper interface or pipe specified.%s", libpcap_warn);
1851 g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
1853 "Please check that \"%s\" is the proper interface.\n"
1856 "Help can be found at:\n"
1858 " http://wiki.wireshark.org/WinPcap\n"
1859 " http://wiki.wireshark.org/CaptureSetup\n",
1860 capture_opts->iface);
1864 * Else pipe (or file) does exist and cap_pipe_open_live() has
1869 /* cap_pipe_open_live() succeeded; don't want
1870 error message from pcap_open_live() */
1871 open_err_str[0] = '\0';
1874 /* XXX - will this work for tshark? */
1875 #ifdef MUST_DO_SELECT
1876 if (!ld->from_cap_pipe) {
1877 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
1878 ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
1880 ld->pcap_fd = pcap_fileno(ld->pcap_h);
1885 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1886 returned a warning; print it, but keep capturing. */
1887 if (open_err_str[0] != '\0') {
1888 sync_msg_str = g_strdup_printf("%s.", open_err_str);
1889 report_capture_error(sync_msg_str, "");
1890 g_free(sync_msg_str);
1897 /* close the capture input file (pcap or capture pipe) */
1898 static void capture_loop_close_input(loop_data *ld) {
1900 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
1902 /* if open, close the capture pipe "input file" */
1904 if (ld->cap_pipe_fd >= 0) {
1905 g_assert(ld->from_cap_pipe);
1906 ws_close(ld->cap_pipe_fd);
1907 ld->cap_pipe_fd = 0;
1910 if (ld->cap_pipe_h != INVALID_HANDLE_VALUE) {
1911 CloseHandle(ld->cap_pipe_h);
1912 ld->cap_pipe_h = INVALID_HANDLE_VALUE;
1916 /* if open, close the pcap "input file" */
1917 if(ld->pcap_h != NULL) {
1918 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)ld->pcap_h);
1919 g_assert(!ld->from_cap_pipe);
1920 pcap_close(ld->pcap_h);
1927 /* Shut down windows sockets */
1933 /* init the capture filter */
1934 static initfilter_status_t
1935 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe, gchar * iface, gchar * cfilter) {
1936 bpf_u_int32 netnum, netmask;
1937 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
1938 struct bpf_program fcode;
1941 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
1943 /* capture filters only work on real interfaces */
1944 if (cfilter && !from_cap_pipe) {
1945 /* A capture filter was specified; set it up. */
1946 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1948 * Well, we can't get the netmask for this interface; it's used
1949 * only for filters that check for broadcast IP addresses, so
1950 * we just punt and use 0. It might be nice to warn the user,
1951 * but that's a pain in a GUI application, as it'd involve popping
1952 * up a message box, and it's not clear how often this would make
1953 * a difference (only filters that check for IP broadcast addresses
1957 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
1960 if (pcap_compile(pcap_h, &fcode, cfilter, 1, netmask) < 0) {
1961 /* Treat this specially - our caller might try to compile this
1962 as a display filter and, if that succeeds, warn the user that
1963 the display and capture filter syntaxes are different. */
1964 return INITFILTER_BAD_FILTER;
1966 if (pcap_setfilter(pcap_h, &fcode) < 0) {
1967 #ifdef HAVE_PCAP_FREECODE
1968 pcap_freecode(&fcode);
1970 return INITFILTER_OTHER_ERROR;
1972 #ifdef HAVE_PCAP_FREECODE
1973 pcap_freecode(&fcode);
1977 return INITFILTER_NO_ERROR;
1981 /* set up to write to the already-opened capture output file/files */
1983 capture_loop_init_output(capture_options *capture_opts, int save_file_fd, loop_data *ld, char *errmsg, int errmsg_len) {
1987 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
1990 if (ld->from_cap_pipe) {
1991 ld->file_snaplen = ld->cap_pipe_hdr.snaplen;
1994 ld->file_snaplen = pcap_snapshot(ld->pcap_h);
1997 /* Set up to write to the capture file. */
1998 if (capture_opts->multi_files_on) {
1999 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2001 ld->pdh = libpcap_fdopen(save_file_fd, &err);
2004 gboolean successful;
2006 ld->bytes_written = 0;
2007 if (capture_opts->use_pcapng) {
2010 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2011 successful = libpcap_write_session_header_block(ld->pdh, appname, &ld->bytes_written, &err) &&
2012 libpcap_write_interface_description_block(ld->pdh, capture_opts->iface, capture_opts->cfilter, ld->linktype, ld->file_snaplen, &ld->bytes_written, &err);
2014 successful = libpcap_write_file_header(ld->pdh, ld->linktype, ld->file_snaplen,
2015 &ld->bytes_written, &err);
2023 if (ld->pdh == NULL) {
2024 /* We couldn't set up to write to the capture file. */
2025 /* XXX - use cf_open_error_message from tshark instead? */
2028 case WTAP_ERR_CANT_OPEN:
2029 g_snprintf(errmsg, errmsg_len, "The file to which the capture would be saved"
2030 " couldn't be created for some unknown reason.");
2033 case WTAP_ERR_SHORT_WRITE:
2034 g_snprintf(errmsg, errmsg_len, "A full header couldn't be written to the file"
2035 " to which the capture would be saved.");
2040 g_snprintf(errmsg, errmsg_len,
2041 "The file to which the capture would be"
2042 " saved (\"%s\") could not be opened: Error %d.",
2043 capture_opts->save_file, err);
2045 g_snprintf(errmsg, errmsg_len,
2046 "The file to which the capture would be"
2047 " saved (\"%s\") could not be opened: %s.",
2048 capture_opts->save_file, strerror(err));
2060 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
2062 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2064 if (capture_opts->multi_files_on) {
2065 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2067 if (capture_opts->use_pcapng) {
2068 libpcap_write_interface_statistics_block(ld->pdh, 0, ld->pcap_h, &ld->bytes_written, err_close);
2070 return libpcap_dump_close(ld->pdh, err_close);
2074 /* dispatch incoming packets (pcap or capture pipe)
2076 * Waits for incoming packets to be available, and calls pcap_dispatch()
2077 * to cause them to be processed.
2079 * Returns the number of packets which were processed.
2081 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2082 * packet-batching behaviour does not cause packets to get held back
2086 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
2087 char *errmsg, int errmsg_len)
2090 gint packet_count_before;
2091 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
2096 packet_count_before = ld->packet_count;
2097 if (ld->from_cap_pipe) {
2098 /* dispatch from capture pipe */
2099 #ifdef LOG_CAPTURE_VERBOSE
2100 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2103 sel_ret = cap_pipe_select(ld->cap_pipe_fd);
2106 if (sel_ret < 0 && errno != EINTR) {
2107 g_snprintf(errmsg, errmsg_len,
2108 "Unexpected error from select: %s", strerror(errno));
2109 report_capture_error(errmsg, please_report);
2114 * "select()" says we can read from the pipe without blocking
2116 #endif /* USE_THREADS */
2117 inpkts = cap_pipe_dispatch(ld, pcap_data, errmsg, errmsg_len);
2127 /* dispatch from pcap */
2128 #ifdef MUST_DO_SELECT
2130 * If we have "pcap_get_selectable_fd()", we use it to get the
2131 * descriptor on which to select; if that's -1, it means there
2132 * is no descriptor on which you can do a "select()" (perhaps
2133 * because you're capturing on a special device, and that device's
2134 * driver unfortunately doesn't support "select()", in which case
2135 * we don't do the select - which means it might not be possible
2136 * to stop a capture until a packet arrives. If that's unacceptable,
2137 * plead with whoever supplies the software for that device to add
2138 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2139 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2140 * later, so it can use pcap_breakloop().
2142 #ifdef LOG_CAPTURE_VERBOSE
2143 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2145 if (ld->pcap_fd != -1) {
2146 sel_ret = cap_pipe_select(ld->pcap_fd);
2149 * "select()" says we can read from it without blocking; go for
2152 * We don't have pcap_breakloop(), so we only process one packet
2153 * per pcap_dispatch() call, to allow a signal to stop the
2154 * processing immediately, rather than processing all packets
2155 * in a batch before quitting.
2157 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb,
2161 /* Error, rather than pcap_breakloop(). */
2162 ld->pcap_err = TRUE;
2164 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2167 if (sel_ret < 0 && errno != EINTR) {
2168 g_snprintf(errmsg, errmsg_len,
2169 "Unexpected error from select: %s", strerror(errno));
2170 report_capture_error(errmsg, please_report);
2176 #endif /* MUST_DO_SELECT */
2178 /* dispatch from pcap without select */
2180 #ifdef LOG_CAPTURE_VERBOSE
2181 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2185 * On Windows, we don't support asynchronously telling a process to
2186 * stop capturing; instead, we check for an indication on a pipe
2187 * after processing packets. We therefore process only one packet
2188 * at a time, so that we can check the pipe after every packet.
2190 inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb, (u_char *) ld);
2192 inpkts = pcap_dispatch(ld->pcap_h, -1, capture_loop_packet_cb, (u_char *) ld);
2196 /* Error, rather than pcap_breakloop(). */
2197 ld->pcap_err = TRUE;
2199 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2201 #else /* pcap_next_ex */
2202 #ifdef LOG_CAPTURE_VERBOSE
2203 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2205 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2208 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2209 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
2210 * This should be fixed in the WinPcap 4.0 alpha release.
2212 * For reference, an example remote interface:
2213 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2216 /* emulate dispatch from pcap */
2219 struct pcap_pkthdr *pkt_header;
2224 (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1)
2225 capture_loop_packet_cb( (u_char *) ld, pkt_header, pkt_data);
2228 ld->pcap_err = TRUE;
2232 #endif /* pcap_next_ex */
2236 #ifdef LOG_CAPTURE_VERBOSE
2237 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2240 return ld->packet_count - packet_count_before;
2244 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2245 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2247 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2248 char *errmsg, int errmsg_len) {
2251 gchar *capfile_name;
2252 gboolean is_tempfile;
2257 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2258 (capture_opts->save_file) ? capture_opts->save_file : "");
2260 if (capture_opts->save_file != NULL) {
2261 /* We return to the caller while the capture is in progress.
2262 * Therefore we need to take a copy of save_file in
2263 * case the caller destroys it after we return.
2265 capfile_name = g_strdup(capture_opts->save_file);
2267 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2268 if (capture_opts->multi_files_on) {
2269 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2270 g_snprintf(errmsg, errmsg_len,
2271 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2272 g_free(capfile_name);
2275 if (strcmp(capfile_name, "-") == 0) {
2276 /* write to stdout */
2279 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
2280 _setmode(1, O_BINARY);
2283 } /* if (...output_to_pipe ... */
2286 if (capture_opts->multi_files_on) {
2287 /* ringbuffer is enabled */
2288 *save_file_fd = ringbuf_init(capfile_name,
2289 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
2291 /* we need the ringbuf name */
2292 if(*save_file_fd != -1) {
2293 g_free(capfile_name);
2294 capfile_name = g_strdup(ringbuf_current_filename());
2297 /* Try to open/create the specified file for use as a capture buffer. */
2298 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
2302 is_tempfile = FALSE;
2304 /* Choose a random name for the temporary capture buffer */
2305 *save_file_fd = create_tempfile(&tmpname, "wireshark");
2306 capfile_name = g_strdup(tmpname);
2310 /* did we fail to open the output file? */
2311 if (*save_file_fd == -1) {
2313 g_snprintf(errmsg, errmsg_len,
2314 "The temporary file to which the capture would be saved (\"%s\") "
2315 "could not be opened: %s.", capfile_name, strerror(errno));
2317 if (capture_opts->multi_files_on) {
2318 ringbuf_error_cleanup();
2321 g_snprintf(errmsg, errmsg_len,
2322 "The file to which the capture would be saved (\"%s\") "
2323 "could not be opened: %s.", capfile_name,
2326 g_free(capfile_name);
2330 if(capture_opts->save_file != NULL) {
2331 g_free(capture_opts->save_file);
2333 capture_opts->save_file = capfile_name;
2334 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2335 "g_free(capfile_name)". */
2337 ret = fchown(*save_file_fd, capture_opts->owner, capture_opts->group);
2345 #define TIME_GET() GetTickCount()
2347 #define TIME_GET() time(NULL)
2350 /* Do the low-level work of a capture.
2351 Returns TRUE if it succeeds, FALSE otherwise. */
2353 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
2355 time_t upd_time, cur_time;
2359 gint inpkts_to_sync_pipe = 0; /* packets not already send out to the sync_pipe */
2360 condition *cnd_file_duration = NULL;
2361 condition *cnd_autostop_files = NULL;
2362 condition *cnd_autostop_size = NULL;
2363 condition *cnd_autostop_duration = NULL;
2364 guint32 autostop_files = 0;
2367 gboolean cfilter_error = FALSE;
2368 #define MSG_MAX_LENGTH 4096
2369 char errmsg[MSG_MAX_LENGTH+1];
2370 char secondary_errmsg[MSG_MAX_LENGTH+1];
2371 int save_file_fd = -1;
2374 *secondary_errmsg = '\0';
2376 /* init the loop data */
2377 global_ld.go = TRUE;
2378 global_ld.packet_count = 0;
2379 if (capture_opts->has_autostop_packets)
2380 global_ld.packet_max = capture_opts->autostop_packets;
2382 global_ld.packet_max = 0; /* no limit */
2383 global_ld.err = 0; /* no error seen yet */
2384 global_ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
2385 global_ld.pcap_err = FALSE;
2386 global_ld.from_cap_pipe = FALSE;
2387 global_ld.pdh = NULL;
2389 global_ld.cap_pipe_fd = -1;
2391 global_ld.cap_pipe_h = INVALID_HANDLE_VALUE;
2393 #ifdef MUST_DO_SELECT
2394 global_ld.pcap_fd = 0;
2397 /* We haven't yet gotten the capture statistics. */
2398 *stats_known = FALSE;
2400 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
2401 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
2403 /* open the "input file" from network interface or capture pipe */
2404 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
2405 secondary_errmsg, sizeof(secondary_errmsg))) {
2409 /* init the input filter from the network interface (capture pipe will do nothing) */
2410 switch (capture_loop_init_filter(global_ld.pcap_h, global_ld.from_cap_pipe,
2411 capture_opts->iface,
2412 capture_opts->cfilter)) {
2414 case INITFILTER_NO_ERROR:
2417 case INITFILTER_BAD_FILTER:
2418 cfilter_error = TRUE;
2419 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(global_ld.pcap_h));
2422 case INITFILTER_OTHER_ERROR:
2423 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
2424 pcap_geterr(global_ld.pcap_h));
2425 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
2429 /* If we're supposed to write to a capture file, open it for output
2430 (temporary/specified name/ringbuffer) */
2431 if (capture_opts->saving_to_file) {
2432 if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
2436 /* set up to write to the already-opened capture output file/files */
2437 if (!capture_loop_init_output(capture_opts, save_file_fd, &global_ld,
2438 errmsg, sizeof(errmsg))) {
2442 /* XXX - capture SIGTERM and close the capture, in case we're on a
2443 Linux 2.0[.x] system and you have to explicitly close the capture
2444 stream in order to turn promiscuous mode off? We need to do that
2445 in other places as well - and I don't think that works all the
2446 time in any case, due to libpcap bugs. */
2448 /* Well, we should be able to start capturing.
2450 Sync out the capture file, so the header makes it to the file system,
2451 and send a "capture started successfully and capture file created"
2452 message to our parent so that they'll open the capture file and
2453 update its windows to indicate that we have a live capture in
2455 libpcap_dump_flush(global_ld.pdh, NULL);
2456 report_new_capture_file(capture_opts->save_file);
2459 /* initialize capture stop (and alike) conditions */
2460 init_capture_stop_conditions();
2461 /* create stop conditions */
2462 if (capture_opts->has_autostop_filesize)
2464 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
2465 if (capture_opts->has_autostop_duration)
2466 cnd_autostop_duration =
2467 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
2469 if (capture_opts->multi_files_on) {
2470 if (capture_opts->has_file_duration)
2472 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
2474 if (capture_opts->has_autostop_files)
2475 cnd_autostop_files =
2476 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
2479 /* init the time values */
2480 start_time = TIME_GET();
2481 upd_time = TIME_GET();
2483 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
2485 /* WOW, everything is prepared! */
2486 /* please fasten your seat belts, we will enter now the actual capture loop */
2487 while (global_ld.go) {
2488 /* dispatch incoming packets */
2489 inpkts = capture_loop_dispatch(capture_opts, &global_ld, errmsg,
2493 /* any news from our parent (signal pipe)? -> just stop the capture */
2494 if (!signal_pipe_check_running()) {
2495 global_ld.go = FALSE;
2500 inpkts_to_sync_pipe += inpkts;
2502 /* check capture size condition */
2503 if (cnd_autostop_size != NULL &&
2504 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)){
2505 /* Capture size limit reached, do we have another file? */
2506 if (capture_opts->multi_files_on) {
2507 if (cnd_autostop_files != NULL &&
2508 cnd_eval(cnd_autostop_files, ++autostop_files)) {
2509 /* no files left: stop here */
2510 global_ld.go = FALSE;
2514 /* Switch to the next ringbuffer file */
2515 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2516 &save_file_fd, &global_ld.err)) {
2517 gboolean successful;
2519 /* File switch succeeded: reset the conditions */
2520 global_ld.bytes_written = 0;
2521 if (capture_opts->use_pcapng) {
2524 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2525 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2526 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);
2528 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2529 &global_ld.bytes_written, &global_ld.err);
2532 fclose(global_ld.pdh);
2533 global_ld.pdh = NULL;
2534 global_ld.go = FALSE;
2537 cnd_reset(cnd_autostop_size);
2538 if (cnd_file_duration) {
2539 cnd_reset(cnd_file_duration);
2541 libpcap_dump_flush(global_ld.pdh, NULL);
2542 report_packet_count(inpkts_to_sync_pipe);
2543 inpkts_to_sync_pipe = 0;
2544 report_new_capture_file(capture_opts->save_file);
2546 /* File switch failed: stop here */
2547 global_ld.go = FALSE;
2551 /* single file, stop now */
2552 global_ld.go = FALSE;
2555 } /* cnd_autostop_size */
2556 if (capture_opts->output_to_pipe) {
2557 libpcap_dump_flush(global_ld.pdh, NULL);
2561 /* Only update once a second (Win32: 500ms) so as not to overload slow
2562 * displays. This also prevents too much context-switching between the
2563 * dumpcap and wireshark processes */
2564 cur_time = TIME_GET();
2566 if ( (cur_time - upd_time) > 500) {
2568 if (cur_time - upd_time > 0) {
2570 upd_time = cur_time;
2572 /*if (pcap_stats(pch, stats) >= 0) {
2573 *stats_known = TRUE;
2576 /* Let the parent process know. */
2577 if (inpkts_to_sync_pipe) {
2579 libpcap_dump_flush(global_ld.pdh, NULL);
2581 /* Send our parent a message saying we've written out "inpkts_to_sync_pipe"
2582 packets to the capture file. */
2583 report_packet_count(inpkts_to_sync_pipe);
2585 inpkts_to_sync_pipe = 0;
2588 /* check capture duration condition */
2589 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
2590 /* The maximum capture time has elapsed; stop the capture. */
2591 global_ld.go = FALSE;
2595 /* check capture file duration condition */
2596 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
2597 /* duration limit reached, do we have another file? */
2598 if (capture_opts->multi_files_on) {
2599 if (cnd_autostop_files != NULL &&
2600 cnd_eval(cnd_autostop_files, ++autostop_files)) {
2601 /* no files left: stop here */
2602 global_ld.go = FALSE;
2606 /* Switch to the next ringbuffer file */
2607 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2608 &save_file_fd, &global_ld.err)) {
2609 gboolean successful;
2611 /* file switch succeeded: reset the conditions */
2612 global_ld.bytes_written = 0;
2613 if (capture_opts->use_pcapng) {
2616 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2617 successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2618 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);
2620 successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2621 &global_ld.bytes_written, &global_ld.err);
2624 fclose(global_ld.pdh);
2625 global_ld.pdh = NULL;
2626 global_ld.go = FALSE;
2629 cnd_reset(cnd_file_duration);
2630 if(cnd_autostop_size)
2631 cnd_reset(cnd_autostop_size);
2632 libpcap_dump_flush(global_ld.pdh, NULL);
2633 report_packet_count(inpkts_to_sync_pipe);
2634 inpkts_to_sync_pipe = 0;
2635 report_new_capture_file(capture_opts->save_file);
2637 /* File switch failed: stop here */
2638 global_ld.go = FALSE;
2642 /* single file, stop now */
2643 global_ld.go = FALSE;
2646 } /* cnd_file_duration */
2649 } /* while (global_ld.go) */
2651 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
2653 /* delete stop conditions */
2654 if (cnd_file_duration != NULL)
2655 cnd_delete(cnd_file_duration);
2656 if (cnd_autostop_files != NULL)
2657 cnd_delete(cnd_autostop_files);
2658 if (cnd_autostop_size != NULL)
2659 cnd_delete(cnd_autostop_size);
2660 if (cnd_autostop_duration != NULL)
2661 cnd_delete(cnd_autostop_duration);
2663 /* did we had a pcap (input) error? */
2664 if (global_ld.pcap_err) {
2665 /* On Linux, if an interface goes down while you're capturing on it,
2666 you'll get a "recvfrom: Network is down" error (ENETDOWN).
2667 (At least you will if strerror() doesn't show a local translation
2670 On FreeBSD and OS X, if a network adapter disappears while
2671 you're capturing on it, you'll get a "read: Device not configured"
2672 error (ENXIO). (See previous parenthetical note.)
2674 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
2676 These should *not* be reported to the Wireshark developers. */
2679 cap_err_str = pcap_geterr(global_ld.pcap_h);
2680 if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
2681 strcmp(cap_err_str, "read: Device not configured") == 0 ||
2682 strcmp(cap_err_str, "read: I/O error") == 0) {
2683 report_capture_error("The network adapter on which the capture was being done "
2684 "is no longer running; the capture has stopped.",
2687 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
2689 report_capture_error(errmsg, please_report);
2692 else if (global_ld.from_cap_pipe && global_ld.cap_pipe_err == PIPERR)
2693 report_capture_error(errmsg, "");
2695 /* did we had an error while capturing? */
2696 if (global_ld.err == 0) {
2699 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
2700 global_ld.err, FALSE);
2701 report_capture_error(errmsg, please_report);
2705 if (capture_opts->saving_to_file) {
2706 /* close the wiretap (output) file */
2707 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
2711 /* there might be packets not yet notified to the parent */
2712 /* (do this after closing the file, so all packets are already flushed) */
2713 if(inpkts_to_sync_pipe) {
2714 report_packet_count(inpkts_to_sync_pipe);
2715 inpkts_to_sync_pipe = 0;
2718 /* If we've displayed a message about a write error, there's no point
2719 in displaying another message about an error on close. */
2720 if (!close_ok && write_ok) {
2721 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
2723 report_capture_error(errmsg, "");
2727 * XXX We exhibit different behaviour between normal mode and sync mode
2728 * when the pipe is stdin and not already at EOF. If we're a child, the
2729 * parent's stdin isn't closed, so if the user starts another capture,
2730 * cap_pipe_open_live() will very likely not see the expected magic bytes and
2731 * will say "Unrecognized libpcap format". On the other hand, in normal
2732 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
2735 /* get packet drop statistics from pcap */
2736 if(global_ld.pcap_h != NULL) {
2737 g_assert(!global_ld.from_cap_pipe);
2738 /* Get the capture statistics, so we know how many packets were
2740 if (pcap_stats(global_ld.pcap_h, stats) >= 0) {
2741 *stats_known = TRUE;
2742 /* Let the parent process know. */
2743 report_packet_drops(stats->ps_drop);
2745 g_snprintf(errmsg, sizeof(errmsg),
2746 "Can't get packet-drop statistics: %s",
2747 pcap_geterr(global_ld.pcap_h));
2748 report_capture_error(errmsg, please_report);
2752 /* close the input file (pcap or capture pipe) */
2753 capture_loop_close_input(&global_ld);
2755 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
2757 /* ok, if the write and the close were successful. */
2758 return write_ok && close_ok;
2761 if (capture_opts->multi_files_on) {
2762 /* cleanup ringbuffer */
2763 ringbuf_error_cleanup();
2765 /* We can't use the save file, and we have no FILE * for the stream
2766 to close in order to close it, so close the FD directly. */
2767 if(save_file_fd != -1) {
2768 ws_close(save_file_fd);
2771 /* We couldn't even start the capture, so get rid of the capture
2773 if(capture_opts->save_file != NULL) {
2774 ws_unlink(capture_opts->save_file);
2775 g_free(capture_opts->save_file);
2778 capture_opts->save_file = NULL;
2780 report_cfilter_error(capture_opts->cfilter, errmsg);
2782 report_capture_error(errmsg, secondary_errmsg);
2784 /* close the input file (pcap or cap_pipe) */
2785 capture_loop_close_input(&global_ld);
2787 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
2793 static void capture_loop_stop(void)
2795 #ifdef HAVE_PCAP_BREAKLOOP
2796 if(global_ld.pcap_h != NULL)
2797 pcap_breakloop(global_ld.pcap_h);
2799 global_ld.go = FALSE;
2804 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
2805 int err, gboolean is_close)
2810 g_snprintf(errmsg, errmsglen,
2811 "Not all the packets could be written to the file"
2812 " to which the capture was being saved\n"
2813 "(\"%s\") because there is no space left on the file system\n"
2814 "on which that file resides.",
2820 g_snprintf(errmsg, errmsglen,
2821 "Not all the packets could be written to the file"
2822 " to which the capture was being saved\n"
2823 "(\"%s\") because you are too close to, or over,"
2824 " your disk quota\n"
2825 "on the file system on which that file resides.",
2830 case WTAP_ERR_CANT_CLOSE:
2831 g_snprintf(errmsg, errmsglen,
2832 "The file to which the capture was being saved"
2833 " couldn't be closed for some unknown reason.");
2836 case WTAP_ERR_SHORT_WRITE:
2837 g_snprintf(errmsg, errmsglen,
2838 "Not all the packets could be written to the file"
2839 " to which the capture was being saved\n"
2846 g_snprintf(errmsg, errmsglen,
2847 "The file to which the capture was being saved\n"
2848 "(\"%s\") could not be closed: %s.",
2849 fname, wtap_strerror(err));
2851 g_snprintf(errmsg, errmsglen,
2852 "An error occurred while writing to the file"
2853 " to which the capture was being saved\n"
2855 fname, wtap_strerror(err));
2862 /* one packet was captured, process it */
2864 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
2867 loop_data *ld = (loop_data *) (void *) user;
2870 /* We may be called multiple times from pcap_dispatch(); if we've set
2871 the "stop capturing" flag, ignore this packet, as we're not
2872 supposed to be saving any more packets. */
2877 gboolean successful;
2878 /* We're supposed to write the packet to a file; do so.
2879 If this fails, set "ld->go" to FALSE, to stop the capture, and set
2880 "ld->err" to the error. */
2881 if (global_capture_opts.use_pcapng) {
2882 successful = libpcap_write_enhanced_packet_block(ld->pdh, phdr, 0, pd, &ld->bytes_written, &err);
2884 successful = libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err);
2891 /* if the user told us to stop after x packets, do we already have enough? */
2892 if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
2901 /* And now our feature presentation... [ fade to music ] */
2903 main(int argc, char *argv[])
2906 gboolean arg_error = FALSE;
2911 struct sigaction action, oldaction;
2914 gboolean start_capture = TRUE;
2915 gboolean stats_known;
2916 struct pcap_stat stats;
2917 GLogLevelFlags log_flags;
2918 gboolean list_interfaces = FALSE;
2919 gboolean list_link_layer_types = FALSE;
2920 gboolean machine_readable = FALSE;
2921 gboolean print_statistics = FALSE;
2922 int status, run_once_args = 0;
2924 #if defined(__APPLE__) && defined(__LP64__)
2925 struct utsname osinfo;
2928 #ifdef HAVE_PCAP_REMOTE
2929 #define OPTSTRING_A "A:"
2930 #define OPTSTRING_r "r"
2931 #define OPTSTRING_u "u"
2933 #define OPTSTRING_A ""
2934 #define OPTSTRING_r ""
2935 #define OPTSTRING_u ""
2938 #ifdef HAVE_PCAP_SETSAMPLING
2939 #define OPTSTRING_m "m:"
2941 #define OPTSTRING_m ""
2944 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
2945 #define OPTSTRING_B "B:"
2947 #define OPTSTRING_B ""
2948 #endif /* _WIN32 or HAVE_PCAP_CREATE */
2950 #ifdef HAVE_PCAP_CREATE
2951 #define OPTSTRING_I "I"
2953 #define OPTSTRING_I ""
2956 #define OPTSTRING "a:" OPTSTRING_A "b:" OPTSTRING_B "c:Df:hi:" OPTSTRING_I "L" OPTSTRING_m "Mnp" OPTSTRING_r "Ss:" OPTSTRING_u "vw:y:Z:"
2958 #ifdef DEBUG_CHILD_DUMPCAP
2959 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
2960 fprintf (stderr, "Unable to open debug log file !\n");
2965 #if defined(__APPLE__) && defined(__LP64__)
2967 * Is this Mac OS X 10.6.x, other than 10.6.2? If so, we need a bug
2968 * workaround - timeouts less than 1 second don't work with libpcap
2969 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
2970 * and re-introduced in 10.6.3. We don't know whether it'll be fixed
2971 * again in a later 10.6.x release; we'll assume that it'll be fixed
2972 * in any future major releases.)
2974 if (uname(&osinfo) == 0) {
2976 * Mac OS X 10.x uses Darwin {x+4}.0.0. Mac OS X 10.x.y uses Darwin
2977 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
2978 * number of 10.0.0, not 10.1.0 - go figure).
2980 if (strncmp(osinfo.release, "10.", 3) == 0) {
2982 * OK, it's Snow Leopard - which version?
2984 if (strcmp(osinfo.release, "10.2.0") != 0) {
2986 need_timeout_workaround = TRUE;
2992 /* Determine if dumpcap is being requested to run in a special */
2993 /* capture_child mode by going thru the command line args to see if */
2994 /* a -Z is present. (-Z is a hidden option). */
2995 /* The primary result of running in capture_child mode is that */
2996 /* all messages sent out on stderr are in a special type/len/string */
2997 /* format to allow message processing by type. */
2998 /* These messages include various 'status' messages which are sent */
2999 /* when an actual capture is in progress. Capture_child mode */
3000 /* would normally be requested by a parent process which invokes */
3001 /* dumpcap and obtains dumpcap stderr output via a pipe to which */
3002 /* dumpcap stderr has been redirected. */
3003 /* Capture_child mode needs to be determined immediately upon */
3004 /* startup so that any messages generated by dumpcap in this mode */
3005 /* (eg: during initialization) will be formatted properly. */
3007 for (i=1; i<argc; i++) {
3008 if (strcmp("-Z", argv[i]) == 0) {
3009 capture_child = TRUE;
3011 /* set output pipe to binary mode, to avoid ugly text conversions */
3012 _setmode(2, O_BINARY);
3017 /* The default_log_handler will use stdout, which makes trouble in */
3018 /* capture child mode, as it uses stdout for it's sync_pipe. */
3019 /* So: the filtering is done in the console_log_handler and not here.*/
3020 /* We set the log handlers right up front to make sure that any log */
3021 /* messages when running as child will be sent back to the parent */
3022 /* with the correct format. */
3026 G_LOG_LEVEL_CRITICAL|
3027 G_LOG_LEVEL_WARNING|
3028 G_LOG_LEVEL_MESSAGE|
3031 G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
3033 g_log_set_handler(NULL,
3035 console_log_handler, NULL /* user_data */);
3036 g_log_set_handler(LOG_DOMAIN_MAIN,
3038 console_log_handler, NULL /* user_data */);
3039 g_log_set_handler(LOG_DOMAIN_CAPTURE,
3041 console_log_handler, NULL /* user_data */);
3042 g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
3044 console_log_handler, NULL /* user_data */);
3047 /* Load wpcap if possible. Do this before collecting the run-time version information */
3050 /* ... and also load the packet.dll from wpcap */
3051 /* XXX - currently not required, may change later. */
3052 /*wpcap_packet_load();*/
3054 /* Start windows sockets */
3055 WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
3057 /* Set handler for Ctrl+C key */
3058 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
3060 /* Prepare to read from a pipe */
3061 if (!g_thread_supported ())
3062 g_thread_init (NULL);
3063 cap_pipe_pending_q = g_async_queue_new();
3064 cap_pipe_done_q = g_async_queue_new();
3065 cap_pipe_read_mtx = g_mutex_new();
3068 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
3070 action.sa_handler = capture_cleanup_handler;
3072 * Arrange that system calls not get restarted, because when
3073 * our signal handler returns we don't want to restart
3074 * a call that was waiting for packets to arrive.
3076 action.sa_flags = 0;
3077 sigemptyset(&action.sa_mask);
3078 sigaction(SIGTERM, &action, NULL);
3079 sigaction(SIGINT, &action, NULL);
3080 sigaction(SIGPIPE, &action, NULL);
3081 sigaction(SIGHUP, NULL, &oldaction);
3082 if (oldaction.sa_handler == SIG_DFL)
3083 sigaction(SIGHUP, &action, NULL);
3086 /* ----------------------------------------------------------------- */
3087 /* Privilege and capability handling */
3089 /* 1. Running not as root or suid root; no special capabilities. */
3092 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
3095 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
3097 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
3098 /* capabilities; Drop all other capabilities; */
3099 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3100 /* else: after pcap_open_live() in capture_loop_open_input() */
3101 /* drop all capabilities (NET_RAW and NET_ADMIN); */
3102 /* (Note: this means that the process, although logged in */
3103 /* as root, does not have various permissions such as the */
3104 /* ability to bypass file access permissions). */
3105 /* XXX: Should we just leave capabilities alone in this case */
3106 /* so that user gets expected effect that root can do */
3109 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
3111 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3112 /* else: after pcap_open_live() in capture_loop_open_input() */
3113 /* drop suid root (set euid=ruid).(ie: keep suid until after */
3114 /* pcap_open_live). */
3116 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
3118 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
3119 /* capabilities; Drop all other capabilities; */
3120 /* Drop suid privileges (euid=ruid); */
3121 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3122 /* else: after pcap_open_live() in capture_loop_open_input() */
3123 /* drop all capabilities (NET_RAW and NET_ADMIN). */
3125 /* XXX: For some Linux versions/distros with capabilities */
3126 /* a 'normal' process with any capabilities cannot be */
3127 /* 'killed' (signaled) from another (same uid) non-privileged */
3129 /* For example: If (non-suid) Wireshark forks a */
3130 /* child suid dumpcap which acts as described here (case 5), */
3131 /* Wireshark will be unable to kill (signal) the child */
3132 /* dumpcap process until the capabilities have been dropped */
3133 /* (after pcap_open_live()). */
3134 /* This behaviour will apparently be changed in the kernel */
3135 /* to allow the kill (signal) in this case. */
3136 /* See the following for details: */
3137 /* http://www.mail-archive.com/ [wrapped] */
3138 /* linux-security-module@vger.kernel.org/msg02913.html */
3140 /* It is therefore conceivable that if dumpcap somehow hangs */
3141 /* in pcap_open_live or before that wireshark will not */
3142 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
3143 /* In this case, exiting wireshark will kill the child */
3144 /* dumpcap process. */
3146 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
3147 /* capabilities; Using libcap. Note: capset cmd (which see) */
3148 /* used to assign capabilities to file. */
3150 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
3151 /* else: after pcap_open_live() in capture_loop_open_input() */
3152 /* drop all capabilities (NET_RAW and NET_ADMIN) */
3154 /* ToDo: -S (stats) should drop privileges/capabilities when no */
3155 /* longer required (similar to capture). */
3157 /* ----------------------------------------------------------------- */
3159 get_credential_info();
3162 /* If 'started with special privileges' (and using libcap) */
3163 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
3164 /* Set euid/egid = ruid/rgid to remove suid privileges */
3165 relinquish_privs_except_capture();
3168 /* Set the initial values in the capture options. This might be overwritten
3169 by the command line parameters. */
3170 capture_opts_init(&global_capture_opts, NULL);
3172 /* Default to capturing the entire packet. */
3173 global_capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
3175 /* We always save to a file - if no file was specified, we save to a
3177 global_capture_opts.saving_to_file = TRUE;
3178 global_capture_opts.has_ring_num_files = TRUE;
3180 /* Now get our args */
3181 while ((opt = getopt(argc, argv, OPTSTRING)) != -1) {
3183 case 'h': /* Print help and exit */
3187 case 'v': /* Show version and exit */
3189 GString *comp_info_str;
3190 GString *runtime_info_str;
3191 /* Assemble the compile-time version information string */
3192 comp_info_str = g_string_new("Compiled ");
3193 get_compiled_version_info(comp_info_str, NULL);
3195 /* Assemble the run-time version information string */
3196 runtime_info_str = g_string_new("Running ");
3197 get_runtime_version_info(runtime_info_str, NULL);
3198 show_version(comp_info_str, runtime_info_str);
3199 g_string_free(comp_info_str, TRUE);
3200 g_string_free(runtime_info_str, TRUE);
3204 /*** capture option specific ***/
3205 case 'a': /* autostop criteria */
3206 case 'b': /* Ringbuffer option */
3207 case 'c': /* Capture x packets */
3208 case 'f': /* capture filter */
3209 case 'i': /* Use interface x */
3210 case 'n': /* Use pcapng format */
3211 case 'p': /* Don't capture in promiscuous mode */
3212 case 's': /* Set the snapshot (capture) length */
3213 case 'w': /* Write to capture file x */
3214 case 'y': /* Set the pcap data link type */
3215 #ifdef HAVE_PCAP_REMOTE
3216 case 'u': /* Use UDP for data transfer */
3217 case 'r': /* Capture own RPCAP traffic too */
3218 case 'A': /* Authentication */
3220 #ifdef HAVE_PCAP_SETSAMPLING
3221 case 'm': /* Sampling */
3223 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
3224 case 'B': /* Buffer size */
3225 #endif /* _WIN32 or HAVE_PCAP_CREATE */
3226 #ifdef HAVE_PCAP_CREATE
3227 case 'I': /* Monitor mode */
3229 status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
3234 /*** hidden option: Wireshark child mode (using binary output messages) ***/
3236 capture_child = TRUE;
3238 /* set output pipe to binary mode, to avoid ugly text conversions */
3239 _setmode(2, O_BINARY);
3241 * optarg = the control ID, aka the PPID, currently used for the
3244 if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
3245 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
3246 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
3247 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
3249 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
3250 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3251 "Signal pipe: Unable to open %s. Dead parent?",
3259 /*** all non capture option specific ***/
3260 case 'D': /* Print a list of capture devices and exit */
3261 list_interfaces = TRUE;
3264 case 'L': /* Print list of link-layer types and exit */
3265 list_link_layer_types = TRUE;
3268 case 'S': /* Print interface statistics once a second */
3269 print_statistics = TRUE;
3272 case 'M': /* For -D and -L, print machine-readable output */
3273 machine_readable = TRUE;
3276 case '?': /* Bad flag - print usage message */
3277 cmdarg_err("Invalid Option: %s", argv[optind-1]);
3285 /* user specified file name as regular command-line argument */
3286 /* XXX - use it as the capture file name (or something else)? */
3293 * Extra command line arguments were specified; complain.
3294 * XXX - interpret as capture filter, as tcpdump and tshark do?
3296 cmdarg_err("Invalid argument: %s", argv[0]);
3305 if (run_once_args > 1) {
3306 cmdarg_err("Only one of -D, -L, or -S may be supplied.");
3308 } else if (list_link_layer_types) {
3309 /* We're supposed to list the link-layer types for an interface;
3310 did the user also specify a capture file to be read? */
3311 /* No - did they specify a ring buffer option? */
3312 if (global_capture_opts.multi_files_on) {
3313 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
3317 /* No - was the ring buffer option specified and, if so, does it make
3319 if (global_capture_opts.multi_files_on) {
3320 /* Ring buffer works only under certain conditions:
3321 a) ring buffer does not work with temporary files;
3322 b) it makes no sense to enable the ring buffer if the maximum
3323 file size is set to "infinite". */
3324 if (global_capture_opts.save_file == NULL) {
3325 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
3326 global_capture_opts.multi_files_on = FALSE;
3328 if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
3329 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
3330 /* XXX - this must be redesigned as the conditions changed */
3331 /* global_capture_opts.multi_files_on = FALSE;*/
3336 if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
3337 /* cmdarg_err() already called .... */
3341 /* Let the user know what interface was chosen. */
3342 /* get_interface_descriptive_name() is not available! */
3343 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", global_capture_opts.iface);
3345 if (list_interfaces) {
3346 /* Get the list of interfaces */
3351 if_list = capture_interface_list(&err, &err_str);
3352 if (if_list == NULL) {
3354 case CANT_GET_INTERFACE_LIST:
3355 cmdarg_err("%s", err_str);
3359 case NO_INTERFACES_FOUND:
3360 cmdarg_err("There are no interfaces on which a capture can be done");
3366 if (machine_readable) /* tab-separated values to stdout */
3367 print_machine_readable_interfaces(if_list);
3369 capture_opts_print_interfaces(if_list);
3370 free_interface_list(if_list);
3372 } else if (list_link_layer_types) {
3373 /* Get the list of link-layer types for the capture device. */
3377 lt_list = get_pcap_linktype_list(global_capture_opts.iface, &err_str);
3378 if (lt_list == NULL) {
3379 if (err_str != NULL) {
3380 cmdarg_err("The list of data link types for the capture device \"%s\" could not be obtained (%s)."
3381 "Please check to make sure you have sufficient permissions, and that\n"
3382 "you have the proper interface or pipe specified.\n", global_capture_opts.iface, err_str);
3385 cmdarg_err("The capture device \"%s\" has no data link types.", global_capture_opts.iface);
3388 if (machine_readable) /* tab-separated values to stdout */
3389 print_machine_readable_link_layer_types(lt_list);
3391 capture_opts_print_link_layer_types(lt_list);
3392 free_pcap_linktype_list(lt_list);
3394 } else if (print_statistics) {
3395 status = print_statistics_loop(machine_readable);
3399 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
3400 capture_opts_trim_ring_num_files(&global_capture_opts);
3402 /* Now start the capture. */
3404 if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
3408 /* capture failed */
3415 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
3416 const char *message, gpointer user_data _U_)
3423 /* ignore log message, if log_level isn't interesting */
3424 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3425 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
3430 /* create a "timestamp" */
3432 today = localtime(&curr);
3434 switch(log_level & G_LOG_LEVEL_MASK) {
3435 case G_LOG_LEVEL_ERROR:
3438 case G_LOG_LEVEL_CRITICAL:
3441 case G_LOG_LEVEL_WARNING:
3444 case G_LOG_LEVEL_MESSAGE:
3447 case G_LOG_LEVEL_INFO:
3450 case G_LOG_LEVEL_DEBUG:
3454 fprintf(stderr, "unknown log_level %u\n", log_level);
3456 g_assert_not_reached();
3459 /* Generate the output message */
3460 if(log_level & G_LOG_LEVEL_MESSAGE) {
3461 /* normal user messages without additional infos */
3462 msg = g_strdup_printf("%s\n", message);
3464 /* info/debug messages with additional infos */
3465 msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
3466 today->tm_hour, today->tm_min, today->tm_sec,
3467 log_domain != NULL ? log_domain : "",
3471 /* DEBUG & INFO msgs (if we're debugging today) */
3472 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3473 if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3474 #ifdef DEBUG_DUMPCAP
3475 fprintf(stderr, "%s", msg);
3478 #ifdef DEBUG_CHILD_DUMPCAP
3479 fprintf(debug_log, "%s", msg);
3487 /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or */
3488 /* to parent especially formatted if dumpcap running as child. */
3489 if (capture_child) {
3490 sync_pipe_errmsg_to_parent(2, msg, "");
3492 fprintf(stderr, "%s", msg);
3499 /****************************************************************************************************************/
3500 /* indication report routines */
3504 report_packet_count(int packet_count)
3506 char tmp[SP_DECISIZE+1+1];
3507 static int count = 0;
3510 g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
3511 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
3512 pipe_write_block(2, SP_PACKET_COUNT, tmp);
3514 count += packet_count;
3515 fprintf(stderr, "\rPackets: %u ", count);
3516 /* stderr could be line buffered */
3522 report_new_capture_file(const char *filename)
3525 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
3526 pipe_write_block(2, SP_FILE, filename);
3528 fprintf(stderr, "File: %s\n", filename);
3529 /* stderr could be line buffered */
3535 report_cfilter_error(const char *cfilter, const char *errmsg)
3537 if (capture_child) {
3538 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
3539 pipe_write_block(2, SP_BAD_FILTER, errmsg);
3542 "Invalid capture filter: \"%s\"!\n"
3544 "That string isn't a valid capture filter (%s).\n"
3545 "See the User's Guide for a description of the capture filter syntax.\n",
3551 report_capture_error(const char *error_msg, const char *secondary_error_msg)
3554 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3555 "Primary Error: %s", error_msg);
3556 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3557 "Secondary Error: %s", secondary_error_msg);
3558 sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
3560 fprintf(stderr, "%s\n%s\n", error_msg, secondary_error_msg);
3565 report_packet_drops(guint32 drops)
3567 char tmp[SP_DECISIZE+1+1];
3569 g_snprintf(tmp, sizeof(tmp), "%u", drops);
3572 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
3573 pipe_write_block(2, SP_DROPS, tmp);
3575 fprintf(stderr, "Packets dropped: %s\n", tmp);
3576 /* stderr could be line buffered */
3582 /****************************************************************************************************************/
3583 /* signal_pipe handling */
3588 signal_pipe_check_running(void)
3590 /* any news from our parent? -> just stop the capture */
3594 /* if we are running standalone, no check required */
3595 if(!capture_child) {
3599 if(!sig_pipe_name || !sig_pipe_handle) {
3600 /* This shouldn't happen */
3601 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3602 "Signal pipe: No name or handle");
3607 * XXX - We should have the process ID of the parent (from the "-Z" flag)
3608 * at this point. Should we check to see if the parent is still alive,
3609 * e.g. by using OpenProcess?
3612 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
3614 if(!result || avail > 0) {
3615 /* peek failed or some bytes really available */
3616 /* (if not piping from stdin this would fail) */
3617 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3618 "Signal pipe: Stop capture: %s", sig_pipe_name);
3619 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3620 "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
3621 sig_pipe_handle, result, avail);
3624 /* pipe ok and no bytes available */
3631 * Editor modelines - http://www.wireshark.org/tools/modelines.html
3636 * indent-tabs-mode: nil
3639 * vi: set shiftwidth=4 tabstop=8 expandtab
3640 * :indentSize=4:tabSize=8:noTabs=true: