3 * Wireshark - Network traffic analyzer
4 * By Gerald Combs <gerald@wireshark.org>
5 * Copyright 1998 Gerald Combs
7 * SPDX-License-Identifier: GPL-2.0-or-later
11 #define WS_LOG_DOMAIN LOG_DOMAIN_CAPCHILD
14 #include <stdlib.h> /* for exit() */
19 #include <ws_exit_codes.h>
21 #include <sys/types.h>
23 #ifdef HAVE_NETINET_IN_H
24 #include <netinet/in.h>
27 #include <wsutil/ws_getopt.h>
29 #if defined(__APPLE__) && defined(__LP64__)
30 #include <sys/utsname.h>
36 #include <wsutil/application_flavor.h>
37 #include <wsutil/array.h>
38 #include <wsutil/cmdarg_err.h>
39 #include <wsutil/report_message.h>
40 #include <wsutil/failure_message_simple.h>
41 #include <wsutil/strtoi.h>
43 #include <wsutil/version_info.h>
45 #include <wsutil/socket.h>
46 #include <wsutil/wslog.h>
47 #include <wsutil/file_util.h>
50 # include <sys/prctl.h>
51 # include <sys/capability.h>
54 #include "ringbuffer.h"
56 #include "capture/capture_ifinfo.h"
57 #include "capture/capture-pcap-util.h"
58 #include "capture/capture-pcap-util-int.h"
60 #include "capture/capture-wpcap.h"
63 #include "writecap/pcapio.h"
69 #include <wsutil/clopts_common.h>
70 #include <wsutil/privileges.h>
72 #include "sync_pipe.h"
74 #include "ui/capture_opts.h"
75 #include <capture/capture_session.h>
76 #include <capture/capture_sync.h>
78 #include "wsutil/tempfile.h"
79 #include "wsutil/file_util.h"
80 #include "wsutil/cpu_info.h"
81 #include "wsutil/os_version_info.h"
82 #include "wsutil/str_util.h"
83 #include "wsutil/inet_addr.h"
84 #include "wsutil/time_util.h"
85 #include "wsutil/please_report_bug.h"
86 #include "wsutil/glib-compat.h"
87 #include <wsutil/json_dumper.h>
88 #include <wsutil/ws_assert.h>
90 #include "capture/ws80211_utils.h"
95 * Get information about libpcap format from "wiretap/libpcap.h".
96 * Get information about pcapng format from "wiretap/pcapng_module.h".
97 * XXX - can we just use pcap_open_offline() to read the pipe?
99 #include "wiretap/libpcap.h"
100 #include "wiretap/pcapng_module.h"
101 #include "wiretap/pcapng.h"
104 * Define these for extra logging. Note that when dumpcap is spawned as
105 * a child process, logs are sent to the parent via the sync pipe.
106 * The parent will pass along the Capchild domain log level settings,
107 * so "--log-debug Capchild" or "--log-level debug" can be used to get
108 * debugging from dumpcap sent to the parent.
110 //#define DEBUG_DUMPCAP /* Waits for keypress on quitting on Windows */
111 //#define DEBUG_CHILD_DUMPCAP /* Writes logs to file */
114 #include "wsutil/win32-utils.h"
116 #include <conio.h> /* _getch() */
120 #ifdef DEBUG_CHILD_DUMPCAP
121 FILE *debug_log
; /* for logging debug messages to */
122 /* a file if DEBUG_CHILD_DUMPCAP */
124 #include <stdarg.h> /* va_copy */
127 static GAsyncQueue
*pcap_queue
;
128 static int64_t pcap_queue_bytes
;
129 static int64_t pcap_queue_packets
;
130 static int64_t pcap_queue_byte_limit
;
131 static int64_t pcap_queue_packet_limit
;
133 static bool capture_child
; /* false: standalone call, true: this is an Wireshark capture child */
134 static const char *report_capture_filename
; /* capture child file name */
136 static char *sig_pipe_name
;
137 static HANDLE sig_pipe_handle
;
138 static bool signal_pipe_check_running(void);
140 static int sync_pipe_fd
= 2;
142 #if defined (ENABLE_ASAN) || defined (ENABLE_LSAN)
143 /* This has public visibility so that if compiled with shared libasan (the
144 * gcc default) function interposition occurs.
147 __lsan_is_turned_off(void)
149 /* If we're in capture child mode, don't run a LSan report and
150 * send it to stderr, because it isn't properly formatted for
152 * We could, if debugging variables are set, send the reports
153 * elsewhere instead, by calling __sanitizer_set_report_path()
154 * or __sanitizer_set_report_fd()
160 /* LSan dies with a fatal error without explanation if it can't ptrace.
161 * Normally, the "dumpable" attribute (which also controls ptracing)
162 * is set to 1 (SUID_DUMP_USER, process is dumpable.) However, it is
163 * reset to the current value in /proc/sys/fs/suid_dumpable in the
164 * following circumstances: euid/egid changes, fsuid/fsgid changes,
165 * execve of a setuid or setgid program that changes the euid or egid,
166 * execve of a program with capabilities exceeding those already
167 * permitted for the process.
169 * Unless we're running as root, one of those applies to dumpcap.
171 * The default value of /proc/sys/fs/suid_dumpable is 0, SUID_DUMP_DISABLE.
172 * In such a case, LeakSanitizer temporarily sets the value to 1 to
173 * allow ptracing, and then sets it back to 0.
175 * Another possible value, used by Ubuntu, Fedora, etc., is 2,
176 * which creates dumps readable by root only. For security reasons,
177 * unprivileged programs are not allowed to change the value to 2.
178 * (See https://nvd.nist.gov/vuln/detail/CVE-2006-2451 )
180 * LSan does not check for the value 2 and change dumpable to 1 in that
181 * case, possibly because if it did it could not change it back to 2
182 * and would have to either leave the process dumpable or change it to 0.
184 * The usual way to control the family of sanitizers is through environment
185 * variables. However, complicating things, changing the dumpable attribute
186 * to 0 or 2 changes the ownership of files in /proc/[pid] (including
187 * /proc/self ) to root:root, in particular /proc/[pid]/environ, and so
188 * ASAN_OPTIONS=detect_leaks=0 has no effect. (Unless the process has
189 * CAP_SYS_PTRACE, which allows tracing of any process, but that's also
190 * a security risk and we'll have dropped that with other privileges.)
192 * So if prctl(PR_GET_DUMPABLE) returns 2, we know that the process will
193 * die with a fatal error if it attempts to run LSan, so don't.
195 * See proc(5), prctl(2), ptrace(2), and
196 * https://github.com/google/sanitizers/issues/1306
197 * https://github.com/llvm/llvm-project/issues/55944
199 if (prctl(PR_GET_DUMPABLE
) == 2) {
200 ws_debug("Not running LeakSanitizer because /proc/sys/fs/suid_dumpable is 2");
207 WS_DLL_PUBLIC
const char*
208 __asan_default_options(void)
210 /* By default don't override our exit code if there's a leak or error.
211 * We particularly don't want to do this if running as a capture child,
212 * because capture/capture_sync doesn't expect the ASan exit codes.
217 WS_DLL_PUBLIC
const char*
218 __lsan_default_options(void)
220 /* By default don't override our exit code if there's a leak or error.
221 * We particularly don't want to do this if running as a capture child,
222 * because capture/capture_sync doesn't expect the LSan exit codes.
229 static bool infodelay
; /* if true, don't print capture info in SIGINFO handler */
230 static bool infoprint
; /* if true, print capture info after clearing infodelay */
233 /** Stop a low-level capture (stops the capture child). */
234 static void capture_loop_stop(void);
235 /** Close a pipe, or socket if \a from_socket is true */
236 static void cap_pipe_close(int pipe_fd
, bool from_socket
);
238 #if defined (__linux__)
239 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
240 * in pcap_dispatch(); on the other hand, select() works just fine there.
241 * Hence we use a select for that come what may.
243 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
244 * internally, and, with TPACKET_V3, once that's supported, it'll
245 * support timeouts, at least as I understand the way the code works.
247 #define MUST_DO_SELECT
250 /** init the capture filter */
253 INITFILTER_BAD_FILTER
,
254 INITFILTER_OTHER_ERROR
255 } initfilter_status_t
;
258 STATE_EXPECT_REC_HDR
,
271 typedef struct _pcap_pipe_info
{
272 bool byte_swapped
; /**< true if data in the pipe is byte swapped. */
273 struct pcap_hdr hdr
; /**< Pcap header when capturing from a pipe */
274 struct pcaprec_modified_hdr rechdr
; /**< Pcap record header when capturing from a pipe */
277 typedef struct _pcapng_pipe_info
{
278 pcapng_block_header_t bh
; /**< Pcapng general block header when capturing from a pipe */
279 GArray
*src_iface_to_global
; /**< Int array mapping local IDB numbers to global_ld.interface_data */
280 } pcapng_pipe_info_t
;
282 struct _loop_data
; /* forward declaration so we can use it in the cap_pipe_dispatch function pointer */
285 * A source of packets from which we're capturing.
287 typedef struct _capture_src
{
292 #ifdef MUST_DO_SELECT
293 int pcap_fd
; /**< pcap file descriptor */
296 unsigned interface_id
;
297 unsigned idb_id
; /**< If from_pcapng is false, the output IDB interface ID. Otherwise the mapping in src_iface_to_global is used. */
301 bool ts_nsec
; /**< true if we're using nanosecond precision. */
302 /**< capture pipe (unix only "input file") */
303 bool from_cap_pipe
; /**< true if we are capturing data from a capture pipe */
304 bool from_cap_socket
; /**< true if we're capturing from socket */
305 bool from_pcapng
; /**< true if we're capturing from pcapng format */
307 pcap_pipe_info_t pcap
; /**< Pcap info when capturing from a pipe */
308 pcapng_pipe_info_t pcapng
; /**< Pcapng info when capturing from a pipe */
311 HANDLE cap_pipe_h
; /**< The handle of the capture pipe */
313 int cap_pipe_fd
; /**< the file descriptor of the capture pipe */
314 bool cap_pipe_modified
; /**< true if data in the pipe uses modified pcap headers */
315 char * cap_pipe_databuf
; /**< Pointer to the data buffer we've allocated */
316 size_t cap_pipe_databuf_size
; /**< Current size of the data buffer */
317 unsigned cap_pipe_max_pkt_size
; /**< Maximum packet size allowed */
319 char * cap_pipe_buf
; /**< Pointer to the buffer we read into */
320 DWORD cap_pipe_bytes_to_read
; /**< Used by cap_pipe_dispatch */
321 DWORD cap_pipe_bytes_read
; /**< Used by cap_pipe_dispatch */
323 size_t cap_pipe_bytes_to_read
; /**< Used by cap_pipe_dispatch */
324 size_t cap_pipe_bytes_read
; /**< Used by cap_pipe_dispatch */
326 int (*cap_pipe_dispatch
)(struct _loop_data
*, struct _capture_src
*, char *, size_t);
327 cap_pipe_state_t cap_pipe_state
;
328 cap_pipe_err_t cap_pipe_err
;
331 GMutex
*cap_pipe_read_mtx
;
332 GAsyncQueue
*cap_pipe_pending_q
, *cap_pipe_done_q
;
336 typedef struct _saved_idb
{
338 unsigned interface_id
; /* capture_src->interface_id for the associated SHB */
339 uint8_t *idb
; /* If non-NULL, IDB read from capture_src. This is an interface specified on the command line otherwise. */
344 * Global capture loop state.
346 typedef struct _loop_data
{
348 bool go
; /**< true as long as we're supposed to keep capturing */
349 int err
; /**< if non-zero, error seen while capturing */
350 int packets_captured
; /**< Number of packets we have already captured */
351 unsigned inpkts_to_sync_pipe
; /**< Packets not already send out to the sync_pipe */
353 bool report_packet_count
; /**< Set by SIGINFO handler; print packet count */
355 GArray
*pcaps
; /**< Array of capture_src's on which we're capturing */
356 bool pcapng_passthrough
; /**< We have one source and it's pcapng. Pass its SHB and IDBs through. */
357 uint8_t *saved_shb
; /**< SHB to write when we have one pcapng input */
358 GArray
*saved_idbs
; /**< Array of saved_idb_t, written when we have a new section or output file. */
359 GRWLock saved_shb_idb_lock
; /**< Saved IDB RW mutex */
363 char *io_buffer
; /**< Our IO buffer if we increase the size from the standard size */
364 uint64_t bytes_written
; /**< Bytes written for the current file. */
365 /* autostop conditions */
366 int packets_written
; /**< Packets written for the current file. */
368 /* ring buffer conditions */
369 GTimer
*file_duration_timer
;
370 time_t next_interval_time
;
374 typedef struct _pcap_queue_element
{
375 capture_src
*pcap_src
;
377 struct pcap_pkthdr phdr
;
378 pcapng_block_header_t bh
;
381 } pcap_queue_element
;
384 * This needs to be static, so that the SIGINT handler can clear the "go"
385 * flag and for saved_shb_idb_lock.
387 static loop_data global_ld
;
390 * Timeout, in milliseconds, for reads from the stream of captured packets
391 * from a capture device.
393 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
394 * 64-bit applications, with sub-second timeouts not to work. The bug is
395 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
397 #if defined(__APPLE__) && defined(__LP64__)
398 static bool need_timeout_workaround
;
400 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
402 #define CAP_READ_TIMEOUT 250
406 * Timeout, in microseconds, for reads from the stream of captured packets
407 * from a pipe. Pipes don't have the same problem that BPF devices do
408 * in Mac OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
409 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
410 * of the offending versions of Snow Leopard.
412 * On Windows this value is converted to milliseconds and passed to
413 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
414 * will return immediately.
417 #define PIPE_READ_TIMEOUT 100000
419 #define PIPE_READ_TIMEOUT 250000
422 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
425 dumpcap_log_writer(const char *domain
, enum ws_log_level level
,
426 const char *file
, long line
, const char *func
,
427 const char *fatal_msg
, ws_log_manifest_t
*mft
,
428 const char *user_format
, va_list user_ap
,
431 /* capture related options */
432 static capture_options global_capture_opts
;
433 static GPtrArray
*capture_comments
;
435 static bool really_quiet
;
436 static bool use_threads
;
437 static uint64_t start_time
;
439 static void capture_loop_write_packet_cb(uint8_t *pcap_src_p
, const struct pcap_pkthdr
*phdr
,
441 static void capture_loop_queue_packet_cb(uint8_t *pcap_src_p
, const struct pcap_pkthdr
*phdr
,
443 static void capture_loop_write_pcapng_cb(capture_src
*pcap_src
, const pcapng_block_header_t
*bh
, uint8_t *pd
);
444 static void capture_loop_queue_pcapng_cb(capture_src
*pcap_src
, const pcapng_block_header_t
*bh
, uint8_t *pd
);
445 static void capture_loop_get_errmsg(char *errmsg
, size_t errmsglen
,
446 char *secondary_errmsg
,
447 size_t secondary_errmsglen
,
448 const char *fname
, int err
,
451 WS_NORETURN
static void exit_main(int err
);
453 static void report_new_capture_file(const char *filename
);
454 static void report_packet_count(unsigned int packet_count
);
455 static void report_packet_drops(uint32_t received
, uint32_t pcap_drops
, uint32_t drops
, uint32_t flushed
, uint32_t ps_ifdrop
, char *name
);
456 static void report_capture_error(const char *error_msg
, const char *secondary_error_msg
);
457 static void report_cfilter_error(capture_options
*capture_opts
, unsigned i
, const char *errmsg
);
459 #define MSG_MAX_LENGTH 4096
462 print_usage(FILE *output
)
464 fprintf(output
, "\nUsage: dumpcap [options] ...\n");
465 fprintf(output
, "\n");
466 fprintf(output
, "Capture interface:\n");
467 fprintf(output
, " -i <interface>, --interface <interface>\n");
468 fprintf(output
, " name or idx of interface (def: first non-loopback)\n"
469 #ifdef HAVE_PCAP_REMOTE
470 " or for remote capturing, use one of these formats:\n"
471 " rpcap://<host>/<interface>\n"
473 " or for remote capturing, use this format:\n"
475 " TCP@<host>:<port>\n");
476 fprintf(output
, " --ifname <name> name to use in the capture file for a pipe from which\n");
477 fprintf(output
, " we're capturing\n");
478 fprintf(output
, " --ifdescr <description>\n");
479 fprintf(output
, " description to use in the capture file for a pipe\n");
480 fprintf(output
, " from which we're capturing\n");
481 fprintf(output
, " -f <capture filter> packet filter in libpcap filter syntax\n");
482 fprintf(output
, " -s <snaplen>, --snapshot-length <snaplen>\n");
483 #ifdef HAVE_PCAP_CREATE
484 fprintf(output
, " packet snapshot length (def: appropriate maximum)\n");
486 fprintf(output
, " packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD
);
488 fprintf(output
, " -p, --no-promiscuous-mode\n");
489 fprintf(output
, " don't capture in promiscuous mode\n");
490 #ifdef HAVE_PCAP_CREATE
491 fprintf(output
, " -I, --monitor-mode capture in monitor mode, if available\n");
493 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
494 fprintf(output
, " -B <buffer size>, --buffer-size <buffer size>\n");
495 fprintf(output
, " size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE
);
497 fprintf(output
, " -y <link type>, --linktype <link type>\n");
498 fprintf(output
, " link layer type (def: first appropriate)\n");
499 fprintf(output
, " --time-stamp-type <type> timestamp method for interface\n");
500 fprintf(output
, " -D, --list-interfaces print list of interfaces and exit\n");
501 fprintf(output
, " -L, --list-data-link-types\n");
502 fprintf(output
, " print list of link-layer types of iface and exit\n");
503 fprintf(output
, " --list-time-stamp-types print list of timestamp types for iface and exit\n");
504 fprintf(output
, " --update-interval interval between updates with new packets, in milliseconds (def: %dms)\n", DEFAULT_UPDATE_INTERVAL
);
505 fprintf(output
, " -d print generated BPF code for capture filter\n");
506 fprintf(output
, " -k <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
507 fprintf(output
, " set channel on wifi interface\n");
508 fprintf(output
, " -S print statistics for each interface once per second\n");
509 fprintf(output
, " -M for -D, -L, and -S, produce machine-readable output\n");
510 fprintf(output
, "\n");
511 #ifdef HAVE_PCAP_REMOTE
512 fprintf(output
, "RPCAP options:\n");
513 fprintf(output
, " -r don't ignore own RPCAP traffic in capture\n");
514 fprintf(output
, " -u use UDP for RPCAP data transfer\n");
515 fprintf(output
, " -A <user>:<password> use RPCAP password authentication\n");
516 #ifdef HAVE_PCAP_SETSAMPLING
517 fprintf(output
, " -m <sampling type> use packet sampling\n");
518 fprintf(output
, " count:NUM - capture one packet of every NUM\n");
519 fprintf(output
, " timer:NUM - capture no more than 1 packet in NUM ms\n");
522 fprintf(output
, "Stop conditions:\n");
523 fprintf(output
, " -c <packet count> stop after n packets (def: infinite)\n");
524 fprintf(output
, " -a <autostop cond.> ..., --autostop <autostop cond.> ...\n");
525 fprintf(output
, " duration:NUM - stop after NUM seconds\n");
526 fprintf(output
, " filesize:NUM - stop this file after NUM kB\n");
527 fprintf(output
, " files:NUM - stop after NUM files\n");
528 fprintf(output
, " packets:NUM - stop after NUM packets\n");
529 /*fprintf(output, "\n");*/
530 fprintf(output
, "Output (files):\n");
531 fprintf(output
, " -w <filename> name of file to save (def: tempfile)\n");
532 fprintf(output
, " -g enable group read access on the output file(s)\n");
533 fprintf(output
, " -b <ringbuffer opt.> ..., --ring-buffer <ringbuffer opt.>\n");
534 fprintf(output
, " duration:NUM - switch to next file after NUM secs\n");
535 fprintf(output
, " filesize:NUM - switch to next file after NUM kB\n");
536 fprintf(output
, " files:NUM - ringbuffer: replace after NUM files\n");
537 fprintf(output
, " packets:NUM - ringbuffer: replace after NUM packets\n");
538 fprintf(output
, " interval:NUM - switch to next file when the time is\n");
539 fprintf(output
, " an exact multiple of NUM secs\n");
540 fprintf(output
, " printname:FILE - print filename to FILE when written\n");
541 fprintf(output
, " (can use 'stdout' or 'stderr')\n");
542 fprintf(output
, " -n use pcapng format instead of pcap (default)\n");
543 fprintf(output
, " -P use libpcap format instead of pcapng\n");
544 fprintf(output
, " --capture-comment <comment>\n");
545 fprintf(output
, " add a capture comment to the output file\n");
546 fprintf(output
, " (only for pcapng)\n");
547 fprintf(output
, " --temp-dir <directory> write temporary files to this directory\n");
548 fprintf(output
, " (default: %s)\n", g_get_tmp_dir());
549 fprintf(output
, "\n");
551 ws_log_print_usage(output
);
552 fprintf(output
, "\n");
554 fprintf(output
, "Miscellaneous:\n");
555 fprintf(output
, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
556 fprintf(output
, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
557 fprintf(output
, " within dumpcap\n");
558 fprintf(output
, " -t use a separate thread per interface\n");
559 fprintf(output
, " -q don't report packet capture counts\n");
560 fprintf(output
, " --application-flavor <flavor>\n");
561 fprintf(output
, " set the application flavor\n");
562 fprintf(output
, " -v, --version print version information and exit\n");
563 fprintf(output
, " -h, --help display this help and exit\n");
564 fprintf(output
, "\n");
566 fprintf(output
, "Dumpcap can benefit from an enabled BPF JIT compiler if available.\n");
567 fprintf(output
, "You might want to enable it by executing:\n");
568 fprintf(output
, " \"echo 1 > /proc/sys/net/core/bpf_jit_enable\"\n");
569 fprintf(output
, "Note that this can make your system less secure!\n");
570 fprintf(output
, "\n");
572 fprintf(output
, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
573 fprintf(output
, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
574 fprintf(output
, "\n");
575 fprintf(output
, "Use Ctrl-C to stop capturing at any time.\n");
579 * Report an error in command-line arguments.
580 * If we're a capture child, send a message back to the parent, otherwise
584 dumpcap_cmdarg_err(const char *fmt
, va_list ap
)
588 /* Generate a 'special format' message back to parent */
589 msg
= ws_strdup_vprintf(fmt
, ap
);
590 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd
, msg
, "");
593 fprintf(stderr
, "dumpcap: ");
594 vfprintf(stderr
, fmt
, ap
);
595 fprintf(stderr
, "\n");
600 * Report additional information for an error in command-line arguments.
601 * If we're a capture child, send a message back to the parent, otherwise
605 dumpcap_cmdarg_err_cont(const char *fmt
, va_list ap
)
609 msg
= ws_strdup_vprintf(fmt
, ap
);
610 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd
, msg
, "");
613 vfprintf(stderr
, fmt
, ap
);
614 fprintf(stderr
, "\n");
620 /* see 'man cap_to_text()' for explanation of output */
621 /* '=' means 'all= ' ie: no capabilities */
622 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
624 print_caps(const char *pfx
) {
625 if (ws_log_msg_is_active(WS_LOG_DOMAIN
, LOG_LEVEL_NOISY
)) {
626 cap_t caps
= cap_get_proc();
627 char *caps_text
= cap_to_text(caps
, NULL
);
628 ws_noisy("%s: EUID: %d Capabilities: %s", pfx
, geteuid(), caps_text
);
635 relinquish_all_capabilities(void)
637 /* Drop any and all capabilities this process may have. */
638 /* Allowed whether or not process has any privileges. */
639 cap_t caps
= cap_init(); /* all capabilities initialized to off */
640 print_caps("Pre-clear");
641 if (cap_set_proc(caps
)) {
642 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno
));
644 print_caps("Post-clear");
650 get_capture_device_open_failure_messages(cap_device_open_status open_status
,
651 const char *open_status_str
,
653 char *errmsg
, size_t errmsg_len
,
654 char *secondary_errmsg
,
655 size_t secondary_errmsg_len
)
657 switch (open_status
) {
659 case CAP_DEVICE_OPEN_ERROR_NO_SUCH_DEVICE
:
660 snprintf(errmsg
, errmsg_len
,
661 "There is no device named \"%s\".\n(%s)",
662 iface
, open_status_str
);
665 case CAP_DEVICE_OPEN_ERROR_RFMON_NOTSUP
:
666 snprintf(errmsg
, errmsg_len
,
667 "Capturing in monitor mode is not supported on device \"%s\".\n(%s)",
668 iface
, open_status_str
);
671 case CAP_DEVICE_OPEN_ERROR_PERM_DENIED
:
672 snprintf(errmsg
, errmsg_len
,
673 "You do not have permission to capture on device \"%s\".\n(%s)",
674 iface
, open_status_str
);
677 case CAP_DEVICE_OPEN_ERROR_IFACE_NOT_UP
:
678 snprintf(errmsg
, errmsg_len
,
679 "Device \"%s\" is not up.\n(%s)",
680 iface
, open_status_str
);
683 case CAP_DEVICE_OPEN_ERROR_PROMISC_PERM_DENIED
:
684 snprintf(errmsg
, errmsg_len
,
685 "You do not have permission to capture in promiscuous mode on device \"%s\".\n(%s)",
686 iface
, open_status_str
);
689 case CAP_DEVICE_OPEN_ERROR_OTHER
:
691 snprintf(errmsg
, errmsg_len
,
692 "The capture session could not be initiated on capture device \"%s\".\n(%s)",
693 iface
, open_status_str
);
696 snprintf(secondary_errmsg
, secondary_errmsg_len
, "%s",
697 get_pcap_failure_secondary_error_message(open_status
, open_status_str
));
701 compile_capture_filter(const char *iface
, pcap_t
*pcap_h
,
702 struct bpf_program
*fcode
, const char *cfilter
)
704 bpf_u_int32 netnum
, netmask
;
705 char lookup_net_err_str
[PCAP_ERRBUF_SIZE
];
707 if (pcap_lookupnet(iface
, &netnum
, &netmask
, lookup_net_err_str
) < 0) {
709 * Well, we can't get the netmask for this interface; it's used
710 * only for filters that check for broadcast IP addresses, so
711 * we just punt and use 0. It might be nice to warn the user,
712 * but that's a pain in a GUI application, as it'd involve popping
713 * up a message box, and it's not clear how often this would make
714 * a difference (only filters that check for IP broadcast addresses
718 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
723 * Sigh. Older versions of libpcap don't properly declare the
724 * third argument to pcap_compile() as a const pointer. Cast
728 if (pcap_compile(pcap_h
, fcode
, (char *)cfilter
, 1, netmask
) < 0)
735 show_filter_code(capture_options
*capture_opts
)
737 interface_options
*interface_opts
;
739 cap_device_open_status open_status
;
740 char open_status_str
[PCAP_ERRBUF_SIZE
];
741 char errmsg
[MSG_MAX_LENGTH
+1];
742 char secondary_errmsg
[MSG_MAX_LENGTH
+1];
743 struct bpf_program fcode
;
744 struct bpf_insn
*insn
;
748 for (j
= 0; j
< capture_opts
->ifaces
->len
; j
++) {
749 interface_opts
= &g_array_index(capture_opts
->ifaces
, interface_options
, j
);
750 pcap_h
= open_capture_device(capture_opts
, interface_opts
,
751 CAP_READ_TIMEOUT
, &open_status
, &open_status_str
);
752 if (pcap_h
== NULL
) {
753 /* Open failed; get messages */
754 get_capture_device_open_failure_messages(open_status
, open_status_str
,
755 interface_opts
->name
,
756 errmsg
, sizeof errmsg
,
758 sizeof secondary_errmsg
);
759 /* And report them */
760 report_capture_error(errmsg
, secondary_errmsg
);
764 /* Set the link-layer type. */
765 if (!set_pcap_datalink(pcap_h
, interface_opts
->linktype
, interface_opts
->name
,
766 errmsg
, sizeof errmsg
,
767 secondary_errmsg
, sizeof secondary_errmsg
)) {
769 report_capture_error(errmsg
, secondary_errmsg
);
773 /* OK, try to compile the capture filter. */
774 if (!compile_capture_filter(interface_opts
->name
, pcap_h
, &fcode
,
775 interface_opts
->cfilter
)) {
776 snprintf(errmsg
, sizeof(errmsg
), "%s", pcap_geterr(pcap_h
));
778 report_cfilter_error(capture_opts
, j
, errmsg
);
783 /* Now print the filter code. */
784 insn
= fcode
.bf_insns
;
786 for (i
= 0; i
< fcode
.bf_len
; insn
++, i
++)
787 printf("%s\n", bpf_image(insn
, i
));
789 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
790 /* to remove any suid privileges. */
791 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
792 /* (euid/egid have already previously been set to ruid/rgid. */
793 /* (See comment in main() for details) */
794 /* XXX - On Linux, if we're capturing on a mac80211 device and enabling */
795 /* rfmon via libpcap with libnl support, that creates a new monitor mode */
796 /* device that libpcap will attempt to delete when capture is done. That */
797 /* will fail with EPERM because we dropped privileges. */
799 relinquish_special_privs_perm();
801 relinquish_all_capabilities();
804 /* Let our parent know we succeeded. */
805 sync_pipe_write_string_msg(sync_pipe_fd
, SP_SUCCESS
, NULL
);
811 print_machine_readable_if_capabilities(json_dumper
*dumper
, if_capabilities_t
*caps
, int queries
);
814 * Output a machine readable list of the interfaces
815 * This list is retrieved by the sync_interface_list_open() function
816 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
819 print_machine_readable_interfaces(GList
*if_list
, int caps_queries
, bool print_statistics
)
825 char addr_str
[WS_INET6_ADDRSTRLEN
];
828 json_dumper dumper
= {
829 .output_string
= g_string_new(NULL
),
830 .flags
= JSON_DUMPER_FLAGS_NO_DEBUG
,
831 // Don't abort on failure
833 json_dumper_begin_array(&dumper
);
836 * Print the contents of the if_entry struct in a parseable format (JSON)
838 for (if_entry
= g_list_first(if_list
); if_entry
!= NULL
;
839 if_entry
= g_list_next(if_entry
)) {
840 if_info
= (if_info_t
*)if_entry
->data
;
842 json_dumper_begin_object(&dumper
);
843 json_dumper_set_member_name(&dumper
, if_info
->name
);
845 json_dumper_begin_object(&dumper
);
847 json_dumper_set_member_name(&dumper
, "friendly_name");
848 json_dumper_value_string(&dumper
, if_info
->friendly_name
);
850 json_dumper_set_member_name(&dumper
, "vendor_description");
851 json_dumper_value_string(&dumper
, if_info
->vendor_description
);
853 json_dumper_set_member_name(&dumper
, "type");
854 json_dumper_value_anyf(&dumper
, "%i", if_info
->type
);
856 json_dumper_set_member_name(&dumper
, "addrs");
858 json_dumper_begin_array(&dumper
);
859 for (addr
= g_slist_nth(if_info
->addrs
, 0); addr
!= NULL
;
860 addr
= g_slist_next(addr
)) {
862 if_addr
= (if_addr_t
*)addr
->data
;
863 switch(if_addr
->ifat_type
) {
865 json_dumper_value_string(&dumper
, ws_inet_ntop4(&if_addr
->addr
.ip4_addr
, addr_str
, sizeof(addr_str
)));
868 json_dumper_value_string(&dumper
, ws_inet_ntop6(&if_addr
->addr
.ip6_addr
, addr_str
, sizeof(addr_str
)));
871 json_dumper_value_anyf(&dumper
, "<type unknown %i>", if_addr
->ifat_type
);
874 json_dumper_end_array(&dumper
);
876 json_dumper_set_member_name(&dumper
, "loopback");
877 json_dumper_value_anyf(&dumper
, "%s", if_info
->loopback
? "true" : "false");
879 json_dumper_set_member_name(&dumper
, "extcap");
880 json_dumper_value_string(&dumper
, if_info
->extcap
);
882 if (if_info
->caps
&& caps_queries
) {
883 json_dumper_set_member_name(&dumper
, "caps");
884 json_dumper_begin_object(&dumper
);
885 print_machine_readable_if_capabilities(&dumper
, if_info
->caps
, caps_queries
);
886 json_dumper_end_object(&dumper
);
888 json_dumper_end_object(&dumper
);
889 json_dumper_end_object(&dumper
);
891 json_dumper_end_array(&dumper
);
892 if (json_dumper_finish(&dumper
)) {
895 if (print_statistics
) {
896 sync_pipe_write_string_msg(sync_pipe_fd
, SP_IFACE_LIST
, dumper
.output_string
->str
);
898 /* Let our parent know we succeeded. */
899 sync_pipe_write_string_msg(sync_pipe_fd
, SP_SUCCESS
, NULL
);
900 printf("%s", dumper
.output_string
->str
);
903 printf("%s", dumper
.output_string
->str
);
908 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd
, "Unexpected JSON error", "");
910 cmdarg_err("Unexpected JSON error");
913 g_string_free(dumper
.output_string
, TRUE
);
918 * If you change the machine-readable output format of this function,
919 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
922 print_machine_readable_if_capabilities(json_dumper
*dumper
, if_capabilities_t
*caps
, int queries
)
924 GList
*lt_entry
, *ts_entry
;
925 const char *desc_str
;
927 json_dumper_set_member_name(dumper
, "status");
928 json_dumper_value_anyf(dumper
, "%i", caps
->status
);
929 if (caps
->primary_msg
) {
930 json_dumper_set_member_name(dumper
, "primary_msg");
931 json_dumper_value_string(dumper
, caps
->primary_msg
);
934 if (queries
& CAPS_QUERY_LINK_TYPES
) {
935 json_dumper_set_member_name(dumper
, "rfmon");
936 json_dumper_value_anyf(dumper
, "%s", caps
->can_set_rfmon
? "true" : "false");
937 json_dumper_set_member_name(dumper
, "data_link_types");
938 json_dumper_begin_array(dumper
);
939 for (lt_entry
= caps
->data_link_types
; lt_entry
!= NULL
;
940 lt_entry
= g_list_next(lt_entry
)) {
941 data_link_info_t
*data_link_info
= (data_link_info_t
*)lt_entry
->data
;
942 if (data_link_info
->description
!= NULL
)
943 desc_str
= data_link_info
->description
;
945 desc_str
= "(not supported)";
946 json_dumper_begin_object(dumper
);
947 json_dumper_set_member_name(dumper
, "dlt");
948 json_dumper_value_anyf(dumper
, "%d", data_link_info
->dlt
);
949 json_dumper_set_member_name(dumper
, "name");
950 json_dumper_value_string(dumper
, data_link_info
->name
);
951 json_dumper_set_member_name(dumper
, "description");
952 json_dumper_value_string(dumper
, desc_str
);
953 json_dumper_end_object(dumper
);
955 json_dumper_end_array(dumper
);
957 json_dumper_set_member_name(dumper
, "data_link_types_rfmon");
958 json_dumper_begin_array(dumper
);
959 for (lt_entry
= caps
->data_link_types_rfmon
; lt_entry
!= NULL
;
960 lt_entry
= g_list_next(lt_entry
)) {
961 data_link_info_t
*data_link_info
= (data_link_info_t
*)lt_entry
->data
;
962 if (data_link_info
->description
!= NULL
)
963 desc_str
= data_link_info
->description
;
965 desc_str
= "(not supported)";
966 json_dumper_begin_object(dumper
);
967 json_dumper_set_member_name(dumper
, "dlt");
968 json_dumper_value_anyf(dumper
, "%d", data_link_info
->dlt
);
969 json_dumper_set_member_name(dumper
, "name");
970 json_dumper_value_string(dumper
, data_link_info
->name
);
971 json_dumper_set_member_name(dumper
, "description");
972 json_dumper_value_string(dumper
, desc_str
);
973 json_dumper_end_object(dumper
);
975 json_dumper_end_array(dumper
);
977 if (queries
& CAPS_QUERY_TIMESTAMP_TYPES
) {
978 json_dumper_set_member_name(dumper
, "timestamp_types");
979 json_dumper_begin_array(dumper
);
980 for (ts_entry
= caps
->timestamp_types
; ts_entry
!= NULL
;
981 ts_entry
= g_list_next(ts_entry
)) {
982 timestamp_info_t
*timestamp
= (timestamp_info_t
*)ts_entry
->data
;
983 if (timestamp
->description
!= NULL
)
984 desc_str
= timestamp
->description
;
987 json_dumper_begin_object(dumper
);
988 json_dumper_set_member_name(dumper
, "name");
989 json_dumper_value_string(dumper
, timestamp
->name
);
990 json_dumper_set_member_name(dumper
, "description");
991 json_dumper_value_string(dumper
, desc_str
);
992 json_dumper_end_object(dumper
);
994 json_dumper_end_array(dumper
);
1003 /* Print the number of packets captured for each interface until we're killed. */
1005 print_statistics_loop(bool machine_readable
)
1007 GList
*if_list
, *if_entry
, *stat_list
= NULL
, *stat_entry
;
1013 char errbuf
[PCAP_ERRBUF_SIZE
];
1014 struct pcap_stat ps
;
1016 if_list
= get_interface_list(&err
, &err_str
);
1017 if (if_list
== NULL
) {
1019 cmdarg_err("There are no interfaces on which a capture can be done");
1020 err
= WS_EXIT_NO_INTERFACES
;
1023 cmdarg_err("%s", err_str
);
1029 for (if_entry
= g_list_first(if_list
); if_entry
!= NULL
; if_entry
= g_list_next(if_entry
)) {
1030 if_info
= (if_info_t
*)if_entry
->data
;
1033 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
1034 * connections. We avoid collecting stats on them.
1036 if (!strncmp(if_info
->name
, "nf", 2)) {
1037 ws_debug("Skipping interface %s for stats", if_info
->name
);
1042 #ifdef HAVE_PCAP_OPEN
1044 * If we're opening a remote device, use pcap_open(); that's currently
1045 * the only open routine that supports remote devices.
1047 if (strncmp(if_info
->name
, "rpcap://", 8) == 0)
1048 pch
= pcap_open(if_info
->name
, MIN_PACKET_SIZE
, 0, 0, NULL
, errbuf
);
1051 pch
= pcap_open_live(if_info
->name
, MIN_PACKET_SIZE
, 0, 0, errbuf
);
1054 if_stat
= g_new(if_stat_t
, 1);
1055 if_stat
->name
= g_strdup(if_info
->name
);
1057 stat_list
= g_list_append(stat_list
, if_stat
);
1062 cmdarg_err("There are no interfaces on which a capture can be done");
1066 if (capture_child
) {
1067 /* Let our parent know we succeeded. */
1068 sync_pipe_write_string_msg(sync_pipe_fd
, SP_SUCCESS
, NULL
);
1071 if (!machine_readable
) {
1072 printf("%-15s %10s %10s\n", "Interface", "Received",
1076 global_ld
.go
= true;
1077 while (global_ld
.go
) {
1078 for (stat_entry
= g_list_first(stat_list
); stat_entry
!= NULL
; stat_entry
= g_list_next(stat_entry
)) {
1079 if_stat
= (if_stat_t
*)stat_entry
->data
;
1080 /* XXX - what if this fails? */
1081 if (pcap_stats(if_stat
->pch
, &ps
) == 0) {
1082 if (!machine_readable
) {
1083 printf("%-15s %10u %10u\n", if_stat
->name
,
1084 ps
.ps_recv
, ps
.ps_drop
);
1086 printf("%s\t%u\t%u\n", if_stat
->name
,
1087 ps
.ps_recv
, ps
.ps_drop
);
1093 /* If we have a dummy signal pipe check it */
1094 if (!signal_pipe_check_running()) {
1095 global_ld
.go
= false;
1103 /* XXX - Not reached. Should we look for 'q' in stdin? */
1104 for (stat_entry
= g_list_first(stat_list
); stat_entry
!= NULL
; stat_entry
= g_list_next(stat_entry
)) {
1105 if_stat
= (if_stat_t
*)stat_entry
->data
;
1106 pcap_close(if_stat
->pch
);
1107 g_free(if_stat
->name
);
1110 g_list_free(stat_list
);
1111 free_interface_list(if_list
);
1119 capture_cleanup_handler(DWORD dwCtrlType
)
1121 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1122 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1123 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1124 like SIGTERM at least when the machine's shutting down.
1126 For now, if we're running as a command rather than a capture child,
1127 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1128 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1129 in that way on UN*X.
1131 If we're not running as a capture child, we might be running as
1132 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1133 user logs out. (XXX - can we explicitly check whether we're
1134 running as a service?) */
1136 ws_info("Console: Control signal");
1137 ws_debug("Console: Control signal, CtrlType: %lu", dwCtrlType
);
1139 /* Keep capture running if we're a service and a user logs off */
1140 if (capture_child
|| (dwCtrlType
!= CTRL_LOGOFF_EVENT
)) {
1141 capture_loop_stop();
1149 capture_cleanup_handler(int signum _U_
)
1151 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1152 SIGTERM. We assume that if the user wanted it to keep running
1153 after they logged out, they'd have nohupped it. */
1155 capture_loop_stop();
1161 report_capture_count(bool reportit
)
1163 /* Don't print this if we're a capture child. */
1164 if (!capture_child
&& reportit
) {
1165 fprintf(stderr
, "\rPackets captured: %d\n", global_ld
.packets_captured
);
1166 /* stderr could be line buffered */
1174 report_counts_for_siginfo(void)
1176 report_capture_count(quiet
);
1177 infoprint
= false; /* we just reported it */
1181 report_counts_siginfo(int signum _U_
)
1183 int sav_errno
= errno
;
1185 /* If we've been told to delay printing, just set a flag asking
1186 that we print counts (if we're supposed to), otherwise print
1187 the count of packets captured (if we're supposed to). */
1191 report_counts_for_siginfo();
1194 #endif /* SIGINFO */
1197 exit_main(int status
)
1199 ws_cleanup_sockets();
1202 /* can be helpful for debugging */
1203 #ifdef DEBUG_DUMPCAP
1204 printf("Press any key\n");
1210 if (ringbuf_is_initialized()) {
1211 /* save_file is managed by ringbuffer, be sure to release the memory and
1212 * avoid capture_opts_cleanup from double-freeing 'save_file'. */
1214 global_capture_opts
.save_file
= NULL
;
1217 capture_opts_cleanup(&global_capture_opts
);
1223 * If we were linked with libcap (not related to libpcap), make sure we have
1224 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1225 * (See comment in main() for details)
1228 relinquish_privs_except_capture(void)
1231 * Drop any capabilities other than NET_ADMIN and NET_RAW:
1233 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1234 * stuff we don't need (and shouldn't have).
1235 * CAP_NET_RAW: Packet capture (raw sockets).
1237 * If 'started_with_special_privs' (ie: suid) then drop our
1241 cap_t current_caps
= cap_get_proc();
1242 print_caps("Pre set");
1244 cap_t caps
= cap_init(); /* all capabilities initialized to off */
1247 * We can only set capabilities that are in the permitted set.
1248 * If the real or effective user ID is 0 (root), then the file
1249 * inherited and permitted sets are ignored, and our permitted
1250 * set should be all ones - unless the effective ID is 0, the
1251 * real ID is not zero, and the binary has file capabilities,
1252 * in which case the permitted set is only that of the file.
1253 * (E.g., set-user-ID-root + file capabilities.)
1255 * If one or more of the euid, ruid, and saved set user ID are
1256 * all zero and all change to nonzero, then all capabilities are
1257 * cleared from the permitted, effective, and ambient sets.
1258 * PR_SET_KEEPCAPS causes the permitted set to be retained, so
1259 * we can relinquish our changed user ID.
1261 * All capabilities are always cleared from the effective set
1262 * when the euid is changed from 0 to nonzero.
1264 * See capabilities(7).
1266 if (prctl(PR_SET_KEEPCAPS
, 1, 0, 0, 0) == -1) {
1267 cmdarg_err("prctl() fail return: %s", g_strerror(errno
));
1270 if (started_with_special_privs()) {
1271 relinquish_special_privs_perm();
1275 * If cap_set_proc() fails, it leaves the capabilities unchanged.
1276 * So the only way to guarantee that we've dropped all other
1277 * capabilities is to ensure that cap_set_proc() succeeds.
1278 * One option might be to exit if cap_set_proc() fails - but some
1279 * captures will work with CAP_NET_RAW but not CAP_NET_ADMIN.
1282 cap_value_t cap_list
[1] = { CAP_NET_ADMIN
};
1283 int cl_len
= array_length(cap_list
);
1284 cap_flag_value_t value
;
1286 cap_get_flag(current_caps
, cap_list
[0], CAP_PERMITTED
, &value
);
1288 if (value
!= CAP_SET
) {
1289 // XXX - Should we warn here? Some captures will still work.
1291 cap_set_flag(caps
, CAP_PERMITTED
, cl_len
, cap_list
, value
);
1292 // XXX - Do we really need CAP_INHERITABLE?
1293 cap_set_flag(caps
, CAP_INHERITABLE
, cl_len
, cap_list
, value
);
1294 cap_set_flag(caps
, CAP_EFFECTIVE
, cl_len
, cap_list
, value
);
1296 cap_list
[0] = CAP_NET_RAW
;
1297 cap_get_flag(current_caps
, cap_list
[0], CAP_PERMITTED
, &value
);
1299 if (value
!= CAP_SET
) {
1300 // XXX - Should we warn here?
1302 cap_set_flag(caps
, CAP_PERMITTED
, cl_len
, cap_list
, value
);
1303 // XXX - Do we really need CAP_INHERITABLE?
1304 cap_set_flag(caps
, CAP_INHERITABLE
, cl_len
, cap_list
, value
);
1305 cap_set_flag(caps
, CAP_EFFECTIVE
, cl_len
, cap_list
, value
);
1307 if (cap_set_proc(caps
)) {
1309 * This shouldn't happen, we're only trying to set capabilities
1310 * already in the permitted set.
1312 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno
));
1315 print_caps("Post set");
1317 cap_free(current_caps
);
1321 #endif /* HAVE_LIBCAP */
1323 /* Map DLT_ values, as returned by pcap_datalink(), to LINKTYPE_ values,
1324 as are written to capture files.
1326 Most of the time, a DLT_ value and the corresponding LINKYPE_ value
1327 are the same, but there are some cases, where a numeric value as
1328 a DLT_ doesn't uniquely identify a particular link-layer header type,
1329 where they differ, so that the values in files *do* identify
1330 particular link-layer header types. */
1332 /* LINKTYPE_ values that don't match corresponding DLT_ values on
1334 #define LINKTYPE_ATM_RFC1483 100
1335 #define LINKTYPE_RAW 101
1336 #define LINKTYPE_SLIP_BSDOS 102
1337 #define LINKTYPE_PPP_BSDOS 103
1338 #define LINKTYPE_C_HDLC 104
1339 #define LINKTYPE_IEEE802_11 105
1340 #define LINKTYPE_ATM_CLIP 106
1341 #define LINKTYPE_FRELAY 107
1342 #define LINKTYPE_LOOP 108
1343 #define LINKTYPE_ENC 109
1344 #define LINKTYPE_NETBSD_HDLC 112
1345 #define LINKTYPE_PFSYNC 246
1346 #define LINKTYPE_PKTAP 258
1349 dlt_to_linktype(int dlt
)
1351 /* DLT_NULL through DLT_FDDI have the same numeric value on
1352 all platforms, so the corresponding LINKTYPE_s have the
1353 same numeric values. */
1354 if (dlt
>= DLT_NULL
&& dlt
<= DLT_FDDI
)
1357 #if defined(DLT_PFSYNC) && DLT_PFSYNC != LINKTYPE_PFSYNC
1358 /* DLT_PFSYNC has a value on several platforms that's in the
1359 non-matching range, a value on FreeBSD that's in the high
1360 matching range and that's *not* equal to LINKTYPE_PFSYNC,
1361 and has a value on the rmaining platforms that's equal
1362 to LINKTYPE_PFSYNC, which is in the high matching range.
1364 Map it to LINKTYPE_PFSYNC if it's not equal to LINKTYPE_PFSYNC. */
1365 if (dlt
== DLT_PFSYNC
)
1366 return (LINKTYPE_PFSYNC
);
1369 /* DLT_PKTAP is defined as DLT_USER2 - which is in the high
1370 matching range - on Darwin because Apple used DLT_USER2
1371 on systems that users ran, not just as an internal thing.
1373 We map it to LINKTYPE_PKTAP if it's not equal to LINKTYPE_PKTAP
1374 so that DLT_PKTAP captures from Apple machines can be read by
1375 software that either doesn't handle DLT_USER2 or that handles it
1376 as something other than Apple PKTAP. */
1377 #if defined(DLT_PKTAP) && DLT_PKTAP != LINKTYPE_PKTAP
1378 if (dlt
== DLT_PKTAP
)
1379 return (LINKTYPE_PKTAP
);
1382 /* For all other DLT_s with values beyond 104, the value
1383 of the corresponding LINKTYPE_ is the same. */
1387 /* These DLT_ values have different values on different
1388 platforms, so we assigned them LINKTYPE_ values just
1389 below the lower bound of the high matchig range;
1390 those values should never be equal to any DLT_
1391 values, so that should avoid collisions.
1393 That way, for example, "raw IP" packets will have
1394 LINKTYPE_RAW as the code in all savefiles for
1395 which the code that writes them maps to that
1396 value, regardless of the platform on which they
1397 were written, so they should be readable on all
1398 platforms without having to determine on which
1399 platform they were written.
1401 We map the DLT_ values on this platform, whatever
1402 it might be, to the corresponding LINKTYPE_ values. */
1403 #ifdef DLT_ATM_RFC1483
1404 if (dlt
== DLT_ATM_RFC1483
)
1405 return (LINKTYPE_ATM_RFC1483
);
1409 return (LINKTYPE_RAW
);
1411 #ifdef DLT_SLIP_BSDOS
1412 if (dlt
== DLT_SLIP_BSDOS
)
1413 return (LINKTYPE_SLIP_BSDOS
);
1415 #ifdef DLT_PPP_BSDOS
1416 if (dlt
== DLT_PPP_BSDOS
)
1417 return (LINKTYPE_PPP_BSDOS
);
1420 /* These DLT_ values were originally defined on some platform,
1421 and weren't defined on other platforms.
1423 At least some of those values, on at least one platform,
1424 collide with the values of other DLT_s on other platforms,
1425 e.g. DLT_LOOP, so we don't just define them, on all
1426 platforms, as having the same value as on the original
1429 Therefore, we assigned new LINKTYPE_ values to them, and,
1430 on the platforms where they weren't originally defined,
1431 define the DLT_s to have the same value as the corresponding
1434 This means that, for capture files with the original
1435 platform's DLT_ value rather than the LINKTYPE_ value
1436 as a link-layer type, we will recognize those types
1437 on that platform, but not on other platforms. */
1439 /* BSD/OS Frame Relay */
1441 return (LINKTYPE_FRELAY
);
1443 #if defined(DLT_HDLC) && DLT_HDLC != LINKTYPE_NETBSD_HDLC
1445 if (dlt
== DLT_HDLC
)
1446 return (LINKTYPE_NETBSD_HDLC
);
1448 #if defined(DLT_C_HDLC) && DLT_C_HDLC != LINKTYPE_C_HDLC
1449 /* BSD/OS Cisco HDLC */
1450 if (dlt
== DLT_C_HDLC
)
1451 return (LINKTYPE_C_HDLC
);
1453 #if defined(DLT_LOOP) && DLT_LOOP != LINKTYPE_LOOP
1454 /* OpenBSD DLT_LOOP */
1455 if (dlt
== DLT_LOOP
)
1456 return (LINKTYPE_LOOP
);
1458 #if defined(DLT_ENC) && DLT_ENC != LINKTYPE_ENC
1459 /* OpenBSD DLT_ENC */
1461 return (LINKTYPE_ENC
);
1464 /* These DLT_ values are not on all platforms, but, so far,
1465 there don't appear to be any platforms that define
1466 other DLT_s with those values; we map them to
1467 different LINKTYPE_ values anyway, just in case. */
1469 /* Linux ATM Classical IP */
1470 if (dlt
== DLT_ATM_CLIP
)
1471 return (LINKTYPE_ATM_CLIP
);
1474 /* Treat all other DLT_s as having the same value as the
1475 corresponding LINKTYPE_. */
1479 /* Take care of byte order in the libpcap headers read from pipes.
1480 * (function taken from wiretap/libpcap.c) */
1482 cap_pipe_adjust_pcap_header(bool byte_swapped
, struct pcap_hdr
*hdr
, struct pcaprec_hdr
*rechdr
)
1485 /* Byte-swap the record header fields. */
1486 rechdr
->ts_sec
= GUINT32_SWAP_LE_BE(rechdr
->ts_sec
);
1487 rechdr
->ts_usec
= GUINT32_SWAP_LE_BE(rechdr
->ts_usec
);
1488 rechdr
->incl_len
= GUINT32_SWAP_LE_BE(rechdr
->incl_len
);
1489 rechdr
->orig_len
= GUINT32_SWAP_LE_BE(rechdr
->orig_len
);
1492 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1493 swapped, in order to match the BPF header layout.
1495 Unfortunately, some files were, according to a comment in the "libpcap"
1496 source, written with version 2.3 in their headers but without the
1497 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1498 would make no sense - we assume that we need to swap them. */
1499 if (hdr
->version_major
== 2 &&
1500 (hdr
->version_minor
< 3 ||
1501 (hdr
->version_minor
== 3 && rechdr
->incl_len
> rechdr
->orig_len
))) {
1504 temp
= rechdr
->orig_len
;
1505 rechdr
->orig_len
= rechdr
->incl_len
;
1506 rechdr
->incl_len
= temp
;
1510 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1514 cap_pipe_read(int pipe_fd
, char *buf
, size_t sz
, bool from_socket _U_
)
1518 return recv(pipe_fd
, buf
, (int)sz
, 0);
1523 return ws_read(pipe_fd
, buf
, sz
);
1529 * Thread function that reads from a pipe and pushes the data
1530 * to the main application thread.
1533 * XXX Right now we use async queues for basic signaling. The main thread
1534 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1535 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1536 * Iff the read is successful cap_pipe_read pushes an item onto
1537 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1538 * the queues themselves (yet).
1540 * We might want to move some of the cap_pipe_dispatch logic here so that
1541 * we can let cap_thread_read run independently, queuing up multiple reads
1542 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1544 static void *cap_thread_read(void *arg
)
1546 capture_src
*pcap_src
;
1549 DWORD last_err
, bytes_read
;
1554 pcap_src
= (capture_src
*)arg
;
1555 while (pcap_src
->cap_pipe_err
== PIPOK
) {
1556 g_async_queue_pop(pcap_src
->cap_pipe_pending_q
); /* Wait for our cue (ahem) from the main thread */
1557 g_mutex_lock(pcap_src
->cap_pipe_read_mtx
);
1559 while (bytes_read
< pcap_src
->cap_pipe_bytes_to_read
) {
1560 if ((pcap_src
->from_cap_socket
)
1567 b
= cap_pipe_read(pcap_src
->cap_pipe_fd
, pcap_src
->cap_pipe_buf
+bytes_read
,
1568 pcap_src
->cap_pipe_bytes_to_read
- bytes_read
, pcap_src
->from_cap_socket
);
1571 pcap_src
->cap_pipe_err
= PIPEOF
;
1575 pcap_src
->cap_pipe_err
= PIPERR
;
1580 bytes_read
+= (DWORD
)b
;
1586 /* If we try to use read() on a named pipe on Windows with partial
1587 * data it appears to return EOF.
1590 res
= ReadFile(pcap_src
->cap_pipe_h
, pcap_src
->cap_pipe_buf
+bytes_read
,
1591 pcap_src
->cap_pipe_bytes_to_read
- bytes_read
,
1596 last_err
= GetLastError();
1597 if (last_err
== ERROR_MORE_DATA
) {
1599 } else if (last_err
== ERROR_HANDLE_EOF
|| last_err
== ERROR_BROKEN_PIPE
|| last_err
== ERROR_PIPE_NOT_CONNECTED
) {
1600 pcap_src
->cap_pipe_err
= PIPEOF
;
1604 pcap_src
->cap_pipe_err
= PIPERR
;
1607 } else if (b
== 0 && pcap_src
->cap_pipe_bytes_to_read
> 0) {
1608 pcap_src
->cap_pipe_err
= PIPEOF
;
1615 pcap_src
->cap_pipe_bytes_read
= bytes_read
;
1616 if (pcap_src
->cap_pipe_bytes_read
>= pcap_src
->cap_pipe_bytes_to_read
) {
1617 g_async_queue_push(pcap_src
->cap_pipe_done_q
, pcap_src
->cap_pipe_buf
); /* Any non-NULL value will do */
1619 g_mutex_unlock(pcap_src
->cap_pipe_read_mtx
);
1621 /* Post to queue if we didn't read enough data as the main thread waits for the message */
1622 g_mutex_lock(pcap_src
->cap_pipe_read_mtx
);
1623 if (pcap_src
->cap_pipe_bytes_read
< pcap_src
->cap_pipe_bytes_to_read
) {
1624 /* There's still more of the record to read. */
1625 g_async_queue_push(pcap_src
->cap_pipe_done_q
, pcap_src
->cap_pipe_buf
); /* Any non-NULL value will do */
1627 g_mutex_unlock(pcap_src
->cap_pipe_read_mtx
);
1632 * Do a blocking read from a pipe within the main thread, by pushing
1633 * the read onto the pipe queue and then popping it off that queue;
1634 * the pipe will block until the pushed read completes.
1636 * We do it with another thread because we can't use select() on
1637 * pipes on Windows, as we can on UN*Xes, we can only use it on
1641 pipe_read_sync(capture_src
*pcap_src
, void *buf
, DWORD nbytes
)
1643 pcap_src
->cap_pipe_buf
= (char *) buf
;
1644 pcap_src
->cap_pipe_bytes_read
= 0;
1645 pcap_src
->cap_pipe_bytes_to_read
= nbytes
;
1646 /* We don't have to worry about cap_pipe_read_mtx here */
1647 g_async_queue_push(pcap_src
->cap_pipe_pending_q
, pcap_src
->cap_pipe_buf
);
1648 g_async_queue_pop(pcap_src
->cap_pipe_done_q
);
1652 /* Provide select() functionality for a single file descriptor
1653 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1655 * Returns the same values as select.
1658 cap_pipe_select(int pipe_fd
)
1661 struct timeval timeout
;
1664 FD_SET(pipe_fd
, &rfds
);
1666 timeout
.tv_sec
= PIPE_READ_TIMEOUT
/ 1000000;
1667 timeout
.tv_usec
= PIPE_READ_TIMEOUT
% 1000000;
1669 return select(pipe_fd
+1, &rfds
, NULL
, NULL
, &timeout
);
1672 #define DEF_TCP_PORT 19000
1675 cap_open_socket(char *pipename
, capture_src
*pcap_src
, char *errmsg
, size_t errmsgl
)
1677 struct sockaddr_storage sa
;
1681 /* Skip the initial "TCP@" in the pipename. */
1682 if (ws_socket_ptoa(&sa
, pipename
+ 4, DEF_TCP_PORT
) < 0) {
1683 snprintf(errmsg
, errmsgl
,
1684 "The capture session could not be initiated because"
1685 "\"%s\" is not a valid socket specification", pipename
);
1686 pcap_src
->cap_pipe_err
= PIPERR
;
1690 if ((fd
= (int)socket(sa
.ss_family
, SOCK_STREAM
, 0)) < 0) {
1691 snprintf(errmsg
, errmsgl
,
1692 "The capture session could not be initiated because"
1693 " the socket couldn't be created due to the socket error: \n"
1695 " %s", win32strerror(WSAGetLastError()));
1697 " %d: %s", errno
, g_strerror(errno
));
1699 pcap_src
->cap_pipe_err
= PIPERR
;
1703 if (sa
.ss_family
== AF_INET6
)
1704 sa_len
= sizeof(struct sockaddr_in6
);
1706 sa_len
= sizeof(struct sockaddr_in
);
1707 if (connect(fd
, (struct sockaddr
*)&sa
, sa_len
) < 0) {
1708 snprintf(errmsg
, errmsgl
,
1709 "The capture session could not be initiated because"
1710 " the socket couldn't be connected due to the socket error: \n"
1712 " %s", win32strerror(WSAGetLastError()));
1714 " %d: %s", errno
, g_strerror(errno
));
1716 pcap_src
->cap_pipe_err
= PIPERR
;
1718 cap_pipe_close(fd
, true);
1722 pcap_src
->from_cap_socket
= true;
1726 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1730 cap_pipe_close(int pipe_fd
, bool from_socket
)
1734 closesocket(pipe_fd
);
1737 (void) from_socket
; /* Mark unused, similar to Q_UNUSED */
1742 /** Read bytes from a capture source, which is assumed to be a pipe or
1745 * Returns -1, or the number of bytes read similar to read(2).
1746 * Sets pcap_src->cap_pipe_err on error or EOF.
1749 cap_pipe_read_data_bytes(capture_src
*pcap_src
, char *errmsg
, size_t errmsgl
)
1752 int fd
= pcap_src
->cap_pipe_fd
;
1754 DWORD sz
, bytes_read
= 0;
1756 ssize_t sz
, bytes_read
= 0;
1760 #ifdef LOG_CAPTURE_VERBOSE
1761 ws_debug("cap_pipe_read_data_bytes read %lu of %lu",
1762 pcap_src
->cap_pipe_bytes_read
, pcap_src
->cap_pipe_bytes_to_read
);
1764 sz
= pcap_src
->cap_pipe_bytes_to_read
- pcap_src
->cap_pipe_bytes_read
;
1765 while (bytes_read
< sz
) {
1767 snprintf(errmsg
, errmsgl
, "Invalid file descriptor.");
1768 pcap_src
->cap_pipe_err
= PIPNEXIST
;
1772 sel_ret
= cap_pipe_select(fd
);
1774 snprintf(errmsg
, errmsgl
,
1775 "Unexpected error from select: %s.", g_strerror(errno
));
1776 pcap_src
->cap_pipe_err
= PIPERR
;
1778 } else if (sel_ret
> 0) {
1779 b
= cap_pipe_read(fd
, pcap_src
->cap_pipe_databuf
+pcap_src
->cap_pipe_bytes_read
+bytes_read
,
1780 sz
-bytes_read
, pcap_src
->from_cap_socket
);
1783 snprintf(errmsg
, errmsgl
,
1784 "End of file reading from pipe or socket.");
1785 pcap_src
->cap_pipe_err
= PIPEOF
;
1789 * On Windows, we only do this for sockets.
1791 DWORD lastError
= WSAGetLastError();
1793 snprintf(errmsg
, errmsgl
,
1794 "Error reading from pipe or socket: %s.",
1795 win32strerror(lastError
));
1797 snprintf(errmsg
, errmsgl
,
1798 "Error reading from pipe or socket: %s.",
1801 pcap_src
->cap_pipe_err
= PIPERR
;
1806 bytes_read
+= (DWORD
)b
;
1812 pcap_src
->cap_pipe_bytes_read
+= bytes_read
;
1813 #ifdef LOG_CAPTURE_VERBOSE
1814 ws_debug("cap_pipe_read_data_bytes read %lu of %lu",
1815 pcap_src
->cap_pipe_bytes_read
, pcap_src
->cap_pipe_bytes_to_read
);
1820 /* Some forward declarations for breaking up cap_pipe_open_live for pcap and pcapng formats */
1821 static void pcap_pipe_open_live(int fd
, capture_src
*pcap_src
,
1822 struct pcap_hdr
*hdr
,
1823 char *errmsg
, size_t errmsgl
,
1824 char *secondary_errmsg
, size_t secondary_errmsgl
);
1825 static void pcapng_pipe_open_live(int fd
, capture_src
*pcap_src
,
1826 char *errmsg
, size_t errmsgl
);
1827 static int pcapng_pipe_dispatch(loop_data
*ld
, capture_src
*pcap_src
,
1828 char *errmsg
, size_t errmsgl
);
1830 /* For problems that are probably Not Our Fault. */
1831 static char not_our_bug
[] =
1832 "Please report this to the developers of the program writing to the pipe.";
1834 /* Mimic pcap_open_live() for pipe captures
1836 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1837 * open it, and read the header.
1839 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1840 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1842 cap_pipe_open_live(char *pipename
,
1843 capture_src
*pcap_src
,
1845 char *errmsg
, size_t errmsgl
,
1846 char *secondary_errmsg
, size_t secondary_errmsgl
)
1849 ws_statb64 pipe_stat
;
1850 struct sockaddr_un sa
;
1852 uintptr_t extcap_pipe_handle
;
1854 bool extcap_pipe
= false;
1856 int fd
= -1, sel_ret
;
1859 pcap_src
->cap_pipe_fd
= -1;
1861 pcap_src
->cap_pipe_h
= INVALID_HANDLE_VALUE
;
1864 ws_debug("cap_pipe_open_live: %s", pipename
);
1867 * XXX - this blocks until a pcap per-file header has been written to
1868 * the pipe, so it could block indefinitely.
1870 if (strcmp(pipename
, "-") == 0) {
1872 fd
= 0; /* read from stdin */
1874 pcap_src
->cap_pipe_h
= GetStdHandle(STD_INPUT_HANDLE
);
1876 } else if (!strncmp(pipename
, "TCP@", 4)) {
1877 if ((fd
= cap_open_socket(pipename
, pcap_src
, errmsg
, errmsgl
)) < 0) {
1882 if ( g_strrstr(pipename
, EXTCAP_PIPE_PREFIX
) != NULL
)
1885 if (ws_stat64(pipename
, &pipe_stat
) < 0) {
1886 if (errno
== ENOENT
|| errno
== ENOTDIR
)
1887 pcap_src
->cap_pipe_err
= PIPNEXIST
;
1889 snprintf(errmsg
, errmsgl
,
1890 "The capture session could not be initiated "
1891 "due to error getting information on pipe or socket: %s.", g_strerror(errno
));
1892 pcap_src
->cap_pipe_err
= PIPERR
;
1896 if (S_ISFIFO(pipe_stat
.st_mode
)) {
1897 fd
= ws_open(pipename
, O_RDONLY
| O_NONBLOCK
, 0000 /* no creation so don't matter */);
1899 snprintf(errmsg
, errmsgl
,
1900 "The capture session could not be initiated "
1901 "due to error on pipe open: %s.", g_strerror(errno
));
1902 pcap_src
->cap_pipe_err
= PIPERR
;
1905 } else if (S_ISSOCK(pipe_stat
.st_mode
)) {
1906 fd
= socket(AF_UNIX
, SOCK_STREAM
, 0);
1908 snprintf(errmsg
, errmsgl
,
1909 "The capture session could not be initiated "
1910 "due to error on socket create: %s.", g_strerror(errno
));
1911 pcap_src
->cap_pipe_err
= PIPERR
;
1914 sa
.sun_family
= AF_UNIX
;
1916 * The Single UNIX Specification says:
1918 * The size of sun_path has intentionally been left undefined.
1919 * This is because different implementations use different sizes.
1920 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1921 * of 104. Since most implementations originate from BSD versions,
1922 * the size is typically in the range 92 to 108.
1924 * Applications should not assume a particular length for sun_path
1925 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1929 * The <sys/un.h> header shall define the sockaddr_un structure,
1930 * which shall include at least the following members:
1932 * sa_family_t sun_family Address family.
1933 * char sun_path[] Socket pathname.
1935 * so we assume that it's an array, with a specified size,
1936 * and that the size reflects the maximum path length.
1938 if (g_strlcpy(sa
.sun_path
, pipename
, sizeof sa
.sun_path
) > sizeof sa
.sun_path
) {
1939 /* Path name too long */
1940 snprintf(errmsg
, errmsgl
,
1941 "The capture session could not be initiated "
1942 "due to error on socket connect: Path name too long.");
1943 pcap_src
->cap_pipe_err
= PIPERR
;
1947 b
= connect(fd
, (struct sockaddr
*)&sa
, sizeof sa
);
1949 snprintf(errmsg
, errmsgl
,
1950 "The capture session could not be initiated "
1951 "due to error on socket connect: %s.", g_strerror(errno
));
1952 pcap_src
->cap_pipe_err
= PIPERR
;
1957 if (S_ISCHR(pipe_stat
.st_mode
)) {
1959 * Assume the user specified an interface on a system where
1960 * interfaces are in /dev. Pretend we haven't seen it.
1962 pcap_src
->cap_pipe_err
= PIPNEXIST
;
1964 snprintf(errmsg
, errmsgl
,
1965 "The capture session could not be initiated because\n"
1966 "\"%s\" is neither an interface nor a socket nor a pipe.", pipename
);
1967 pcap_src
->cap_pipe_err
= PIPERR
;
1973 if (sscanf(pipename
, EXTCAP_PIPE_PREFIX
"%" SCNuPTR
, &extcap_pipe_handle
) == 1)
1975 /* The client is already connected to extcap pipe.
1976 * We have inherited the handle from parent process.
1979 pcap_src
->cap_pipe_h
= (HANDLE
)extcap_pipe_handle
;
1983 if (!win32_is_pipe_name(pipename
)) {
1984 snprintf(errmsg
, errmsgl
,
1985 "The capture session could not be initiated because\n"
1986 "\"%s\" is neither an interface nor a pipe.", pipename
);
1987 pcap_src
->cap_pipe_err
= PIPNEXIST
;
1991 /* Wait for the pipe to appear */
1993 pcap_src
->cap_pipe_h
= CreateFile(utf_8to16(pipename
), GENERIC_READ
, 0, NULL
,
1994 OPEN_EXISTING
, 0, NULL
);
1996 if (pcap_src
->cap_pipe_h
!= INVALID_HANDLE_VALUE
)
1999 if (GetLastError() != ERROR_PIPE_BUSY
) {
2000 snprintf(errmsg
, errmsgl
,
2001 "The capture session on \"%s\" could not be started "
2002 "due to error on pipe open: %s.",
2003 pipename
, win32strerror(GetLastError()));
2004 pcap_src
->cap_pipe_err
= PIPERR
;
2008 if (!WaitNamedPipe(utf_8to16(pipename
), 30 * 1000)) {
2009 snprintf(errmsg
, errmsgl
,
2010 "The capture session on \"%s\" timed out during "
2012 pipename
, win32strerror(GetLastError()));
2013 pcap_src
->cap_pipe_err
= PIPERR
;
2021 pcap_src
->from_cap_pipe
= true;
2024 * We start with a 2KB buffer for packet data, which should be
2025 * large enough for most regular network packets. We increase it,
2026 * up to the maximum size we allow, as necessary.
2028 pcap_src
->cap_pipe_databuf
= (char*)g_malloc(2048);
2029 pcap_src
->cap_pipe_databuf_size
= 2048;
2032 * Read the first 4 bytes of data from the pipe.
2034 * If a pcap file is being written to it, that will be
2035 * the pcap magic number.
2037 * If a pcapng file is being written to it, that will be
2038 * the block type of the initial SHB.
2042 * On UN*X, we can use select() on pipes or sockets.
2044 * On Windows, we can only use it on sockets; to do non-blocking
2045 * reads from pipes, we currently do reads in a separate thread
2046 * and use GLib asynchronous queues from the main thread to start
2047 * read operations and to wait for them to complete.
2049 if (pcap_src
->from_cap_socket
)
2053 while (bytes_read
< sizeof magic
) {
2054 sel_ret
= cap_pipe_select(fd
);
2056 snprintf(errmsg
, errmsgl
,
2057 "Unexpected error from select: %s.",
2060 } else if (sel_ret
> 0) {
2061 b
= cap_pipe_read(fd
, ((char *)&magic
)+bytes_read
,
2062 sizeof magic
-bytes_read
,
2063 pcap_src
->from_cap_socket
);
2064 /* jump messaging, if extcap had an error, stderr will provide the correct message */
2065 if (extcap_pipe
&& b
<= 0)
2070 snprintf(errmsg
, errmsgl
,
2071 "End of file on pipe magic during open.");
2073 snprintf(errmsg
, errmsgl
,
2074 "Error on pipe magic during open: %s.",
2084 /* Create a thread to read from this pipe */
2085 g_thread_new("cap_pipe_open_live", &cap_thread_read
, pcap_src
);
2087 pipe_read_sync(pcap_src
, &magic
, sizeof(magic
));
2088 /* jump messaging, if extcap had an error, stderr will provide the correct message */
2089 if (pcap_src
->cap_pipe_bytes_read
<= 0 && extcap_pipe
)
2092 if (pcap_src
->cap_pipe_bytes_read
<= 0) {
2093 if (pcap_src
->cap_pipe_bytes_read
== 0)
2094 snprintf(errmsg
, errmsgl
,
2095 "End of file on pipe magic during open.");
2097 snprintf(errmsg
, errmsgl
,
2098 "Error on pipe magic during open: %s.",
2107 case PCAP_NSEC_MAGIC
:
2108 /* This is a pcap file.
2109 The host that wrote it has our byte order, and was running
2110 a program using either standard or ss990417 libpcap. */
2111 pcap_src
->cap_pipe_info
.pcap
.byte_swapped
= false;
2112 pcap_src
->cap_pipe_modified
= false;
2113 pcap_src
->ts_nsec
= magic
== PCAP_NSEC_MAGIC
;
2115 case PCAP_MODIFIED_MAGIC
:
2116 /* This is a pcap file.
2117 The host that wrote it has our byte order, but was running
2118 a program using either ss990915 or ss991029 libpcap. */
2119 pcap_src
->cap_pipe_info
.pcap
.byte_swapped
= false;
2120 pcap_src
->cap_pipe_modified
= true;
2122 case PCAP_SWAPPED_MAGIC
:
2123 case PCAP_SWAPPED_NSEC_MAGIC
:
2124 /* This is a pcap file.
2125 The host that wrote it has a byte order opposite to ours,
2126 and was running a program using either standard or
2127 ss990417 libpcap. */
2128 pcap_src
->cap_pipe_info
.pcap
.byte_swapped
= true;
2129 pcap_src
->cap_pipe_modified
= false;
2130 pcap_src
->ts_nsec
= magic
== PCAP_SWAPPED_NSEC_MAGIC
;
2132 case PCAP_SWAPPED_MODIFIED_MAGIC
:
2133 /* This is a pcap file.
2134 The host that wrote it out has a byte order opposite to
2135 ours, and was running a program using either ss990915
2136 or ss991029 libpcap. */
2137 pcap_src
->cap_pipe_info
.pcap
.byte_swapped
= true;
2138 pcap_src
->cap_pipe_modified
= true;
2140 case BLOCK_TYPE_SHB
:
2141 /* This is a pcapng file. */
2142 pcap_src
->from_pcapng
= true;
2143 pcap_src
->cap_pipe_dispatch
= pcapng_pipe_dispatch
;
2144 pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
= g_array_new(FALSE
, FALSE
, sizeof(uint32_t));
2145 global_capture_opts
.use_pcapng
= true; /* we can only output in pcapng format */
2148 /* Not a pcapng file, and either not a pcap type we know about
2149 or not a pcap file, either. */
2150 snprintf(errmsg
, errmsgl
,
2151 "File type is neither a supported pcap nor pcapng format. (magic = 0x%08x)", magic
);
2152 snprintf(secondary_errmsg
, secondary_errmsgl
, "%s",
2157 if (pcap_src
->from_pcapng
)
2158 pcapng_pipe_open_live(fd
, pcap_src
, errmsg
, errmsgl
);
2160 pcap_pipe_open_live(fd
, pcap_src
, (struct pcap_hdr
*) hdr
, errmsg
, errmsgl
,
2161 secondary_errmsg
, secondary_errmsgl
);
2166 ws_debug("cap_pipe_open_live: error %s", errmsg
);
2167 pcap_src
->cap_pipe_err
= PIPERR
;
2168 cap_pipe_close(fd
, pcap_src
->from_cap_socket
);
2169 pcap_src
->cap_pipe_fd
= -1;
2171 pcap_src
->cap_pipe_h
= INVALID_HANDLE_VALUE
;
2176 * Read the part of the pcap file header that follows the magic
2177 * number (we've already read the magic number).
2180 pcap_pipe_open_live(int fd
,
2181 capture_src
*pcap_src
,
2182 struct pcap_hdr
*hdr
,
2183 char *errmsg
, size_t errmsgl
,
2184 char *secondary_errmsg
, size_t secondary_errmsgl
)
2191 * We're reading from a pcap file. We've already read the magic
2192 * number; read the rest of the header.
2194 * (Note that struct pcap_hdr is a structure for the part of a
2195 * pcap file header *following the magic number*; it does not
2196 * include the magic number itself.)
2199 if (pcap_src
->from_cap_socket
)
2202 /* Keep reading until we get the rest of the header. */
2204 while (bytes_read
< sizeof(struct pcap_hdr
)) {
2205 sel_ret
= cap_pipe_select(fd
);
2207 snprintf(errmsg
, errmsgl
,
2208 "Unexpected error from select: %s.",
2211 } else if (sel_ret
> 0) {
2212 b
= cap_pipe_read(fd
, ((char *)hdr
)+bytes_read
,
2213 sizeof(struct pcap_hdr
) - bytes_read
,
2214 pcap_src
->from_cap_socket
);
2217 snprintf(errmsg
, errmsgl
,
2218 "End of file on pipe header during open.");
2220 snprintf(errmsg
, errmsgl
,
2221 "Error on pipe header during open: %s.",
2223 snprintf(secondary_errmsg
, secondary_errmsgl
,
2233 pipe_read_sync(pcap_src
, hdr
, sizeof(struct pcap_hdr
));
2234 if (pcap_src
->cap_pipe_bytes_read
<= 0) {
2235 if (pcap_src
->cap_pipe_bytes_read
== 0)
2236 snprintf(errmsg
, errmsgl
,
2237 "End of file on pipe header during open.");
2239 snprintf(errmsg
, errmsgl
,
2240 "Error on pipe header header during open: %s.",
2242 snprintf(secondary_errmsg
, secondary_errmsgl
, "%s",
2249 if (pcap_src
->cap_pipe_info
.pcap
.byte_swapped
) {
2250 /* Byte-swap the header fields about which we care. */
2251 hdr
->version_major
= GUINT16_SWAP_LE_BE(hdr
->version_major
);
2252 hdr
->version_minor
= GUINT16_SWAP_LE_BE(hdr
->version_minor
);
2253 hdr
->snaplen
= GUINT32_SWAP_LE_BE(hdr
->snaplen
);
2254 hdr
->network
= GUINT32_SWAP_LE_BE(hdr
->network
);
2257 * The link-layer header type field of the pcap header is
2258 * probably a LINKTYPE_ value, as the vast majority of
2259 * LINKTYPE_ values and their corresponding DLT_ values
2262 * However, in case the file was written by a program
2263 * that used a DLT_ value, rather than a LINKTYPE_ value,
2264 * in one of the cases where the two differ, use dlt_to_linktype()
2265 * to map to a LINKTYPE_ value, just as we use it to map
2266 * the result of pcap_datalink() to a LINKTYPE_ value.
2268 pcap_src
->linktype
= dlt_to_linktype(hdr
->network
);
2269 /* Pick the appropriate maximum packet size for the link type */
2270 switch (pcap_src
->linktype
) {
2272 case 231: /* DLT_DBUS */
2273 pcap_src
->cap_pipe_max_pkt_size
= WTAP_MAX_PACKET_SIZE_DBUS
;
2276 case 279: /* DLT_EBHSCR */
2277 pcap_src
->cap_pipe_max_pkt_size
= WTAP_MAX_PACKET_SIZE_EBHSCR
;
2280 case 249: /* DLT_USBPCAP */
2281 pcap_src
->cap_pipe_max_pkt_size
= WTAP_MAX_PACKET_SIZE_USBPCAP
;
2285 pcap_src
->cap_pipe_max_pkt_size
= WTAP_MAX_PACKET_SIZE_STANDARD
;
2289 if (hdr
->version_major
< 2) {
2290 snprintf(errmsg
, errmsgl
,
2291 "The old pcap format version %d.%d is not supported.",
2292 hdr
->version_major
, hdr
->version_minor
);
2293 snprintf(secondary_errmsg
, secondary_errmsgl
, "%s",
2298 pcap_src
->cap_pipe_fd
= fd
;
2302 ws_debug("pcap_pipe_open_live: error %s", errmsg
);
2303 pcap_src
->cap_pipe_err
= PIPERR
;
2304 cap_pipe_close(fd
, pcap_src
->from_cap_socket
);
2305 pcap_src
->cap_pipe_fd
= -1;
2307 pcap_src
->cap_pipe_h
= INVALID_HANDLE_VALUE
;
2312 * Synchronously read the fixed portion of the pcapng section header block
2313 * (we've already read the pcapng block header).
2316 pcapng_read_shb(capture_src
*pcap_src
,
2320 pcapng_section_header_block_t shb
;
2323 if (pcap_src
->from_cap_socket
)
2326 pcap_src
->cap_pipe_bytes_to_read
= sizeof(pcapng_block_header_t
) + sizeof(pcapng_section_header_block_t
);
2327 if (cap_pipe_read_data_bytes(pcap_src
, errmsg
, errmsgl
) < 0) {
2333 pipe_read_sync(pcap_src
, pcap_src
->cap_pipe_databuf
+ sizeof(pcapng_block_header_t
),
2334 sizeof(pcapng_section_header_block_t
));
2335 if (pcap_src
->cap_pipe_bytes_read
<= 0) {
2336 if (pcap_src
->cap_pipe_bytes_read
== 0)
2337 snprintf(errmsg
, errmsgl
,
2338 "End of file reading from pipe or socket.");
2340 snprintf(errmsg
, errmsgl
,
2341 "Error reading from pipe or socket: %s.",
2345 /* Continuing with STATE_EXPECT_DATA requires reading into cap_pipe_databuf at offset cap_pipe_bytes_read */
2346 pcap_src
->cap_pipe_bytes_read
= sizeof(pcapng_block_header_t
) + sizeof(pcapng_section_header_block_t
);
2349 memcpy(&shb
, pcap_src
->cap_pipe_databuf
+ sizeof(pcapng_block_header_t
), sizeof(pcapng_section_header_block_t
));
2353 ws_debug("pcapng SHB MAGIC");
2355 case PCAPNG_SWAPPED_MAGIC
:
2356 ws_debug("pcapng SHB SWAPPED MAGIC");
2358 * pcapng sources can contain all sorts of block types.
2359 * Rather than add a bunch of complexity to this code (which is
2360 * often privileged), punt and tell the user to swap bytes
2363 * XXX - punting means that the Wireshark test suite must be
2366 * 1) have both little-endian and big-endian versions of
2367 * all pcapng files piped to dumpcap;
2369 * 2) pipe the appropriate file to dumpcap, depending on
2370 * the byte order of the host on which the tests are
2373 * as per comments in bug 15772 and 15754.
2375 * Are we *really* certain that the complexity added would be
2376 * significant enough to make adding it a security risk? And
2377 * why would this code even be running with any elevated
2378 * privileges if you're capturing from a pipe? We should not
2379 * only have given up all additional privileges if we're reading
2380 * from a pipe, we should give them up in such a fashion that
2381 * we can't reclaim them.
2383 #if G_BYTE_ORDER == G_BIG_ENDIAN
2384 #define OUR_ENDIAN "big"
2385 #define IFACE_ENDIAN "little"
2387 #define OUR_ENDIAN "little"
2388 #define IFACE_ENDIAN "big"
2390 snprintf(errmsg
, errmsgl
,
2391 "Interface %u is " IFACE_ENDIAN
" endian but we're " OUR_ENDIAN
" endian.",
2392 pcap_src
->interface_id
);
2395 /* Not a pcapng type we know about, or not pcapng at all. */
2396 snprintf(errmsg
, errmsgl
,
2397 "Unrecognized pcapng format or not pcapng data.");
2401 pcap_src
->cap_pipe_max_pkt_size
= WTAP_MAX_PACKET_SIZE_STANDARD
;
2403 /* Setup state to capture any options following the section header block */
2404 pcap_src
->cap_pipe_state
= STATE_EXPECT_DATA
;
2410 * Save IDB blocks for playback whenever we change output files, and
2411 * fix LINKTYPE_ values that are really platform-dependent DLT_ values.
2412 * Rewrite EPB and ISB interface IDs.
2415 pcapng_adjust_block(capture_src
*pcap_src
, const pcapng_block_header_t
*bh
, uint8_t *pd
)
2417 switch(bh
->block_type
) {
2418 case BLOCK_TYPE_SHB
:
2420 if (global_ld
.pcapng_passthrough
) {
2422 * We have a single pcapng input. We pass the SHB through when
2423 * writing a single output file and for the first ring buffer
2424 * file. We need to save it for the second and subsequent ring
2427 g_free(global_ld
.saved_shb
);
2428 global_ld
.saved_shb
= (uint8_t *) g_memdup2(pd
, bh
->block_total_length
);
2431 * We're dealing with one section at a time, so we can (and must)
2432 * get rid of our old IDBs.
2434 for (unsigned i
= 0; i
< global_ld
.saved_idbs
->len
; i
++) {
2435 saved_idb_t
*idb_source
= &g_array_index(global_ld
.saved_idbs
, saved_idb_t
, i
);
2436 g_free(idb_source
->idb
);
2438 g_array_set_size(global_ld
.saved_idbs
, 0);
2441 * We have a new SHB from this capture source. We need to keep
2442 * global_ld.saved_idbs intact, so we mark IDBs we previously
2443 * collected from this source as deleted.
2445 for (unsigned i
= 0; i
< pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
->len
; i
++) {
2446 uint32_t iface_id
= g_array_index(pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
, uint32_t, i
);
2447 saved_idb_t
*idb_source
= &g_array_index(global_ld
.saved_idbs
, saved_idb_t
, iface_id
);
2448 ws_assert(idb_source
->interface_id
== pcap_src
->interface_id
);
2449 g_free(idb_source
->idb
);
2450 memset(idb_source
, 0, sizeof(saved_idb_t
));
2451 idb_source
->deleted
= true;
2452 ws_debug("%s: deleted pcapng IDB %u", G_STRFUNC
, iface_id
);
2455 g_array_set_size(pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
, 0);
2458 case BLOCK_TYPE_IDB
:
2461 * Always gather IDBs. We can remove them or mark them as deleted
2462 * when we get a new SHB.
2464 saved_idb_t idb_source
= { 0 };
2465 idb_source
.interface_id
= pcap_src
->interface_id
;
2466 idb_source
.idb_len
= bh
->block_total_length
;
2467 idb_source
.idb
= (uint8_t *) g_memdup2(pd
, idb_source
.idb_len
);
2468 g_array_append_val(global_ld
.saved_idbs
, idb_source
);
2469 uint32_t iface_id
= global_ld
.saved_idbs
->len
- 1;
2470 g_array_append_val(pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
, iface_id
);
2471 ws_debug("%s: mapped pcapng IDB %u -> %u from source %u",
2472 G_STRFUNC
, pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
->len
- 1, iface_id
, pcap_src
->interface_id
);
2475 case BLOCK_TYPE_EPB
:
2476 case BLOCK_TYPE_ISB
:
2478 if (global_ld
.pcapng_passthrough
) {
2479 /* Our input and output interface IDs are the same. */
2482 /* The interface ID is the first 32-bit field after the BH for both EPBs and ISBs. */
2484 memcpy(&iface_id
, pd
+ sizeof(pcapng_block_header_t
), 4);
2485 if (iface_id
< pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
->len
) {
2486 memcpy(pd
+ sizeof(pcapng_block_header_t
),
2487 &g_array_index(pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
, uint32_t, iface_id
), 4);
2489 ws_debug("%s: pcapng EPB or ISB interface id %u > max %u", G_STRFUNC
, iface_id
, pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
->len
);
2502 * Return true if the block contains packet, event, or log data. Return false otherwise.
2504 static bool is_data_block(uint32_t block_type
)
2506 // Any block types that lead to calling wtap_read_packet_bytes in
2507 // wiretap/pcapng.c should be listed here.
2508 switch (block_type
) {
2510 case BLOCK_TYPE_EPB
:
2511 case BLOCK_TYPE_SPB
:
2512 case BLOCK_TYPE_SYSTEMD_JOURNAL_EXPORT
:
2513 case BLOCK_TYPE_SYSDIG_EVENT
:
2514 case BLOCK_TYPE_SYSDIG_EVENT_V2
:
2515 case BLOCK_TYPE_SYSDIG_EVENT_V2_LARGE
:
2524 * Read the part of the initial pcapng SHB following the block type
2525 * (we've already read the block type).
2528 pcapng_pipe_open_live(int fd
,
2529 capture_src
*pcap_src
,
2533 uint32_t type
= BLOCK_TYPE_SHB
;
2534 pcapng_block_header_t
*bh
= &pcap_src
->cap_pipe_info
.pcapng
.bh
;
2536 ws_debug("pcapng_pipe_open_live: fd %d", fd
);
2539 * A pcapng block begins with the block type followed by the block
2540 * total length; we've already read the block type, now read the
2545 * On UN*X, we can use select() on pipes or sockets.
2547 * On Windows, we can only use it on sockets; to do non-blocking
2548 * reads from pipes, we currently do reads in a separate thread
2549 * and use GLib asynchronous queues from the main thread to start
2550 * read operations and to wait for them to complete.
2552 if (pcap_src
->from_cap_socket
)
2555 memcpy(pcap_src
->cap_pipe_databuf
, &type
, sizeof(uint32_t));
2556 pcap_src
->cap_pipe_bytes_read
= sizeof(uint32_t);
2557 pcap_src
->cap_pipe_bytes_to_read
= sizeof(pcapng_block_header_t
);
2558 pcap_src
->cap_pipe_fd
= fd
;
2559 if (cap_pipe_read_data_bytes(pcap_src
, errmsg
, errmsgl
) < 0) {
2562 memcpy(bh
, pcap_src
->cap_pipe_databuf
, sizeof(pcapng_block_header_t
));
2566 g_thread_new("cap_pipe_open_live", &cap_thread_read
, pcap_src
);
2568 bh
->block_type
= type
;
2569 pipe_read_sync(pcap_src
, &bh
->block_total_length
,
2570 sizeof(bh
->block_total_length
));
2571 if (pcap_src
->cap_pipe_bytes_read
<= 0) {
2572 if (pcap_src
->cap_pipe_bytes_read
== 0)
2573 snprintf(errmsg
, errmsgl
,
2574 "End of file reading from pipe or socket.");
2576 snprintf(errmsg
, errmsgl
,
2577 "Error reading from pipe or socket: %s.",
2581 pcap_src
->cap_pipe_bytes_read
= sizeof(pcapng_block_header_t
);
2582 memcpy(pcap_src
->cap_pipe_databuf
, bh
, sizeof(pcapng_block_header_t
));
2583 pcap_src
->cap_pipe_fd
= fd
;
2586 if ((bh
->block_total_length
& 0x03) != 0) {
2587 snprintf(errmsg
, errmsgl
,
2588 "block_total_length read from pipe is %u, which is not a multiple of 4.",
2589 bh
->block_total_length
);
2592 if (pcapng_read_shb(pcap_src
, errmsg
, errmsgl
)) {
2599 ws_debug("pcapng_pipe_open_live: error %s", errmsg
);
2600 pcap_src
->cap_pipe_err
= PIPERR
;
2601 cap_pipe_close(fd
, pcap_src
->from_cap_socket
);
2602 pcap_src
->cap_pipe_fd
= -1;
2604 pcap_src
->cap_pipe_h
= INVALID_HANDLE_VALUE
;
2608 /* We read one record from the pipe, take care of byte order in the record
2609 * header, write the record to the capture file, and update capture statistics. */
2611 pcap_pipe_dispatch(loop_data
*ld
, capture_src
*pcap_src
, char *errmsg
, size_t errmsgl
)
2613 struct pcap_pkthdr phdr
;
2614 enum { PD_REC_HDR_READ
, PD_DATA_READ
, PD_PIPE_EOF
, PD_PIPE_ERR
,
2620 unsigned new_bufsize
;
2621 pcap_pipe_info_t
*pcap_info
= &pcap_src
->cap_pipe_info
.pcap
;
2623 #ifdef LOG_CAPTURE_VERBOSE
2624 ws_debug("pcap_pipe_dispatch");
2627 switch (pcap_src
->cap_pipe_state
) {
2629 case STATE_EXPECT_REC_HDR
:
2631 if (g_mutex_trylock(pcap_src
->cap_pipe_read_mtx
)) {
2634 pcap_src
->cap_pipe_state
= STATE_READ_REC_HDR
;
2635 pcap_src
->cap_pipe_bytes_to_read
= pcap_src
->cap_pipe_modified
?
2636 sizeof(struct pcaprec_modified_hdr
) : sizeof(struct pcaprec_hdr
);
2637 pcap_src
->cap_pipe_bytes_read
= 0;
2640 pcap_src
->cap_pipe_buf
= (char *) &pcap_info
->rechdr
;
2641 g_async_queue_push(pcap_src
->cap_pipe_pending_q
, pcap_src
->cap_pipe_buf
);
2642 g_mutex_unlock(pcap_src
->cap_pipe_read_mtx
);
2647 case STATE_READ_REC_HDR
:
2649 if (pcap_src
->from_cap_socket
)
2652 b
= cap_pipe_read(pcap_src
->cap_pipe_fd
, ((char *)&pcap_info
->rechdr
)+pcap_src
->cap_pipe_bytes_read
,
2653 pcap_src
->cap_pipe_bytes_to_read
- pcap_src
->cap_pipe_bytes_read
, pcap_src
->from_cap_socket
);
2656 result
= PD_PIPE_EOF
;
2658 result
= PD_PIPE_ERR
;
2662 pcap_src
->cap_pipe_bytes_read
+= (DWORD
)b
;
2664 pcap_src
->cap_pipe_bytes_read
+= b
;
2669 q_status
= g_async_queue_timeout_pop(pcap_src
->cap_pipe_done_q
, PIPE_READ_TIMEOUT
);
2670 if (pcap_src
->cap_pipe_err
== PIPEOF
) {
2671 result
= PD_PIPE_EOF
;
2673 } else if (pcap_src
->cap_pipe_err
== PIPERR
) {
2674 result
= PD_PIPE_ERR
;
2682 if (pcap_src
->cap_pipe_bytes_read
< pcap_src
->cap_pipe_bytes_to_read
) {
2683 /* There's still more of the pcap packet header to read. */
2686 result
= PD_REC_HDR_READ
;
2689 case STATE_EXPECT_DATA
:
2691 if (g_mutex_trylock(pcap_src
->cap_pipe_read_mtx
)) {
2694 pcap_src
->cap_pipe_state
= STATE_READ_DATA
;
2695 pcap_src
->cap_pipe_bytes_to_read
= pcap_info
->rechdr
.hdr
.incl_len
;
2696 pcap_src
->cap_pipe_bytes_read
= 0;
2699 pcap_src
->cap_pipe_buf
= pcap_src
->cap_pipe_databuf
;
2700 g_async_queue_push(pcap_src
->cap_pipe_pending_q
, pcap_src
->cap_pipe_buf
);
2701 g_mutex_unlock(pcap_src
->cap_pipe_read_mtx
);
2706 case STATE_READ_DATA
:
2708 if (pcap_src
->from_cap_socket
)
2711 b
= cap_pipe_read(pcap_src
->cap_pipe_fd
,
2712 pcap_src
->cap_pipe_databuf
+pcap_src
->cap_pipe_bytes_read
,
2713 pcap_src
->cap_pipe_bytes_to_read
- pcap_src
->cap_pipe_bytes_read
,
2714 pcap_src
->from_cap_socket
);
2717 result
= PD_PIPE_EOF
;
2719 result
= PD_PIPE_ERR
;
2723 pcap_src
->cap_pipe_bytes_read
+= (DWORD
)b
;
2725 pcap_src
->cap_pipe_bytes_read
+= b
;
2731 q_status
= g_async_queue_timeout_pop(pcap_src
->cap_pipe_done_q
, PIPE_READ_TIMEOUT
);
2732 if (pcap_src
->cap_pipe_err
== PIPEOF
) {
2733 result
= PD_PIPE_EOF
;
2735 } else if (pcap_src
->cap_pipe_err
== PIPERR
) {
2736 result
= PD_PIPE_ERR
;
2744 if (pcap_src
->cap_pipe_bytes_read
< pcap_src
->cap_pipe_bytes_to_read
) {
2745 /* There's still more of the pcap packet data to read. */
2748 result
= PD_DATA_READ
;
2752 snprintf(errmsg
, errmsgl
,
2753 "pcap_pipe_dispatch: invalid state");
2756 } /* switch (pcap_src->cap_pipe_state) */
2759 * We've now read as much data as we were expecting, so process it.
2763 case PD_REC_HDR_READ
:
2765 * We've read the packet header, so we know the captured length,
2766 * and thus the number of packet data bytes. Take care of byte order.
2768 cap_pipe_adjust_pcap_header(pcap_src
->cap_pipe_info
.pcap
.byte_swapped
, &pcap_info
->hdr
,
2769 &pcap_info
->rechdr
.hdr
);
2770 if (pcap_info
->rechdr
.hdr
.incl_len
> pcap_src
->cap_pipe_max_pkt_size
) {
2772 * The record contains more data than the advertised/allowed in the
2773 * pcap header, do not try to read more data (do not change to
2774 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2775 * instead stop with an error.
2777 snprintf(errmsg
, errmsgl
, "Frame %u too long (%d bytes)",
2778 ld
->packets_captured
+1, pcap_info
->rechdr
.hdr
.incl_len
);
2782 if (pcap_info
->rechdr
.hdr
.incl_len
> pcap_src
->cap_pipe_databuf_size
) {
2784 * Grow the buffer to the packet size, rounded up to a power of
2787 new_bufsize
= pcap_info
->rechdr
.hdr
.incl_len
;
2789 * https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2792 new_bufsize
|= new_bufsize
>> 1;
2793 new_bufsize
|= new_bufsize
>> 2;
2794 new_bufsize
|= new_bufsize
>> 4;
2795 new_bufsize
|= new_bufsize
>> 8;
2796 new_bufsize
|= new_bufsize
>> 16;
2798 pcap_src
->cap_pipe_databuf
= (char*)g_realloc(pcap_src
->cap_pipe_databuf
, new_bufsize
);
2799 pcap_src
->cap_pipe_databuf_size
= new_bufsize
;
2802 if (pcap_info
->rechdr
.hdr
.incl_len
) {
2804 * The record has some data following the header, try
2805 * to read it next time.
2807 pcap_src
->cap_pipe_state
= STATE_EXPECT_DATA
;
2812 * No data following the record header? Then no more data needs to be
2813 * read and we will fallthrough and emit an empty packet.
2819 * We've read the full contents of the packet record.
2820 * Fill in a "struct pcap_pkthdr", and process the packet.
2822 phdr
.ts
.tv_sec
= pcap_info
->rechdr
.hdr
.ts_sec
;
2823 phdr
.ts
.tv_usec
= pcap_info
->rechdr
.hdr
.ts_usec
;
2824 phdr
.caplen
= pcap_info
->rechdr
.hdr
.incl_len
;
2825 phdr
.len
= pcap_info
->rechdr
.hdr
.orig_len
;
2828 capture_loop_queue_packet_cb((uint8_t *)pcap_src
, &phdr
, pcap_src
->cap_pipe_databuf
);
2830 capture_loop_write_packet_cb((uint8_t *)pcap_src
, &phdr
, pcap_src
->cap_pipe_databuf
);
2834 * Now we want to read the next packet's header.
2836 pcap_src
->cap_pipe_state
= STATE_EXPECT_REC_HDR
;
2840 pcap_src
->cap_pipe_err
= PIPEOF
;
2844 snprintf(errmsg
, errmsgl
, "Error reading from pipe: %s",
2846 win32strerror(GetLastError()));
2855 pcap_src
->cap_pipe_err
= PIPERR
;
2856 /* Return here rather than inside the switch to prevent GCC warning */
2861 pcapng_pipe_dispatch(loop_data
*ld
, capture_src
*pcap_src
, char *errmsg
, size_t errmsgl
)
2863 enum { PD_REC_HDR_READ
, PD_DATA_READ
, PD_PIPE_EOF
, PD_PIPE_ERR
,
2868 unsigned new_bufsize
;
2869 pcapng_block_header_t
*bh
= &pcap_src
->cap_pipe_info
.pcapng
.bh
;
2871 #ifdef LOG_CAPTURE_VERBOSE
2872 ws_debug("pcapng_pipe_dispatch");
2875 switch (pcap_src
->cap_pipe_state
) {
2877 case STATE_EXPECT_REC_HDR
:
2878 #ifdef LOG_CAPTURE_VERBOSE
2879 ws_debug("pcapng_pipe_dispatch STATE_EXPECT_REC_HDR");
2882 if (g_mutex_trylock(pcap_src
->cap_pipe_read_mtx
)) {
2885 pcap_src
->cap_pipe_state
= STATE_READ_REC_HDR
;
2886 pcap_src
->cap_pipe_bytes_to_read
= sizeof(pcapng_block_header_t
);
2887 pcap_src
->cap_pipe_bytes_read
= 0;
2890 if (!pcap_src
->from_cap_socket
) {
2891 pcap_src
->cap_pipe_buf
= pcap_src
->cap_pipe_databuf
;
2892 g_async_queue_push(pcap_src
->cap_pipe_pending_q
, pcap_src
->cap_pipe_buf
);
2894 g_mutex_unlock(pcap_src
->cap_pipe_read_mtx
);
2899 case STATE_READ_REC_HDR
:
2900 #ifdef LOG_CAPTURE_VERBOSE
2901 ws_debug("pcapng_pipe_dispatch STATE_READ_REC_HDR");
2904 if (pcap_src
->from_cap_socket
) {
2906 if (cap_pipe_read_data_bytes(pcap_src
, errmsg
, errmsgl
) < 0) {
2911 q_status
= g_async_queue_timeout_pop(pcap_src
->cap_pipe_done_q
, PIPE_READ_TIMEOUT
);
2912 if (pcap_src
->cap_pipe_err
== PIPEOF
) {
2913 result
= PD_PIPE_EOF
;
2915 } else if (pcap_src
->cap_pipe_err
== PIPERR
) {
2916 result
= PD_PIPE_ERR
;
2924 if (pcap_src
->cap_pipe_bytes_read
< pcap_src
->cap_pipe_bytes_to_read
) {
2925 /* There's still more of the pcapng block header to read. */
2928 memcpy(bh
, pcap_src
->cap_pipe_databuf
, sizeof(pcapng_block_header_t
));
2929 result
= PD_REC_HDR_READ
;
2932 case STATE_EXPECT_DATA
:
2933 #ifdef LOG_CAPTURE_VERBOSE
2934 ws_debug("pcapng_pipe_dispatch STATE_EXPECT_DATA");
2937 if (g_mutex_trylock(pcap_src
->cap_pipe_read_mtx
)) {
2939 pcap_src
->cap_pipe_state
= STATE_READ_DATA
;
2940 pcap_src
->cap_pipe_bytes_to_read
= bh
->block_total_length
;
2943 if (!pcap_src
->from_cap_socket
) {
2944 pcap_src
->cap_pipe_bytes_to_read
-= pcap_src
->cap_pipe_bytes_read
;
2945 pcap_src
->cap_pipe_buf
= pcap_src
->cap_pipe_databuf
+ pcap_src
->cap_pipe_bytes_read
;
2946 pcap_src
->cap_pipe_bytes_read
= 0;
2947 g_async_queue_push(pcap_src
->cap_pipe_pending_q
, pcap_src
->cap_pipe_buf
);
2949 g_mutex_unlock(pcap_src
->cap_pipe_read_mtx
);
2954 case STATE_READ_DATA
:
2955 #ifdef LOG_CAPTURE_VERBOSE
2956 ws_debug("pcapng_pipe_dispatch STATE_READ_DATA");
2959 if (pcap_src
->from_cap_socket
) {
2961 if (cap_pipe_read_data_bytes(pcap_src
, errmsg
, errmsgl
) < 0) {
2967 q_status
= g_async_queue_timeout_pop(pcap_src
->cap_pipe_done_q
, PIPE_READ_TIMEOUT
);
2968 if (pcap_src
->cap_pipe_err
== PIPEOF
) {
2969 result
= PD_PIPE_EOF
;
2971 } else if (pcap_src
->cap_pipe_err
== PIPERR
) {
2972 result
= PD_PIPE_ERR
;
2980 if (pcap_src
->cap_pipe_bytes_read
< pcap_src
->cap_pipe_bytes_to_read
) {
2981 /* There's still more of the pcap block contents to read. */
2984 result
= PD_DATA_READ
;
2988 snprintf(errmsg
, errmsgl
,
2989 "pcapng_pipe_dispatch: invalid state");
2992 } /* switch (pcap_src->cap_pipe_state) */
2995 * We've now read as much data as we were expecting, so process it.
2999 case PD_REC_HDR_READ
:
3001 * We've read the pcapng block header, so we know the block type
3004 if (bh
->block_type
== BLOCK_TYPE_SHB
) {
3006 * We need to read the fixed portion of the SHB before to
3007 * get the endianness before we can interpret the block length.
3008 * (The block type of the SHB is byte-order-independent, so that
3009 * an SHB can be recognized before we know the endianness of
3012 * Continue the read process.
3014 pcapng_read_shb(pcap_src
, errmsg
, errmsgl
);
3018 if ((bh
->block_total_length
& 0x03) != 0) {
3019 snprintf(errmsg
, errmsgl
,
3020 "Total length of pcapng block read from pipe is %u, which is not a multiple of 4.",
3021 bh
->block_total_length
);
3024 if (is_data_block(bh
->block_type
) && bh
->block_total_length
> pcap_src
->cap_pipe_max_pkt_size
) {
3026 * The record contains more data than the advertised/allowed in the
3027 * pcapng header, do not try to read more data (do not change to
3028 * STATE_EXPECT_DATA) as that would not fit in the buffer and
3029 * instead stop with an error.
3031 snprintf(errmsg
, errmsgl
, "Block %u type 0x%08x too long (%d bytes)",
3032 ld
->packets_captured
+1, bh
->block_type
, bh
->block_total_length
);
3036 if (bh
->block_total_length
> pcap_src
->cap_pipe_databuf_size
) {
3038 * Grow the buffer to the packet size, rounded up to a power of
3041 new_bufsize
= bh
->block_total_length
;
3043 * https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
3046 new_bufsize
|= new_bufsize
>> 1;
3047 new_bufsize
|= new_bufsize
>> 2;
3048 new_bufsize
|= new_bufsize
>> 4;
3049 new_bufsize
|= new_bufsize
>> 8;
3050 new_bufsize
|= new_bufsize
>> 16;
3052 pcap_src
->cap_pipe_databuf
= (unsigned char*)g_realloc(pcap_src
->cap_pipe_databuf
, new_bufsize
);
3053 pcap_src
->cap_pipe_databuf_size
= new_bufsize
;
3056 /* The record always has at least the block total length following the header */
3057 if (bh
->block_total_length
< sizeof(pcapng_block_header_t
)+sizeof(uint32_t)) {
3058 snprintf(errmsg
, errmsgl
,
3059 "malformed pcapng block_total_length < minimum");
3060 pcap_src
->cap_pipe_err
= PIPEOF
;
3065 * Now we want to read the block contents.
3067 pcap_src
->cap_pipe_state
= STATE_EXPECT_DATA
;
3072 * We've read the full contents of the block.
3073 * Process the block.
3076 capture_loop_queue_pcapng_cb(pcap_src
, bh
, pcap_src
->cap_pipe_databuf
);
3078 capture_loop_write_pcapng_cb(pcap_src
, bh
, pcap_src
->cap_pipe_databuf
);
3082 * Now we want to read the next block's header.
3084 pcap_src
->cap_pipe_state
= STATE_EXPECT_REC_HDR
;
3088 pcap_src
->cap_pipe_err
= PIPEOF
;
3092 snprintf(errmsg
, errmsgl
, "Error reading from pipe: %s",
3094 win32strerror(GetLastError()));
3103 pcap_src
->cap_pipe_err
= PIPERR
;
3104 /* Return here rather than inside the switch to prevent GCC warning */
3108 /** Open the capture input sources; each one is either a pcap device,
3109 * a capture pipe, or a capture socket.
3110 * Returns true if it succeeds, false otherwise. */
3112 capture_loop_open_input(capture_options
*capture_opts
, loop_data
*ld
,
3113 char *errmsg
, size_t errmsg_len
,
3114 char *secondary_errmsg
, size_t secondary_errmsg_len
)
3116 cap_device_open_status open_status
;
3117 char open_status_str
[PCAP_ERRBUF_SIZE
];
3119 interface_options
*interface_opts
;
3120 capture_src
*pcap_src
;
3123 if ((use_threads
== false) &&
3124 (capture_opts
->ifaces
->len
> 1)) {
3125 snprintf(errmsg
, errmsg_len
,
3126 "Using threads is required for capturing on multiple interfaces.");
3130 int pcapng_src_count
= 0;
3131 for (i
= 0; i
< capture_opts
->ifaces
->len
; i
++) {
3132 interface_opts
= &g_array_index(capture_opts
->ifaces
, interface_options
, i
);
3133 pcap_src
= g_new0(capture_src
, 1);
3134 if (pcap_src
== NULL
) {
3135 snprintf(errmsg
, errmsg_len
,
3136 "Could not allocate memory.");
3140 #ifdef MUST_DO_SELECT
3141 pcap_src
->pcap_fd
= -1;
3143 pcap_src
->interface_id
= i
;
3144 pcap_src
->linktype
= -1;
3146 pcap_src
->cap_pipe_h
= INVALID_HANDLE_VALUE
;
3148 pcap_src
->cap_pipe_fd
= -1;
3149 pcap_src
->cap_pipe_dispatch
= pcap_pipe_dispatch
;
3150 pcap_src
->cap_pipe_state
= STATE_EXPECT_REC_HDR
;
3151 pcap_src
->cap_pipe_err
= PIPOK
;
3153 pcap_src
->cap_pipe_read_mtx
= g_new(GMutex
, 1);
3154 g_mutex_init(pcap_src
->cap_pipe_read_mtx
);
3155 pcap_src
->cap_pipe_pending_q
= g_async_queue_new();
3156 pcap_src
->cap_pipe_done_q
= g_async_queue_new();
3158 g_array_append_val(ld
->pcaps
, pcap_src
);
3160 ws_debug("capture_loop_open_input : %s", interface_opts
->name
);
3161 pcap_src
->pcap_h
= open_capture_device(capture_opts
, interface_opts
,
3162 CAP_READ_TIMEOUT
, &open_status
, &open_status_str
);
3164 if (pcap_src
->pcap_h
!= NULL
) {
3165 /* we've opened "iface" as a network device */
3167 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
3168 /* Find out if we're getting nanosecond-precision time stamps */
3169 pcap_src
->ts_nsec
= have_high_resolution_timestamp(pcap_src
->pcap_h
);
3172 #if defined(HAVE_PCAP_SETSAMPLING)
3173 if (interface_opts
->sampling_method
!= CAPTURE_SAMP_NONE
) {
3174 struct pcap_samp
*samp
;
3176 if ((samp
= pcap_setsampling(pcap_src
->pcap_h
)) != NULL
) {
3177 switch (interface_opts
->sampling_method
) {
3178 case CAPTURE_SAMP_BY_COUNT
:
3179 samp
->method
= PCAP_SAMP_1_EVERY_N
;
3182 case CAPTURE_SAMP_BY_TIMER
:
3183 samp
->method
= PCAP_SAMP_FIRST_AFTER_N_MS
;
3187 sync_msg_str
= ws_strdup_printf(
3188 "Unknown sampling method %d specified,\n"
3189 "continue without packet sampling",
3190 interface_opts
->sampling_method
);
3191 report_capture_error("Couldn't set the capture "
3192 "sampling", sync_msg_str
);
3193 g_free(sync_msg_str
);
3195 samp
->value
= interface_opts
->sampling_param
;
3197 report_capture_error("Couldn't set the capture sampling",
3198 "Cannot get packet sampling data structure");
3203 /* setting the data link type only works on real interfaces */
3204 if (!set_pcap_datalink(pcap_src
->pcap_h
, interface_opts
->linktype
,
3205 interface_opts
->name
,
3207 secondary_errmsg
, secondary_errmsg_len
)) {
3210 pcap_src
->linktype
= dlt_to_linktype(get_pcap_datalink(pcap_src
->pcap_h
, interface_opts
->name
));
3212 /* We couldn't open "iface" as a network device. */
3213 /* Try to open it as a pipe */
3214 bool pipe_err
= false;
3215 cap_pipe_open_live(interface_opts
->name
, pcap_src
,
3216 &pcap_src
->cap_pipe_info
.pcap
.hdr
,
3218 secondary_errmsg
, secondary_errmsg_len
);
3221 if (pcap_src
->from_cap_socket
) {
3223 if (pcap_src
->cap_pipe_fd
== -1) {
3228 if (pcap_src
->cap_pipe_h
== INVALID_HANDLE_VALUE
) {
3235 if (pcap_src
->cap_pipe_err
== PIPNEXIST
) {
3237 * We tried opening as an interface, and that failed,
3238 * so we tried to open it as a pipe, but the pipe
3239 * doesn't exist. Report the error message for
3242 get_capture_device_open_failure_messages(open_status
,
3244 interface_opts
->name
,
3248 secondary_errmsg_len
);
3251 * Else pipe (or file) does exist and cap_pipe_open_live() has
3257 * We tried opening as an interface, and that failed,
3258 * so we tried to open it as a pipe, and that succeeded.
3260 open_status
= CAP_DEVICE_OPEN_NO_ERR
;
3264 /* XXX - will this work for tshark? */
3265 #ifdef MUST_DO_SELECT
3266 if (!pcap_src
->from_cap_pipe
) {
3267 pcap_src
->pcap_fd
= pcap_get_selectable_fd(pcap_src
->pcap_h
);
3271 /* Is "open_status" something other than CAP_DEVICE_OPEN_NO_ERR?
3272 If so, "open_capture_device()" returned a warning; print it,
3273 but keep capturing. */
3274 if (open_status
!= CAP_DEVICE_OPEN_NO_ERR
) {
3275 sync_msg_str
= ws_strdup_printf("%s.", open_status_str
);
3276 report_capture_error(sync_msg_str
, "");
3277 g_free(sync_msg_str
);
3279 if (pcap_src
->from_pcapng
) {
3281 * We will use the IDBs from the source (but rewrite the
3282 * interface IDs if there's more than one source.)
3287 * Add our pcapng interface entry.
3289 saved_idb_t idb_source
= { 0 };
3290 idb_source
.interface_id
= i
;
3291 g_rw_lock_writer_lock (&ld
->saved_shb_idb_lock
);
3292 pcap_src
->idb_id
= global_ld
.saved_idbs
->len
;
3293 g_array_append_val(global_ld
.saved_idbs
, idb_source
);
3294 g_rw_lock_writer_unlock (&ld
->saved_shb_idb_lock
);
3295 ws_debug("%s: saved capture_opts %u to IDB %u",
3296 G_STRFUNC
, i
, pcap_src
->idb_id
);
3301 * Are we capturing from one source that is providing pcapng
3304 if (capture_opts
->ifaces
->len
== 1 && pcapng_src_count
== 1) {
3306 * Yes; pass through SHBs and IDBs from the source, rather
3307 * than generating our own.
3309 ld
->pcapng_passthrough
= true;
3310 g_rw_lock_writer_lock (&ld
->saved_shb_idb_lock
);
3311 ws_assert(global_ld
.saved_idbs
->len
== 0);
3312 ws_debug("%s: Pass through SHBs and IDBs directly", G_STRFUNC
);
3313 g_rw_lock_writer_unlock (&ld
->saved_shb_idb_lock
);
3316 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
3317 /* to remove any suid privileges. */
3318 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
3319 /* (euid/egid have already previously been set to ruid/rgid. */
3320 /* (See comment in main() for details) */
3322 relinquish_special_privs_perm();
3324 relinquish_all_capabilities();
3329 /* close the capture input file (pcap or capture pipe) */
3330 static void capture_loop_close_input(loop_data
*ld
)
3333 capture_src
*pcap_src
;
3335 ws_debug("capture_loop_close_input");
3337 for (i
= 0; i
< ld
->pcaps
->len
; i
++) {
3338 pcap_src
= g_array_index(ld
->pcaps
, capture_src
*, i
);
3339 /* Pipe, or capture device? */
3340 if (pcap_src
->from_cap_pipe
) {
3341 /* Pipe. If open, close the capture pipe "input file". */
3342 if (pcap_src
->cap_pipe_fd
>= 0) {
3343 cap_pipe_close(pcap_src
->cap_pipe_fd
, pcap_src
->from_cap_socket
);
3344 pcap_src
->cap_pipe_fd
= -1;
3347 if (pcap_src
->cap_pipe_h
!= INVALID_HANDLE_VALUE
) {
3348 CloseHandle(pcap_src
->cap_pipe_h
);
3349 pcap_src
->cap_pipe_h
= INVALID_HANDLE_VALUE
;
3352 if (pcap_src
->cap_pipe_databuf
!= NULL
) {
3353 /* Free the buffer. */
3354 g_free(pcap_src
->cap_pipe_databuf
);
3355 pcap_src
->cap_pipe_databuf
= NULL
;
3357 if (pcap_src
->from_pcapng
) {
3358 g_array_free(pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
, TRUE
);
3359 pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
= NULL
;
3362 /* Capture device. If open, close the pcap_t. */
3363 if (pcap_src
->pcap_h
!= NULL
) {
3364 ws_debug("capture_loop_close_input: closing %p", (void *)pcap_src
->pcap_h
);
3365 pcap_close(pcap_src
->pcap_h
);
3366 pcap_src
->pcap_h
= NULL
;
3375 /* init the capture filter */
3376 static initfilter_status_t
3377 capture_loop_init_filter(pcap_t
*pcap_h
, bool from_cap_pipe
,
3378 const char * name
, const char * cfilter
)
3380 struct bpf_program fcode
;
3382 ws_debug("capture_loop_init_filter: %s", cfilter
);
3384 /* capture filters only work on real interfaces */
3385 if (cfilter
&& !from_cap_pipe
) {
3386 /* A capture filter was specified; set it up. */
3387 if (!compile_capture_filter(name
, pcap_h
, &fcode
, cfilter
)) {
3388 /* Treat this specially - our caller might try to compile this
3389 as a display filter and, if that succeeds, warn the user that
3390 the display and capture filter syntaxes are different. */
3391 return INITFILTER_BAD_FILTER
;
3393 if (pcap_setfilter(pcap_h
, &fcode
) < 0) {
3394 #ifdef HAVE_PCAP_FREECODE
3395 pcap_freecode(&fcode
);
3397 return INITFILTER_OTHER_ERROR
;
3399 #ifdef HAVE_PCAP_FREECODE
3400 pcap_freecode(&fcode
);
3404 return INITFILTER_NO_ERROR
;
3408 * Write the dumpcap pcapng SHB and IDBs if needed.
3409 * Called from capture_loop_init_output and do_file_switch_or_stop.
3412 capture_loop_init_pcapng_output(capture_options
*capture_opts
, loop_data
*ld
,
3415 g_rw_lock_reader_lock (&ld
->saved_shb_idb_lock
);
3417 if (ld
->pcapng_passthrough
&& !ld
->saved_shb
) {
3418 /* We have a single pcapng capture interface and this is the first or only output file. */
3419 ws_debug("%s: skipping dumpcap SHB and IDBs in favor of source", G_STRFUNC
);
3420 g_rw_lock_reader_unlock (&ld
->saved_shb_idb_lock
);
3424 bool successful
= true;
3425 GString
*os_info_str
= g_string_new("");
3428 get_os_version_info(os_info_str
);
3430 if (ld
->saved_shb
) {
3431 /* We have a single pcapng capture interface and multiple output files. */
3433 pcapng_block_header_t bh
;
3435 memcpy(&bh
, ld
->saved_shb
, sizeof(pcapng_block_header_t
));
3437 successful
= pcapng_write_block(ld
->pdh
, ld
->saved_shb
, bh
.block_total_length
, &ld
->bytes_written
, err
);
3439 ws_debug("%s: wrote saved passthrough SHB %d", G_STRFUNC
, successful
);
3441 GString
*cpu_info_str
= g_string_new("");
3442 get_cpu_info(cpu_info_str
);
3444 successful
= pcapng_write_section_header_block(ld
->pdh
,
3445 capture_comments
, /* Comments */
3446 cpu_info_str
->str
, /* HW */
3447 os_info_str
->str
, /* OS */
3448 get_appname_and_version(),
3449 -1, /* section_length */
3452 ws_debug("%s: wrote dumpcap SHB %d", G_STRFUNC
, successful
);
3453 g_string_free(cpu_info_str
, TRUE
);
3456 for (unsigned i
= 0; successful
&& (i
< ld
->saved_idbs
->len
); i
++) {
3457 saved_idb_t idb_source
= g_array_index(ld
->saved_idbs
, saved_idb_t
, i
);
3458 if (idb_source
.deleted
) {
3460 * Our interface is out of scope. Suppose we're writing multiple
3461 * files and a source switches sections. We currently write dummy
3464 * File 1: IDB0, IDB1, IDB2
3465 * [ The source of IDBs 1 and 2 writes an SHB with two new IDBs ]
3466 * [ We switch output files ]
3467 * File 2: IDB0, dummy IDB, dummy IDB, IDB3, IDB4
3469 * It might make more sense to write the original data so that
3470 * so that our IDB lists are more consistent across files.
3472 successful
= pcapng_write_interface_description_block(global_ld
.pdh
,
3473 "Interface went out of scope", /* OPT_COMMENT 1 */
3474 "dummy", /* IDB_NAME 2 */
3475 "Dumpcap dummy interface", /* IDB_DESCRIPTION 3 */
3476 NULL
, /* IDB_FILTER 11 */
3477 os_info_str
->str
, /* IDB_OS 12 */
3478 NULL
, /* IDB_HARDWARE 15 */
3481 &(global_ld
.bytes_written
),
3482 0, /* IDB_IF_SPEED 8 */
3483 6, /* IDB_TSRESOL 9 */
3485 ws_debug("%s: skipping deleted pcapng IDB %u", G_STRFUNC
, i
);
3486 } else if (idb_source
.idb
&& idb_source
.idb_len
) {
3487 successful
= pcapng_write_block(global_ld
.pdh
, idb_source
.idb
, idb_source
.idb_len
, &ld
->bytes_written
, err
);
3488 ws_debug("%s: wrote pcapng IDB %d", G_STRFUNC
, successful
);
3489 } else if (idb_source
.interface_id
< capture_opts
->ifaces
->len
) {
3490 unsigned if_id
= idb_source
.interface_id
;
3491 interface_options
*interface_opts
= &g_array_index(capture_opts
->ifaces
, interface_options
, if_id
);
3492 capture_src
*pcap_src
= g_array_index(ld
->pcaps
, capture_src
*, if_id
);
3493 if (pcap_src
->from_cap_pipe
) {
3494 pcap_src
->snaplen
= pcap_src
->cap_pipe_info
.pcap
.hdr
.snaplen
;
3496 pcap_src
->snaplen
= pcap_snapshot(pcap_src
->pcap_h
);
3498 successful
= pcapng_write_interface_description_block(global_ld
.pdh
,
3499 NULL
, /* OPT_COMMENT 1 */
3500 (interface_opts
->ifname
!= NULL
) ? interface_opts
->ifname
: interface_opts
->name
, /* IDB_NAME 2 */
3501 interface_opts
->descr
, /* IDB_DESCRIPTION 3 */
3502 interface_opts
->cfilter
, /* IDB_FILTER 11 */
3503 os_info_str
->str
, /* IDB_OS 12 */
3504 interface_opts
->hardware
, /* IDB_HARDWARE 15 */
3507 &(global_ld
.bytes_written
),
3508 0, /* IDB_IF_SPEED 8 */
3509 pcap_src
->ts_nsec
? 9 : 6, /* IDB_TSRESOL 9 */
3511 ws_debug("%s: wrote capture_opts IDB %d: %d", G_STRFUNC
, if_id
, successful
);
3514 g_rw_lock_reader_unlock (&ld
->saved_shb_idb_lock
);
3516 g_string_free(os_info_str
, TRUE
);
3521 /* set up to write to the already-opened capture output file/files */
3523 capture_loop_init_output(capture_options
*capture_opts
, loop_data
*ld
, char *errmsg
, int errmsg_len
)
3527 ws_debug("capture_loop_init_output");
3529 if ((capture_opts
->use_pcapng
== false) &&
3530 (capture_opts
->ifaces
->len
> 1)) {
3531 snprintf(errmsg
, errmsg_len
,
3532 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
3536 /* Set up to write to the capture file. */
3537 if (capture_opts
->multi_files_on
) {
3538 ld
->pdh
= ringbuf_init_libpcap_fdopen(&err
);
3540 ld
->pdh
= ws_fdopen(ld
->save_file_fd
, "wb");
3541 if (ld
->pdh
== NULL
) {
3544 size_t buffsize
= IO_BUF_SIZE
;
3545 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
3548 if (ws_fstat64(ld
->save_file_fd
, &statb
) == 0) {
3549 if (statb
.st_blksize
> IO_BUF_SIZE
) {
3550 buffsize
= statb
.st_blksize
;
3554 /* Increase the size of the IO buffer */
3555 ld
->io_buffer
= (char *)g_malloc(buffsize
);
3556 setvbuf(ld
->pdh
, ld
->io_buffer
, _IOFBF
, buffsize
);
3557 ws_debug("capture_loop_init_output: buffsize %zu", buffsize
);
3562 if (capture_opts
->use_pcapng
) {
3563 successful
= capture_loop_init_pcapng_output(capture_opts
, ld
, &err
);
3565 capture_src
*pcap_src
;
3566 pcap_src
= g_array_index(ld
->pcaps
, capture_src
*, 0);
3567 if (pcap_src
->from_cap_pipe
) {
3568 pcap_src
->snaplen
= pcap_src
->cap_pipe_info
.pcap
.hdr
.snaplen
;
3570 pcap_src
->snaplen
= pcap_snapshot(pcap_src
->pcap_h
);
3572 successful
= libpcap_write_file_header(ld
->pdh
, pcap_src
->linktype
, pcap_src
->snaplen
,
3573 pcap_src
->ts_nsec
, &ld
->bytes_written
, &err
);
3578 g_free(ld
->io_buffer
);
3579 ld
->io_buffer
= NULL
;
3583 if (ld
->pdh
== NULL
) {
3584 /* We couldn't set up to write to the capture file. */
3585 /* XXX - use cf_open_error_message from tshark instead? */
3587 snprintf(errmsg
, errmsg_len
,
3588 "The file to which the capture would be"
3589 " saved (\"%s\") could not be opened: Error %d.",
3590 capture_opts
->save_file
, err
);
3592 snprintf(errmsg
, errmsg_len
,
3593 "The file to which the capture would be"
3594 " saved (\"%s\") could not be opened: %s.",
3595 capture_opts
->save_file
, g_strerror(err
));
3604 capture_loop_close_output(capture_options
*capture_opts
, loop_data
*ld
, int *err_close
)
3608 capture_src
*pcap_src
;
3609 uint64_t end_time
= create_timestamp();
3612 ws_debug("capture_loop_close_output");
3614 if (capture_opts
->multi_files_on
) {
3615 return ringbuf_libpcap_dump_close(&capture_opts
->save_file
, err_close
);
3617 if (capture_opts
->use_pcapng
) {
3618 for (i
= 0; i
< global_ld
.pcaps
->len
; i
++) {
3619 pcap_src
= g_array_index(global_ld
.pcaps
, capture_src
*, i
);
3620 if (!pcap_src
->from_cap_pipe
) {
3621 uint64_t isb_ifrecv
, isb_ifdrop
;
3622 struct pcap_stat stats
;
3624 if (pcap_stats(pcap_src
->pcap_h
, &stats
) >= 0) {
3625 isb_ifrecv
= pcap_src
->received
;
3626 isb_ifdrop
= stats
.ps_drop
+ pcap_src
->dropped
+ pcap_src
->flushed
;
3628 isb_ifrecv
= UINT64_MAX
;
3629 isb_ifdrop
= UINT64_MAX
;
3631 pcapng_write_interface_statistics_block(ld
->pdh
,
3634 "Counters provided by dumpcap",
3643 if (fclose(ld
->pdh
) == EOF
) {
3644 if (err_close
!= NULL
) {
3651 g_free(ld
->io_buffer
);
3652 ld
->io_buffer
= NULL
;
3657 /* dispatch incoming packets (pcap or capture pipe)
3659 * Waits for incoming packets to be available, and calls pcap_dispatch()
3660 * to cause them to be processed.
3662 * Returns the number of packets which were processed.
3664 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3665 * packet-batching behaviour does not cause packets to get held back
3669 capture_loop_dispatch(loop_data
*ld
,
3670 char *errmsg
, int errmsg_len
, capture_src
*pcap_src
)
3673 int packet_count_before
;
3676 packet_count_before
= ld
->packets_captured
;
3677 if (pcap_src
->from_cap_pipe
) {
3678 /* dispatch from capture pipe */
3679 #ifdef LOG_CAPTURE_VERBOSE
3680 ws_debug("capture_loop_dispatch: from capture pipe");
3683 if (pcap_src
->from_cap_socket
) {
3685 sel_ret
= cap_pipe_select(pcap_src
->cap_pipe_fd
);
3687 if (sel_ret
< 0 && errno
!= EINTR
) {
3688 snprintf(errmsg
, errmsg_len
,
3689 "Unexpected error from select: %s", g_strerror(errno
));
3690 report_capture_error(errmsg
, please_report_bug());
3696 /* Windows does not have select() for pipes. */
3697 /* Proceed with _dispatch() which waits for cap_pipe_done_q
3698 * notification from cap_thread_read() when ReadFile() on
3699 * the pipe has read enough bytes. */
3705 * "select()" says we can read from the pipe without blocking
3707 inpkts
= pcap_src
->cap_pipe_dispatch(ld
, pcap_src
, errmsg
, errmsg_len
);
3709 ws_debug("%s: src %u pipe reached EOF or err, rcv: %u drop: %u flush: %u",
3710 G_STRFUNC
, pcap_src
->interface_id
, pcap_src
->received
, pcap_src
->dropped
, pcap_src
->flushed
);
3711 ws_assert(pcap_src
->cap_pipe_err
!= PIPOK
);
3717 /* dispatch from pcap */
3718 #ifdef MUST_DO_SELECT
3720 * If we have "pcap_get_selectable_fd()", we use it to get the
3721 * descriptor on which to select; if that's -1, it means there
3722 * is no descriptor on which you can do a "select()" (perhaps
3723 * because you're capturing on a special device, and that device's
3724 * driver unfortunately doesn't support "select()", in which case
3725 * we don't do the select - which means it might not be possible
3726 * to stop a capture until a packet arrives. If that's unacceptable,
3727 * plead with whoever supplies the software for that device to add
3728 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3729 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3730 * later, so it can use pcap_breakloop().
3732 #ifdef LOG_CAPTURE_VERBOSE
3733 ws_debug("capture_loop_dispatch: from pcap_dispatch with select");
3735 if (pcap_src
->pcap_fd
!= -1) {
3736 sel_ret
= cap_pipe_select(pcap_src
->pcap_fd
);
3739 * "select()" says we can read from it without blocking; go for
3742 * We don't have pcap_breakloop(), so we only process one packet
3743 * per pcap_dispatch() call, to allow a signal to stop the
3744 * processing immediately, rather than processing all packets
3745 * in a batch before quitting.
3748 inpkts
= pcap_dispatch(pcap_src
->pcap_h
, 1, capture_loop_queue_packet_cb
, (uint8_t *)pcap_src
);
3750 inpkts
= pcap_dispatch(pcap_src
->pcap_h
, 1, capture_loop_write_packet_cb
, (uint8_t *)pcap_src
);
3754 /* Error, rather than pcap_breakloop(). */
3755 pcap_src
->pcap_err
= true;
3757 ld
->go
= false; /* error or pcap_breakloop() - stop capturing */
3760 if (sel_ret
< 0 && errno
!= EINTR
) {
3761 snprintf(errmsg
, errmsg_len
,
3762 "Unexpected error from select: %s", g_strerror(errno
));
3763 report_capture_error(errmsg
, please_report_bug());
3769 #endif /* MUST_DO_SELECT */
3771 /* dispatch from pcap without select */
3773 #ifdef LOG_CAPTURE_VERBOSE
3774 ws_debug("capture_loop_dispatch: from pcap_dispatch");
3778 * On Windows, we don't support asynchronously telling a process to
3779 * stop capturing; instead, we check for an indication on a pipe
3780 * after processing packets. We therefore process only one packet
3781 * at a time, so that we can check the pipe after every packet.
3784 inpkts
= pcap_dispatch(pcap_src
->pcap_h
, 1, capture_loop_queue_packet_cb
, (uint8_t *)pcap_src
);
3786 inpkts
= pcap_dispatch(pcap_src
->pcap_h
, 1, capture_loop_write_packet_cb
, (uint8_t *)pcap_src
);
3790 inpkts
= pcap_dispatch(pcap_src
->pcap_h
, -1, capture_loop_queue_packet_cb
, (uint8_t *)pcap_src
);
3792 inpkts
= pcap_dispatch(pcap_src
->pcap_h
, -1, capture_loop_write_packet_cb
, (uint8_t *)pcap_src
);
3797 /* Error, rather than pcap_breakloop(). */
3798 pcap_src
->pcap_err
= true;
3800 ld
->go
= false; /* error or pcap_breakloop() - stop capturing */
3802 #else /* pcap_next_ex */
3803 #ifdef LOG_CAPTURE_VERBOSE
3804 ws_debug("capture_loop_dispatch: from pcap_next_ex");
3806 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3809 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3810 * see https://gitlab.com/wireshark/wireshark/-/wikis/CaptureSetup/WinPcapRemote
3811 * This should be fixed in the WinPcap 4.0 alpha release.
3813 * For reference, an example remote interface:
3814 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3817 /* emulate dispatch from pcap */
3820 struct pcap_pkthdr
*pkt_header
;
3825 (in
= pcap_next_ex(pcap_src
->pcap_h
, &pkt_header
, &pkt_data
)) == 1) {
3827 capture_loop_queue_packet_cb((uint8_t *)pcap_src
, pkt_header
, pkt_data
);
3829 capture_loop_write_packet_cb((uint8_t *)pcap_src
, pkt_header
, pkt_data
);
3834 pcap_src
->pcap_err
= true;
3838 #endif /* pcap_next_ex */
3842 #ifdef LOG_CAPTURE_VERBOSE
3843 ws_debug("capture_loop_dispatch: %d new packet%s", inpkts
, plurality(inpkts
, "", "s"));
3846 return ld
->packets_captured
- packet_count_before
;
3850 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3851 * want to grab only the characters between the '{' and '}' delimiters.
3853 * Returns a GString that must be freed with g_string_free(). */
3855 isolate_uuid(const char *iface
)
3860 ptr
= strchr(iface
, '{');
3862 return g_string_new(iface
);
3863 gstr
= g_string_new(ptr
+ 1);
3865 ptr
= strchr(gstr
->str
, '}');
3869 gstr
= g_string_truncate(gstr
, ptr
- gstr
->str
);
3874 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3875 /* Returns true if the file opened successfully, false otherwise. */
3877 capture_loop_open_output(capture_options
*capture_opts
, int *save_file_fd
,
3878 char *errmsg
, int errmsg_len
)
3880 char *capfile_name
= NULL
;
3881 char *prefix
, *suffix
;
3883 GError
*err_tempfile
= NULL
;
3885 ws_debug("capture_loop_open_output: %s",
3886 (capture_opts
->save_file
) ? capture_opts
->save_file
: "(not specified)");
3888 if (capture_opts
->save_file
!= NULL
) {
3889 /* We return to the caller while the capture is in progress.
3890 * Therefore we need to take a copy of save_file in
3891 * case the caller destroys it after we return.
3893 capfile_name
= g_strdup(capture_opts
->save_file
);
3895 if (capture_opts
->output_to_pipe
== true) { /* either "-" or named pipe */
3896 if (capture_opts
->multi_files_on
) {
3897 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3898 snprintf(errmsg
, errmsg_len
,
3899 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3900 g_free(capfile_name
);
3903 if (strcmp(capfile_name
, "-") == 0) {
3904 /* write to stdout */
3907 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3908 _setmode(1, O_BINARY
);
3911 /* Try to open the specified FIFO for use as a capture buffer.
3912 Do *not* create it if it doesn't exist. There's nothing
3913 to truncate. If we need to read it, We Have A Problem. */
3914 *save_file_fd
= ws_open(capfile_name
, O_WRONLY
|O_BINARY
, 0);
3916 } /* if (...output_to_pipe ... */
3919 if (capture_opts
->multi_files_on
) {
3920 /* ringbuffer is enabled */
3921 *save_file_fd
= ringbuf_init(capfile_name
,
3922 (capture_opts
->has_ring_num_files
) ? capture_opts
->ring_num_files
: 0,
3923 capture_opts
->group_read_access
,
3924 capture_opts
->compress_type
,
3925 capture_opts
->has_nametimenum
);
3927 /* capfile_name is unused as the ringbuffer provides its own filename. */
3928 if (*save_file_fd
!= -1) {
3929 g_free(capfile_name
);
3930 capfile_name
= NULL
;
3932 if (capture_opts
->print_file_names
) {
3933 if (!ringbuf_set_print_name(capture_opts
->print_name_to
, NULL
)) {
3934 snprintf(errmsg
, errmsg_len
, "Could not write filenames to %s: %s.\n",
3935 capture_opts
->print_name_to
,
3937 g_free(capfile_name
);
3938 ringbuf_error_cleanup();
3943 /* Try to open/create the specified file for use as a capture buffer. */
3944 *save_file_fd
= ws_open(capfile_name
, O_WRONLY
|O_BINARY
|O_TRUNC
|O_CREAT
,
3945 (capture_opts
->group_read_access
) ? 0640 : 0600);
3948 is_tempfile
= false;
3950 /* Choose a random name for the temporary capture buffer */
3951 if (global_capture_opts
.ifaces
->len
> 1) {
3953 * More than one interface; just use the number of interfaces
3954 * to generate the temporary file name prefix.
3956 prefix
= ws_strdup_printf("wireshark_%d_interfaces", global_capture_opts
.ifaces
->len
);
3959 * One interface; use its description, if it has one, to generate
3960 * the temporary file name, otherwise use its name.
3963 const interface_options
*interface_opts
;
3965 interface_opts
= &g_array_index(global_capture_opts
.ifaces
, interface_options
, 0);
3968 * Do we have a description?
3970 if (interface_opts
->descr
) {
3974 * Strip off any stuff we shouldn't use in the file name,
3975 * by getting the last component of what would be a file
3978 basename
= g_path_get_basename(interface_opts
->descr
);
3981 * No - use the name.
3983 * Strip off any stuff we shouldn't use in the file name,
3984 * by getting the last component of what would be a file
3987 basename
= g_path_get_basename(interface_opts
->name
);
3990 * This is Windows, where we might have an ugly GUID-based
3993 * If it's an ugly GUID-based name, use the generic portion
3994 * of the interface GUID to form the basis of the filename.
3996 if (strncmp("NPF_{", basename
, 5) == 0) {
3998 * We have a GUID-based name; extract the GUID digits
3999 * as the basis of the filename.
4002 iface
= isolate_uuid(basename
);
4004 basename
= g_strdup(iface
->str
);
4005 g_string_free(iface
, TRUE
);
4009 /* generate the temp file name prefix */
4010 prefix
= g_strconcat("wireshark_", basename
, NULL
);
4014 /* Generate the appropriate suffix. */
4015 if (capture_opts
->use_pcapng
) {
4020 *save_file_fd
= create_tempfile(capture_opts
->temp_dir
, &capfile_name
, prefix
, suffix
, &err_tempfile
);
4025 /* did we fail to open the output file? */
4026 if (*save_file_fd
== -1) {
4028 snprintf(errmsg
, errmsg_len
,
4029 "The temporary file to which the capture would be saved "
4030 "could not be opened: %s.", err_tempfile
->message
);
4031 g_error_free(err_tempfile
);
4033 if (capture_opts
->multi_files_on
) {
4034 /* Ensures that the ringbuffer is not used. This ensures that
4035 * !ringbuf_is_initialized() is equivalent to
4036 * capture_opts->save_file not being part of ringbuffer. */
4037 ringbuf_error_cleanup();
4040 snprintf(errmsg
, errmsg_len
,
4041 "The file to which the capture would be saved (\"%s\") "
4042 "could not be opened: %s.", capfile_name
,
4045 g_free(capfile_name
);
4049 g_free(capture_opts
->save_file
);
4050 if (!is_tempfile
&& capture_opts
->multi_files_on
) {
4051 /* In ringbuffer mode, save_file points to a filename from ringbuffer.c.
4052 * capfile_name was already freed before. */
4053 capture_opts
->save_file
= (char *)ringbuf_current_filename();
4055 /* capture_opts_cleanup will g_free(capture_opts->save_file). */
4056 capture_opts
->save_file
= capfile_name
;
4062 static time_t get_next_time_interval(int interval_s
) {
4063 time_t next_time
= time(NULL
);
4064 next_time
-= next_time
% interval_s
;
4065 next_time
+= interval_s
;
4069 /* Do the work of handling either the file size or file duration capture
4070 conditions being reached, and switching files or stopping. */
4072 do_file_switch_or_stop(capture_options
*capture_opts
)
4076 if (capture_opts
->multi_files_on
) {
4077 if (capture_opts
->has_autostop_files
&&
4078 ++global_ld
.file_count
>= capture_opts
->autostop_files
) {
4079 /* no files left: stop here */
4080 global_ld
.go
= false;
4084 /* Switch to the next ringbuffer file */
4085 if (ringbuf_switch_file(&global_ld
.pdh
, &capture_opts
->save_file
,
4086 &global_ld
.save_file_fd
, &global_ld
.err
)) {
4088 /* File switch succeeded: reset the conditions */
4089 global_ld
.bytes_written
= 0;
4090 global_ld
.packets_written
= 0;
4091 if (capture_opts
->use_pcapng
) {
4092 successful
= capture_loop_init_pcapng_output(capture_opts
, &global_ld
, &global_ld
.err
);
4094 capture_src
*pcap_src
;
4095 pcap_src
= g_array_index(global_ld
.pcaps
, capture_src
*, 0);
4096 successful
= libpcap_write_file_header(global_ld
.pdh
, pcap_src
->linktype
, pcap_src
->snaplen
,
4097 pcap_src
->ts_nsec
, &global_ld
.bytes_written
, &global_ld
.err
);
4101 fclose(global_ld
.pdh
);
4102 global_ld
.pdh
= NULL
;
4103 global_ld
.go
= false;
4104 g_free(global_ld
.io_buffer
);
4105 global_ld
.io_buffer
= NULL
;
4108 if (global_ld
.file_duration_timer
) {
4109 g_timer_reset(global_ld
.file_duration_timer
);
4111 if (global_ld
.next_interval_time
) {
4112 global_ld
.next_interval_time
= get_next_time_interval(global_ld
.interval_s
);
4114 fflush(global_ld
.pdh
);
4115 if (global_ld
.inpkts_to_sync_pipe
) {
4117 report_packet_count(global_ld
.inpkts_to_sync_pipe
);
4118 global_ld
.inpkts_to_sync_pipe
= 0;
4120 report_new_capture_file(capture_opts
->save_file
);
4122 /* File switch failed: stop here */
4123 global_ld
.go
= false;
4127 /* single file, stop now */
4128 global_ld
.go
= false;
4135 pcap_read_handler(void* arg
)
4137 capture_src
*pcap_src
= (capture_src
*)arg
;
4138 char errmsg
[MSG_MAX_LENGTH
+1];
4140 ws_info("Started thread for interface %d.", pcap_src
->interface_id
);
4142 /* If this is a pipe input it might finish early. */
4143 while (global_ld
.go
&& pcap_src
->cap_pipe_err
== PIPOK
) {
4144 /* dispatch incoming packets */
4145 capture_loop_dispatch(&global_ld
, errmsg
, sizeof(errmsg
), pcap_src
);
4148 ws_info("Stopped thread for interface %d.", pcap_src
->interface_id
);
4149 g_thread_exit(NULL
);
4153 /* Try to pop an item off the packet queue and if it exists, write it */
4155 capture_loop_dequeue_packet(void) {
4156 pcap_queue_element
*queue_element
;
4158 g_async_queue_lock(pcap_queue
);
4159 queue_element
= (pcap_queue_element
*)g_async_queue_timeout_pop_unlocked(pcap_queue
, WRITER_THREAD_TIMEOUT
);
4160 if (queue_element
) {
4161 if (queue_element
->pcap_src
->from_pcapng
) {
4162 pcap_queue_bytes
-= queue_element
->u
.bh
.block_total_length
;
4164 pcap_queue_bytes
-= queue_element
->u
.phdr
.caplen
;
4166 pcap_queue_packets
-= 1;
4168 g_async_queue_unlock(pcap_queue
);
4169 if (queue_element
) {
4170 if (queue_element
->pcap_src
->from_pcapng
) {
4171 ws_info("Dequeued a block of type 0x%08x of length %d captured on interface %d.",
4172 queue_element
->u
.bh
.block_type
, queue_element
->u
.bh
.block_total_length
,
4173 queue_element
->pcap_src
->interface_id
);
4175 capture_loop_write_pcapng_cb(queue_element
->pcap_src
,
4176 &queue_element
->u
.bh
,
4179 ws_info("Dequeued a packet of length %d captured on interface %d.",
4180 queue_element
->u
.phdr
.caplen
, queue_element
->pcap_src
->interface_id
);
4182 capture_loop_write_packet_cb((uint8_t *) queue_element
->pcap_src
,
4183 &queue_element
->u
.phdr
,
4186 g_free(queue_element
->pd
);
4187 g_free(queue_element
);
4194 * Note: this code will never be run on any OS other than Windows.
4196 * We keep the arguments in case there's something in the future
4197 * that needs to be reported as an NPCAP bug.
4200 handle_npcap_bug(char *adapter_name _U_
, char *cap_err_str _U_
)
4202 bool have_npcap
= false;
4205 have_npcap
= caplibs_have_npcap();
4210 * We're not using Npcap, so don't recommend a user
4211 * file a bug against Npcap.
4213 return g_strdup("");
4216 return ws_strdup_printf("If you have not removed that adapter, this "
4217 "is probably a known issue in Npcap resulting from "
4218 "the behavior of the Windows networking stack. "
4219 "Work is being done in Npcap to improve the "
4220 "handling of this issue; it does not need to "
4221 "be reported as a Wireshark or Npcap bug.");
4224 /* Do the low-level work of a capture.
4225 Returns true if it succeeds, false otherwise. */
4227 capture_loop_start(capture_options
*capture_opts
, bool *stats_known
, struct pcap_stat
*stats
)
4230 ULONGLONG upd_time
, cur_time
; /* GetTickCount64() returns a "ULONGLONG" */
4232 struct timeval upd_time
, cur_time
;
4236 GTimer
*autostop_duration_timer
= NULL
;
4239 bool cfilter_error
= false;
4240 char errmsg
[MSG_MAX_LENGTH
+1];
4241 char secondary_errmsg
[MSG_MAX_LENGTH
+1];
4242 capture_src
*pcap_src
;
4243 interface_options
*interface_opts
;
4244 unsigned i
, error_index
= 0;
4247 *secondary_errmsg
= '\0';
4249 /* init the loop data */
4250 global_ld
.go
= true;
4251 global_ld
.packets_captured
= 0;
4253 global_ld
.report_packet_count
= false;
4255 global_ld
.inpkts_to_sync_pipe
= 0;
4256 global_ld
.err
= 0; /* no error seen yet */
4257 global_ld
.pdh
= NULL
;
4258 global_ld
.save_file_fd
= -1;
4259 global_ld
.io_buffer
= NULL
;
4260 global_ld
.file_count
= 0;
4261 global_ld
.file_duration_timer
= NULL
;
4262 global_ld
.next_interval_time
= 0;
4263 global_ld
.interval_s
= 0;
4265 /* We haven't yet gotten the capture statistics. */
4266 *stats_known
= false;
4268 ws_info("Capture loop starting ...");
4269 capture_opts_log(LOG_DOMAIN_CAPCHILD
, LOG_LEVEL_DEBUG
, capture_opts
);
4271 /* open the "input file" from network interface or capture pipe */
4272 if (!capture_loop_open_input(capture_opts
, &global_ld
, errmsg
, sizeof(errmsg
),
4273 secondary_errmsg
, sizeof(secondary_errmsg
))) {
4276 for (i
= 0; i
< capture_opts
->ifaces
->len
; i
++) {
4277 pcap_src
= g_array_index(global_ld
.pcaps
, capture_src
*, i
);
4278 interface_opts
= &g_array_index(capture_opts
->ifaces
, interface_options
, i
);
4279 /* init the input filter from the network interface (capture pipe will do nothing) */
4281 * When remote capturing WinPCap crashes when the capture filter
4282 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
4285 switch (capture_loop_init_filter(pcap_src
->pcap_h
, pcap_src
->from_cap_pipe
,
4286 interface_opts
->name
,
4287 interface_opts
->cfilter
?interface_opts
->cfilter
:"")) {
4289 case INITFILTER_NO_ERROR
:
4292 case INITFILTER_BAD_FILTER
:
4293 cfilter_error
= true;
4295 snprintf(errmsg
, sizeof(errmsg
), "%s", pcap_geterr(pcap_src
->pcap_h
));
4298 case INITFILTER_OTHER_ERROR
:
4299 snprintf(errmsg
, sizeof(errmsg
), "Can't install filter (%s).",
4300 pcap_geterr(pcap_src
->pcap_h
));
4301 snprintf(secondary_errmsg
, sizeof(secondary_errmsg
), "%s", please_report_bug());
4306 /* If we're supposed to write to a capture file, open it for output
4307 (temporary/specified name/ringbuffer) */
4308 if (capture_opts
->saving_to_file
) {
4309 if (!capture_loop_open_output(capture_opts
, &global_ld
.save_file_fd
,
4310 errmsg
, sizeof(errmsg
))) {
4314 /* set up to write to the already-opened capture output file/files */
4315 if (!capture_loop_init_output(capture_opts
, &global_ld
, errmsg
,
4320 /* XXX - capture SIGTERM and close the capture, in case we're on a
4321 Linux 2.0[.x] system and you have to explicitly close the capture
4322 stream in order to turn promiscuous mode off? We need to do that
4323 in other places as well - and I don't think that works all the
4324 time in any case, due to libpcap bugs. */
4326 /* Well, we should be able to start capturing.
4328 Sync out the capture file, so the header makes it to the file system,
4329 and send a "capture started successfully and capture file created"
4330 message to our parent so that they'll open the capture file and
4331 update its windows to indicate that we have a live capture in
4333 fflush(global_ld
.pdh
);
4334 report_new_capture_file(capture_opts
->save_file
);
4337 if (capture_opts
->has_file_interval
) {
4338 global_ld
.interval_s
= capture_opts
->file_interval
;
4339 global_ld
.next_interval_time
= get_next_time_interval(global_ld
.interval_s
);
4341 /* create stop conditions */
4342 if (capture_opts
->has_autostop_filesize
) {
4343 if (capture_opts
->autostop_filesize
> UINT32_C(2000000000)) {
4344 capture_opts
->autostop_filesize
= UINT32_C(2000000000);
4347 if (capture_opts
->has_autostop_duration
) {
4348 autostop_duration_timer
= g_timer_new();
4351 if (capture_opts
->multi_files_on
) {
4352 if (capture_opts
->has_file_duration
) {
4353 global_ld
.file_duration_timer
= g_timer_new();
4357 /* init the time values */
4359 upd_time
= GetTickCount64();
4361 gettimeofday(&upd_time
, NULL
);
4363 start_time
= create_timestamp();
4364 ws_info("Capture loop running.");
4365 capture_opts_log(LOG_DOMAIN_CAPCHILD
, LOG_LEVEL_DEBUG
, capture_opts
);
4367 /* WOW, everything is prepared! */
4368 /* please fasten your seat belts, we will enter now the actual capture loop */
4370 pcap_queue
= g_async_queue_new();
4371 pcap_queue_bytes
= 0;
4372 pcap_queue_packets
= 0;
4373 for (i
= 0; i
< global_ld
.pcaps
->len
; i
++) {
4374 pcap_src
= g_array_index(global_ld
.pcaps
, capture_src
*, i
);
4375 /* XXX - Add an interface name here? */
4376 pcap_src
->tid
= g_thread_new("Capture read", pcap_read_handler
, pcap_src
);
4379 while (global_ld
.go
) {
4380 /* dispatch incoming packets */
4382 bool dequeued
= capture_loop_dequeue_packet();
4390 pcap_src
= g_array_index(global_ld
.pcaps
, capture_src
*, 0);
4391 inpkts
= capture_loop_dispatch(&global_ld
, errmsg
,
4392 sizeof(errmsg
), pcap_src
);
4395 /* Stop capturing if all of our sources are pipes and none of them are open. */
4396 bool open_interfaces
= false;
4397 for (i
= 0; i
< global_ld
.pcaps
->len
; i
++) {
4398 pcap_src
= g_array_index(global_ld
.pcaps
, capture_src
*, i
);
4399 if (pcap_src
->cap_pipe_err
== PIPOK
) {
4400 /* True for both non-pipes and open pipes. */
4401 open_interfaces
= true;
4404 if (!open_interfaces
) {
4405 global_ld
.go
= false;
4409 /* Were we asked to print packet counts by the SIGINFO handler? */
4410 if (global_ld
.report_packet_count
) {
4411 fprintf(stderr
, "%u packet%s captured\n", global_ld
.packets_captured
,
4412 plurality(global_ld
.packets_captured
, "", "s"));
4413 global_ld
.report_packet_count
= false;
4418 /* any news from our parent (signal pipe)? -> just stop the capture */
4419 if (!signal_pipe_check_running()) {
4420 global_ld
.go
= false;
4425 if (capture_opts
->output_to_pipe
) {
4426 fflush(global_ld
.pdh
);
4430 /* Only update after an interval so as not to overload slow displays.
4431 * This also prevents too much context-switching between the dumpcap
4432 * and wireshark processes.
4433 * XXX: Should we send updates sooner if there have been lots of
4434 * packets we haven't notified the parent about, such as on fast links?
4437 cur_time
= GetTickCount64();
4438 if ((cur_time
- upd_time
) > capture_opts
->update_interval
)
4440 gettimeofday(&cur_time
, NULL
);
4441 if (((uint64_t)cur_time
.tv_sec
* 1000000 + cur_time
.tv_usec
) >
4442 ((uint64_t)upd_time
.tv_sec
* 1000000 + upd_time
.tv_usec
+ capture_opts
->update_interval
*1000))
4446 upd_time
= cur_time
;
4449 if (pcap_stats(pch
, stats
) >= 0) {
4450 *stats_known
= true;
4453 /* Let the parent process know. */
4454 if (global_ld
.inpkts_to_sync_pipe
) {
4456 fflush(global_ld
.pdh
);
4458 /* Send our parent a message saying we've written out
4459 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
4461 report_packet_count(global_ld
.inpkts_to_sync_pipe
);
4463 global_ld
.inpkts_to_sync_pipe
= 0;
4466 /* check capture duration condition */
4467 if (autostop_duration_timer
!= NULL
&& g_timer_elapsed(autostop_duration_timer
, NULL
) >= capture_opts
->autostop_duration
) {
4468 /* The maximum capture time has elapsed; stop the capture. */
4469 global_ld
.go
= false;
4473 /* check capture file duration condition */
4474 if (global_ld
.file_duration_timer
!= NULL
&& g_timer_elapsed(global_ld
.file_duration_timer
, NULL
) >= capture_opts
->file_duration
) {
4475 /* duration limit reached, do we have another file? */
4476 if (!do_file_switch_or_stop(capture_opts
))
4478 } /* cnd_file_duration */
4480 /* check capture file interval condition */
4481 if (global_ld
.interval_s
&& time(NULL
) >= global_ld
.next_interval_time
) {
4482 /* end of interval reached, do we have another file? */
4483 if (!do_file_switch_or_stop(capture_opts
))
4485 } /* cnd_file_interval */
4489 ws_info("Capture loop stopping ...");
4492 for (i
= 0; i
< global_ld
.pcaps
->len
; i
++) {
4493 pcap_src
= g_array_index(global_ld
.pcaps
, capture_src
*, i
);
4494 ws_info("Waiting for thread of interface %u...", pcap_src
->interface_id
);
4495 g_thread_join(pcap_src
->tid
);
4496 ws_info("Thread of interface %u terminated.", pcap_src
->interface_id
);
4499 bool dequeued
= capture_loop_dequeue_packet();
4503 if (capture_opts
->output_to_pipe
) {
4504 fflush(global_ld
.pdh
);
4510 /* delete stop conditions */
4511 if (global_ld
.file_duration_timer
!= NULL
)
4512 g_timer_destroy(global_ld
.file_duration_timer
);
4513 if (autostop_duration_timer
!= NULL
)
4514 g_timer_destroy(autostop_duration_timer
);
4516 /* did we have a pcap (input) error? */
4517 for (i
= 0; i
< capture_opts
->ifaces
->len
; i
++) {
4518 pcap_src
= g_array_index(global_ld
.pcaps
, capture_src
*, i
);
4519 if (pcap_src
->pcap_err
) {
4520 /* On Linux, if an interface goes down while you're capturing on it,
4521 you'll get "recvfrom: Network is down".
4522 (At least you will if g_strerror() doesn't show a local translation
4525 Newer versions of libpcap maps that to just
4526 "The interface went down".
4528 On FreeBSD, DragonFly BSD, and macOS, if a network adapter
4529 disappears while you're capturing on it, you'll get
4530 "read: Device not configured" error (ENXIO). (See previous
4531 parenthetical note.)
4533 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
4535 With WinPcap and Npcap, you'll get
4536 "read error: PacketReceivePacket failed" or
4537 "PacketReceivePacket error: The device has been removed. (1617)".
4539 Newer versions of libpcap map some or all of those to just
4540 "The interface disappeared" or something beginning with
4541 "The interface disappeared".
4543 These should *not* be reported to the Wireshark developers,
4544 although, with Npcap, "The interface disappeared" messages
4545 should perhaps be reported to the Npcap developers, at least
4546 until errors of that sort that shouldn't happen are fixed,
4547 if that's possible. */
4550 char *secondary_msg
;
4552 interface_opts
= &g_array_index(capture_opts
->ifaces
, interface_options
, i
);
4553 cap_err_str
= pcap_geterr(pcap_src
->pcap_h
);
4554 if (strcmp(cap_err_str
, "The interface went down") == 0 ||
4555 strcmp(cap_err_str
, "recvfrom: Network is down") == 0) {
4556 primary_msg
= ws_strdup_printf("The network adapter \"%s\" "
4557 "is no longer running; the "
4558 "capture has stopped.",
4559 interface_opts
->display_name
);
4560 secondary_msg
= g_strdup("");
4561 } else if (strcmp(cap_err_str
, "The interface disappeared") == 0 ||
4562 strcmp(cap_err_str
, "read: Device not configured") == 0 ||
4563 strcmp(cap_err_str
, "read: I/O error") == 0 ||
4564 strcmp(cap_err_str
, "read error: PacketReceivePacket failed") == 0) {
4565 primary_msg
= ws_strdup_printf("The network adapter \"%s\" "
4566 "is no longer attached; the "
4567 "capture has stopped.",
4568 interface_opts
->display_name
);
4569 secondary_msg
= g_strdup("");
4570 } else if (g_str_has_prefix(cap_err_str
, "The interface disappeared ")) {
4572 * Npcap, if it picks up a recent commit to libpcap, will
4573 * report an error *beginning* with "The interface
4574 * disappeared", with the name of the Windows status code,
4575 * and the corresponding NT status code, after it.
4577 * Those should be reported as Npcap issues.
4579 primary_msg
= ws_strdup_printf("The network adapter \"%s\" "
4580 "is no longer attached; the "
4581 "capture has stopped.",
4582 interface_opts
->display_name
);
4583 secondary_msg
= handle_npcap_bug(interface_opts
->display_name
,
4585 } else if (g_str_has_prefix(cap_err_str
, "PacketReceivePacket error:") &&
4586 g_str_has_suffix(cap_err_str
, "(1617)")) {
4588 * "PacketReceivePacket error: {message in arbitrary language} (1617)",
4589 * which is ERROR_DEVICE_REMOVED.
4591 * Current libpcap/Npcap treat ERROR_GEN_FAILURE as
4592 * "the device is no longer attached"; users are also
4593 * getting ERROR_DEVICE_REMOVED.
4595 * For now, some users appear to be getg ERROR_DEVICE_REMOVED
4596 * in cases where the device *wasn't* removed, so tell
4597 * them to report this as an Npcap issue; I seem to
4598 * remember some discussion between Daniel and somebody
4599 * at Microsoft about the Windows 10 network stack setup/
4600 * teardown code being modified to try to prevent those
4601 * sort of problems popping up, but I can't find that
4604 primary_msg
= ws_strdup_printf("The network adapter \"%s\" "
4605 "is no longer attached; the "
4606 "capture has stopped.",
4607 interface_opts
->display_name
);
4608 secondary_msg
= handle_npcap_bug(interface_opts
->display_name
,
4609 "The interface disappeared (error code ERROR_DEVICE_REMOVED/STATUS_DEVICE_REMOVED)");
4610 } else if (strcmp(cap_err_str
, "The other host terminated the connection.") == 0 ||
4611 g_str_has_prefix(cap_err_str
, "Is the server properly installed?")) {
4613 * Networking error for a remote capture.
4615 primary_msg
= g_strdup(cap_err_str
);
4616 secondary_msg
= g_strdup("This may be a problem with the "
4617 "remote host on which you are "
4618 "capturing packets.");
4620 primary_msg
= ws_strdup_printf("Error while capturing packets: %s",
4622 secondary_msg
= g_strdup(please_report_bug());
4624 report_capture_error(primary_msg
, secondary_msg
);
4625 g_free(primary_msg
);
4626 g_free(secondary_msg
);
4628 } else if (pcap_src
->from_cap_pipe
&& pcap_src
->cap_pipe_err
== PIPERR
) {
4629 report_capture_error(errmsg
, "");
4633 /* did we have an output error while capturing? */
4634 if (global_ld
.err
== 0) {
4637 capture_loop_get_errmsg(errmsg
, sizeof(errmsg
), secondary_errmsg
,
4638 sizeof(secondary_errmsg
),
4639 capture_opts
->save_file
, global_ld
.err
, false);
4640 report_capture_error(errmsg
, secondary_errmsg
);
4644 if (capture_opts
->saving_to_file
) {
4645 /* close the output file */
4646 close_ok
= capture_loop_close_output(capture_opts
, &global_ld
, &err_close
);
4650 /* there might be packets not yet notified to the parent */
4651 /* (do this after closing the file, so all packets are already flushed) */
4652 if (global_ld
.inpkts_to_sync_pipe
) {
4654 report_packet_count(global_ld
.inpkts_to_sync_pipe
);
4655 global_ld
.inpkts_to_sync_pipe
= 0;
4658 /* If we've displayed a message about a write error, there's no point
4659 in displaying another message about an error on close. */
4660 if (!close_ok
&& write_ok
) {
4661 capture_loop_get_errmsg(errmsg
, sizeof(errmsg
), secondary_errmsg
,
4662 sizeof(secondary_errmsg
),
4663 capture_opts
->save_file
, err_close
, true);
4664 report_capture_error(errmsg
, secondary_errmsg
);
4668 * XXX We exhibit different behaviour between normal mode and sync mode
4669 * when the pipe is stdin and not already at EOF. If we're a child, the
4670 * parent's stdin isn't closed, so if the user starts another capture,
4671 * cap_pipe_open_live() will very likely not see the expected magic bytes and
4672 * will say "Unrecognized libpcap format". On the other hand, in normal
4673 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
4676 report_capture_count(!really_quiet
);
4678 /* get packet drop statistics from pcap */
4679 for (i
= 0; i
< capture_opts
->ifaces
->len
; i
++) {
4681 uint32_t pcap_dropped
= 0;
4683 pcap_src
= g_array_index(global_ld
.pcaps
, capture_src
*, i
);
4684 interface_opts
= &g_array_index(capture_opts
->ifaces
, interface_options
, i
);
4685 received
= pcap_src
->received
;
4686 if (pcap_src
->pcap_h
!= NULL
) {
4687 ws_assert(!pcap_src
->from_cap_pipe
);
4688 /* Get the capture statistics, so we know how many packets were dropped. */
4689 if (pcap_stats(pcap_src
->pcap_h
, stats
) >= 0) {
4690 *stats_known
= true;
4691 /* Let the parent process know. */
4692 pcap_dropped
+= stats
->ps_drop
;
4694 snprintf(errmsg
, sizeof(errmsg
),
4695 "Can't get packet-drop statistics: %s",
4696 pcap_geterr(pcap_src
->pcap_h
));
4697 report_capture_error(errmsg
, please_report_bug());
4700 report_packet_drops(received
, pcap_dropped
, pcap_src
->dropped
, pcap_src
->flushed
, stats
->ps_ifdrop
, interface_opts
->display_name
);
4703 /* close the input file (pcap or capture pipe) */
4704 capture_loop_close_input(&global_ld
);
4706 ws_info("Capture loop stopped.");
4708 /* ok, if the write and the close were successful. */
4709 return write_ok
&& close_ok
;
4712 if (capture_opts
->multi_files_on
) {
4713 /* cleanup ringbuffer */
4714 ringbuf_error_cleanup();
4716 /* We can't use the save file, and we have no FILE * for the stream
4717 to close in order to close it, so close the FD directly. */
4718 if (global_ld
.save_file_fd
!= -1) {
4719 ws_close(global_ld
.save_file_fd
);
4722 /* We couldn't even start the capture, so get rid of the capture
4724 if (capture_opts
->save_file
!= NULL
) {
4725 ws_unlink(capture_opts
->save_file
);
4729 report_cfilter_error(capture_opts
, error_index
, errmsg
);
4731 report_capture_error(errmsg
, secondary_errmsg
);
4733 /* close the input file (pcap or cap_pipe) */
4734 capture_loop_close_input(&global_ld
);
4736 ws_info("Capture loop stopped with error");
4743 capture_loop_stop(void)
4746 capture_src
*pcap_src
;
4748 for (i
= 0; i
< global_ld
.pcaps
->len
; i
++) {
4749 pcap_src
= g_array_index(global_ld
.pcaps
, capture_src
*, i
);
4750 if (pcap_src
->pcap_h
!= NULL
)
4751 pcap_breakloop(pcap_src
->pcap_h
);
4753 global_ld
.go
= false;
4758 capture_loop_get_errmsg(char *errmsg
, size_t errmsglen
, char *secondary_errmsg
,
4759 size_t secondary_errmsglen
, const char *fname
,
4760 int err
, bool is_close
)
4762 static const char find_space
[] =
4763 "You will need to free up space on that file system"
4764 " or put the capture file on a different file system.";
4769 snprintf(errmsg
, errmsglen
,
4770 "Not all the packets could be written to the file"
4771 " to which the capture was being saved\n"
4772 "(\"%s\") because there is no space left on the file system\n"
4773 "on which that file resides.",
4775 snprintf(secondary_errmsg
, secondary_errmsglen
, "%s", find_space
);
4780 snprintf(errmsg
, errmsglen
,
4781 "Not all the packets could be written to the file"
4782 " to which the capture was being saved\n"
4783 "(\"%s\") because you are too close to, or over,"
4784 " your disk quota\n"
4785 "on the file system on which that file resides.",
4787 snprintf(secondary_errmsg
, secondary_errmsglen
, "%s", find_space
);
4793 snprintf(errmsg
, errmsglen
,
4794 "The file to which the capture was being saved\n"
4795 "(\"%s\") could not be closed: %s.",
4796 fname
, g_strerror(err
));
4798 snprintf(errmsg
, errmsglen
,
4799 "An error occurred while writing to the file"
4800 " to which the capture was being saved\n"
4802 fname
, g_strerror(err
));
4804 snprintf(secondary_errmsg
, secondary_errmsglen
,
4805 "%s", please_report_bug());
4811 * We wrote one packet. Update some statistics and check if we've met any
4812 * autostop or ring buffer conditions.
4815 capture_loop_wrote_one_packet(capture_src
*pcap_src
) {
4816 global_ld
.packets_captured
++;
4817 global_ld
.packets_written
++;
4818 global_ld
.inpkts_to_sync_pipe
++;
4821 pcap_src
->received
++;
4825 if (global_capture_opts
.has_autostop_packets
&& global_ld
.packets_captured
>= global_capture_opts
.autostop_packets
) {
4826 fflush(global_ld
.pdh
);
4827 global_ld
.go
= false;
4830 /* check -a packets:NUM (treat like -c NUM) */
4831 if (global_capture_opts
.has_autostop_written_packets
&& global_ld
.packets_captured
>= global_capture_opts
.autostop_written_packets
) {
4832 fflush(global_ld
.pdh
);
4833 global_ld
.go
= false;
4836 /* check -b packets:NUM */
4837 if (global_capture_opts
.has_file_packets
&& global_ld
.packets_written
>= global_capture_opts
.file_packets
) {
4838 do_file_switch_or_stop(&global_capture_opts
);
4841 /* check -a filesize:NUM */
4842 if (global_capture_opts
.has_autostop_filesize
&&
4843 global_capture_opts
.autostop_filesize
> 0 &&
4844 global_ld
.bytes_written
/ 1000 >= global_capture_opts
.autostop_filesize
) {
4845 /* Capture size limit reached, do we have another file? */
4846 do_file_switch_or_stop(&global_capture_opts
);
4851 /* one pcapng block was captured, process it */
4853 capture_loop_write_pcapng_cb(capture_src
*pcap_src
, const pcapng_block_header_t
*bh
, uint8_t *pd
)
4858 * This should never be called if we're not writing pcapng.
4860 ws_assert(global_capture_opts
.use_pcapng
);
4862 /* We may be called multiple times from pcap_dispatch(); if we've set
4863 the "stop capturing" flag, ignore this packet, as we're not
4864 supposed to be saving any more packets. */
4865 if (!global_ld
.go
) {
4866 pcap_src
->flushed
++;
4870 if (!pcapng_adjust_block(pcap_src
, bh
, pd
)) {
4871 ws_info("%s failed to adjust pcapng block.", G_STRFUNC
);
4872 ws_assert_not_reached();
4876 if (bh
->block_type
== BLOCK_TYPE_SHB
&& !global_ld
.pcapng_passthrough
) {
4878 * capture_loop_init_pcapng_output should've handled this. We need
4879 * to write ISBs when they're initially read so we shouldn't skip
4885 if (global_ld
.pdh
) {
4888 /* We're supposed to write the packet to a file; do so.
4889 If this fails, set "ld->go" to false, to stop the capture, and set
4890 "ld->err" to the error. */
4891 successful
= pcapng_write_block(global_ld
.pdh
,
4893 bh
->block_total_length
,
4894 &global_ld
.bytes_written
, &err
);
4896 fflush(global_ld
.pdh
);
4898 global_ld
.go
= false;
4899 global_ld
.err
= err
;
4900 pcap_src
->dropped
++;
4901 } else if (is_data_block(bh
->block_type
)) {
4902 /* Count packets for block types that should be dissected, i.e. ones that show up in the packet list. */
4903 ws_debug("Wrote a pcapng block type 0x%04x of length %d captured on interface %u.",
4904 bh
->block_type
, bh
->block_total_length
, pcap_src
->interface_id
);
4905 capture_loop_wrote_one_packet(pcap_src
);
4906 } else if (bh
->block_type
== BLOCK_TYPE_SHB
&& report_capture_filename
) {
4907 ws_debug("Sending SP_FILE on first SHB");
4908 /* SHB is now ready for capture parent to read on SP_FILE message */
4909 sync_pipe_write_string_msg(sync_pipe_fd
, SP_FILE
, report_capture_filename
);
4910 report_capture_filename
= NULL
;
4915 /* one pcap packet was captured, process it */
4917 capture_loop_write_packet_cb(uint8_t *pcap_src_p
, const struct pcap_pkthdr
*phdr
,
4920 capture_src
*pcap_src
= (capture_src
*) (void *) pcap_src_p
;
4922 unsigned ts_mul
= pcap_src
->ts_nsec
? 1000000000 : 1000000;
4924 ws_debug("capture_loop_write_packet_cb");
4926 /* We may be called multiple times from pcap_dispatch(); if we've set
4927 the "stop capturing" flag, ignore this packet, as we're not
4928 supposed to be saving any more packets. */
4929 if (!global_ld
.go
) {
4930 pcap_src
->flushed
++;
4934 if (global_ld
.pdh
) {
4937 /* We're supposed to write the packet to a file; do so.
4938 If this fails, set "ld->go" to false, to stop the capture, and set
4939 "ld->err" to the error. */
4940 if (global_capture_opts
.use_pcapng
) {
4941 successful
= pcapng_write_enhanced_packet_block(global_ld
.pdh
,
4943 phdr
->ts
.tv_sec
, (int32_t)phdr
->ts
.tv_usec
,
4944 phdr
->caplen
, phdr
->len
,
4948 &global_ld
.bytes_written
, &err
);
4950 successful
= libpcap_write_packet(global_ld
.pdh
,
4951 phdr
->ts
.tv_sec
, (int32_t)phdr
->ts
.tv_usec
,
4952 phdr
->caplen
, phdr
->len
,
4954 &global_ld
.bytes_written
, &err
);
4957 global_ld
.go
= false;
4958 global_ld
.err
= err
;
4959 pcap_src
->dropped
++;
4961 ws_debug("Wrote a pcap packet of length %d captured on interface %u.",
4962 phdr
->caplen
, pcap_src
->interface_id
);
4963 capture_loop_wrote_one_packet(pcap_src
);
4968 /* one packet was captured, queue it */
4970 capture_loop_queue_packet_cb(uint8_t *pcap_src_p
, const struct pcap_pkthdr
*phdr
,
4973 capture_src
*pcap_src
= (capture_src
*) (void *) pcap_src_p
;
4974 pcap_queue_element
*queue_element
;
4977 /* We may be called multiple times from pcap_dispatch(); if we've set
4978 the "stop capturing" flag, ignore this packet, as we're not
4979 supposed to be saving any more packets. */
4980 if (!global_ld
.go
) {
4981 pcap_src
->flushed
++;
4985 queue_element
= g_new(pcap_queue_element
, 1);
4986 if (queue_element
== NULL
) {
4987 pcap_src
->dropped
++;
4990 queue_element
->pcap_src
= pcap_src
;
4991 queue_element
->u
.phdr
= *phdr
;
4992 queue_element
->pd
= (uint8_t *)g_malloc(phdr
->caplen
);
4993 if (queue_element
->pd
== NULL
) {
4994 pcap_src
->dropped
++;
4995 g_free(queue_element
);
4998 memcpy(queue_element
->pd
, pd
, phdr
->caplen
);
4999 g_async_queue_lock(pcap_queue
);
5000 if (((pcap_queue_byte_limit
== 0) || (pcap_queue_bytes
< pcap_queue_byte_limit
)) &&
5001 ((pcap_queue_packet_limit
== 0) || (pcap_queue_packets
< pcap_queue_packet_limit
))) {
5002 limit_reached
= false;
5003 g_async_queue_push_unlocked(pcap_queue
, queue_element
);
5004 pcap_queue_bytes
+= phdr
->caplen
;
5005 pcap_queue_packets
+= 1;
5007 limit_reached
= true;
5009 g_async_queue_unlock(pcap_queue
);
5010 if (limit_reached
) {
5011 pcap_src
->dropped
++;
5012 g_free(queue_element
->pd
);
5013 g_free(queue_element
);
5014 ws_info("Dropped a packet of length %d captured on interface %u.",
5015 phdr
->caplen
, pcap_src
->interface_id
);
5017 pcap_src
->received
++;
5018 ws_info("Queued a packet of length %d captured on interface %u.",
5019 phdr
->caplen
, pcap_src
->interface_id
);
5021 /* I don't want to hold the mutex over the debug output. So the
5022 output may be wrong */
5023 ws_info("Queue size is now %" PRId64
" bytes (%" PRId64
" packets)",
5024 pcap_queue_bytes
, pcap_queue_packets
);
5027 /* one pcapng block was captured, queue it */
5029 capture_loop_queue_pcapng_cb(capture_src
*pcap_src
, const pcapng_block_header_t
*bh
, uint8_t *pd
)
5031 pcap_queue_element
*queue_element
;
5034 /* We may be called multiple times from pcap_dispatch(); if we've set
5035 the "stop capturing" flag, ignore this packet, as we're not
5036 supposed to be saving any more packets. */
5037 if (!global_ld
.go
) {
5038 pcap_src
->flushed
++;
5042 queue_element
= g_new(pcap_queue_element
, 1);
5043 if (queue_element
== NULL
) {
5044 pcap_src
->dropped
++;
5047 queue_element
->pcap_src
= pcap_src
;
5048 queue_element
->u
.bh
= *bh
;
5049 queue_element
->pd
= (uint8_t *)g_malloc(bh
->block_total_length
);
5050 if (queue_element
->pd
== NULL
) {
5051 pcap_src
->dropped
++;
5052 g_free(queue_element
);
5055 memcpy(queue_element
->pd
, pd
, bh
->block_total_length
);
5056 g_async_queue_lock(pcap_queue
);
5057 if (((pcap_queue_byte_limit
== 0) || (pcap_queue_bytes
< pcap_queue_byte_limit
)) &&
5058 ((pcap_queue_packet_limit
== 0) || (pcap_queue_packets
< pcap_queue_packet_limit
))) {
5059 limit_reached
= false;
5060 g_async_queue_push_unlocked(pcap_queue
, queue_element
);
5061 pcap_queue_bytes
+= bh
->block_total_length
;
5062 pcap_queue_packets
+= 1;
5064 limit_reached
= true;
5066 g_async_queue_unlock(pcap_queue
);
5067 if (limit_reached
) {
5068 pcap_src
->dropped
++;
5069 g_free(queue_element
->pd
);
5070 g_free(queue_element
);
5071 ws_info("Dropped a packet of length %d captured on interface %u.",
5072 bh
->block_total_length
, pcap_src
->interface_id
);
5074 pcap_src
->received
++;
5075 ws_info("Queued a block of type 0x%08x of length %d captured on interface %u.",
5076 bh
->block_type
, bh
->block_total_length
, pcap_src
->interface_id
);
5078 /* I don't want to hold the mutex over the debug output. So the
5079 output may be wrong */
5080 ws_info("Queue size is now %" PRId64
" bytes (%" PRId64
" packets)",
5081 pcap_queue_bytes
, pcap_queue_packets
);
5085 set_80211_channel(const char *iface
, const char *opt
)
5089 uint32_t center_freq1
= 0;
5090 uint32_t center_freq2
= 0;
5093 char **options
= NULL
;
5095 options
= g_strsplit_set(opt
, ",", 4);
5096 for (args
= 0; options
[args
]; args
++)
5099 ret
= ws80211_init();
5100 if (ret
!= WS80211_INIT_OK
) {
5101 if (ret
== WS80211_INIT_NOT_SUPPORTED
)
5102 cmdarg_err("Setting 802.11 channels is not supported on this platform");
5104 cmdarg_err("Failed to init ws80211: %s", g_strerror(abs(ret
)));
5110 freq
= get_nonzero_uint32(options
[0], "802.11 channel frequency");
5112 if (args
>= 1 && options
[1]) {
5113 type
= ws80211_str_to_chan_type(options
[1]);
5115 cmdarg_err("\"%s\" is not a valid 802.11 channel type", options
[1]);
5121 if (args
>= 2 && options
[2])
5122 center_freq1
= get_nonzero_uint32(options
[2], "VHT center frequency");
5124 if (args
>= 3 && options
[3])
5125 center_freq2
= get_nonzero_uint32(options
[3], "VHT center frequency 2");
5127 ret
= ws80211_set_freq(iface
, freq
, type
, center_freq1
, center_freq2
);
5130 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret
), g_strerror(abs(ret
)));
5136 sync_pipe_write_string_msg(sync_pipe_fd
, SP_SUCCESS
, NULL
);
5139 g_strfreev(options
);
5144 gather_dumpcap_compiled_info(feature_list l
)
5146 /* Capture libraries */
5147 gather_caplibs_compile_info(l
);
5151 gather_dumpcap_runtime_info(feature_list l
)
5153 /* Capture libraries */
5154 gather_caplibs_runtime_info(l
);
5157 #define LONGOPT_IFNAME LONGOPT_BASE_APPLICATION+1
5158 #define LONGOPT_IFDESCR LONGOPT_BASE_APPLICATION+2
5159 #define LONGOPT_CAPTURE_COMMENT LONGOPT_BASE_APPLICATION+3
5160 #define LONGOPT_APPLICATION_FLAVOR LONGOPT_BASE_APPLICATION+4
5162 #define LONGOPT_SIGNAL_PIPE LONGOPT_BASE_APPLICATION+5
5165 /* And now our feature presentation... [ fade to music ] */
5167 main(int argc
, char *argv
[])
5171 static const struct ws_option long_options
[] = {
5172 {"help", ws_no_argument
, NULL
, 'h'},
5173 {"version", ws_no_argument
, NULL
, 'v'},
5174 LONGOPT_CAPTURE_COMMON
5175 {"ifname", ws_required_argument
, NULL
, LONGOPT_IFNAME
},
5176 {"ifdescr", ws_required_argument
, NULL
, LONGOPT_IFDESCR
},
5177 {"capture-comment", ws_required_argument
, NULL
, LONGOPT_CAPTURE_COMMENT
},
5178 {"application-flavor", ws_required_argument
, NULL
, LONGOPT_APPLICATION_FLAVOR
},
5180 {"signal-pipe", ws_required_argument
, NULL
, LONGOPT_SIGNAL_PIPE
},
5185 bool arg_error
= false;
5188 struct sigaction action
, oldaction
;
5192 struct pcap_stat stats
= {0};
5193 bool list_interfaces
= false;
5194 int caps_queries
= 0;
5195 bool print_bpf_code
= false;
5196 bool set_chan
= false;
5197 char *set_chan_arg
= NULL
;
5198 bool machine_readable
= false;
5199 bool print_statistics
= false;
5200 int status
, run_once_args
= 0;
5203 #if defined(__APPLE__) && defined(__LP64__)
5204 struct utsname osinfo
;
5208 /* Set the program name. */
5209 g_set_prgname("dumpcap");
5212 * Determine if dumpcap is being requested to run in a special
5213 * capture_child mode by going thru the command line args to see if
5214 * a -Z is present. (-Z is a hidden option).
5216 * The primary result of running in capture_child mode is that
5217 * all messages sent out on stderr are in a special type/len/string
5218 * format to allow message processing by type. These messages include
5219 * error messages if dumpcap fails to start the operation it was
5220 * requested to do, as well as various "status" messages which are sent
5221 * when an actual capture is in progress, and a "success" message sent
5222 * if dumpcap was requested to perform an operation other than a
5225 * Capture_child mode would normally be requested by a parent process
5226 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
5227 * to which dumpcap stderr has been redirected. It might also have
5228 * another pipe to obtain dumpcap stdout output; for operations other
5229 * than a capture, that information is formatted specially for easier
5230 * parsing by the parent process.
5232 * Capture_child mode needs to be determined immediately upon
5233 * startup so that any messages generated by dumpcap in this mode
5234 * (eg: during initialization) will be formatted properly.
5237 for (i
=1; i
<argc
; i
++) {
5238 if (strcmp("-Z", argv
[i
]) == 0) {
5239 capture_child
= true;
5240 machine_readable
= true; /* request machine-readable output */
5246 if (strcmp(argv
[i
], SIGNAL_PIPE_CTRL_ID_NONE
) != 0) {
5247 // get_positive_int calls cmdarg_err
5248 if (!ws_strtoi(argv
[i
], NULL
, &sync_pipe_fd
) || sync_pipe_fd
<= 0) {
5252 /* On UN*X the fd is the same when we fork + exec.
5253 * On Windows the HANDLE value is the same for inherited
5254 * handles in the child process and the parent, although
5255 * not necessarily the fd value from _open_osfhandle.
5256 * https://learn.microsoft.com/en-us/windows/win32/procthread/inheritance
5257 * Also, "64-bit versions of Windows use 32-bit handles for
5258 * interoperability... only the lower 32 bits are significant,
5259 * so it is safe to truncate... or sign-extend the handle."
5260 * https://learn.microsoft.com/en-us/windows/win32/winprog64/interprocess-communication
5262 /* set output pipe to binary mode, avoid ugly text conversions */
5263 sync_pipe_fd
= _open_osfhandle( (intptr_t) sync_pipe_fd
, _O_BINARY
);
5269 cmdarg_err_init(dumpcap_cmdarg_err
, dumpcap_cmdarg_err_cont
);
5271 /* Initialize log handler early so we can have proper logging during startup. */
5272 ws_log_init_with_writer(dumpcap_log_writer
, vcmdarg_err
);
5274 /* Early logging command-line initialization. */
5275 ws_log_parse_args(&argc
, argv
, vcmdarg_err
, 1);
5277 #if DEBUG_CHILD_DUMPCAP
5278 /* Assume that if we're specially compiled with dumpcap debugging
5279 * then we want maximum debugging.
5281 if (capture_child
) {
5282 ws_log_set_level(LOG_LEVEL_NOISY
);
5285 if ((debug_log
= ws_fopen("dumpcap_debug_log.tmp","w")) == NULL
) {
5286 fprintf (stderr
, "Unable to open debug log file .\n");
5291 ws_noisy("Finished log init and parsing command line log arguments");
5294 create_app_running_mutex();
5297 * Initialize our DLL search path. MUST be called before LoadLibrary
5300 ws_init_dll_search_path();
5302 /* Load wpcap if possible. Do this before collecting the run-time version information */
5306 /* Initialize the version information. */
5307 ws_init_version_info("Dumpcap", gather_dumpcap_compiled_info
,
5308 gather_dumpcap_runtime_info
);
5310 #ifdef HAVE_PCAP_REMOTE
5311 #define OPTSTRING_r "r"
5312 #define OPTSTRING_u "u"
5318 #ifdef HAVE_PCAP_SETSAMPLING
5319 #define OPTSTRING_m "m:"
5324 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:dghk:" OPTSTRING_m "MN:nPqQ" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
5326 #if defined(__APPLE__) && defined(__LP64__)
5328 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
5329 * a bug workaround - timeouts less than 1 second don't work with libpcap
5330 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
5331 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
5332 * The problem is extremely unlikely to be reintroduced in a future
5335 if (uname(&osinfo
) == 0) {
5337 * {Mac} OS X/macOS 10.x uses Darwin {x+4}.0.0; 10.x.y uses Darwin
5338 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
5339 * number of 10.0.0, not 10.1.0 - go figure).
5341 if (strcmp(osinfo
.release
, "10.0.0") == 0 || /* 10.6, 10.6.1 */
5342 strcmp(osinfo
.release
, "10.3.0") == 0 || /* 10.6.3 */
5343 strcmp(osinfo
.release
, "10.4.0") == 0) /* 10.6.4 */
5344 need_timeout_workaround
= true;
5348 /* Initialize the pcaps list and IDBs */
5349 global_ld
.pcaps
= g_array_new(FALSE
, FALSE
, sizeof(capture_src
*));
5350 global_ld
.pcapng_passthrough
= false;
5351 global_ld
.saved_shb
= NULL
;
5352 global_ld
.saved_idbs
= g_array_new(FALSE
, TRUE
, sizeof(saved_idb_t
));
5354 err_msg
= ws_init_sockets();
5355 if (err_msg
!= NULL
)
5357 ws_log(LOG_DOMAIN_CAPCHILD
, LOG_LEVEL_ERROR
,
5358 "ERROR: %s", err_msg
);
5360 ws_log(LOG_DOMAIN_CAPCHILD
, LOG_LEVEL_ERROR
,
5361 "%s", please_report_bug());
5366 /* Set handler for Ctrl+C key */
5367 SetConsoleCtrlHandler(capture_cleanup_handler
, true);
5369 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
5370 and exit. Do the same with SIGPIPE, in case, for example,
5371 we're writing to our standard output and it's a pipe.
5372 Do the same with SIGHUP if it's not being ignored (if we're
5373 being run under nohup, it might be ignored, in which case we
5374 should leave it ignored).
5376 XXX - apparently, Coverity complained that part of action
5377 wasn't initialized. Perhaps it's running on Linux, where
5378 struct sigaction has an ignored "sa_restorer" element and
5379 where "sa_handler" and "sa_sigaction" might not be two
5380 members of a union. */
5381 memset(&action
, 0, sizeof(action
));
5382 action
.sa_handler
= capture_cleanup_handler
;
5384 * Arrange that system calls not get restarted, because when
5385 * our signal handler returns we don't want to restart
5386 * a call that was waiting for packets to arrive.
5388 action
.sa_flags
= 0;
5389 sigemptyset(&action
.sa_mask
);
5390 sigaction(SIGTERM
, &action
, NULL
);
5391 sigaction(SIGINT
, &action
, NULL
);
5392 sigaction(SIGPIPE
, &action
, NULL
);
5393 sigaction(SIGHUP
, NULL
, &oldaction
);
5394 if (oldaction
.sa_handler
== SIG_DFL
)
5395 sigaction(SIGHUP
, &action
, NULL
);
5398 /* Catch SIGINFO and, if we get it and we're capturing in
5399 quiet mode, report the number of packets we've captured. */
5400 action
.sa_handler
= report_counts_siginfo
;
5401 action
.sa_flags
= SA_RESTART
;
5402 sigemptyset(&action
.sa_mask
);
5403 sigaction(SIGINFO
, &action
, NULL
);
5404 #endif /* SIGINFO */
5407 /* ----------------------------------------------------------------- */
5408 /* Privilege and capability handling */
5410 /* 1. Running not as root or suid root; no special capabilities. */
5413 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
5416 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
5418 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
5419 /* capabilities; Drop all other capabilities; */
5420 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5421 /* else: after pcap_open_live() in capture_loop_open_input() */
5422 /* drop all capabilities (NET_RAW and NET_ADMIN); */
5423 /* (Note: this means that the process, although logged in */
5424 /* as root, does not have various permissions such as the */
5425 /* ability to bypass file access permissions). */
5426 /* XXX: Should we just leave capabilities alone in this case */
5427 /* so that user gets expected effect that root can do */
5430 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
5432 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5433 /* else: after pcap_open_live() in capture_loop_open_input() */
5434 /* drop suid root (set euid=ruid).(ie: keep suid until after */
5435 /* pcap_open_live). */
5437 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
5439 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
5440 /* capabilities; Drop all other capabilities; */
5441 /* Drop suid privileges (euid=ruid); */
5442 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5443 /* else: after pcap_open_live() in capture_loop_open_input() */
5444 /* drop all capabilities (NET_RAW and NET_ADMIN). */
5446 /* XXX: For some Linux versions/distros with capabilities */
5447 /* a 'normal' process with any capabilities cannot be */
5448 /* 'killed' (signaled) from another (same uid) non-privileged */
5450 /* For example: If (non-suid) Wireshark forks a */
5451 /* child suid dumpcap which acts as described here (case 5), */
5452 /* Wireshark will be unable to kill (signal) the child */
5453 /* dumpcap process until the capabilities have been dropped */
5454 /* (after pcap_open_live()). */
5455 /* This behaviour will apparently be changed in the kernel */
5456 /* to allow the kill (signal) in this case. */
5457 /* See the following for details: */
5458 /* https://www.mail-archive.com/ [wrapped] */
5459 /* linux-security-module@vger.kernel.org/msg02913.html */
5461 /* It is therefore conceivable that if dumpcap somehow hangs */
5462 /* in pcap_open_live or before that wireshark will not */
5463 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
5464 /* In this case, exiting wireshark will kill the child */
5465 /* dumpcap process. */
5467 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
5468 /* capabilities; Using libcap. Note: capset cmd (which see) */
5469 /* used to assign capabilities to file. */
5471 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5472 /* else: after pcap_open_live() in capture_loop_open_input() */
5473 /* drop all capabilities (NET_RAW and NET_ADMIN) */
5475 /* ToDo: -S (stats) should drop privileges/capabilities when no */
5476 /* longer required (similar to capture). */
5478 /* ----------------------------------------------------------------- */
5480 init_process_policies();
5483 /* If 'started with special privileges' (and using libcap) */
5484 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
5485 /* Set euid/egid = ruid/rgid to remove suid privileges */
5486 relinquish_privs_except_capture();
5489 init_report_failure_message_simple("dumpcap");
5491 /* Set the initial values in the capture options. This might be overwritten
5492 by the command line parameters. */
5493 capture_opts_init(&global_capture_opts
, get_interface_list
);
5494 /* We always save to a file - if no file was specified, we save to a
5496 global_capture_opts
.saving_to_file
= true;
5497 global_capture_opts
.has_ring_num_files
= true;
5499 /* Pass on capture_child mode for capture_opts */
5500 global_capture_opts
.capture_child
= capture_child
;
5502 /* Now get our args */
5503 while ((opt
= ws_getopt_long(argc
, argv
, OPTSTRING
, long_options
, NULL
)) != -1) {
5505 case 'h': /* Print help and exit */
5506 show_help_header("Capture network packets and dump them into a pcapng or pcap file.");
5507 print_usage(stdout
);
5510 case 'v': /* Show version and exit */
5514 case LONGOPT_APPLICATION_FLAVOR
:
5515 set_application_flavor(application_name_to_flavor(ws_optarg
));
5517 /*** capture option specific ***/
5518 case 'a': /* autostop criteria */
5519 case 'b': /* Ringbuffer option */
5520 case 'c': /* Capture x packets */
5521 case 'f': /* capture filter */
5522 case 'F': /* capture file type */
5523 case 'g': /* enable group read access on file(s) */
5524 case 'i': /* Use interface x */
5525 case LONGOPT_SET_TSTAMP_TYPE
: /* Set capture timestamp type */
5526 case 'n': /* Use pcapng format */
5527 case 'p': /* Don't capture in promiscuous mode */
5528 case 'P': /* Use pcap format */
5529 case 's': /* Set the snapshot (capture) length */
5530 case 'w': /* Write to capture file x */
5531 case 'y': /* Set the pcap data link type */
5532 #ifdef HAVE_PCAP_REMOTE
5533 case 'u': /* Use UDP for data transfer */
5534 case 'r': /* Capture own RPCAP traffic too */
5535 case 'A': /* Authentication */
5537 #ifdef HAVE_PCAP_SETSAMPLING
5538 case 'm': /* Sampling */
5540 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
5541 case 'B': /* Buffer size */
5543 #ifdef HAVE_PCAP_CREATE
5544 case 'I': /* Monitor mode */
5546 case LONGOPT_COMPRESS_TYPE
: /* compress type */
5547 case LONGOPT_CAPTURE_TMPDIR
: /* capture temp directory */
5548 case LONGOPT_UPDATE_INTERVAL
: /* sync pipe update interval */
5549 status
= capture_opts_add_opt(&global_capture_opts
, opt
, ws_optarg
);
5554 /*** hidden option: Wireshark child mode (using binary output messages) ***/
5555 case LONGOPT_IFNAME
:
5556 if (global_capture_opts
.ifaces
->len
> 0) {
5557 interface_options
*interface_opts
;
5559 interface_opts
= &g_array_index(global_capture_opts
.ifaces
, interface_options
, global_capture_opts
.ifaces
->len
- 1);
5560 interface_opts
->ifname
= g_strdup(ws_optarg
);
5562 cmdarg_err("--ifname must be specified after a -i option");
5566 case LONGOPT_IFDESCR
:
5567 if (global_capture_opts
.ifaces
->len
> 0) {
5568 interface_options
*interface_opts
;
5570 interface_opts
= &g_array_index(global_capture_opts
.ifaces
, interface_options
, global_capture_opts
.ifaces
->len
- 1);
5571 interface_opts
->descr
= g_strdup(ws_optarg
);
5573 cmdarg_err("--ifdescr must be specified after a -i option");
5577 case LONGOPT_CAPTURE_COMMENT
: /* capture comment */
5578 if (capture_comments
== NULL
) {
5579 capture_comments
= g_ptr_array_new_with_free_func(g_free
);
5581 g_ptr_array_add(capture_comments
, g_strdup(ws_optarg
));
5584 capture_child
= true;
5590 case LONGOPT_SIGNAL_PIPE
:
5591 if (!capture_child
) {
5592 /* We have already checked for -Z at the very beginning. */
5593 cmdarg_err("--signal-pipe may only be specified with -Z");
5597 * ws_optarg = the control ID, aka the PPID, currently used for the
5600 if (strcmp(ws_optarg
, SIGNAL_PIPE_CTRL_ID_NONE
) != 0) {
5601 sig_pipe_name
= ws_strdup_printf(SIGNAL_PIPE_FORMAT
, ws_optarg
);
5602 sig_pipe_handle
= CreateFile(utf_8to16(sig_pipe_name
),
5603 GENERIC_READ
, 0, NULL
, OPEN_EXISTING
, 0, NULL
);
5605 if (sig_pipe_handle
== INVALID_HANDLE_VALUE
) {
5606 ws_info("Signal pipe: Unable to open %s. Dead parent?",
5613 case 'q': /* Quiet */
5616 case 'Q': /* Really quiet */
5618 really_quiet
= true;
5623 /*** all non capture option specific ***/
5624 case 'D': /* Print a list of capture devices and exit */
5625 if (!list_interfaces
&& !caps_queries
& !print_statistics
) {
5628 list_interfaces
= true;
5630 case 'L': /* Print list of link-layer types and exit */
5631 if (!list_interfaces
&& !caps_queries
& !print_statistics
) {
5634 caps_queries
|= CAPS_QUERY_LINK_TYPES
;
5636 case LONGOPT_LIST_TSTAMP_TYPES
:
5637 if (!list_interfaces
&& !caps_queries
& !print_statistics
) {
5640 caps_queries
|= CAPS_QUERY_TIMESTAMP_TYPES
;
5642 case 'd': /* Print BPF code for capture filter and exit */
5643 if (!print_bpf_code
) {
5644 print_bpf_code
= true;
5648 case 'S': /* Print interface statistics once a second */
5649 if (!list_interfaces
&& !caps_queries
& !print_statistics
) {
5652 print_statistics
= true;
5654 case 'k': /* Set wireless channel */
5657 set_chan_arg
= ws_optarg
;
5660 cmdarg_err("Only one -k flag may be specified");
5664 case 'M': /* For -D, -L, and -S, print machine-readable output */
5665 machine_readable
= true;
5668 pcap_queue_byte_limit
= get_positive_int(ws_optarg
, "byte_limit");
5671 pcap_queue_packet_limit
= get_positive_int(ws_optarg
, "packet_limit");
5674 cmdarg_err("Invalid Option: %s", argv
[ws_optind
-1]);
5676 case '?': /* Bad flag - print usage message */
5685 /* user specified file name as regular command-line argument */
5686 /* XXX - use it as the capture file name (or something else)? */
5692 * Extra command line arguments were specified; complain.
5693 * XXX - interpret as capture filter, as tcpdump and tshark do?
5695 cmdarg_err("Invalid argument: %s", argv
[0]);
5700 if ((pcap_queue_byte_limit
> 0) || (pcap_queue_packet_limit
> 0)) {
5703 if ((pcap_queue_byte_limit
== 0) && (pcap_queue_packet_limit
== 0)) {
5704 /* Use some default if the user hasn't specified some */
5705 /* XXX: Are these defaults good enough? */
5706 pcap_queue_byte_limit
= 1000 * 1000;
5707 pcap_queue_packet_limit
= 1000;
5710 if (ws_optopt
== 'F') {
5711 capture_opts_list_file_types();
5714 print_usage(stderr
);
5718 if (run_once_args
> 1) {
5719 cmdarg_err("Only one of -D, -L, -d, -k or -S may be supplied.");
5721 } else if (run_once_args
== 1) {
5722 /* We're supposed to print some information, rather than
5723 to capture traffic; did they specify a ring buffer option? */
5724 if (global_capture_opts
.multi_files_on
) {
5725 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
5729 /* We're supposed to capture traffic; */
5731 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
5732 if (global_capture_opts
.ifaces
->len
> 1) {
5734 global_capture_opts
.use_pcapng
= true;
5737 if (capture_comments
&&
5738 (!global_capture_opts
.use_pcapng
|| global_capture_opts
.multi_files_on
)) {
5739 /* XXX - for ringbuffer, should we apply the comments to each file? */
5740 cmdarg_err("Capture comments can only be set if we capture into a single pcapng file.");
5744 /* Was the ring buffer option specified and, if so, does it make sense? */
5745 if (global_capture_opts
.multi_files_on
) {
5746 /* Ring buffer works only under certain conditions:
5747 a) ring buffer does not work with temporary files;
5748 b) it makes no sense to enable the ring buffer if the maximum
5749 file size is set to "infinite". */
5750 if (global_capture_opts
.save_file
== NULL
) {
5751 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
5752 global_capture_opts
.multi_files_on
= false;
5754 if (!global_capture_opts
.has_autostop_filesize
&&
5755 !global_capture_opts
.has_file_duration
&&
5756 !global_capture_opts
.has_file_interval
&&
5757 !global_capture_opts
.has_file_packets
) {
5758 cmdarg_err("Ring buffer requested, but no maximum capture file size, duration "
5759 "interval, or packets were specified.");
5761 /* XXX - this must be redesigned as the conditions changed */
5762 global_capture_opts
.multi_files_on
= false;
5765 if (global_capture_opts
.has_file_duration
&& global_capture_opts
.has_file_interval
) {
5766 cmdarg_err("Ring buffer file duration and interval can't be used at the same time.");
5773 * "-D" requires no interface to be selected; it's supposed to list
5776 if (list_interfaces
) {
5777 /* Get the list of interfaces */
5782 if_list
= get_interface_list(&err
, &err_str
);
5783 if (if_list
== NULL
) {
5786 * If we're being run by another program, just give them
5787 * an empty list of interfaces, don't report this as
5788 * an error; that lets them decide whether to report
5789 * this as an error or not.
5791 if (!machine_readable
) {
5792 cmdarg_err("There are no interfaces on which a capture can be done");
5796 cmdarg_err("%s", err_str
);
5802 if (!machine_readable
) {
5804 capture_opts_print_interfaces(if_list
);
5809 interface_options
*interface_opts
;
5810 cap_device_open_status open_status
;
5811 char *open_status_str
;
5812 for (GList
*if_entry
= if_list
; if_entry
!= NULL
; if_entry
= g_list_next(if_entry
)) {
5813 if_info
= (if_info_t
*)if_entry
->data
;
5816 * XXX - If on the command line we had the options -i <interface> -I,
5817 * we should retrieve the link-types for the interface in monitor mode.
5818 * We've already copied that information to global_capture_opts, but
5819 * the below statement wipes it away.
5821 interface_opts
= interface_opts_from_if_info(&global_capture_opts
, if_info
);
5823 if_info
->caps
= get_if_capabilities(interface_opts
, &open_status
, &open_status_str
);
5825 if (!machine_readable
) {
5826 if (if_info
->caps
== NULL
) {
5827 cmdarg_err("The capabilities of the capture device "
5828 "\"%s\" could not be obtained (%s).\n%s",
5829 interface_opts
->name
, open_status_str
,
5830 get_pcap_failure_secondary_error_message(open_status
, open_status_str
));
5831 g_free(open_status_str
);
5832 /* Break after one error, as when printing selected
5833 * interface capabilities. (XXX: We could print all
5834 * the primary status strings, and only the unique
5835 * set of secondary messages / suggestions; printing
5836 * the same long secondary error is a lot.)
5838 interface_opts_free(interface_opts
);
5839 g_free(interface_opts
);
5842 status
= capture_opts_print_if_capabilities(if_info
->caps
, interface_opts
, caps_queries
);
5844 interface_opts_free(interface_opts
);
5845 g_free(interface_opts
);
5850 if (if_info
->caps
== NULL
) {
5851 if_info
->caps
= g_new0(if_capabilities_t
, 1);
5852 if_info
->caps
->primary_msg
= open_status_str
;
5853 if_info
->caps
->secondary_msg
= get_pcap_failure_secondary_error_message(open_status
, open_status_str
);
5855 if_info
->caps
->status
= open_status
;
5858 interface_opts_free(interface_opts
);
5859 g_free(interface_opts
);
5863 if (machine_readable
) {
5864 status
= print_machine_readable_interfaces(if_list
, caps_queries
, print_statistics
);
5866 free_interface_list(if_list
);
5867 if (!print_statistics
) {
5873 * "-S" requires no interface to be selected; it gives statistics
5874 * for all interfaces.
5876 if (print_statistics
) {
5877 status
= print_statistics_loop(machine_readable
);
5882 interface_options
*interface_opts
;
5884 if (global_capture_opts
.ifaces
->len
!= 1) {
5885 cmdarg_err("Need one interface");
5889 interface_opts
= &g_array_index(global_capture_opts
.ifaces
, interface_options
, 0);
5890 status
= set_80211_channel(interface_opts
->name
, set_chan_arg
);
5895 * "-L", "-d", and capturing act on a particular interface, so we have to
5896 * have an interface; if none was specified, pick a default.
5898 status
= capture_opts_default_iface_if_necessary(&global_capture_opts
, NULL
);
5900 /* cmdarg_err() already called .... */
5905 /* Get the list of link-layer and/or timestamp types for the capture device. */
5906 if_capabilities_t
*caps
;
5907 cap_device_open_status open_status
;
5908 char *open_status_str
;
5911 if (machine_readable
) {
5912 json_dumper dumper
= {
5913 .output_file
= stdout
,
5914 .flags
= JSON_DUMPER_FLAGS_NO_DEBUG
,
5915 // Don't abort on failure
5917 json_dumper_begin_array(&dumper
);
5918 for (ii
= 0; ii
< global_capture_opts
.ifaces
->len
; ii
++) {
5919 interface_options
*interface_opts
;
5921 interface_opts
= &g_array_index(global_capture_opts
.ifaces
, interface_options
, ii
);
5923 json_dumper_begin_object(&dumper
);
5924 json_dumper_set_member_name(&dumper
, interface_opts
->name
);
5926 json_dumper_begin_object(&dumper
);
5928 open_status
= CAP_DEVICE_OPEN_NO_ERR
;
5929 caps
= get_if_capabilities(interface_opts
, &open_status
, &open_status_str
);
5931 json_dumper_set_member_name(&dumper
, "status");
5932 json_dumper_value_anyf(&dumper
, "%i", open_status
);
5933 json_dumper_set_member_name(&dumper
, "primary_msg");
5934 json_dumper_value_string(&dumper
, open_status_str
);
5935 g_free(open_status_str
);
5937 caps
->status
= open_status
;
5938 print_machine_readable_if_capabilities(&dumper
, caps
, caps_queries
);
5939 free_if_capabilities(caps
);
5941 json_dumper_end_object(&dumper
);
5942 json_dumper_end_object(&dumper
);
5944 json_dumper_end_array(&dumper
);
5945 if (json_dumper_finish(&dumper
)) {
5947 if (capture_child
) {
5948 /* Let our parent know we succeeded. */
5949 sync_pipe_write_string_msg(sync_pipe_fd
, SP_SUCCESS
, NULL
);
5953 if (capture_child
) {
5954 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd
, "Unexpected JSON error", "");
5958 for (ii
= 0; ii
< global_capture_opts
.ifaces
->len
; ii
++) {
5959 interface_options
*interface_opts
;
5961 interface_opts
= &g_array_index(global_capture_opts
.ifaces
, interface_options
, ii
);
5963 caps
= get_if_capabilities(interface_opts
, &open_status
, &open_status_str
);
5965 if (capture_child
) {
5966 char *error_msg
= ws_strdup_printf("The capabilities of the capture device "
5967 "\"%s\" could not be obtained (%s)",
5968 interface_opts
->name
, open_status_str
);
5969 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd
, error_msg
,
5970 get_pcap_failure_secondary_error_message(open_status
, open_status_str
));
5974 cmdarg_err("The capabilities of the capture device "
5975 "\"%s\" could not be obtained (%s).\n%s",
5976 interface_opts
->name
, open_status_str
,
5977 get_pcap_failure_secondary_error_message(open_status
, open_status_str
));
5979 g_free(open_status_str
);
5983 /* XXX: We might want to print also the interface name */
5984 status
= capture_opts_print_if_capabilities(caps
,
5987 free_if_capabilities(caps
);
5995 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
5996 for (j
= 0; j
< global_capture_opts
.ifaces
->len
; j
++) {
5997 interface_options
*interface_opts
;
5999 interface_opts
= &g_array_index(global_capture_opts
.ifaces
, interface_options
, j
);
6000 if (interface_opts
->timestamp_type
) {
6001 interface_opts
->timestamp_type_id
= pcap_tstamp_type_name_to_val(interface_opts
->timestamp_type
);
6002 if (interface_opts
->timestamp_type_id
< 0) {
6003 cmdarg_err("Invalid argument to option: --time-stamp-type=%s", interface_opts
->timestamp_type
);
6010 /* We're supposed to do a capture, or print the BPF code for a filter. */
6012 /* Let the user know what interfaces were chosen. */
6013 if (capture_child
) {
6014 for (j
= 0; j
< global_capture_opts
.ifaces
->len
; j
++) {
6015 interface_options
*interface_opts
;
6017 interface_opts
= &g_array_index(global_capture_opts
.ifaces
, interface_options
, j
);
6018 ws_debug("Interface: %s\n", interface_opts
->name
);
6021 str
= g_string_new("");
6023 if (global_capture_opts
.ifaces
->len
< 2)
6025 if (global_capture_opts
.ifaces
->len
< 4)
6028 for (j
= 0; j
< global_capture_opts
.ifaces
->len
; j
++) {
6029 interface_options
*interface_opts
;
6031 interface_opts
= &g_array_index(global_capture_opts
.ifaces
, interface_options
, j
);
6033 if (global_capture_opts
.ifaces
->len
> 2) {
6034 g_string_append_printf(str
, ",");
6036 g_string_append_printf(str
, " ");
6037 if (j
== global_capture_opts
.ifaces
->len
- 1) {
6038 g_string_append_printf(str
, "and ");
6041 if (interface_opts
->ifname
!= NULL
) {
6043 * Re-generate the display name based on the strins
6046 g_free(interface_opts
->display_name
);
6047 if (interface_opts
->descr
!= NULL
) {
6049 interface_opts
->display_name
= ws_strdup_printf("%s",
6050 interface_opts
->descr
);
6052 interface_opts
->display_name
= ws_strdup_printf("%s: %s",
6053 interface_opts
->descr
, interface_opts
->ifname
);
6056 interface_opts
->display_name
= ws_strdup_printf("%s",
6057 interface_opts
->ifname
);
6060 g_string_append_printf(str
, "'%s'", interface_opts
->display_name
);
6063 g_string_append_printf(str
, "%u interfaces", global_capture_opts
.ifaces
->len
);
6066 fprintf(stderr
, "Capturing on %s\n", str
->str
);
6067 g_string_free(str
, TRUE
);
6070 /* Process the snapshot length, as that affects the generated BPF code. */
6071 capture_opts_trim_snaplen(&global_capture_opts
, MIN_PACKET_SIZE
);
6073 if (print_bpf_code
) {
6074 show_filter_code(&global_capture_opts
);
6078 /* We're supposed to do a capture. Process the ring buffer arguments. */
6079 capture_opts_trim_ring_num_files(&global_capture_opts
);
6081 /* flush stderr prior to starting the main capture loop */
6084 /* Now start the capture. */
6085 if (capture_loop_start(&global_capture_opts
, &stats_known
, &stats
) == true) {
6089 /* capture failed */
6092 return 0; /* never here, make compiler happy */
6096 dumpcap_log_writer(const char *domain
, enum ws_log_level level
,
6097 const char *file
, long line
, const char *func
,
6098 const char *fatal_msg _U_
,
6099 ws_log_manifest_t
*mft
,
6100 const char *user_format
, va_list user_ap
,
6101 void *user_data _U_
)
6103 if (ws_log_msg_is_active(domain
, level
)) {
6104 /* log messages go to stderr or */
6105 /* to parent especially formatted if dumpcap running as child. */
6106 #ifdef DEBUG_CHILD_DUMPCAP
6107 va_list user_ap_copy
;
6108 va_copy(user_ap_copy
, user_ap
);
6110 if (capture_child
) {
6111 /* Format the log mesage as the numeric level, followed
6112 * by a colon and then a string matching the standard log
6113 * string. In the future perhaps we serialize file, line,
6114 * and func (which can be NULL) instead.
6116 GString
*msg
= g_string_new(NULL
);
6117 g_string_append_printf(msg
, "%u:", level
);
6119 g_string_append_printf(msg
, "%s", file
);
6121 g_string_append_printf(msg
, ":%ld", line
);
6124 g_string_append(msg
, " --");
6126 g_string_append_printf(msg
, " %s():", func
);
6128 g_string_append_c(msg
, ' ');
6129 g_string_append_vprintf(msg
, user_format
, user_ap
);
6131 sync_pipe_write_string_msg(sync_pipe_fd
, SP_LOG_MSG
, msg
->str
);
6132 g_string_free(msg
, TRUE
);
6134 ws_log_console_writer(domain
, level
, file
, line
, func
, mft
, user_format
, user_ap
);
6136 #ifdef DEBUG_CHILD_DUMPCAP
6137 ws_log_file_writer(debug_log
, domain
, level
, file
, line
, func
, mft
, user_format
, user_ap_copy
);
6138 va_end(user_ap_copy
);
6144 /****************************************************************************************************************/
6145 /* indication report routines */
6149 report_packet_count(unsigned int packet_count
)
6151 static unsigned int count
= 0;
6153 if (capture_child
) {
6154 ws_debug("Packets: %u", packet_count
);
6155 sync_pipe_write_uint_msg(sync_pipe_fd
, SP_PACKET_COUNT
, packet_count
);
6157 count
+= packet_count
;
6158 fprintf(stderr
, "\rPackets: %u ", count
);
6159 /* stderr could be line buffered */
6165 report_new_capture_file(const char *filename
)
6167 if (capture_child
) {
6168 ws_debug("File: %s", filename
);
6169 if (global_ld
.pcapng_passthrough
) {
6170 /* Save filename for sending SP_FILE to capture parent after SHB is passed-through */
6171 ws_debug("Delaying SP_FILE until first SHB");
6172 report_capture_filename
= filename
;
6174 sync_pipe_write_string_msg(sync_pipe_fd
, SP_FILE
, filename
);
6179 * Prevent a SIGINFO handler from writing to the standard error
6180 * while we're doing so; instead, have it just set a flag telling
6181 * us to print that information when we're done.
6184 #endif /* SIGINFO */
6185 if (!really_quiet
) {
6186 fprintf(stderr
, "File: %s\n", filename
);
6187 /* stderr could be line buffered */
6193 * Allow SIGINFO handlers to write.
6198 * If a SIGINFO handler asked us to write out capture counts, do so.
6201 report_counts_for_siginfo();
6202 #endif /* SIGINFO */
6207 report_cfilter_error(capture_options
*capture_opts
, unsigned i
, const char *errmsg
)
6209 interface_options
*interface_opts
;
6210 char tmp
[MSG_MAX_LENGTH
+1+6];
6212 if (i
< capture_opts
->ifaces
->len
) {
6213 if (capture_child
) {
6214 snprintf(tmp
, sizeof(tmp
), "%u:%s", i
, errmsg
);
6215 ws_debug("Capture filter error: %s", errmsg
);
6216 sync_pipe_write_string_msg(sync_pipe_fd
, SP_BAD_FILTER
, tmp
);
6219 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
6220 * the error message below.
6222 interface_opts
= &g_array_index(capture_opts
->ifaces
, interface_options
, i
);
6224 "Invalid capture filter \"%s\" for interface '%s'.\n"
6226 "That string isn't a valid capture filter (%s).\n"
6227 "See the User's Guide for a description of the capture filter syntax.",
6228 interface_opts
->cfilter
, interface_opts
->name
, errmsg
);
6234 report_capture_error(const char *error_msg
, const char *secondary_error_msg
)
6236 if (capture_child
) {
6237 ws_debug("Primary Error: %s", error_msg
);
6238 ws_debug("Secondary Error: %s", secondary_error_msg
);
6239 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd
, error_msg
, secondary_error_msg
);
6241 cmdarg_err("%s", error_msg
);
6242 if (secondary_error_msg
[0] != '\0')
6243 cmdarg_err_cont("%s", secondary_error_msg
);
6248 report_packet_drops(uint32_t received
, uint32_t pcap_drops
, uint32_t drops
, uint32_t flushed
, uint32_t ps_ifdrop
, char *name
)
6250 uint32_t total_drops
= pcap_drops
+ drops
+ flushed
;
6252 if (capture_child
) {
6253 char* tmp
= ws_strdup_printf("%u:%s", total_drops
, name
);
6255 ws_debug("Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
6256 name
, received
, total_drops
, pcap_drops
, drops
, flushed
, ps_ifdrop
);
6257 sync_pipe_write_string_msg(sync_pipe_fd
, SP_DROPS
, tmp
);
6260 if (!really_quiet
) {
6262 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
6263 name
, received
, total_drops
, pcap_drops
, drops
, flushed
, ps_ifdrop
,
6264 received
? 100.0 * received
/ (received
+ total_drops
) : 0.0);
6265 /* stderr could be line buffered */
6272 /************************************************************************************************/
6273 /* signal_pipe handling */
6278 signal_pipe_check_running(void)
6280 /* any news from our parent? -> just stop the capture */
6284 /* if we are running standalone, no check required */
6285 if (!capture_child
) {
6289 if (!sig_pipe_name
|| !sig_pipe_handle
) {
6290 /* This shouldn't happen */
6291 ws_info("Signal pipe: No name or handle");
6296 * XXX - We should have the process ID of the parent (from the "-Z" flag)
6297 * at this point. Should we check to see if the parent is still alive,
6298 * e.g. by using OpenProcess?
6301 result
= PeekNamedPipe(sig_pipe_handle
, NULL
, 0, NULL
, &avail
, NULL
);
6303 if (!result
|| avail
> 0) {
6304 /* peek failed or some bytes really available */
6305 /* (if not piping from stdin this would fail) */
6306 ws_info("Signal pipe: Stop capture: %s", sig_pipe_name
);
6307 ws_debug("Signal pipe: %s (%p) result: %u avail: %lu", sig_pipe_name
,
6308 sig_pipe_handle
, result
, avail
);
6311 /* pipe ok and no bytes available */
6318 * Editor modelines - https://www.wireshark.org/tools/modelines.html
6323 * indent-tabs-mode: nil
6326 * vi: set shiftwidth=4 tabstop=8 expandtab:
6327 * :indentSize=4:tabSize=8:noTabs=true: