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/array.h>
37 #include <wsutil/cmdarg_err.h>
38 #include <wsutil/strtoi.h>
40 #include <wsutil/version_info.h>
42 #include <wsutil/socket.h>
43 #include <wsutil/wslog.h>
44 #include <wsutil/file_util.h>
47 # include <sys/prctl.h>
48 # include <sys/capability.h>
51 #include "ringbuffer.h"
53 #include "capture/capture_ifinfo.h"
54 #include "capture/capture-pcap-util.h"
55 #include "capture/capture-pcap-util-int.h"
57 #include "capture/capture-wpcap.h"
60 #include "writecap/pcapio.h"
66 #include <wsutil/clopts_common.h>
67 #include <wsutil/privileges.h>
69 #include "sync_pipe.h"
71 #include "capture_opts.h"
72 #include <capture/capture_session.h>
73 #include <capture/capture_sync.h>
75 #include "wsutil/tempfile.h"
76 #include "wsutil/file_util.h"
77 #include "wsutil/cpu_info.h"
78 #include "wsutil/os_version_info.h"
79 #include "wsutil/str_util.h"
80 #include "wsutil/inet_addr.h"
81 #include "wsutil/time_util.h"
82 #include "wsutil/please_report_bug.h"
83 #include "wsutil/glib-compat.h"
84 #include <wsutil/json_dumper.h>
85 #include <wsutil/ws_assert.h>
87 #include "capture/ws80211_utils.h"
92 * Get information about libpcap format from "wiretap/libpcap.h".
93 * Get information about pcapng format from "wiretap/pcapng_module.h".
94 * XXX - can we just use pcap_open_offline() to read the pipe?
96 #include "wiretap/libpcap.h"
97 #include "wiretap/pcapng_module.h"
98 #include "wiretap/pcapng.h"
101 * Define these for extra logging. Note that when dumpcap is spawned as
102 * a child process, logs are sent to the parent via the sync pipe.
103 * The parent will pass along the Capchild domain log level settings,
104 * so "--log-debug Capchild" or "--log-level debug" can be used to get
105 * debugging from dumpcap sent to the parent.
107 //#define DEBUG_DUMPCAP /* Waits for keypress on quitting on Windows */
108 //#define DEBUG_CHILD_DUMPCAP /* Writes logs to file */
111 #include "wsutil/win32-utils.h"
113 #include <conio.h> /* _getch() */
117 #ifdef DEBUG_CHILD_DUMPCAP
118 FILE *debug_log
; /* for logging debug messages to */
119 /* a file if DEBUG_CHILD_DUMPCAP */
121 #include <stdarg.h> /* va_copy */
124 static GAsyncQueue
*pcap_queue
;
125 static int64_t pcap_queue_bytes
;
126 static int64_t pcap_queue_packets
;
127 static int64_t pcap_queue_byte_limit
;
128 static int64_t pcap_queue_packet_limit
;
130 static bool capture_child
; /* false: standalone call, true: this is an Wireshark capture child */
131 static const char *report_capture_filename
; /* capture child file name */
133 static char *sig_pipe_name
;
134 static HANDLE sig_pipe_handle
;
135 static bool signal_pipe_check_running(void);
137 static int sync_pipe_fd
= 2;
139 #if defined (ENABLE_ASAN) || defined (ENABLE_LSAN)
140 /* This has public visibility so that if compiled with shared libasan (the
141 * gcc default) function interposition occurs.
144 __lsan_is_turned_off(void)
146 /* If we're in capture child mode, don't run a LSan report and
147 * send it to stderr, because it isn't properly formatted for
149 * We could, if debugging variables are set, send the reports
150 * elsewhere instead, by calling __sanitizer_set_report_path()
151 * or __sanitizer_set_report_fd()
157 /* LSan dies with a fatal error without explanation if it can't ptrace.
158 * Normally, the "dumpable" attribute (which also controls ptracing)
159 * is set to 1 (SUID_DUMP_USER, process is dumpable.) However, it is
160 * reset to the current value in /proc/sys/fs/suid_dumpable in the
161 * following circumstances: euid/egid changes, fsuid/fsgid changes,
162 * execve of a setuid or setgid program that changes the euid or egid,
163 * execve of a program with capabilities exceeding those already
164 * permitted for the process.
166 * Unless we're running as root, one of those applies to dumpcap.
168 * The default value of /proc/sys/fs/suid_dumpable is 0, SUID_DUMP_DISABLE.
169 * In such a case, LeakSanitizer temporarily sets the value to 1 to
170 * allow ptracing, and then sets it back to 0.
172 * Another possible value, used by Ubuntu, Fedora, etc., is 2,
173 * which creates dumps readable by root only. For security reasons,
174 * unprivileged programs are not allowed to change the value to 2.
175 * (See https://nvd.nist.gov/vuln/detail/CVE-2006-2451 )
177 * LSan does not check for the value 2 and change dumpable to 1 in that
178 * case, possibly because if it did it could not change it back to 2
179 * and would have to either leave the process dumpable or change it to 0.
181 * The usual way to control the family of sanitizers is through environment
182 * variables. However, complicating things, changing the dumpable attribute
183 * to 0 or 2 changes the ownership of files in /proc/[pid] (including
184 * /proc/self ) to root:root, in particular /proc/[pid]/environ, and so
185 * ASAN_OPTIONS=detect_leaks=0 has no effect. (Unless the process has
186 * CAP_SYS_PTRACE, which allows tracing of any process, but that's also
187 * a security risk and we'll have dropped that with other privileges.)
189 * So if prctl(PR_GET_DUMPABLE) returns 2, we know that the process will
190 * die with a fatal error if it attempts to run LSan, so don't.
192 * See proc(5), prctl(2), ptrace(2), and
193 * https://github.com/google/sanitizers/issues/1306
194 * https://github.com/llvm/llvm-project/issues/55944
196 if (prctl(PR_GET_DUMPABLE
) == 2) {
197 ws_debug("Not running LeakSanitizer because /proc/sys/fs/suid_dumpable is 2");
204 WS_DLL_PUBLIC
const char*
205 __asan_default_options(void)
207 /* By default don't override our exit code if there's a leak or error.
208 * We particularly don't want to do this if running as a capture child,
209 * because capture/capture_sync doesn't expect the ASan exit codes.
214 WS_DLL_PUBLIC
const char*
215 __lsan_default_options(void)
217 /* By default don't override our exit code if there's a leak or error.
218 * We particularly don't want to do this if running as a capture child,
219 * because capture/capture_sync doesn't expect the LSan exit codes.
226 static bool infodelay
; /* if true, don't print capture info in SIGINFO handler */
227 static bool infoprint
; /* if true, print capture info after clearing infodelay */
230 /** Stop a low-level capture (stops the capture child). */
231 static void capture_loop_stop(void);
232 /** Close a pipe, or socket if \a from_socket is true */
233 static void cap_pipe_close(int pipe_fd
, bool from_socket
);
235 #if defined (__linux__)
236 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
237 * in pcap_dispatch(); on the other hand, select() works just fine there.
238 * Hence we use a select for that come what may.
240 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
241 * internally, and, with TPACKET_V3, once that's supported, it'll
242 * support timeouts, at least as I understand the way the code works.
244 #define MUST_DO_SELECT
247 /** init the capture filter */
250 INITFILTER_BAD_FILTER
,
251 INITFILTER_OTHER_ERROR
252 } initfilter_status_t
;
255 STATE_EXPECT_REC_HDR
,
268 typedef struct _pcap_pipe_info
{
269 bool byte_swapped
; /**< true if data in the pipe is byte swapped. */
270 struct pcap_hdr hdr
; /**< Pcap header when capturing from a pipe */
271 struct pcaprec_modified_hdr rechdr
; /**< Pcap record header when capturing from a pipe */
274 typedef struct _pcapng_pipe_info
{
275 pcapng_block_header_t bh
; /**< Pcapng general block header when capturing from a pipe */
276 GArray
*src_iface_to_global
; /**< Int array mapping local IDB numbers to global_ld.interface_data */
277 } pcapng_pipe_info_t
;
279 struct _loop_data
; /* forward declaration so we can use it in the cap_pipe_dispatch function pointer */
282 * A source of packets from which we're capturing.
284 typedef struct _capture_src
{
289 #ifdef MUST_DO_SELECT
290 int pcap_fd
; /**< pcap file descriptor */
293 unsigned interface_id
;
294 unsigned idb_id
; /**< If from_pcapng is false, the output IDB interface ID. Otherwise the mapping in src_iface_to_global is used. */
298 bool ts_nsec
; /**< true if we're using nanosecond precision. */
299 /**< capture pipe (unix only "input file") */
300 bool from_cap_pipe
; /**< true if we are capturing data from a capture pipe */
301 bool from_cap_socket
; /**< true if we're capturing from socket */
302 bool from_pcapng
; /**< true if we're capturing from pcapng format */
304 pcap_pipe_info_t pcap
; /**< Pcap info when capturing from a pipe */
305 pcapng_pipe_info_t pcapng
; /**< Pcapng info when capturing from a pipe */
308 HANDLE cap_pipe_h
; /**< The handle of the capture pipe */
310 int cap_pipe_fd
; /**< the file descriptor of the capture pipe */
311 bool cap_pipe_modified
; /**< true if data in the pipe uses modified pcap headers */
312 char * cap_pipe_databuf
; /**< Pointer to the data buffer we've allocated */
313 size_t cap_pipe_databuf_size
; /**< Current size of the data buffer */
314 unsigned cap_pipe_max_pkt_size
; /**< Maximum packet size allowed */
316 char * cap_pipe_buf
; /**< Pointer to the buffer we read into */
317 DWORD cap_pipe_bytes_to_read
; /**< Used by cap_pipe_dispatch */
318 DWORD cap_pipe_bytes_read
; /**< Used by cap_pipe_dispatch */
320 size_t cap_pipe_bytes_to_read
; /**< Used by cap_pipe_dispatch */
321 size_t cap_pipe_bytes_read
; /**< Used by cap_pipe_dispatch */
323 int (*cap_pipe_dispatch
)(struct _loop_data
*, struct _capture_src
*, char *, size_t);
324 cap_pipe_state_t cap_pipe_state
;
325 cap_pipe_err_t cap_pipe_err
;
328 GMutex
*cap_pipe_read_mtx
;
329 GAsyncQueue
*cap_pipe_pending_q
, *cap_pipe_done_q
;
333 typedef struct _saved_idb
{
335 unsigned interface_id
; /* capture_src->interface_id for the associated SHB */
336 uint8_t *idb
; /* If non-NULL, IDB read from capture_src. This is an interface specified on the command line otherwise. */
341 * Global capture loop state.
343 typedef struct _loop_data
{
345 bool go
; /**< true as long as we're supposed to keep capturing */
346 int err
; /**< if non-zero, error seen while capturing */
347 int packets_captured
; /**< Number of packets we have already captured */
348 unsigned inpkts_to_sync_pipe
; /**< Packets not already send out to the sync_pipe */
350 bool report_packet_count
; /**< Set by SIGINFO handler; print packet count */
352 GArray
*pcaps
; /**< Array of capture_src's on which we're capturing */
353 bool pcapng_passthrough
; /**< We have one source and it's pcapng. Pass its SHB and IDBs through. */
354 uint8_t *saved_shb
; /**< SHB to write when we have one pcapng input */
355 GArray
*saved_idbs
; /**< Array of saved_idb_t, written when we have a new section or output file. */
356 GRWLock saved_shb_idb_lock
; /**< Saved IDB RW mutex */
360 char *io_buffer
; /**< Our IO buffer if we increase the size from the standard size */
361 uint64_t bytes_written
; /**< Bytes written for the current file. */
362 /* autostop conditions */
363 int packets_written
; /**< Packets written for the current file. */
365 /* ring buffer conditions */
366 GTimer
*file_duration_timer
;
367 time_t next_interval_time
;
371 typedef struct _pcap_queue_element
{
372 capture_src
*pcap_src
;
374 struct pcap_pkthdr phdr
;
375 pcapng_block_header_t bh
;
378 } pcap_queue_element
;
381 * This needs to be static, so that the SIGINT handler can clear the "go"
382 * flag and for saved_shb_idb_lock.
384 static loop_data global_ld
;
387 * Timeout, in milliseconds, for reads from the stream of captured packets
388 * from a capture device.
390 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
391 * 64-bit applications, with sub-second timeouts not to work. The bug is
392 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
394 #if defined(__APPLE__) && defined(__LP64__)
395 static bool need_timeout_workaround
;
397 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
399 #define CAP_READ_TIMEOUT 250
403 * Timeout, in microseconds, for reads from the stream of captured packets
404 * from a pipe. Pipes don't have the same problem that BPF devices do
405 * in Mac OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
406 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
407 * of the offending versions of Snow Leopard.
409 * On Windows this value is converted to milliseconds and passed to
410 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
411 * will return immediately.
414 #define PIPE_READ_TIMEOUT 100000
416 #define PIPE_READ_TIMEOUT 250000
419 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
422 dumpcap_log_writer(const char *domain
, enum ws_log_level level
,
423 const char *file
, long line
, const char *func
,
424 const char *fatal_msg
, ws_log_manifest_t
*mft
,
425 const char *user_format
, va_list user_ap
,
428 /* capture related options */
429 static capture_options global_capture_opts
;
430 static GPtrArray
*capture_comments
;
432 static bool really_quiet
;
433 static bool use_threads
;
434 static uint64_t start_time
;
436 static void capture_loop_write_packet_cb(uint8_t *pcap_src_p
, const struct pcap_pkthdr
*phdr
,
438 static void capture_loop_queue_packet_cb(uint8_t *pcap_src_p
, const struct pcap_pkthdr
*phdr
,
440 static void capture_loop_write_pcapng_cb(capture_src
*pcap_src
, const pcapng_block_header_t
*bh
, uint8_t *pd
);
441 static void capture_loop_queue_pcapng_cb(capture_src
*pcap_src
, const pcapng_block_header_t
*bh
, uint8_t *pd
);
442 static void capture_loop_get_errmsg(char *errmsg
, size_t errmsglen
,
443 char *secondary_errmsg
,
444 size_t secondary_errmsglen
,
445 const char *fname
, int err
,
448 WS_NORETURN
static void exit_main(int err
);
450 static void report_new_capture_file(const char *filename
);
451 static void report_packet_count(unsigned int packet_count
);
452 static void report_packet_drops(uint32_t received
, uint32_t pcap_drops
, uint32_t drops
, uint32_t flushed
, uint32_t ps_ifdrop
, char *name
);
453 static void report_capture_error(const char *error_msg
, const char *secondary_error_msg
);
454 static void report_cfilter_error(capture_options
*capture_opts
, unsigned i
, const char *errmsg
);
456 #define MSG_MAX_LENGTH 4096
459 print_usage(FILE *output
)
461 fprintf(output
, "\nUsage: dumpcap [options] ...\n");
462 fprintf(output
, "\n");
463 fprintf(output
, "Capture interface:\n");
464 fprintf(output
, " -i <interface>, --interface <interface>\n");
465 fprintf(output
, " name or idx of interface (def: first non-loopback),\n"
466 #ifdef HAVE_PCAP_REMOTE
467 " or for remote capturing, use one of these formats:\n"
468 " rpcap://<host>/<interface>\n"
470 " or for remote capturing, use this format:\n"
472 " TCP@<host>:<port>\n");
473 fprintf(output
, " --ifname <name> name to use in the capture file for a pipe from which\n");
474 fprintf(output
, " we're capturing\n");
475 fprintf(output
, " --ifdescr <description>\n");
476 fprintf(output
, " description to use in the capture file for a pipe\n");
477 fprintf(output
, " from which we're capturing\n");
478 fprintf(output
, " -f <capture filter> packet filter in libpcap filter syntax\n");
479 fprintf(output
, " -s <snaplen>, --snapshot-length <snaplen>\n");
480 #ifdef HAVE_PCAP_CREATE
481 fprintf(output
, " packet snapshot length (def: appropriate maximum)\n");
483 fprintf(output
, " packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD
);
485 fprintf(output
, " -p, --no-promiscuous-mode\n");
486 fprintf(output
, " don't capture in promiscuous mode\n");
487 #ifdef HAVE_PCAP_CREATE
488 fprintf(output
, " -I, --monitor-mode capture in monitor mode, if available\n");
490 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
491 fprintf(output
, " -B <buffer size>, --buffer-size <buffer size>\n");
492 fprintf(output
, " size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE
);
494 fprintf(output
, " -y <link type>, --linktype <link type>\n");
495 fprintf(output
, " link layer type (def: first appropriate)\n");
496 fprintf(output
, " --time-stamp-type <type> timestamp method for interface\n");
497 fprintf(output
, " -D, --list-interfaces print list of interfaces and exit\n");
498 fprintf(output
, " -L, --list-data-link-types\n");
499 fprintf(output
, " print list of link-layer types of iface and exit\n");
500 fprintf(output
, " --list-time-stamp-types print list of timestamp types for iface and exit\n");
501 fprintf(output
, " --update-interval interval between updates with new packets (def: %dms)\n", DEFAULT_UPDATE_INTERVAL
);
502 fprintf(output
, " -d print generated BPF code for capture filter\n");
503 fprintf(output
, " -k <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
504 fprintf(output
, " set channel on wifi interface\n");
505 fprintf(output
, " -S print statistics for each interface once per second\n");
506 fprintf(output
, " -M for -D, -L, and -S, produce machine-readable output\n");
507 fprintf(output
, "\n");
508 #ifdef HAVE_PCAP_REMOTE
509 fprintf(output
, "RPCAP options:\n");
510 fprintf(output
, " -r don't ignore own RPCAP traffic in capture\n");
511 fprintf(output
, " -u use UDP for RPCAP data transfer\n");
512 fprintf(output
, " -A <user>:<password> use RPCAP password authentication\n");
513 #ifdef HAVE_PCAP_SETSAMPLING
514 fprintf(output
, " -m <sampling type> use packet sampling\n");
515 fprintf(output
, " count:NUM - capture one packet of every NUM\n");
516 fprintf(output
, " timer:NUM - capture no more than 1 packet in NUM ms\n");
519 fprintf(output
, "Stop conditions:\n");
520 fprintf(output
, " -c <packet count> stop after n packets (def: infinite)\n");
521 fprintf(output
, " -a <autostop cond.> ..., --autostop <autostop cond.> ...\n");
522 fprintf(output
, " duration:NUM - stop after NUM seconds\n");
523 fprintf(output
, " filesize:NUM - stop this file after NUM kB\n");
524 fprintf(output
, " files:NUM - stop after NUM files\n");
525 fprintf(output
, " packets:NUM - stop after NUM packets\n");
526 /*fprintf(output, "\n");*/
527 fprintf(output
, "Output (files):\n");
528 fprintf(output
, " -w <filename> name of file to save (def: tempfile)\n");
529 fprintf(output
, " -g enable group read access on the output file(s)\n");
530 fprintf(output
, " -b <ringbuffer opt.> ..., --ring-buffer <ringbuffer opt.>\n");
531 fprintf(output
, " duration:NUM - switch to next file after NUM secs\n");
532 fprintf(output
, " filesize:NUM - switch to next file after NUM kB\n");
533 fprintf(output
, " files:NUM - ringbuffer: replace after NUM files\n");
534 fprintf(output
, " packets:NUM - ringbuffer: replace after NUM packets\n");
535 fprintf(output
, " interval:NUM - switch to next file when the time is\n");
536 fprintf(output
, " an exact multiple of NUM secs\n");
537 fprintf(output
, " printname:FILE - print filename to FILE when written\n");
538 fprintf(output
, " (can use 'stdout' or 'stderr')\n");
539 fprintf(output
, " -n use pcapng format instead of pcap (default)\n");
540 fprintf(output
, " -P use libpcap format instead of pcapng\n");
541 fprintf(output
, " --capture-comment <comment>\n");
542 fprintf(output
, " add a capture comment to the output file\n");
543 fprintf(output
, " (only for pcapng)\n");
544 fprintf(output
, " --temp-dir <directory> write temporary files to this directory\n");
545 fprintf(output
, " (default: %s)\n", g_get_tmp_dir());
546 fprintf(output
, "\n");
548 ws_log_print_usage(output
);
549 fprintf(output
, "\n");
551 fprintf(output
, "Miscellaneous:\n");
552 fprintf(output
, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
553 fprintf(output
, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
554 fprintf(output
, " within dumpcap\n");
555 fprintf(output
, " -t use a separate thread per interface\n");
556 fprintf(output
, " -q don't report packet capture counts\n");
557 fprintf(output
, " -v, --version print version information and exit\n");
558 fprintf(output
, " -h, --help display this help and exit\n");
559 fprintf(output
, "\n");
561 fprintf(output
, "Dumpcap can benefit from an enabled BPF JIT compiler if available.\n");
562 fprintf(output
, "You might want to enable it by executing:\n");
563 fprintf(output
, " \"echo 1 > /proc/sys/net/core/bpf_jit_enable\"\n");
564 fprintf(output
, "Note that this can make your system less secure!\n");
565 fprintf(output
, "\n");
567 fprintf(output
, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
568 fprintf(output
, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
569 fprintf(output
, "\n");
570 fprintf(output
, "Use Ctrl-C to stop capturing at any time.\n");
574 * Report an error in command-line arguments.
575 * If we're a capture child, send a message back to the parent, otherwise
579 dumpcap_cmdarg_err(const char *fmt
, va_list ap
)
583 /* Generate a 'special format' message back to parent */
584 msg
= ws_strdup_vprintf(fmt
, ap
);
585 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd
, msg
, "");
588 fprintf(stderr
, "dumpcap: ");
589 vfprintf(stderr
, fmt
, ap
);
590 fprintf(stderr
, "\n");
595 * Report additional information for an error in command-line arguments.
596 * If we're a capture child, send a message back to the parent, otherwise
600 dumpcap_cmdarg_err_cont(const char *fmt
, va_list ap
)
604 msg
= ws_strdup_vprintf(fmt
, ap
);
605 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd
, msg
, "");
608 vfprintf(stderr
, fmt
, ap
);
609 fprintf(stderr
, "\n");
615 /* see 'man cap_to_text()' for explanation of output */
616 /* '=' means 'all= ' ie: no capabilities */
617 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
619 print_caps(const char *pfx
) {
620 if (ws_log_msg_is_active(WS_LOG_DOMAIN
, LOG_LEVEL_NOISY
)) {
621 cap_t caps
= cap_get_proc();
622 char *caps_text
= cap_to_text(caps
, NULL
);
623 ws_noisy("%s: EUID: %d Capabilities: %s", pfx
, geteuid(), caps_text
);
630 relinquish_all_capabilities(void)
632 /* Drop any and all capabilities this process may have. */
633 /* Allowed whether or not process has any privileges. */
634 cap_t caps
= cap_init(); /* all capabilities initialized to off */
635 print_caps("Pre-clear");
636 if (cap_set_proc(caps
)) {
637 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno
));
639 print_caps("Post-clear");
645 get_capture_device_open_failure_messages(cap_device_open_status open_status
,
646 const char *open_status_str
,
648 char *errmsg
, size_t errmsg_len
,
649 char *secondary_errmsg
,
650 size_t secondary_errmsg_len
)
652 switch (open_status
) {
654 case CAP_DEVICE_OPEN_ERROR_NO_SUCH_DEVICE
:
655 snprintf(errmsg
, errmsg_len
,
656 "There is no device named \"%s\".\n(%s)",
657 iface
, open_status_str
);
660 case CAP_DEVICE_OPEN_ERROR_RFMON_NOTSUP
:
661 snprintf(errmsg
, errmsg_len
,
662 "Capturing in monitor mode is not supported on device \"%s\".\n(%s)",
663 iface
, open_status_str
);
666 case CAP_DEVICE_OPEN_ERROR_PERM_DENIED
:
667 snprintf(errmsg
, errmsg_len
,
668 "You do not have permission to capture on device \"%s\".\n(%s)",
669 iface
, open_status_str
);
672 case CAP_DEVICE_OPEN_ERROR_IFACE_NOT_UP
:
673 snprintf(errmsg
, errmsg_len
,
674 "Device \"%s\" is not up.\n(%s)",
675 iface
, open_status_str
);
678 case CAP_DEVICE_OPEN_ERROR_PROMISC_PERM_DENIED
:
679 snprintf(errmsg
, errmsg_len
,
680 "You do not have permission to capture in promiscuous mode on device \"%s\".\n(%s)",
681 iface
, open_status_str
);
684 case CAP_DEVICE_OPEN_ERROR_OTHER
:
686 snprintf(errmsg
, errmsg_len
,
687 "The capture session could not be initiated on capture device \"%s\".\n(%s)",
688 iface
, open_status_str
);
691 snprintf(secondary_errmsg
, secondary_errmsg_len
, "%s",
692 get_pcap_failure_secondary_error_message(open_status
, open_status_str
));
696 compile_capture_filter(const char *iface
, pcap_t
*pcap_h
,
697 struct bpf_program
*fcode
, const char *cfilter
)
699 bpf_u_int32 netnum
, netmask
;
700 char lookup_net_err_str
[PCAP_ERRBUF_SIZE
];
702 if (pcap_lookupnet(iface
, &netnum
, &netmask
, lookup_net_err_str
) < 0) {
704 * Well, we can't get the netmask for this interface; it's used
705 * only for filters that check for broadcast IP addresses, so
706 * we just punt and use 0. It might be nice to warn the user,
707 * but that's a pain in a GUI application, as it'd involve popping
708 * up a message box, and it's not clear how often this would make
709 * a difference (only filters that check for IP broadcast addresses
713 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
718 * Sigh. Older versions of libpcap don't properly declare the
719 * third argument to pcap_compile() as a const pointer. Cast
723 if (pcap_compile(pcap_h
, fcode
, (char *)cfilter
, 1, netmask
) < 0)
730 show_filter_code(capture_options
*capture_opts
)
732 interface_options
*interface_opts
;
734 cap_device_open_status open_status
;
735 char open_status_str
[PCAP_ERRBUF_SIZE
];
736 char errmsg
[MSG_MAX_LENGTH
+1];
737 char secondary_errmsg
[MSG_MAX_LENGTH
+1];
738 struct bpf_program fcode
;
739 struct bpf_insn
*insn
;
743 for (j
= 0; j
< capture_opts
->ifaces
->len
; j
++) {
744 interface_opts
= &g_array_index(capture_opts
->ifaces
, interface_options
, j
);
745 pcap_h
= open_capture_device(capture_opts
, interface_opts
,
746 CAP_READ_TIMEOUT
, &open_status
, &open_status_str
);
747 if (pcap_h
== NULL
) {
748 /* Open failed; get messages */
749 get_capture_device_open_failure_messages(open_status
, open_status_str
,
750 interface_opts
->name
,
751 errmsg
, sizeof errmsg
,
753 sizeof secondary_errmsg
);
754 /* And report them */
755 report_capture_error(errmsg
, secondary_errmsg
);
759 /* Set the link-layer type. */
760 if (!set_pcap_datalink(pcap_h
, interface_opts
->linktype
, interface_opts
->name
,
761 errmsg
, sizeof errmsg
,
762 secondary_errmsg
, sizeof secondary_errmsg
)) {
764 report_capture_error(errmsg
, secondary_errmsg
);
768 /* OK, try to compile the capture filter. */
769 if (!compile_capture_filter(interface_opts
->name
, pcap_h
, &fcode
,
770 interface_opts
->cfilter
)) {
771 snprintf(errmsg
, sizeof(errmsg
), "%s", pcap_geterr(pcap_h
));
773 report_cfilter_error(capture_opts
, j
, errmsg
);
778 /* Now print the filter code. */
779 insn
= fcode
.bf_insns
;
781 for (i
= 0; i
< fcode
.bf_len
; insn
++, i
++)
782 printf("%s\n", bpf_image(insn
, i
));
784 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
785 /* to remove any suid privileges. */
786 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
787 /* (euid/egid have already previously been set to ruid/rgid. */
788 /* (See comment in main() for details) */
789 /* XXX - On Linux, if we're capturing on a mac80211 device and enabling */
790 /* rfmon via libpcap with libnl support, that creates a new monitor mode */
791 /* device that libpcap will attempt to delete when capture is done. That */
792 /* will fail with EPERM because we dropped privileges. */
794 relinquish_special_privs_perm();
796 relinquish_all_capabilities();
799 /* Let our parent know we succeeded. */
800 sync_pipe_write_string_msg(sync_pipe_fd
, SP_SUCCESS
, NULL
);
806 print_machine_readable_if_capabilities(json_dumper
*dumper
, if_capabilities_t
*caps
, int queries
);
809 * Output a machine readable list of the interfaces
810 * This list is retrieved by the sync_interface_list_open() function
811 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
814 print_machine_readable_interfaces(GList
*if_list
, int caps_queries
, bool print_statistics
)
820 char addr_str
[WS_INET6_ADDRSTRLEN
];
823 json_dumper dumper
= {
824 .output_string
= g_string_new(NULL
),
825 .flags
= JSON_DUMPER_FLAGS_NO_DEBUG
,
826 // Don't abort on failure
828 json_dumper_begin_array(&dumper
);
831 * Print the contents of the if_entry struct in a parseable format (JSON)
833 for (if_entry
= g_list_first(if_list
); if_entry
!= NULL
;
834 if_entry
= g_list_next(if_entry
)) {
835 if_info
= (if_info_t
*)if_entry
->data
;
837 json_dumper_begin_object(&dumper
);
838 json_dumper_set_member_name(&dumper
, if_info
->name
);
840 json_dumper_begin_object(&dumper
);
842 json_dumper_set_member_name(&dumper
, "friendly_name");
843 json_dumper_value_string(&dumper
, if_info
->friendly_name
);
845 json_dumper_set_member_name(&dumper
, "vendor_description");
846 json_dumper_value_string(&dumper
, if_info
->vendor_description
);
848 json_dumper_set_member_name(&dumper
, "type");
849 json_dumper_value_anyf(&dumper
, "%i", if_info
->type
);
851 json_dumper_set_member_name(&dumper
, "addrs");
853 json_dumper_begin_array(&dumper
);
854 for (addr
= g_slist_nth(if_info
->addrs
, 0); addr
!= NULL
;
855 addr
= g_slist_next(addr
)) {
857 if_addr
= (if_addr_t
*)addr
->data
;
858 switch(if_addr
->ifat_type
) {
860 json_dumper_value_string(&dumper
, ws_inet_ntop4(&if_addr
->addr
.ip4_addr
, addr_str
, sizeof(addr_str
)));
863 json_dumper_value_string(&dumper
, ws_inet_ntop6(&if_addr
->addr
.ip6_addr
, addr_str
, sizeof(addr_str
)));
866 json_dumper_value_anyf(&dumper
, "<type unknown %i>", if_addr
->ifat_type
);
869 json_dumper_end_array(&dumper
);
871 json_dumper_set_member_name(&dumper
, "loopback");
872 json_dumper_value_anyf(&dumper
, "%s", if_info
->loopback
? "true" : "false");
874 json_dumper_set_member_name(&dumper
, "extcap");
875 json_dumper_value_string(&dumper
, if_info
->extcap
);
877 if (if_info
->caps
&& caps_queries
) {
878 json_dumper_set_member_name(&dumper
, "caps");
879 json_dumper_begin_object(&dumper
);
880 print_machine_readable_if_capabilities(&dumper
, if_info
->caps
, caps_queries
);
881 json_dumper_end_object(&dumper
);
883 json_dumper_end_object(&dumper
);
884 json_dumper_end_object(&dumper
);
886 json_dumper_end_array(&dumper
);
887 if (json_dumper_finish(&dumper
)) {
890 if (print_statistics
) {
891 sync_pipe_write_string_msg(sync_pipe_fd
, SP_IFACE_LIST
, dumper
.output_string
->str
);
893 /* Let our parent know we succeeded. */
894 sync_pipe_write_string_msg(sync_pipe_fd
, SP_SUCCESS
, NULL
);
895 printf("%s", dumper
.output_string
->str
);
898 printf("%s", dumper
.output_string
->str
);
903 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd
, "Unexpected JSON error", "");
905 cmdarg_err("Unexpected JSON error");
908 g_string_free(dumper
.output_string
, TRUE
);
913 * If you change the machine-readable output format of this function,
914 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
917 print_machine_readable_if_capabilities(json_dumper
*dumper
, if_capabilities_t
*caps
, int queries
)
919 GList
*lt_entry
, *ts_entry
;
920 const char *desc_str
;
922 json_dumper_set_member_name(dumper
, "status");
923 json_dumper_value_anyf(dumper
, "%i", caps
->status
);
924 if (caps
->primary_msg
) {
925 json_dumper_set_member_name(dumper
, "primary_msg");
926 json_dumper_value_string(dumper
, caps
->primary_msg
);
929 if (queries
& CAPS_QUERY_LINK_TYPES
) {
930 json_dumper_set_member_name(dumper
, "rfmon");
931 json_dumper_value_anyf(dumper
, "%s", caps
->can_set_rfmon
? "true" : "false");
932 json_dumper_set_member_name(dumper
, "data_link_types");
933 json_dumper_begin_array(dumper
);
934 for (lt_entry
= caps
->data_link_types
; lt_entry
!= NULL
;
935 lt_entry
= g_list_next(lt_entry
)) {
936 data_link_info_t
*data_link_info
= (data_link_info_t
*)lt_entry
->data
;
937 if (data_link_info
->description
!= NULL
)
938 desc_str
= data_link_info
->description
;
940 desc_str
= "(not supported)";
941 json_dumper_begin_object(dumper
);
942 json_dumper_set_member_name(dumper
, "dlt");
943 json_dumper_value_anyf(dumper
, "%d", data_link_info
->dlt
);
944 json_dumper_set_member_name(dumper
, "name");
945 json_dumper_value_string(dumper
, data_link_info
->name
);
946 json_dumper_set_member_name(dumper
, "description");
947 json_dumper_value_string(dumper
, desc_str
);
948 json_dumper_end_object(dumper
);
950 json_dumper_end_array(dumper
);
952 json_dumper_set_member_name(dumper
, "data_link_types_rfmon");
953 json_dumper_begin_array(dumper
);
954 for (lt_entry
= caps
->data_link_types_rfmon
; lt_entry
!= NULL
;
955 lt_entry
= g_list_next(lt_entry
)) {
956 data_link_info_t
*data_link_info
= (data_link_info_t
*)lt_entry
->data
;
957 if (data_link_info
->description
!= NULL
)
958 desc_str
= data_link_info
->description
;
960 desc_str
= "(not supported)";
961 json_dumper_begin_object(dumper
);
962 json_dumper_set_member_name(dumper
, "dlt");
963 json_dumper_value_anyf(dumper
, "%d", data_link_info
->dlt
);
964 json_dumper_set_member_name(dumper
, "name");
965 json_dumper_value_string(dumper
, data_link_info
->name
);
966 json_dumper_set_member_name(dumper
, "description");
967 json_dumper_value_string(dumper
, desc_str
);
968 json_dumper_end_object(dumper
);
970 json_dumper_end_array(dumper
);
972 if (queries
& CAPS_QUERY_TIMESTAMP_TYPES
) {
973 json_dumper_set_member_name(dumper
, "timestamp_types");
974 json_dumper_begin_array(dumper
);
975 for (ts_entry
= caps
->timestamp_types
; ts_entry
!= NULL
;
976 ts_entry
= g_list_next(ts_entry
)) {
977 timestamp_info_t
*timestamp
= (timestamp_info_t
*)ts_entry
->data
;
978 if (timestamp
->description
!= NULL
)
979 desc_str
= timestamp
->description
;
982 json_dumper_begin_object(dumper
);
983 json_dumper_set_member_name(dumper
, "name");
984 json_dumper_value_string(dumper
, timestamp
->name
);
985 json_dumper_set_member_name(dumper
, "description");
986 json_dumper_value_string(dumper
, desc_str
);
987 json_dumper_end_object(dumper
);
989 json_dumper_end_array(dumper
);
998 /* Print the number of packets captured for each interface until we're killed. */
1000 print_statistics_loop(bool machine_readable
)
1002 GList
*if_list
, *if_entry
, *stat_list
= NULL
, *stat_entry
;
1008 char errbuf
[PCAP_ERRBUF_SIZE
];
1009 struct pcap_stat ps
;
1011 if_list
= get_interface_list(&err
, &err_str
);
1012 if (if_list
== NULL
) {
1014 cmdarg_err("There are no interfaces on which a capture can be done");
1015 err
= WS_EXIT_NO_INTERFACES
;
1018 cmdarg_err("%s", err_str
);
1024 for (if_entry
= g_list_first(if_list
); if_entry
!= NULL
; if_entry
= g_list_next(if_entry
)) {
1025 if_info
= (if_info_t
*)if_entry
->data
;
1028 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
1029 * connections. We avoid collecting stats on them.
1031 if (!strncmp(if_info
->name
, "nf", 2)) {
1032 ws_debug("Skipping interface %s for stats", if_info
->name
);
1037 #ifdef HAVE_PCAP_OPEN
1039 * If we're opening a remote device, use pcap_open(); that's currently
1040 * the only open routine that supports remote devices.
1042 if (strncmp(if_info
->name
, "rpcap://", 8) == 0)
1043 pch
= pcap_open(if_info
->name
, MIN_PACKET_SIZE
, 0, 0, NULL
, errbuf
);
1046 pch
= pcap_open_live(if_info
->name
, MIN_PACKET_SIZE
, 0, 0, errbuf
);
1049 if_stat
= g_new(if_stat_t
, 1);
1050 if_stat
->name
= g_strdup(if_info
->name
);
1052 stat_list
= g_list_append(stat_list
, if_stat
);
1057 cmdarg_err("There are no interfaces on which a capture can be done");
1061 if (capture_child
) {
1062 /* Let our parent know we succeeded. */
1063 sync_pipe_write_string_msg(sync_pipe_fd
, SP_SUCCESS
, NULL
);
1066 if (!machine_readable
) {
1067 printf("%-15s %10s %10s\n", "Interface", "Received",
1071 global_ld
.go
= true;
1072 while (global_ld
.go
) {
1073 for (stat_entry
= g_list_first(stat_list
); stat_entry
!= NULL
; stat_entry
= g_list_next(stat_entry
)) {
1074 if_stat
= (if_stat_t
*)stat_entry
->data
;
1075 /* XXX - what if this fails? */
1076 if (pcap_stats(if_stat
->pch
, &ps
) == 0) {
1077 if (!machine_readable
) {
1078 printf("%-15s %10u %10u\n", if_stat
->name
,
1079 ps
.ps_recv
, ps
.ps_drop
);
1081 printf("%s\t%u\t%u\n", if_stat
->name
,
1082 ps
.ps_recv
, ps
.ps_drop
);
1088 /* If we have a dummy signal pipe check it */
1089 if (!signal_pipe_check_running()) {
1090 global_ld
.go
= false;
1098 /* XXX - Not reached. Should we look for 'q' in stdin? */
1099 for (stat_entry
= g_list_first(stat_list
); stat_entry
!= NULL
; stat_entry
= g_list_next(stat_entry
)) {
1100 if_stat
= (if_stat_t
*)stat_entry
->data
;
1101 pcap_close(if_stat
->pch
);
1102 g_free(if_stat
->name
);
1105 g_list_free(stat_list
);
1106 free_interface_list(if_list
);
1114 capture_cleanup_handler(DWORD dwCtrlType
)
1116 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1117 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1118 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1119 like SIGTERM at least when the machine's shutting down.
1121 For now, if we're running as a command rather than a capture child,
1122 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1123 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1124 in that way on UN*X.
1126 If we're not running as a capture child, we might be running as
1127 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1128 user logs out. (XXX - can we explicitly check whether we're
1129 running as a service?) */
1131 ws_info("Console: Control signal");
1132 ws_debug("Console: Control signal, CtrlType: %lu", dwCtrlType
);
1134 /* Keep capture running if we're a service and a user logs off */
1135 if (capture_child
|| (dwCtrlType
!= CTRL_LOGOFF_EVENT
)) {
1136 capture_loop_stop();
1144 capture_cleanup_handler(int signum _U_
)
1146 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1147 SIGTERM. We assume that if the user wanted it to keep running
1148 after they logged out, they'd have nohupped it. */
1150 capture_loop_stop();
1156 report_capture_count(bool reportit
)
1158 /* Don't print this if we're a capture child. */
1159 if (!capture_child
&& reportit
) {
1160 fprintf(stderr
, "\rPackets captured: %d\n", global_ld
.packets_captured
);
1161 /* stderr could be line buffered */
1169 report_counts_for_siginfo(void)
1171 report_capture_count(quiet
);
1172 infoprint
= false; /* we just reported it */
1176 report_counts_siginfo(int signum _U_
)
1178 int sav_errno
= errno
;
1180 /* If we've been told to delay printing, just set a flag asking
1181 that we print counts (if we're supposed to), otherwise print
1182 the count of packets captured (if we're supposed to). */
1186 report_counts_for_siginfo();
1189 #endif /* SIGINFO */
1192 exit_main(int status
)
1194 ws_cleanup_sockets();
1197 /* can be helpful for debugging */
1198 #ifdef DEBUG_DUMPCAP
1199 printf("Press any key\n");
1205 if (ringbuf_is_initialized()) {
1206 /* save_file is managed by ringbuffer, be sure to release the memory and
1207 * avoid capture_opts_cleanup from double-freeing 'save_file'. */
1209 global_capture_opts
.save_file
= NULL
;
1212 capture_opts_cleanup(&global_capture_opts
);
1218 * If we were linked with libcap (not related to libpcap), make sure we have
1219 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1220 * (See comment in main() for details)
1223 relinquish_privs_except_capture(void)
1226 * Drop any capabilities other than NET_ADMIN and NET_RAW:
1228 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1229 * stuff we don't need (and shouldn't have).
1230 * CAP_NET_RAW: Packet capture (raw sockets).
1232 * If 'started_with_special_privs' (ie: suid) then drop our
1236 cap_t current_caps
= cap_get_proc();
1237 print_caps("Pre set");
1239 cap_t caps
= cap_init(); /* all capabilities initialized to off */
1242 * We can only set capabilities that are in the permitted set.
1243 * If the real or effective user ID is 0 (root), then the file
1244 * inherited and permitted sets are ignored, and our permitted
1245 * set should be all ones - unless the effective ID is 0, the
1246 * real ID is not zero, and the binary has file capabilities,
1247 * in which case the permitted set is only that of the file.
1248 * (E.g., set-user-ID-root + file capabilities.)
1250 * If one or more of the euid, ruid, and saved set user ID are
1251 * all zero and all change to nonzero, then all capabilities are
1252 * cleared from the permitted, effective, and ambient sets.
1253 * PR_SET_KEEPCAPS causes the permitted set to be retained, so
1254 * we can relinquish our changed user ID.
1256 * All capabilities are always cleared from the effective set
1257 * when the euid is changed from 0 to nonzero.
1259 * See capabilities(7).
1261 if (prctl(PR_SET_KEEPCAPS
, 1, 0, 0, 0) == -1) {
1262 cmdarg_err("prctl() fail return: %s", g_strerror(errno
));
1265 if (started_with_special_privs()) {
1266 relinquish_special_privs_perm();
1270 * If cap_set_proc() fails, it leaves the capabilities unchanged.
1271 * So the only way to guarantee that we've dropped all other
1272 * capabilities is to ensure that cap_set_proc() succeeds.
1273 * One option might be to exit if cap_set_proc() fails - but some
1274 * captures will work with CAP_NET_RAW but not CAP_NET_ADMIN.
1277 cap_value_t cap_list
[1] = { CAP_NET_ADMIN
};
1278 int cl_len
= array_length(cap_list
);
1279 cap_flag_value_t value
;
1281 cap_get_flag(current_caps
, cap_list
[0], CAP_PERMITTED
, &value
);
1283 if (value
!= CAP_SET
) {
1284 // XXX - Should we warn here? Some captures will still work.
1286 cap_set_flag(caps
, CAP_PERMITTED
, cl_len
, cap_list
, value
);
1287 // XXX - Do we really need CAP_INHERITABLE?
1288 cap_set_flag(caps
, CAP_INHERITABLE
, cl_len
, cap_list
, value
);
1289 cap_set_flag(caps
, CAP_EFFECTIVE
, cl_len
, cap_list
, value
);
1291 cap_list
[0] = CAP_NET_RAW
;
1292 cap_get_flag(current_caps
, cap_list
[0], CAP_PERMITTED
, &value
);
1294 if (value
!= CAP_SET
) {
1295 // XXX - Should we warn here?
1297 cap_set_flag(caps
, CAP_PERMITTED
, cl_len
, cap_list
, value
);
1298 // XXX - Do we really need CAP_INHERITABLE?
1299 cap_set_flag(caps
, CAP_INHERITABLE
, cl_len
, cap_list
, value
);
1300 cap_set_flag(caps
, CAP_EFFECTIVE
, cl_len
, cap_list
, value
);
1302 if (cap_set_proc(caps
)) {
1304 * This shouldn't happen, we're only trying to set capabilities
1305 * already in the permitted set.
1307 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno
));
1310 print_caps("Post set");
1312 cap_free(current_caps
);
1316 #endif /* HAVE_LIBCAP */
1318 /* Map DLT_ values, as returned by pcap_datalink(), to LINKTYPE_ values,
1319 as are written to capture files.
1321 Most of the time, a DLT_ value and the corresponding LINKYPE_ value
1322 are the same, but there are some cases, where a numeric value as
1323 a DLT_ doesn't uniquely identify a particular link-layer header type,
1324 where they differ, so that the values in files *do* identify
1325 particular link-layer header types. */
1327 /* LINKTYPE_ values that don't match corresponding DLT_ values on
1329 #define LINKTYPE_ATM_RFC1483 100
1330 #define LINKTYPE_RAW 101
1331 #define LINKTYPE_SLIP_BSDOS 102
1332 #define LINKTYPE_PPP_BSDOS 103
1333 #define LINKTYPE_C_HDLC 104
1334 #define LINKTYPE_IEEE802_11 105
1335 #define LINKTYPE_ATM_CLIP 106
1336 #define LINKTYPE_FRELAY 107
1337 #define LINKTYPE_LOOP 108
1338 #define LINKTYPE_ENC 109
1339 #define LINKTYPE_NETBSD_HDLC 112
1340 #define LINKTYPE_PFSYNC 246
1341 #define LINKTYPE_PKTAP 258
1344 dlt_to_linktype(int dlt
)
1346 /* DLT_NULL through DLT_FDDI have the same numeric value on
1347 all platforms, so the corresponding LINKTYPE_s have the
1348 same numeric values. */
1349 if (dlt
>= DLT_NULL
&& dlt
<= DLT_FDDI
)
1352 #if defined(DLT_PFSYNC) && DLT_PFSYNC != LINKTYPE_PFSYNC
1353 /* DLT_PFSYNC has a value on several platforms that's in the
1354 non-matching range, a value on FreeBSD that's in the high
1355 matching range and that's *not* equal to LINKTYPE_PFSYNC,
1356 and has a value on the rmaining platforms that's equal
1357 to LINKTYPE_PFSYNC, which is in the high matching range.
1359 Map it to LINKTYPE_PFSYNC if it's not equal to LINKTYPE_PFSYNC. */
1360 if (dlt
== DLT_PFSYNC
)
1361 return (LINKTYPE_PFSYNC
);
1364 /* DLT_PKTAP is defined as DLT_USER2 - which is in the high
1365 matching range - on Darwin because Apple used DLT_USER2
1366 on systems that users ran, not just as an internal thing.
1368 We map it to LINKTYPE_PKTAP if it's not equal to LINKTYPE_PKTAP
1369 so that DLT_PKTAP captures from Apple machines can be read by
1370 software that either doesn't handle DLT_USER2 or that handles it
1371 as something other than Apple PKTAP. */
1372 #if defined(DLT_PKTAP) && DLT_PKTAP != LINKTYPE_PKTAP
1373 if (dlt
== DLT_PKTAP
)
1374 return (LINKTYPE_PKTAP
);
1377 /* For all other DLT_s with values beyond 104, the value
1378 of the corresponding LINKTYPE_ is the same. */
1382 /* These DLT_ values have different values on different
1383 platforms, so we assigned them LINKTYPE_ values just
1384 below the lower bound of the high matchig range;
1385 those values should never be equal to any DLT_
1386 values, so that should avoid collisions.
1388 That way, for example, "raw IP" packets will have
1389 LINKTYPE_RAW as the code in all savefiles for
1390 which the code that writes them maps to that
1391 value, regardless of the platform on which they
1392 were written, so they should be readable on all
1393 platforms without having to determine on which
1394 platform they were written.
1396 We map the DLT_ values on this platform, whatever
1397 it might be, to the corresponding LINKTYPE_ values. */
1398 #ifdef DLT_ATM_RFC1483
1399 if (dlt
== DLT_ATM_RFC1483
)
1400 return (LINKTYPE_ATM_RFC1483
);
1404 return (LINKTYPE_RAW
);
1406 #ifdef DLT_SLIP_BSDOS
1407 if (dlt
== DLT_SLIP_BSDOS
)
1408 return (LINKTYPE_SLIP_BSDOS
);
1410 #ifdef DLT_PPP_BSDOS
1411 if (dlt
== DLT_PPP_BSDOS
)
1412 return (LINKTYPE_PPP_BSDOS
);
1415 /* These DLT_ values were originally defined on some platform,
1416 and weren't defined on other platforms.
1418 At least some of those values, on at least one platform,
1419 collide with the values of other DLT_s on other platforms,
1420 e.g. DLT_LOOP, so we don't just define them, on all
1421 platforms, as having the same value as on the original
1424 Therefore, we assigned new LINKTYPE_ values to them, and,
1425 on the platforms where they weren't originally defined,
1426 define the DLT_s to have the same value as the corresponding
1429 This means that, for capture files with the original
1430 platform's DLT_ value rather than the LINKTYPE_ value
1431 as a link-layer type, we will recognize those types
1432 on that platform, but not on other platforms. */
1434 /* BSD/OS Frame Relay */
1436 return (LINKTYPE_FRELAY
);
1438 #if defined(DLT_HDLC) && DLT_HDLC != LINKTYPE_NETBSD_HDLC
1440 if (dlt
== DLT_HDLC
)
1441 return (LINKTYPE_NETBSD_HDLC
);
1443 #if defined(DLT_C_HDLC) && DLT_C_HDLC != LINKTYPE_C_HDLC
1444 /* BSD/OS Cisco HDLC */
1445 if (dlt
== DLT_C_HDLC
)
1446 return (LINKTYPE_C_HDLC
);
1448 #if defined(DLT_LOOP) && DLT_LOOP != LINKTYPE_LOOP
1449 /* OpenBSD DLT_LOOP */
1450 if (dlt
== DLT_LOOP
)
1451 return (LINKTYPE_LOOP
);
1453 #if defined(DLT_ENC) && DLT_ENC != LINKTYPE_ENC
1454 /* OpenBSD DLT_ENC */
1456 return (LINKTYPE_ENC
);
1459 /* These DLT_ values are not on all platforms, but, so far,
1460 there don't appear to be any platforms that define
1461 other DLT_s with those values; we map them to
1462 different LINKTYPE_ values anyway, just in case. */
1464 /* Linux ATM Classical IP */
1465 if (dlt
== DLT_ATM_CLIP
)
1466 return (LINKTYPE_ATM_CLIP
);
1469 /* Treat all other DLT_s as having the same value as the
1470 corresponding LINKTYPE_. */
1474 /* Take care of byte order in the libpcap headers read from pipes.
1475 * (function taken from wiretap/libpcap.c) */
1477 cap_pipe_adjust_pcap_header(bool byte_swapped
, struct pcap_hdr
*hdr
, struct pcaprec_hdr
*rechdr
)
1480 /* Byte-swap the record header fields. */
1481 rechdr
->ts_sec
= GUINT32_SWAP_LE_BE(rechdr
->ts_sec
);
1482 rechdr
->ts_usec
= GUINT32_SWAP_LE_BE(rechdr
->ts_usec
);
1483 rechdr
->incl_len
= GUINT32_SWAP_LE_BE(rechdr
->incl_len
);
1484 rechdr
->orig_len
= GUINT32_SWAP_LE_BE(rechdr
->orig_len
);
1487 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1488 swapped, in order to match the BPF header layout.
1490 Unfortunately, some files were, according to a comment in the "libpcap"
1491 source, written with version 2.3 in their headers but without the
1492 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1493 would make no sense - we assume that we need to swap them. */
1494 if (hdr
->version_major
== 2 &&
1495 (hdr
->version_minor
< 3 ||
1496 (hdr
->version_minor
== 3 && rechdr
->incl_len
> rechdr
->orig_len
))) {
1499 temp
= rechdr
->orig_len
;
1500 rechdr
->orig_len
= rechdr
->incl_len
;
1501 rechdr
->incl_len
= temp
;
1505 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1509 cap_pipe_read(int pipe_fd
, char *buf
, size_t sz
, bool from_socket _U_
)
1513 return recv(pipe_fd
, buf
, (int)sz
, 0);
1518 return ws_read(pipe_fd
, buf
, sz
);
1524 * Thread function that reads from a pipe and pushes the data
1525 * to the main application thread.
1528 * XXX Right now we use async queues for basic signaling. The main thread
1529 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1530 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1531 * Iff the read is successful cap_pipe_read pushes an item onto
1532 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1533 * the queues themselves (yet).
1535 * We might want to move some of the cap_pipe_dispatch logic here so that
1536 * we can let cap_thread_read run independently, queuing up multiple reads
1537 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1539 static void *cap_thread_read(void *arg
)
1541 capture_src
*pcap_src
;
1544 DWORD last_err
, bytes_read
;
1549 pcap_src
= (capture_src
*)arg
;
1550 while (pcap_src
->cap_pipe_err
== PIPOK
) {
1551 g_async_queue_pop(pcap_src
->cap_pipe_pending_q
); /* Wait for our cue (ahem) from the main thread */
1552 g_mutex_lock(pcap_src
->cap_pipe_read_mtx
);
1554 while (bytes_read
< pcap_src
->cap_pipe_bytes_to_read
) {
1555 if ((pcap_src
->from_cap_socket
)
1562 b
= cap_pipe_read(pcap_src
->cap_pipe_fd
, pcap_src
->cap_pipe_buf
+bytes_read
,
1563 pcap_src
->cap_pipe_bytes_to_read
- bytes_read
, pcap_src
->from_cap_socket
);
1566 pcap_src
->cap_pipe_err
= PIPEOF
;
1570 pcap_src
->cap_pipe_err
= PIPERR
;
1575 bytes_read
+= (DWORD
)b
;
1581 /* If we try to use read() on a named pipe on Windows with partial
1582 * data it appears to return EOF.
1585 res
= ReadFile(pcap_src
->cap_pipe_h
, pcap_src
->cap_pipe_buf
+bytes_read
,
1586 pcap_src
->cap_pipe_bytes_to_read
- bytes_read
,
1591 last_err
= GetLastError();
1592 if (last_err
== ERROR_MORE_DATA
) {
1594 } else if (last_err
== ERROR_HANDLE_EOF
|| last_err
== ERROR_BROKEN_PIPE
|| last_err
== ERROR_PIPE_NOT_CONNECTED
) {
1595 pcap_src
->cap_pipe_err
= PIPEOF
;
1599 pcap_src
->cap_pipe_err
= PIPERR
;
1602 } else if (b
== 0 && pcap_src
->cap_pipe_bytes_to_read
> 0) {
1603 pcap_src
->cap_pipe_err
= PIPEOF
;
1610 pcap_src
->cap_pipe_bytes_read
= bytes_read
;
1611 if (pcap_src
->cap_pipe_bytes_read
>= pcap_src
->cap_pipe_bytes_to_read
) {
1612 g_async_queue_push(pcap_src
->cap_pipe_done_q
, pcap_src
->cap_pipe_buf
); /* Any non-NULL value will do */
1614 g_mutex_unlock(pcap_src
->cap_pipe_read_mtx
);
1616 /* Post to queue if we didn't read enough data as the main thread waits for the message */
1617 g_mutex_lock(pcap_src
->cap_pipe_read_mtx
);
1618 if (pcap_src
->cap_pipe_bytes_read
< pcap_src
->cap_pipe_bytes_to_read
) {
1619 /* There's still more of the record to read. */
1620 g_async_queue_push(pcap_src
->cap_pipe_done_q
, pcap_src
->cap_pipe_buf
); /* Any non-NULL value will do */
1622 g_mutex_unlock(pcap_src
->cap_pipe_read_mtx
);
1627 * Do a blocking read from a pipe within the main thread, by pushing
1628 * the read onto the pipe queue and then popping it off that queue;
1629 * the pipe will block until the pushed read completes.
1631 * We do it with another thread because we can't use select() on
1632 * pipes on Windows, as we can on UN*Xes, we can only use it on
1636 pipe_read_sync(capture_src
*pcap_src
, void *buf
, DWORD nbytes
)
1638 pcap_src
->cap_pipe_buf
= (char *) buf
;
1639 pcap_src
->cap_pipe_bytes_read
= 0;
1640 pcap_src
->cap_pipe_bytes_to_read
= nbytes
;
1641 /* We don't have to worry about cap_pipe_read_mtx here */
1642 g_async_queue_push(pcap_src
->cap_pipe_pending_q
, pcap_src
->cap_pipe_buf
);
1643 g_async_queue_pop(pcap_src
->cap_pipe_done_q
);
1647 /* Provide select() functionality for a single file descriptor
1648 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1650 * Returns the same values as select.
1653 cap_pipe_select(int pipe_fd
)
1656 struct timeval timeout
;
1659 FD_SET(pipe_fd
, &rfds
);
1661 timeout
.tv_sec
= PIPE_READ_TIMEOUT
/ 1000000;
1662 timeout
.tv_usec
= PIPE_READ_TIMEOUT
% 1000000;
1664 return select(pipe_fd
+1, &rfds
, NULL
, NULL
, &timeout
);
1667 #define DEF_TCP_PORT 19000
1670 cap_open_socket(char *pipename
, capture_src
*pcap_src
, char *errmsg
, size_t errmsgl
)
1672 struct sockaddr_storage sa
;
1676 /* Skip the initial "TCP@" in the pipename. */
1677 if (ws_socket_ptoa(&sa
, pipename
+ 4, DEF_TCP_PORT
) < 0) {
1678 snprintf(errmsg
, errmsgl
,
1679 "The capture session could not be initiated because"
1680 "\"%s\" is not a valid socket specification", pipename
);
1681 pcap_src
->cap_pipe_err
= PIPERR
;
1685 if ((fd
= (int)socket(sa
.ss_family
, SOCK_STREAM
, 0)) < 0) {
1686 snprintf(errmsg
, errmsgl
,
1687 "The capture session could not be initiated because"
1688 " the socket couldn't be created due to the socket error: \n"
1690 " %s", win32strerror(WSAGetLastError()));
1692 " %d: %s", errno
, g_strerror(errno
));
1694 pcap_src
->cap_pipe_err
= PIPERR
;
1698 if (sa
.ss_family
== AF_INET6
)
1699 sa_len
= sizeof(struct sockaddr_in6
);
1701 sa_len
= sizeof(struct sockaddr_in
);
1702 if (connect(fd
, (struct sockaddr
*)&sa
, sa_len
) < 0) {
1703 snprintf(errmsg
, errmsgl
,
1704 "The capture session could not be initiated because"
1705 " the socket couldn't be connected due to the socket error: \n"
1707 " %s", win32strerror(WSAGetLastError()));
1709 " %d: %s", errno
, g_strerror(errno
));
1711 pcap_src
->cap_pipe_err
= PIPERR
;
1713 cap_pipe_close(fd
, true);
1717 pcap_src
->from_cap_socket
= true;
1721 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1725 cap_pipe_close(int pipe_fd
, bool from_socket
)
1729 closesocket(pipe_fd
);
1732 (void) from_socket
; /* Mark unused, similar to Q_UNUSED */
1737 /** Read bytes from a capture source, which is assumed to be a pipe or
1740 * Returns -1, or the number of bytes read similar to read(2).
1741 * Sets pcap_src->cap_pipe_err on error or EOF.
1744 cap_pipe_read_data_bytes(capture_src
*pcap_src
, char *errmsg
, size_t errmsgl
)
1747 int fd
= pcap_src
->cap_pipe_fd
;
1749 DWORD sz
, bytes_read
= 0;
1751 ssize_t sz
, bytes_read
= 0;
1755 #ifdef LOG_CAPTURE_VERBOSE
1756 ws_debug("cap_pipe_read_data_bytes read %lu of %lu",
1757 pcap_src
->cap_pipe_bytes_read
, pcap_src
->cap_pipe_bytes_to_read
);
1759 sz
= pcap_src
->cap_pipe_bytes_to_read
- pcap_src
->cap_pipe_bytes_read
;
1760 while (bytes_read
< sz
) {
1762 snprintf(errmsg
, errmsgl
, "Invalid file descriptor.");
1763 pcap_src
->cap_pipe_err
= PIPNEXIST
;
1767 sel_ret
= cap_pipe_select(fd
);
1769 snprintf(errmsg
, errmsgl
,
1770 "Unexpected error from select: %s.", g_strerror(errno
));
1771 pcap_src
->cap_pipe_err
= PIPERR
;
1773 } else if (sel_ret
> 0) {
1774 b
= cap_pipe_read(fd
, pcap_src
->cap_pipe_databuf
+pcap_src
->cap_pipe_bytes_read
+bytes_read
,
1775 sz
-bytes_read
, pcap_src
->from_cap_socket
);
1778 snprintf(errmsg
, errmsgl
,
1779 "End of file reading from pipe or socket.");
1780 pcap_src
->cap_pipe_err
= PIPEOF
;
1784 * On Windows, we only do this for sockets.
1786 DWORD lastError
= WSAGetLastError();
1788 snprintf(errmsg
, errmsgl
,
1789 "Error reading from pipe or socket: %s.",
1790 win32strerror(lastError
));
1792 snprintf(errmsg
, errmsgl
,
1793 "Error reading from pipe or socket: %s.",
1796 pcap_src
->cap_pipe_err
= PIPERR
;
1801 bytes_read
+= (DWORD
)b
;
1807 pcap_src
->cap_pipe_bytes_read
+= bytes_read
;
1808 #ifdef LOG_CAPTURE_VERBOSE
1809 ws_debug("cap_pipe_read_data_bytes read %lu of %lu",
1810 pcap_src
->cap_pipe_bytes_read
, pcap_src
->cap_pipe_bytes_to_read
);
1815 /* Some forward declarations for breaking up cap_pipe_open_live for pcap and pcapng formats */
1816 static void pcap_pipe_open_live(int fd
, capture_src
*pcap_src
,
1817 struct pcap_hdr
*hdr
,
1818 char *errmsg
, size_t errmsgl
,
1819 char *secondary_errmsg
, size_t secondary_errmsgl
);
1820 static void pcapng_pipe_open_live(int fd
, capture_src
*pcap_src
,
1821 char *errmsg
, size_t errmsgl
);
1822 static int pcapng_pipe_dispatch(loop_data
*ld
, capture_src
*pcap_src
,
1823 char *errmsg
, size_t errmsgl
);
1825 /* For problems that are probably Not Our Fault. */
1826 static char not_our_bug
[] =
1827 "Please report this to the developers of the program writing to the pipe.";
1829 /* Mimic pcap_open_live() for pipe captures
1831 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1832 * open it, and read the header.
1834 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1835 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1837 cap_pipe_open_live(char *pipename
,
1838 capture_src
*pcap_src
,
1840 char *errmsg
, size_t errmsgl
,
1841 char *secondary_errmsg
, size_t secondary_errmsgl
)
1844 ws_statb64 pipe_stat
;
1845 struct sockaddr_un sa
;
1847 uintptr_t extcap_pipe_handle
;
1849 bool extcap_pipe
= false;
1851 int fd
= -1, sel_ret
;
1854 pcap_src
->cap_pipe_fd
= -1;
1856 pcap_src
->cap_pipe_h
= INVALID_HANDLE_VALUE
;
1859 ws_debug("cap_pipe_open_live: %s", pipename
);
1862 * XXX - this blocks until a pcap per-file header has been written to
1863 * the pipe, so it could block indefinitely.
1865 if (strcmp(pipename
, "-") == 0) {
1867 fd
= 0; /* read from stdin */
1869 pcap_src
->cap_pipe_h
= GetStdHandle(STD_INPUT_HANDLE
);
1871 } else if (!strncmp(pipename
, "TCP@", 4)) {
1872 if ((fd
= cap_open_socket(pipename
, pcap_src
, errmsg
, errmsgl
)) < 0) {
1877 if ( g_strrstr(pipename
, EXTCAP_PIPE_PREFIX
) != NULL
)
1880 if (ws_stat64(pipename
, &pipe_stat
) < 0) {
1881 if (errno
== ENOENT
|| errno
== ENOTDIR
)
1882 pcap_src
->cap_pipe_err
= PIPNEXIST
;
1884 snprintf(errmsg
, errmsgl
,
1885 "The capture session could not be initiated "
1886 "due to error getting information on pipe or socket: %s.", g_strerror(errno
));
1887 pcap_src
->cap_pipe_err
= PIPERR
;
1891 if (S_ISFIFO(pipe_stat
.st_mode
)) {
1892 fd
= ws_open(pipename
, O_RDONLY
| O_NONBLOCK
, 0000 /* no creation so don't matter */);
1894 snprintf(errmsg
, errmsgl
,
1895 "The capture session could not be initiated "
1896 "due to error on pipe open: %s.", g_strerror(errno
));
1897 pcap_src
->cap_pipe_err
= PIPERR
;
1900 } else if (S_ISSOCK(pipe_stat
.st_mode
)) {
1901 fd
= socket(AF_UNIX
, SOCK_STREAM
, 0);
1903 snprintf(errmsg
, errmsgl
,
1904 "The capture session could not be initiated "
1905 "due to error on socket create: %s.", g_strerror(errno
));
1906 pcap_src
->cap_pipe_err
= PIPERR
;
1909 sa
.sun_family
= AF_UNIX
;
1911 * The Single UNIX Specification says:
1913 * The size of sun_path has intentionally been left undefined.
1914 * This is because different implementations use different sizes.
1915 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1916 * of 104. Since most implementations originate from BSD versions,
1917 * the size is typically in the range 92 to 108.
1919 * Applications should not assume a particular length for sun_path
1920 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1924 * The <sys/un.h> header shall define the sockaddr_un structure,
1925 * which shall include at least the following members:
1927 * sa_family_t sun_family Address family.
1928 * char sun_path[] Socket pathname.
1930 * so we assume that it's an array, with a specified size,
1931 * and that the size reflects the maximum path length.
1933 if (g_strlcpy(sa
.sun_path
, pipename
, sizeof sa
.sun_path
) > sizeof sa
.sun_path
) {
1934 /* Path name too long */
1935 snprintf(errmsg
, errmsgl
,
1936 "The capture session could not be initiated "
1937 "due to error on socket connect: Path name too long.");
1938 pcap_src
->cap_pipe_err
= PIPERR
;
1942 b
= connect(fd
, (struct sockaddr
*)&sa
, sizeof sa
);
1944 snprintf(errmsg
, errmsgl
,
1945 "The capture session could not be initiated "
1946 "due to error on socket connect: %s.", g_strerror(errno
));
1947 pcap_src
->cap_pipe_err
= PIPERR
;
1952 if (S_ISCHR(pipe_stat
.st_mode
)) {
1954 * Assume the user specified an interface on a system where
1955 * interfaces are in /dev. Pretend we haven't seen it.
1957 pcap_src
->cap_pipe_err
= PIPNEXIST
;
1959 snprintf(errmsg
, errmsgl
,
1960 "The capture session could not be initiated because\n"
1961 "\"%s\" is neither an interface nor a socket nor a pipe.", pipename
);
1962 pcap_src
->cap_pipe_err
= PIPERR
;
1968 if (sscanf(pipename
, EXTCAP_PIPE_PREFIX
"%" SCNuPTR
, &extcap_pipe_handle
) == 1)
1970 /* The client is already connected to extcap pipe.
1971 * We have inherited the handle from parent process.
1974 pcap_src
->cap_pipe_h
= (HANDLE
)extcap_pipe_handle
;
1978 if (!win32_is_pipe_name(pipename
)) {
1979 snprintf(errmsg
, errmsgl
,
1980 "The capture session could not be initiated because\n"
1981 "\"%s\" is neither an interface nor a pipe.", pipename
);
1982 pcap_src
->cap_pipe_err
= PIPNEXIST
;
1986 /* Wait for the pipe to appear */
1988 pcap_src
->cap_pipe_h
= CreateFile(utf_8to16(pipename
), GENERIC_READ
, 0, NULL
,
1989 OPEN_EXISTING
, 0, NULL
);
1991 if (pcap_src
->cap_pipe_h
!= INVALID_HANDLE_VALUE
)
1994 if (GetLastError() != ERROR_PIPE_BUSY
) {
1995 snprintf(errmsg
, errmsgl
,
1996 "The capture session on \"%s\" could not be started "
1997 "due to error on pipe open: %s.",
1998 pipename
, win32strerror(GetLastError()));
1999 pcap_src
->cap_pipe_err
= PIPERR
;
2003 if (!WaitNamedPipe(utf_8to16(pipename
), 30 * 1000)) {
2004 snprintf(errmsg
, errmsgl
,
2005 "The capture session on \"%s\" timed out during "
2007 pipename
, win32strerror(GetLastError()));
2008 pcap_src
->cap_pipe_err
= PIPERR
;
2016 pcap_src
->from_cap_pipe
= true;
2019 * We start with a 2KB buffer for packet data, which should be
2020 * large enough for most regular network packets. We increase it,
2021 * up to the maximum size we allow, as necessary.
2023 pcap_src
->cap_pipe_databuf
= (char*)g_malloc(2048);
2024 pcap_src
->cap_pipe_databuf_size
= 2048;
2027 * Read the first 4 bytes of data from the pipe.
2029 * If a pcap file is being written to it, that will be
2030 * the pcap magic number.
2032 * If a pcapng file is being written to it, that will be
2033 * the block type of the initial SHB.
2037 * On UN*X, we can use select() on pipes or sockets.
2039 * On Windows, we can only use it on sockets; to do non-blocking
2040 * reads from pipes, we currently do reads in a separate thread
2041 * and use GLib asynchronous queues from the main thread to start
2042 * read operations and to wait for them to complete.
2044 if (pcap_src
->from_cap_socket
)
2048 while (bytes_read
< sizeof magic
) {
2049 sel_ret
= cap_pipe_select(fd
);
2051 snprintf(errmsg
, errmsgl
,
2052 "Unexpected error from select: %s.",
2055 } else if (sel_ret
> 0) {
2056 b
= cap_pipe_read(fd
, ((char *)&magic
)+bytes_read
,
2057 sizeof magic
-bytes_read
,
2058 pcap_src
->from_cap_socket
);
2059 /* jump messaging, if extcap had an error, stderr will provide the correct message */
2060 if (extcap_pipe
&& b
<= 0)
2065 snprintf(errmsg
, errmsgl
,
2066 "End of file on pipe magic during open.");
2068 snprintf(errmsg
, errmsgl
,
2069 "Error on pipe magic during open: %s.",
2079 /* Create a thread to read from this pipe */
2080 g_thread_new("cap_pipe_open_live", &cap_thread_read
, pcap_src
);
2082 pipe_read_sync(pcap_src
, &magic
, sizeof(magic
));
2083 /* jump messaging, if extcap had an error, stderr will provide the correct message */
2084 if (pcap_src
->cap_pipe_bytes_read
<= 0 && extcap_pipe
)
2087 if (pcap_src
->cap_pipe_bytes_read
<= 0) {
2088 if (pcap_src
->cap_pipe_bytes_read
== 0)
2089 snprintf(errmsg
, errmsgl
,
2090 "End of file on pipe magic during open.");
2092 snprintf(errmsg
, errmsgl
,
2093 "Error on pipe magic during open: %s.",
2102 case PCAP_NSEC_MAGIC
:
2103 /* This is a pcap file.
2104 The host that wrote it has our byte order, and was running
2105 a program using either standard or ss990417 libpcap. */
2106 pcap_src
->cap_pipe_info
.pcap
.byte_swapped
= false;
2107 pcap_src
->cap_pipe_modified
= false;
2108 pcap_src
->ts_nsec
= magic
== PCAP_NSEC_MAGIC
;
2110 case PCAP_MODIFIED_MAGIC
:
2111 /* This is a pcap file.
2112 The host that wrote it has our byte order, but was running
2113 a program using either ss990915 or ss991029 libpcap. */
2114 pcap_src
->cap_pipe_info
.pcap
.byte_swapped
= false;
2115 pcap_src
->cap_pipe_modified
= true;
2117 case PCAP_SWAPPED_MAGIC
:
2118 case PCAP_SWAPPED_NSEC_MAGIC
:
2119 /* This is a pcap file.
2120 The host that wrote it has a byte order opposite to ours,
2121 and was running a program using either standard or
2122 ss990417 libpcap. */
2123 pcap_src
->cap_pipe_info
.pcap
.byte_swapped
= true;
2124 pcap_src
->cap_pipe_modified
= false;
2125 pcap_src
->ts_nsec
= magic
== PCAP_SWAPPED_NSEC_MAGIC
;
2127 case PCAP_SWAPPED_MODIFIED_MAGIC
:
2128 /* This is a pcap file.
2129 The host that wrote it out has a byte order opposite to
2130 ours, and was running a program using either ss990915
2131 or ss991029 libpcap. */
2132 pcap_src
->cap_pipe_info
.pcap
.byte_swapped
= true;
2133 pcap_src
->cap_pipe_modified
= true;
2135 case BLOCK_TYPE_SHB
:
2136 /* This is a pcapng file. */
2137 pcap_src
->from_pcapng
= true;
2138 pcap_src
->cap_pipe_dispatch
= pcapng_pipe_dispatch
;
2139 pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
= g_array_new(FALSE
, FALSE
, sizeof(uint32_t));
2140 global_capture_opts
.use_pcapng
= true; /* we can only output in pcapng format */
2143 /* Not a pcapng file, and either not a pcap type we know about
2144 or not a pcap file, either. */
2145 snprintf(errmsg
, errmsgl
,
2146 "File type is neither a supported pcap nor pcapng format. (magic = 0x%08x)", magic
);
2147 snprintf(secondary_errmsg
, secondary_errmsgl
, "%s",
2152 if (pcap_src
->from_pcapng
)
2153 pcapng_pipe_open_live(fd
, pcap_src
, errmsg
, errmsgl
);
2155 pcap_pipe_open_live(fd
, pcap_src
, (struct pcap_hdr
*) hdr
, errmsg
, errmsgl
,
2156 secondary_errmsg
, secondary_errmsgl
);
2161 ws_debug("cap_pipe_open_live: error %s", errmsg
);
2162 pcap_src
->cap_pipe_err
= PIPERR
;
2163 cap_pipe_close(fd
, pcap_src
->from_cap_socket
);
2164 pcap_src
->cap_pipe_fd
= -1;
2166 pcap_src
->cap_pipe_h
= INVALID_HANDLE_VALUE
;
2171 * Read the part of the pcap file header that follows the magic
2172 * number (we've already read the magic number).
2175 pcap_pipe_open_live(int fd
,
2176 capture_src
*pcap_src
,
2177 struct pcap_hdr
*hdr
,
2178 char *errmsg
, size_t errmsgl
,
2179 char *secondary_errmsg
, size_t secondary_errmsgl
)
2186 * We're reading from a pcap file. We've already read the magic
2187 * number; read the rest of the header.
2189 * (Note that struct pcap_hdr is a structure for the part of a
2190 * pcap file header *following the magic number*; it does not
2191 * include the magic number itself.)
2194 if (pcap_src
->from_cap_socket
)
2197 /* Keep reading until we get the rest of the header. */
2199 while (bytes_read
< sizeof(struct pcap_hdr
)) {
2200 sel_ret
= cap_pipe_select(fd
);
2202 snprintf(errmsg
, errmsgl
,
2203 "Unexpected error from select: %s.",
2206 } else if (sel_ret
> 0) {
2207 b
= cap_pipe_read(fd
, ((char *)hdr
)+bytes_read
,
2208 sizeof(struct pcap_hdr
) - bytes_read
,
2209 pcap_src
->from_cap_socket
);
2212 snprintf(errmsg
, errmsgl
,
2213 "End of file on pipe header during open.");
2215 snprintf(errmsg
, errmsgl
,
2216 "Error on pipe header during open: %s.",
2218 snprintf(secondary_errmsg
, secondary_errmsgl
,
2228 pipe_read_sync(pcap_src
, hdr
, sizeof(struct pcap_hdr
));
2229 if (pcap_src
->cap_pipe_bytes_read
<= 0) {
2230 if (pcap_src
->cap_pipe_bytes_read
== 0)
2231 snprintf(errmsg
, errmsgl
,
2232 "End of file on pipe header during open.");
2234 snprintf(errmsg
, errmsgl
,
2235 "Error on pipe header header during open: %s.",
2237 snprintf(secondary_errmsg
, secondary_errmsgl
, "%s",
2244 if (pcap_src
->cap_pipe_info
.pcap
.byte_swapped
) {
2245 /* Byte-swap the header fields about which we care. */
2246 hdr
->version_major
= GUINT16_SWAP_LE_BE(hdr
->version_major
);
2247 hdr
->version_minor
= GUINT16_SWAP_LE_BE(hdr
->version_minor
);
2248 hdr
->snaplen
= GUINT32_SWAP_LE_BE(hdr
->snaplen
);
2249 hdr
->network
= GUINT32_SWAP_LE_BE(hdr
->network
);
2252 * The link-layer header type field of the pcap header is
2253 * probably a LINKTYPE_ value, as the vast majority of
2254 * LINKTYPE_ values and their corresponding DLT_ values
2257 * However, in case the file was written by a program
2258 * that used a DLT_ value, rather than a LINKTYPE_ value,
2259 * in one of the cases where the two differ, use dlt_to_linktype()
2260 * to map to a LINKTYPE_ value, just as we use it to map
2261 * the result of pcap_datalink() to a LINKTYPE_ value.
2263 pcap_src
->linktype
= dlt_to_linktype(hdr
->network
);
2264 /* Pick the appropriate maximum packet size for the link type */
2265 switch (pcap_src
->linktype
) {
2267 case 231: /* DLT_DBUS */
2268 pcap_src
->cap_pipe_max_pkt_size
= WTAP_MAX_PACKET_SIZE_DBUS
;
2271 case 279: /* DLT_EBHSCR */
2272 pcap_src
->cap_pipe_max_pkt_size
= WTAP_MAX_PACKET_SIZE_EBHSCR
;
2275 case 249: /* DLT_USBPCAP */
2276 pcap_src
->cap_pipe_max_pkt_size
= WTAP_MAX_PACKET_SIZE_USBPCAP
;
2280 pcap_src
->cap_pipe_max_pkt_size
= WTAP_MAX_PACKET_SIZE_STANDARD
;
2284 if (hdr
->version_major
< 2) {
2285 snprintf(errmsg
, errmsgl
,
2286 "The old pcap format version %d.%d is not supported.",
2287 hdr
->version_major
, hdr
->version_minor
);
2288 snprintf(secondary_errmsg
, secondary_errmsgl
, "%s",
2293 pcap_src
->cap_pipe_fd
= fd
;
2297 ws_debug("pcap_pipe_open_live: error %s", errmsg
);
2298 pcap_src
->cap_pipe_err
= PIPERR
;
2299 cap_pipe_close(fd
, pcap_src
->from_cap_socket
);
2300 pcap_src
->cap_pipe_fd
= -1;
2302 pcap_src
->cap_pipe_h
= INVALID_HANDLE_VALUE
;
2307 * Synchronously read the fixed portion of the pcapng section header block
2308 * (we've already read the pcapng block header).
2311 pcapng_read_shb(capture_src
*pcap_src
,
2315 pcapng_section_header_block_t shb
;
2318 if (pcap_src
->from_cap_socket
)
2321 pcap_src
->cap_pipe_bytes_to_read
= sizeof(pcapng_block_header_t
) + sizeof(pcapng_section_header_block_t
);
2322 if (cap_pipe_read_data_bytes(pcap_src
, errmsg
, errmsgl
) < 0) {
2328 pipe_read_sync(pcap_src
, pcap_src
->cap_pipe_databuf
+ sizeof(pcapng_block_header_t
),
2329 sizeof(pcapng_section_header_block_t
));
2330 if (pcap_src
->cap_pipe_bytes_read
<= 0) {
2331 if (pcap_src
->cap_pipe_bytes_read
== 0)
2332 snprintf(errmsg
, errmsgl
,
2333 "End of file reading from pipe or socket.");
2335 snprintf(errmsg
, errmsgl
,
2336 "Error reading from pipe or socket: %s.",
2340 /* Continuing with STATE_EXPECT_DATA requires reading into cap_pipe_databuf at offset cap_pipe_bytes_read */
2341 pcap_src
->cap_pipe_bytes_read
= sizeof(pcapng_block_header_t
) + sizeof(pcapng_section_header_block_t
);
2344 memcpy(&shb
, pcap_src
->cap_pipe_databuf
+ sizeof(pcapng_block_header_t
), sizeof(pcapng_section_header_block_t
));
2348 ws_debug("pcapng SHB MAGIC");
2350 case PCAPNG_SWAPPED_MAGIC
:
2351 ws_debug("pcapng SHB SWAPPED MAGIC");
2353 * pcapng sources can contain all sorts of block types.
2354 * Rather than add a bunch of complexity to this code (which is
2355 * often privileged), punt and tell the user to swap bytes
2358 * XXX - punting means that the Wireshark test suite must be
2361 * 1) have both little-endian and big-endian versions of
2362 * all pcapng files piped to dumpcap;
2364 * 2) pipe the appropriate file to dumpcap, depending on
2365 * the byte order of the host on which the tests are
2368 * as per comments in bug 15772 and 15754.
2370 * Are we *really* certain that the complexity added would be
2371 * significant enough to make adding it a security risk? And
2372 * why would this code even be running with any elevated
2373 * privileges if you're capturing from a pipe? We should not
2374 * only have given up all additional privileges if we're reading
2375 * from a pipe, we should give them up in such a fashion that
2376 * we can't reclaim them.
2378 #if G_BYTE_ORDER == G_BIG_ENDIAN
2379 #define OUR_ENDIAN "big"
2380 #define IFACE_ENDIAN "little"
2382 #define OUR_ENDIAN "little"
2383 #define IFACE_ENDIAN "big"
2385 snprintf(errmsg
, errmsgl
,
2386 "Interface %u is " IFACE_ENDIAN
" endian but we're " OUR_ENDIAN
" endian.",
2387 pcap_src
->interface_id
);
2390 /* Not a pcapng type we know about, or not pcapng at all. */
2391 snprintf(errmsg
, errmsgl
,
2392 "Unrecognized pcapng format or not pcapng data.");
2396 pcap_src
->cap_pipe_max_pkt_size
= WTAP_MAX_PACKET_SIZE_STANDARD
;
2398 /* Setup state to capture any options following the section header block */
2399 pcap_src
->cap_pipe_state
= STATE_EXPECT_DATA
;
2405 * Save IDB blocks for playback whenever we change output files, and
2406 * fix LINKTYPE_ values that are really platform-dependent DLT_ values.
2407 * Rewrite EPB and ISB interface IDs.
2410 pcapng_adjust_block(capture_src
*pcap_src
, const pcapng_block_header_t
*bh
, uint8_t *pd
)
2412 switch(bh
->block_type
) {
2413 case BLOCK_TYPE_SHB
:
2415 if (global_ld
.pcapng_passthrough
) {
2417 * We have a single pcapng input. We pass the SHB through when
2418 * writing a single output file and for the first ring buffer
2419 * file. We need to save it for the second and subsequent ring
2422 g_free(global_ld
.saved_shb
);
2423 global_ld
.saved_shb
= (uint8_t *) g_memdup2(pd
, bh
->block_total_length
);
2426 * We're dealing with one section at a time, so we can (and must)
2427 * get rid of our old IDBs.
2429 for (unsigned i
= 0; i
< global_ld
.saved_idbs
->len
; i
++) {
2430 saved_idb_t
*idb_source
= &g_array_index(global_ld
.saved_idbs
, saved_idb_t
, i
);
2431 g_free(idb_source
->idb
);
2433 g_array_set_size(global_ld
.saved_idbs
, 0);
2436 * We have a new SHB from this capture source. We need to keep
2437 * global_ld.saved_idbs intact, so we mark IDBs we previously
2438 * collected from this source as deleted.
2440 for (unsigned i
= 0; i
< pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
->len
; i
++) {
2441 uint32_t iface_id
= g_array_index(pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
, uint32_t, i
);
2442 saved_idb_t
*idb_source
= &g_array_index(global_ld
.saved_idbs
, saved_idb_t
, iface_id
);
2443 ws_assert(idb_source
->interface_id
== pcap_src
->interface_id
);
2444 g_free(idb_source
->idb
);
2445 memset(idb_source
, 0, sizeof(saved_idb_t
));
2446 idb_source
->deleted
= true;
2447 ws_debug("%s: deleted pcapng IDB %u", G_STRFUNC
, iface_id
);
2450 g_array_set_size(pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
, 0);
2453 case BLOCK_TYPE_IDB
:
2456 * Always gather IDBs. We can remove them or mark them as deleted
2457 * when we get a new SHB.
2459 saved_idb_t idb_source
= { 0 };
2460 idb_source
.interface_id
= pcap_src
->interface_id
;
2461 idb_source
.idb_len
= bh
->block_total_length
;
2462 idb_source
.idb
= (uint8_t *) g_memdup2(pd
, idb_source
.idb_len
);
2463 g_array_append_val(global_ld
.saved_idbs
, idb_source
);
2464 uint32_t iface_id
= global_ld
.saved_idbs
->len
- 1;
2465 g_array_append_val(pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
, iface_id
);
2466 ws_debug("%s: mapped pcapng IDB %u -> %u from source %u",
2467 G_STRFUNC
, pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
->len
- 1, iface_id
, pcap_src
->interface_id
);
2470 case BLOCK_TYPE_EPB
:
2471 case BLOCK_TYPE_ISB
:
2473 if (global_ld
.pcapng_passthrough
) {
2474 /* Our input and output interface IDs are the same. */
2477 /* The interface ID is the first 32-bit field after the BH for both EPBs and ISBs. */
2479 memcpy(&iface_id
, pd
+ sizeof(pcapng_block_header_t
), 4);
2480 if (iface_id
< pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
->len
) {
2481 memcpy(pd
+ sizeof(pcapng_block_header_t
),
2482 &g_array_index(pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
, uint32_t, iface_id
), 4);
2484 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
);
2497 * Return true if the block contains packet, event, or log data. Return false otherwise.
2499 static bool is_data_block(uint32_t block_type
)
2501 // Any block types that lead to calling wtap_read_packet_bytes in
2502 // wiretap/pcapng.c should be listed here.
2503 switch (block_type
) {
2505 case BLOCK_TYPE_EPB
:
2506 case BLOCK_TYPE_SPB
:
2507 case BLOCK_TYPE_SYSTEMD_JOURNAL_EXPORT
:
2508 case BLOCK_TYPE_SYSDIG_EVENT
:
2509 case BLOCK_TYPE_SYSDIG_EVENT_V2
:
2510 case BLOCK_TYPE_SYSDIG_EVENT_V2_LARGE
:
2519 * Read the part of the initial pcapng SHB following the block type
2520 * (we've already read the block type).
2523 pcapng_pipe_open_live(int fd
,
2524 capture_src
*pcap_src
,
2528 uint32_t type
= BLOCK_TYPE_SHB
;
2529 pcapng_block_header_t
*bh
= &pcap_src
->cap_pipe_info
.pcapng
.bh
;
2531 ws_debug("pcapng_pipe_open_live: fd %d", fd
);
2534 * A pcapng block begins with the block type followed by the block
2535 * total length; we've already read the block type, now read the
2540 * On UN*X, we can use select() on pipes or sockets.
2542 * On Windows, we can only use it on sockets; to do non-blocking
2543 * reads from pipes, we currently do reads in a separate thread
2544 * and use GLib asynchronous queues from the main thread to start
2545 * read operations and to wait for them to complete.
2547 if (pcap_src
->from_cap_socket
)
2550 memcpy(pcap_src
->cap_pipe_databuf
, &type
, sizeof(uint32_t));
2551 pcap_src
->cap_pipe_bytes_read
= sizeof(uint32_t);
2552 pcap_src
->cap_pipe_bytes_to_read
= sizeof(pcapng_block_header_t
);
2553 pcap_src
->cap_pipe_fd
= fd
;
2554 if (cap_pipe_read_data_bytes(pcap_src
, errmsg
, errmsgl
) < 0) {
2557 memcpy(bh
, pcap_src
->cap_pipe_databuf
, sizeof(pcapng_block_header_t
));
2561 g_thread_new("cap_pipe_open_live", &cap_thread_read
, pcap_src
);
2563 bh
->block_type
= type
;
2564 pipe_read_sync(pcap_src
, &bh
->block_total_length
,
2565 sizeof(bh
->block_total_length
));
2566 if (pcap_src
->cap_pipe_bytes_read
<= 0) {
2567 if (pcap_src
->cap_pipe_bytes_read
== 0)
2568 snprintf(errmsg
, errmsgl
,
2569 "End of file reading from pipe or socket.");
2571 snprintf(errmsg
, errmsgl
,
2572 "Error reading from pipe or socket: %s.",
2576 pcap_src
->cap_pipe_bytes_read
= sizeof(pcapng_block_header_t
);
2577 memcpy(pcap_src
->cap_pipe_databuf
, bh
, sizeof(pcapng_block_header_t
));
2578 pcap_src
->cap_pipe_fd
= fd
;
2581 if ((bh
->block_total_length
& 0x03) != 0) {
2582 snprintf(errmsg
, errmsgl
,
2583 "block_total_length read from pipe is %u, which is not a multiple of 4.",
2584 bh
->block_total_length
);
2587 if (pcapng_read_shb(pcap_src
, errmsg
, errmsgl
)) {
2594 ws_debug("pcapng_pipe_open_live: error %s", errmsg
);
2595 pcap_src
->cap_pipe_err
= PIPERR
;
2596 cap_pipe_close(fd
, pcap_src
->from_cap_socket
);
2597 pcap_src
->cap_pipe_fd
= -1;
2599 pcap_src
->cap_pipe_h
= INVALID_HANDLE_VALUE
;
2603 /* We read one record from the pipe, take care of byte order in the record
2604 * header, write the record to the capture file, and update capture statistics. */
2606 pcap_pipe_dispatch(loop_data
*ld
, capture_src
*pcap_src
, char *errmsg
, size_t errmsgl
)
2608 struct pcap_pkthdr phdr
;
2609 enum { PD_REC_HDR_READ
, PD_DATA_READ
, PD_PIPE_EOF
, PD_PIPE_ERR
,
2615 unsigned new_bufsize
;
2616 pcap_pipe_info_t
*pcap_info
= &pcap_src
->cap_pipe_info
.pcap
;
2618 #ifdef LOG_CAPTURE_VERBOSE
2619 ws_debug("pcap_pipe_dispatch");
2622 switch (pcap_src
->cap_pipe_state
) {
2624 case STATE_EXPECT_REC_HDR
:
2626 if (g_mutex_trylock(pcap_src
->cap_pipe_read_mtx
)) {
2629 pcap_src
->cap_pipe_state
= STATE_READ_REC_HDR
;
2630 pcap_src
->cap_pipe_bytes_to_read
= pcap_src
->cap_pipe_modified
?
2631 sizeof(struct pcaprec_modified_hdr
) : sizeof(struct pcaprec_hdr
);
2632 pcap_src
->cap_pipe_bytes_read
= 0;
2635 pcap_src
->cap_pipe_buf
= (char *) &pcap_info
->rechdr
;
2636 g_async_queue_push(pcap_src
->cap_pipe_pending_q
, pcap_src
->cap_pipe_buf
);
2637 g_mutex_unlock(pcap_src
->cap_pipe_read_mtx
);
2642 case STATE_READ_REC_HDR
:
2644 if (pcap_src
->from_cap_socket
)
2647 b
= cap_pipe_read(pcap_src
->cap_pipe_fd
, ((char *)&pcap_info
->rechdr
)+pcap_src
->cap_pipe_bytes_read
,
2648 pcap_src
->cap_pipe_bytes_to_read
- pcap_src
->cap_pipe_bytes_read
, pcap_src
->from_cap_socket
);
2651 result
= PD_PIPE_EOF
;
2653 result
= PD_PIPE_ERR
;
2657 pcap_src
->cap_pipe_bytes_read
+= (DWORD
)b
;
2659 pcap_src
->cap_pipe_bytes_read
+= b
;
2664 q_status
= g_async_queue_timeout_pop(pcap_src
->cap_pipe_done_q
, PIPE_READ_TIMEOUT
);
2665 if (pcap_src
->cap_pipe_err
== PIPEOF
) {
2666 result
= PD_PIPE_EOF
;
2668 } else if (pcap_src
->cap_pipe_err
== PIPERR
) {
2669 result
= PD_PIPE_ERR
;
2677 if (pcap_src
->cap_pipe_bytes_read
< pcap_src
->cap_pipe_bytes_to_read
) {
2678 /* There's still more of the pcap packet header to read. */
2681 result
= PD_REC_HDR_READ
;
2684 case STATE_EXPECT_DATA
:
2686 if (g_mutex_trylock(pcap_src
->cap_pipe_read_mtx
)) {
2689 pcap_src
->cap_pipe_state
= STATE_READ_DATA
;
2690 pcap_src
->cap_pipe_bytes_to_read
= pcap_info
->rechdr
.hdr
.incl_len
;
2691 pcap_src
->cap_pipe_bytes_read
= 0;
2694 pcap_src
->cap_pipe_buf
= pcap_src
->cap_pipe_databuf
;
2695 g_async_queue_push(pcap_src
->cap_pipe_pending_q
, pcap_src
->cap_pipe_buf
);
2696 g_mutex_unlock(pcap_src
->cap_pipe_read_mtx
);
2701 case STATE_READ_DATA
:
2703 if (pcap_src
->from_cap_socket
)
2706 b
= cap_pipe_read(pcap_src
->cap_pipe_fd
,
2707 pcap_src
->cap_pipe_databuf
+pcap_src
->cap_pipe_bytes_read
,
2708 pcap_src
->cap_pipe_bytes_to_read
- pcap_src
->cap_pipe_bytes_read
,
2709 pcap_src
->from_cap_socket
);
2712 result
= PD_PIPE_EOF
;
2714 result
= PD_PIPE_ERR
;
2718 pcap_src
->cap_pipe_bytes_read
+= (DWORD
)b
;
2720 pcap_src
->cap_pipe_bytes_read
+= b
;
2726 q_status
= g_async_queue_timeout_pop(pcap_src
->cap_pipe_done_q
, PIPE_READ_TIMEOUT
);
2727 if (pcap_src
->cap_pipe_err
== PIPEOF
) {
2728 result
= PD_PIPE_EOF
;
2730 } else if (pcap_src
->cap_pipe_err
== PIPERR
) {
2731 result
= PD_PIPE_ERR
;
2739 if (pcap_src
->cap_pipe_bytes_read
< pcap_src
->cap_pipe_bytes_to_read
) {
2740 /* There's still more of the pcap packet data to read. */
2743 result
= PD_DATA_READ
;
2747 snprintf(errmsg
, errmsgl
,
2748 "pcap_pipe_dispatch: invalid state");
2751 } /* switch (pcap_src->cap_pipe_state) */
2754 * We've now read as much data as we were expecting, so process it.
2758 case PD_REC_HDR_READ
:
2760 * We've read the packet header, so we know the captured length,
2761 * and thus the number of packet data bytes. Take care of byte order.
2763 cap_pipe_adjust_pcap_header(pcap_src
->cap_pipe_info
.pcap
.byte_swapped
, &pcap_info
->hdr
,
2764 &pcap_info
->rechdr
.hdr
);
2765 if (pcap_info
->rechdr
.hdr
.incl_len
> pcap_src
->cap_pipe_max_pkt_size
) {
2767 * The record contains more data than the advertised/allowed in the
2768 * pcap header, do not try to read more data (do not change to
2769 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2770 * instead stop with an error.
2772 snprintf(errmsg
, errmsgl
, "Frame %u too long (%d bytes)",
2773 ld
->packets_captured
+1, pcap_info
->rechdr
.hdr
.incl_len
);
2777 if (pcap_info
->rechdr
.hdr
.incl_len
> pcap_src
->cap_pipe_databuf_size
) {
2779 * Grow the buffer to the packet size, rounded up to a power of
2782 new_bufsize
= pcap_info
->rechdr
.hdr
.incl_len
;
2784 * https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2787 new_bufsize
|= new_bufsize
>> 1;
2788 new_bufsize
|= new_bufsize
>> 2;
2789 new_bufsize
|= new_bufsize
>> 4;
2790 new_bufsize
|= new_bufsize
>> 8;
2791 new_bufsize
|= new_bufsize
>> 16;
2793 pcap_src
->cap_pipe_databuf
= (char*)g_realloc(pcap_src
->cap_pipe_databuf
, new_bufsize
);
2794 pcap_src
->cap_pipe_databuf_size
= new_bufsize
;
2797 if (pcap_info
->rechdr
.hdr
.incl_len
) {
2799 * The record has some data following the header, try
2800 * to read it next time.
2802 pcap_src
->cap_pipe_state
= STATE_EXPECT_DATA
;
2807 * No data following the record header? Then no more data needs to be
2808 * read and we will fallthrough and emit an empty packet.
2814 * We've read the full contents of the packet record.
2815 * Fill in a "struct pcap_pkthdr", and process the packet.
2817 phdr
.ts
.tv_sec
= pcap_info
->rechdr
.hdr
.ts_sec
;
2818 phdr
.ts
.tv_usec
= pcap_info
->rechdr
.hdr
.ts_usec
;
2819 phdr
.caplen
= pcap_info
->rechdr
.hdr
.incl_len
;
2820 phdr
.len
= pcap_info
->rechdr
.hdr
.orig_len
;
2823 capture_loop_queue_packet_cb((uint8_t *)pcap_src
, &phdr
, pcap_src
->cap_pipe_databuf
);
2825 capture_loop_write_packet_cb((uint8_t *)pcap_src
, &phdr
, pcap_src
->cap_pipe_databuf
);
2829 * Now we want to read the next packet's header.
2831 pcap_src
->cap_pipe_state
= STATE_EXPECT_REC_HDR
;
2835 pcap_src
->cap_pipe_err
= PIPEOF
;
2839 snprintf(errmsg
, errmsgl
, "Error reading from pipe: %s",
2841 win32strerror(GetLastError()));
2850 pcap_src
->cap_pipe_err
= PIPERR
;
2851 /* Return here rather than inside the switch to prevent GCC warning */
2856 pcapng_pipe_dispatch(loop_data
*ld
, capture_src
*pcap_src
, char *errmsg
, size_t errmsgl
)
2858 enum { PD_REC_HDR_READ
, PD_DATA_READ
, PD_PIPE_EOF
, PD_PIPE_ERR
,
2863 unsigned new_bufsize
;
2864 pcapng_block_header_t
*bh
= &pcap_src
->cap_pipe_info
.pcapng
.bh
;
2866 #ifdef LOG_CAPTURE_VERBOSE
2867 ws_debug("pcapng_pipe_dispatch");
2870 switch (pcap_src
->cap_pipe_state
) {
2872 case STATE_EXPECT_REC_HDR
:
2873 #ifdef LOG_CAPTURE_VERBOSE
2874 ws_debug("pcapng_pipe_dispatch STATE_EXPECT_REC_HDR");
2877 if (g_mutex_trylock(pcap_src
->cap_pipe_read_mtx
)) {
2880 pcap_src
->cap_pipe_state
= STATE_READ_REC_HDR
;
2881 pcap_src
->cap_pipe_bytes_to_read
= sizeof(pcapng_block_header_t
);
2882 pcap_src
->cap_pipe_bytes_read
= 0;
2885 if (!pcap_src
->from_cap_socket
) {
2886 pcap_src
->cap_pipe_buf
= pcap_src
->cap_pipe_databuf
;
2887 g_async_queue_push(pcap_src
->cap_pipe_pending_q
, pcap_src
->cap_pipe_buf
);
2889 g_mutex_unlock(pcap_src
->cap_pipe_read_mtx
);
2894 case STATE_READ_REC_HDR
:
2895 #ifdef LOG_CAPTURE_VERBOSE
2896 ws_debug("pcapng_pipe_dispatch STATE_READ_REC_HDR");
2899 if (pcap_src
->from_cap_socket
) {
2901 if (cap_pipe_read_data_bytes(pcap_src
, errmsg
, errmsgl
) < 0) {
2906 q_status
= g_async_queue_timeout_pop(pcap_src
->cap_pipe_done_q
, PIPE_READ_TIMEOUT
);
2907 if (pcap_src
->cap_pipe_err
== PIPEOF
) {
2908 result
= PD_PIPE_EOF
;
2910 } else if (pcap_src
->cap_pipe_err
== PIPERR
) {
2911 result
= PD_PIPE_ERR
;
2919 if (pcap_src
->cap_pipe_bytes_read
< pcap_src
->cap_pipe_bytes_to_read
) {
2920 /* There's still more of the pcapng block header to read. */
2923 memcpy(bh
, pcap_src
->cap_pipe_databuf
, sizeof(pcapng_block_header_t
));
2924 result
= PD_REC_HDR_READ
;
2927 case STATE_EXPECT_DATA
:
2928 #ifdef LOG_CAPTURE_VERBOSE
2929 ws_debug("pcapng_pipe_dispatch STATE_EXPECT_DATA");
2932 if (g_mutex_trylock(pcap_src
->cap_pipe_read_mtx
)) {
2934 pcap_src
->cap_pipe_state
= STATE_READ_DATA
;
2935 pcap_src
->cap_pipe_bytes_to_read
= bh
->block_total_length
;
2938 if (!pcap_src
->from_cap_socket
) {
2939 pcap_src
->cap_pipe_bytes_to_read
-= pcap_src
->cap_pipe_bytes_read
;
2940 pcap_src
->cap_pipe_buf
= pcap_src
->cap_pipe_databuf
+ pcap_src
->cap_pipe_bytes_read
;
2941 pcap_src
->cap_pipe_bytes_read
= 0;
2942 g_async_queue_push(pcap_src
->cap_pipe_pending_q
, pcap_src
->cap_pipe_buf
);
2944 g_mutex_unlock(pcap_src
->cap_pipe_read_mtx
);
2949 case STATE_READ_DATA
:
2950 #ifdef LOG_CAPTURE_VERBOSE
2951 ws_debug("pcapng_pipe_dispatch STATE_READ_DATA");
2954 if (pcap_src
->from_cap_socket
) {
2956 if (cap_pipe_read_data_bytes(pcap_src
, errmsg
, errmsgl
) < 0) {
2962 q_status
= g_async_queue_timeout_pop(pcap_src
->cap_pipe_done_q
, PIPE_READ_TIMEOUT
);
2963 if (pcap_src
->cap_pipe_err
== PIPEOF
) {
2964 result
= PD_PIPE_EOF
;
2966 } else if (pcap_src
->cap_pipe_err
== PIPERR
) {
2967 result
= PD_PIPE_ERR
;
2975 if (pcap_src
->cap_pipe_bytes_read
< pcap_src
->cap_pipe_bytes_to_read
) {
2976 /* There's still more of the pcap block contents to read. */
2979 result
= PD_DATA_READ
;
2983 snprintf(errmsg
, errmsgl
,
2984 "pcapng_pipe_dispatch: invalid state");
2987 } /* switch (pcap_src->cap_pipe_state) */
2990 * We've now read as much data as we were expecting, so process it.
2994 case PD_REC_HDR_READ
:
2996 * We've read the pcapng block header, so we know the block type
2999 if (bh
->block_type
== BLOCK_TYPE_SHB
) {
3001 * We need to read the fixed portion of the SHB before to
3002 * get the endianness before we can interpret the block length.
3003 * (The block type of the SHB is byte-order-independent, so that
3004 * an SHB can be recognized before we know the endianness of
3007 * Continue the read process.
3009 pcapng_read_shb(pcap_src
, errmsg
, errmsgl
);
3013 if ((bh
->block_total_length
& 0x03) != 0) {
3014 snprintf(errmsg
, errmsgl
,
3015 "Total length of pcapng block read from pipe is %u, which is not a multiple of 4.",
3016 bh
->block_total_length
);
3019 if (is_data_block(bh
->block_type
) && bh
->block_total_length
> pcap_src
->cap_pipe_max_pkt_size
) {
3021 * The record contains more data than the advertised/allowed in the
3022 * pcapng header, do not try to read more data (do not change to
3023 * STATE_EXPECT_DATA) as that would not fit in the buffer and
3024 * instead stop with an error.
3026 snprintf(errmsg
, errmsgl
, "Block %u type 0x%08x too long (%d bytes)",
3027 ld
->packets_captured
+1, bh
->block_type
, bh
->block_total_length
);
3031 if (bh
->block_total_length
> pcap_src
->cap_pipe_databuf_size
) {
3033 * Grow the buffer to the packet size, rounded up to a power of
3036 new_bufsize
= bh
->block_total_length
;
3038 * https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
3041 new_bufsize
|= new_bufsize
>> 1;
3042 new_bufsize
|= new_bufsize
>> 2;
3043 new_bufsize
|= new_bufsize
>> 4;
3044 new_bufsize
|= new_bufsize
>> 8;
3045 new_bufsize
|= new_bufsize
>> 16;
3047 pcap_src
->cap_pipe_databuf
= (unsigned char*)g_realloc(pcap_src
->cap_pipe_databuf
, new_bufsize
);
3048 pcap_src
->cap_pipe_databuf_size
= new_bufsize
;
3051 /* The record always has at least the block total length following the header */
3052 if (bh
->block_total_length
< sizeof(pcapng_block_header_t
)+sizeof(uint32_t)) {
3053 snprintf(errmsg
, errmsgl
,
3054 "malformed pcapng block_total_length < minimum");
3055 pcap_src
->cap_pipe_err
= PIPEOF
;
3060 * Now we want to read the block contents.
3062 pcap_src
->cap_pipe_state
= STATE_EXPECT_DATA
;
3067 * We've read the full contents of the block.
3068 * Process the block.
3071 capture_loop_queue_pcapng_cb(pcap_src
, bh
, pcap_src
->cap_pipe_databuf
);
3073 capture_loop_write_pcapng_cb(pcap_src
, bh
, pcap_src
->cap_pipe_databuf
);
3077 * Now we want to read the next block's header.
3079 pcap_src
->cap_pipe_state
= STATE_EXPECT_REC_HDR
;
3083 pcap_src
->cap_pipe_err
= PIPEOF
;
3087 snprintf(errmsg
, errmsgl
, "Error reading from pipe: %s",
3089 win32strerror(GetLastError()));
3098 pcap_src
->cap_pipe_err
= PIPERR
;
3099 /* Return here rather than inside the switch to prevent GCC warning */
3103 /** Open the capture input sources; each one is either a pcap device,
3104 * a capture pipe, or a capture socket.
3105 * Returns true if it succeeds, false otherwise. */
3107 capture_loop_open_input(capture_options
*capture_opts
, loop_data
*ld
,
3108 char *errmsg
, size_t errmsg_len
,
3109 char *secondary_errmsg
, size_t secondary_errmsg_len
)
3111 cap_device_open_status open_status
;
3112 char open_status_str
[PCAP_ERRBUF_SIZE
];
3114 interface_options
*interface_opts
;
3115 capture_src
*pcap_src
;
3118 if ((use_threads
== false) &&
3119 (capture_opts
->ifaces
->len
> 1)) {
3120 snprintf(errmsg
, errmsg_len
,
3121 "Using threads is required for capturing on multiple interfaces.");
3125 int pcapng_src_count
= 0;
3126 for (i
= 0; i
< capture_opts
->ifaces
->len
; i
++) {
3127 interface_opts
= &g_array_index(capture_opts
->ifaces
, interface_options
, i
);
3128 pcap_src
= g_new0(capture_src
, 1);
3129 if (pcap_src
== NULL
) {
3130 snprintf(errmsg
, errmsg_len
,
3131 "Could not allocate memory.");
3135 #ifdef MUST_DO_SELECT
3136 pcap_src
->pcap_fd
= -1;
3138 pcap_src
->interface_id
= i
;
3139 pcap_src
->linktype
= -1;
3141 pcap_src
->cap_pipe_h
= INVALID_HANDLE_VALUE
;
3143 pcap_src
->cap_pipe_fd
= -1;
3144 pcap_src
->cap_pipe_dispatch
= pcap_pipe_dispatch
;
3145 pcap_src
->cap_pipe_state
= STATE_EXPECT_REC_HDR
;
3146 pcap_src
->cap_pipe_err
= PIPOK
;
3148 pcap_src
->cap_pipe_read_mtx
= g_new(GMutex
, 1);
3149 g_mutex_init(pcap_src
->cap_pipe_read_mtx
);
3150 pcap_src
->cap_pipe_pending_q
= g_async_queue_new();
3151 pcap_src
->cap_pipe_done_q
= g_async_queue_new();
3153 g_array_append_val(ld
->pcaps
, pcap_src
);
3155 ws_debug("capture_loop_open_input : %s", interface_opts
->name
);
3156 pcap_src
->pcap_h
= open_capture_device(capture_opts
, interface_opts
,
3157 CAP_READ_TIMEOUT
, &open_status
, &open_status_str
);
3159 if (pcap_src
->pcap_h
!= NULL
) {
3160 /* we've opened "iface" as a network device */
3162 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
3163 /* Find out if we're getting nanosecond-precision time stamps */
3164 pcap_src
->ts_nsec
= have_high_resolution_timestamp(pcap_src
->pcap_h
);
3167 #if defined(HAVE_PCAP_SETSAMPLING)
3168 if (interface_opts
->sampling_method
!= CAPTURE_SAMP_NONE
) {
3169 struct pcap_samp
*samp
;
3171 if ((samp
= pcap_setsampling(pcap_src
->pcap_h
)) != NULL
) {
3172 switch (interface_opts
->sampling_method
) {
3173 case CAPTURE_SAMP_BY_COUNT
:
3174 samp
->method
= PCAP_SAMP_1_EVERY_N
;
3177 case CAPTURE_SAMP_BY_TIMER
:
3178 samp
->method
= PCAP_SAMP_FIRST_AFTER_N_MS
;
3182 sync_msg_str
= ws_strdup_printf(
3183 "Unknown sampling method %d specified,\n"
3184 "continue without packet sampling",
3185 interface_opts
->sampling_method
);
3186 report_capture_error("Couldn't set the capture "
3187 "sampling", sync_msg_str
);
3188 g_free(sync_msg_str
);
3190 samp
->value
= interface_opts
->sampling_param
;
3192 report_capture_error("Couldn't set the capture sampling",
3193 "Cannot get packet sampling data structure");
3198 /* setting the data link type only works on real interfaces */
3199 if (!set_pcap_datalink(pcap_src
->pcap_h
, interface_opts
->linktype
,
3200 interface_opts
->name
,
3202 secondary_errmsg
, secondary_errmsg_len
)) {
3205 pcap_src
->linktype
= dlt_to_linktype(get_pcap_datalink(pcap_src
->pcap_h
, interface_opts
->name
));
3207 /* We couldn't open "iface" as a network device. */
3208 /* Try to open it as a pipe */
3209 bool pipe_err
= false;
3210 cap_pipe_open_live(interface_opts
->name
, pcap_src
,
3211 &pcap_src
->cap_pipe_info
.pcap
.hdr
,
3213 secondary_errmsg
, secondary_errmsg_len
);
3216 if (pcap_src
->from_cap_socket
) {
3218 if (pcap_src
->cap_pipe_fd
== -1) {
3223 if (pcap_src
->cap_pipe_h
== INVALID_HANDLE_VALUE
) {
3230 if (pcap_src
->cap_pipe_err
== PIPNEXIST
) {
3232 * We tried opening as an interface, and that failed,
3233 * so we tried to open it as a pipe, but the pipe
3234 * doesn't exist. Report the error message for
3237 get_capture_device_open_failure_messages(open_status
,
3239 interface_opts
->name
,
3243 secondary_errmsg_len
);
3246 * Else pipe (or file) does exist and cap_pipe_open_live() has
3252 * We tried opening as an interface, and that failed,
3253 * so we tried to open it as a pipe, and that succeeded.
3255 open_status
= CAP_DEVICE_OPEN_NO_ERR
;
3259 /* XXX - will this work for tshark? */
3260 #ifdef MUST_DO_SELECT
3261 if (!pcap_src
->from_cap_pipe
) {
3262 pcap_src
->pcap_fd
= pcap_get_selectable_fd(pcap_src
->pcap_h
);
3266 /* Is "open_status" something other than CAP_DEVICE_OPEN_NO_ERR?
3267 If so, "open_capture_device()" returned a warning; print it,
3268 but keep capturing. */
3269 if (open_status
!= CAP_DEVICE_OPEN_NO_ERR
) {
3270 sync_msg_str
= ws_strdup_printf("%s.", open_status_str
);
3271 report_capture_error(sync_msg_str
, "");
3272 g_free(sync_msg_str
);
3274 if (pcap_src
->from_pcapng
) {
3276 * We will use the IDBs from the source (but rewrite the
3277 * interface IDs if there's more than one source.)
3282 * Add our pcapng interface entry.
3284 saved_idb_t idb_source
= { 0 };
3285 idb_source
.interface_id
= i
;
3286 g_rw_lock_writer_lock (&ld
->saved_shb_idb_lock
);
3287 pcap_src
->idb_id
= global_ld
.saved_idbs
->len
;
3288 g_array_append_val(global_ld
.saved_idbs
, idb_source
);
3289 g_rw_lock_writer_unlock (&ld
->saved_shb_idb_lock
);
3290 ws_debug("%s: saved capture_opts %u to IDB %u",
3291 G_STRFUNC
, i
, pcap_src
->idb_id
);
3296 * Are we capturing from one source that is providing pcapng
3299 if (capture_opts
->ifaces
->len
== 1 && pcapng_src_count
== 1) {
3301 * Yes; pass through SHBs and IDBs from the source, rather
3302 * than generating our own.
3304 ld
->pcapng_passthrough
= true;
3305 g_rw_lock_writer_lock (&ld
->saved_shb_idb_lock
);
3306 ws_assert(global_ld
.saved_idbs
->len
== 0);
3307 ws_debug("%s: Pass through SHBs and IDBs directly", G_STRFUNC
);
3308 g_rw_lock_writer_unlock (&ld
->saved_shb_idb_lock
);
3311 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
3312 /* to remove any suid privileges. */
3313 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
3314 /* (euid/egid have already previously been set to ruid/rgid. */
3315 /* (See comment in main() for details) */
3317 relinquish_special_privs_perm();
3319 relinquish_all_capabilities();
3324 /* close the capture input file (pcap or capture pipe) */
3325 static void capture_loop_close_input(loop_data
*ld
)
3328 capture_src
*pcap_src
;
3330 ws_debug("capture_loop_close_input");
3332 for (i
= 0; i
< ld
->pcaps
->len
; i
++) {
3333 pcap_src
= g_array_index(ld
->pcaps
, capture_src
*, i
);
3334 /* Pipe, or capture device? */
3335 if (pcap_src
->from_cap_pipe
) {
3336 /* Pipe. If open, close the capture pipe "input file". */
3337 if (pcap_src
->cap_pipe_fd
>= 0) {
3338 cap_pipe_close(pcap_src
->cap_pipe_fd
, pcap_src
->from_cap_socket
);
3339 pcap_src
->cap_pipe_fd
= -1;
3342 if (pcap_src
->cap_pipe_h
!= INVALID_HANDLE_VALUE
) {
3343 CloseHandle(pcap_src
->cap_pipe_h
);
3344 pcap_src
->cap_pipe_h
= INVALID_HANDLE_VALUE
;
3347 if (pcap_src
->cap_pipe_databuf
!= NULL
) {
3348 /* Free the buffer. */
3349 g_free(pcap_src
->cap_pipe_databuf
);
3350 pcap_src
->cap_pipe_databuf
= NULL
;
3352 if (pcap_src
->from_pcapng
) {
3353 g_array_free(pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
, TRUE
);
3354 pcap_src
->cap_pipe_info
.pcapng
.src_iface_to_global
= NULL
;
3357 /* Capture device. If open, close the pcap_t. */
3358 if (pcap_src
->pcap_h
!= NULL
) {
3359 ws_debug("capture_loop_close_input: closing %p", (void *)pcap_src
->pcap_h
);
3360 pcap_close(pcap_src
->pcap_h
);
3361 pcap_src
->pcap_h
= NULL
;
3370 /* init the capture filter */
3371 static initfilter_status_t
3372 capture_loop_init_filter(pcap_t
*pcap_h
, bool from_cap_pipe
,
3373 const char * name
, const char * cfilter
)
3375 struct bpf_program fcode
;
3377 ws_debug("capture_loop_init_filter: %s", cfilter
);
3379 /* capture filters only work on real interfaces */
3380 if (cfilter
&& !from_cap_pipe
) {
3381 /* A capture filter was specified; set it up. */
3382 if (!compile_capture_filter(name
, pcap_h
, &fcode
, cfilter
)) {
3383 /* Treat this specially - our caller might try to compile this
3384 as a display filter and, if that succeeds, warn the user that
3385 the display and capture filter syntaxes are different. */
3386 return INITFILTER_BAD_FILTER
;
3388 if (pcap_setfilter(pcap_h
, &fcode
) < 0) {
3389 #ifdef HAVE_PCAP_FREECODE
3390 pcap_freecode(&fcode
);
3392 return INITFILTER_OTHER_ERROR
;
3394 #ifdef HAVE_PCAP_FREECODE
3395 pcap_freecode(&fcode
);
3399 return INITFILTER_NO_ERROR
;
3403 * Write the dumpcap pcapng SHB and IDBs if needed.
3404 * Called from capture_loop_init_output and do_file_switch_or_stop.
3407 capture_loop_init_pcapng_output(capture_options
*capture_opts
, loop_data
*ld
,
3410 g_rw_lock_reader_lock (&ld
->saved_shb_idb_lock
);
3412 if (ld
->pcapng_passthrough
&& !ld
->saved_shb
) {
3413 /* We have a single pcapng capture interface and this is the first or only output file. */
3414 ws_debug("%s: skipping dumpcap SHB and IDBs in favor of source", G_STRFUNC
);
3415 g_rw_lock_reader_unlock (&ld
->saved_shb_idb_lock
);
3419 bool successful
= true;
3420 GString
*os_info_str
= g_string_new("");
3423 get_os_version_info(os_info_str
);
3425 if (ld
->saved_shb
) {
3426 /* We have a single pcapng capture interface and multiple output files. */
3428 pcapng_block_header_t bh
;
3430 memcpy(&bh
, ld
->saved_shb
, sizeof(pcapng_block_header_t
));
3432 successful
= pcapng_write_block(ld
->pdh
, ld
->saved_shb
, bh
.block_total_length
, &ld
->bytes_written
, err
);
3434 ws_debug("%s: wrote saved passthrough SHB %d", G_STRFUNC
, successful
);
3436 GString
*cpu_info_str
= g_string_new("");
3437 get_cpu_info(cpu_info_str
);
3439 successful
= pcapng_write_section_header_block(ld
->pdh
,
3440 capture_comments
, /* Comments */
3441 cpu_info_str
->str
, /* HW */
3442 os_info_str
->str
, /* OS */
3443 get_appname_and_version(),
3444 -1, /* section_length */
3447 ws_debug("%s: wrote dumpcap SHB %d", G_STRFUNC
, successful
);
3448 g_string_free(cpu_info_str
, TRUE
);
3451 for (unsigned i
= 0; successful
&& (i
< ld
->saved_idbs
->len
); i
++) {
3452 saved_idb_t idb_source
= g_array_index(ld
->saved_idbs
, saved_idb_t
, i
);
3453 if (idb_source
.deleted
) {
3455 * Our interface is out of scope. Suppose we're writing multiple
3456 * files and a source switches sections. We currently write dummy
3459 * File 1: IDB0, IDB1, IDB2
3460 * [ The source of IDBs 1 and 2 writes an SHB with two new IDBs ]
3461 * [ We switch output files ]
3462 * File 2: IDB0, dummy IDB, dummy IDB, IDB3, IDB4
3464 * It might make more sense to write the original data so that
3465 * so that our IDB lists are more consistent across files.
3467 successful
= pcapng_write_interface_description_block(global_ld
.pdh
,
3468 "Interface went out of scope", /* OPT_COMMENT 1 */
3469 "dummy", /* IDB_NAME 2 */
3470 "Dumpcap dummy interface", /* IDB_DESCRIPTION 3 */
3471 NULL
, /* IDB_FILTER 11 */
3472 os_info_str
->str
, /* IDB_OS 12 */
3473 NULL
, /* IDB_HARDWARE 15 */
3476 &(global_ld
.bytes_written
),
3477 0, /* IDB_IF_SPEED 8 */
3478 6, /* IDB_TSRESOL 9 */
3480 ws_debug("%s: skipping deleted pcapng IDB %u", G_STRFUNC
, i
);
3481 } else if (idb_source
.idb
&& idb_source
.idb_len
) {
3482 successful
= pcapng_write_block(global_ld
.pdh
, idb_source
.idb
, idb_source
.idb_len
, &ld
->bytes_written
, err
);
3483 ws_debug("%s: wrote pcapng IDB %d", G_STRFUNC
, successful
);
3484 } else if (idb_source
.interface_id
< capture_opts
->ifaces
->len
) {
3485 unsigned if_id
= idb_source
.interface_id
;
3486 interface_options
*interface_opts
= &g_array_index(capture_opts
->ifaces
, interface_options
, if_id
);
3487 capture_src
*pcap_src
= g_array_index(ld
->pcaps
, capture_src
*, if_id
);
3488 if (pcap_src
->from_cap_pipe
) {
3489 pcap_src
->snaplen
= pcap_src
->cap_pipe_info
.pcap
.hdr
.snaplen
;
3491 pcap_src
->snaplen
= pcap_snapshot(pcap_src
->pcap_h
);
3493 successful
= pcapng_write_interface_description_block(global_ld
.pdh
,
3494 NULL
, /* OPT_COMMENT 1 */
3495 (interface_opts
->ifname
!= NULL
) ? interface_opts
->ifname
: interface_opts
->name
, /* IDB_NAME 2 */
3496 interface_opts
->descr
, /* IDB_DESCRIPTION 3 */
3497 interface_opts
->cfilter
, /* IDB_FILTER 11 */
3498 os_info_str
->str
, /* IDB_OS 12 */
3499 interface_opts
->hardware
, /* IDB_HARDWARE 15 */
3502 &(global_ld
.bytes_written
),
3503 0, /* IDB_IF_SPEED 8 */
3504 pcap_src
->ts_nsec
? 9 : 6, /* IDB_TSRESOL 9 */
3506 ws_debug("%s: wrote capture_opts IDB %d: %d", G_STRFUNC
, if_id
, successful
);
3509 g_rw_lock_reader_unlock (&ld
->saved_shb_idb_lock
);
3511 g_string_free(os_info_str
, TRUE
);
3516 /* set up to write to the already-opened capture output file/files */
3518 capture_loop_init_output(capture_options
*capture_opts
, loop_data
*ld
, char *errmsg
, int errmsg_len
)
3522 ws_debug("capture_loop_init_output");
3524 if ((capture_opts
->use_pcapng
== false) &&
3525 (capture_opts
->ifaces
->len
> 1)) {
3526 snprintf(errmsg
, errmsg_len
,
3527 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
3531 /* Set up to write to the capture file. */
3532 if (capture_opts
->multi_files_on
) {
3533 ld
->pdh
= ringbuf_init_libpcap_fdopen(&err
);
3535 ld
->pdh
= ws_fdopen(ld
->save_file_fd
, "wb");
3536 if (ld
->pdh
== NULL
) {
3539 size_t buffsize
= IO_BUF_SIZE
;
3540 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
3543 if (ws_fstat64(ld
->save_file_fd
, &statb
) == 0) {
3544 if (statb
.st_blksize
> IO_BUF_SIZE
) {
3545 buffsize
= statb
.st_blksize
;
3549 /* Increase the size of the IO buffer */
3550 ld
->io_buffer
= (char *)g_malloc(buffsize
);
3551 setvbuf(ld
->pdh
, ld
->io_buffer
, _IOFBF
, buffsize
);
3552 ws_debug("capture_loop_init_output: buffsize %zu", buffsize
);
3557 if (capture_opts
->use_pcapng
) {
3558 successful
= capture_loop_init_pcapng_output(capture_opts
, ld
, &err
);
3560 capture_src
*pcap_src
;
3561 pcap_src
= g_array_index(ld
->pcaps
, capture_src
*, 0);
3562 if (pcap_src
->from_cap_pipe
) {
3563 pcap_src
->snaplen
= pcap_src
->cap_pipe_info
.pcap
.hdr
.snaplen
;
3565 pcap_src
->snaplen
= pcap_snapshot(pcap_src
->pcap_h
);
3567 successful
= libpcap_write_file_header(ld
->pdh
, pcap_src
->linktype
, pcap_src
->snaplen
,
3568 pcap_src
->ts_nsec
, &ld
->bytes_written
, &err
);
3573 g_free(ld
->io_buffer
);
3574 ld
->io_buffer
= NULL
;
3578 if (ld
->pdh
== NULL
) {
3579 /* We couldn't set up to write to the capture file. */
3580 /* XXX - use cf_open_error_message from tshark instead? */
3582 snprintf(errmsg
, errmsg_len
,
3583 "The file to which the capture would be"
3584 " saved (\"%s\") could not be opened: Error %d.",
3585 capture_opts
->save_file
, err
);
3587 snprintf(errmsg
, errmsg_len
,
3588 "The file to which the capture would be"
3589 " saved (\"%s\") could not be opened: %s.",
3590 capture_opts
->save_file
, g_strerror(err
));
3599 capture_loop_close_output(capture_options
*capture_opts
, loop_data
*ld
, int *err_close
)
3603 capture_src
*pcap_src
;
3604 uint64_t end_time
= create_timestamp();
3607 ws_debug("capture_loop_close_output");
3609 if (capture_opts
->multi_files_on
) {
3610 return ringbuf_libpcap_dump_close(&capture_opts
->save_file
, err_close
);
3612 if (capture_opts
->use_pcapng
) {
3613 for (i
= 0; i
< global_ld
.pcaps
->len
; i
++) {
3614 pcap_src
= g_array_index(global_ld
.pcaps
, capture_src
*, i
);
3615 if (!pcap_src
->from_cap_pipe
) {
3616 uint64_t isb_ifrecv
, isb_ifdrop
;
3617 struct pcap_stat stats
;
3619 if (pcap_stats(pcap_src
->pcap_h
, &stats
) >= 0) {
3620 isb_ifrecv
= pcap_src
->received
;
3621 isb_ifdrop
= stats
.ps_drop
+ pcap_src
->dropped
+ pcap_src
->flushed
;
3623 isb_ifrecv
= UINT64_MAX
;
3624 isb_ifdrop
= UINT64_MAX
;
3626 pcapng_write_interface_statistics_block(ld
->pdh
,
3629 "Counters provided by dumpcap",
3638 if (fclose(ld
->pdh
) == EOF
) {
3639 if (err_close
!= NULL
) {
3646 g_free(ld
->io_buffer
);
3647 ld
->io_buffer
= NULL
;
3652 /* dispatch incoming packets (pcap or capture pipe)
3654 * Waits for incoming packets to be available, and calls pcap_dispatch()
3655 * to cause them to be processed.
3657 * Returns the number of packets which were processed.
3659 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3660 * packet-batching behaviour does not cause packets to get held back
3664 capture_loop_dispatch(loop_data
*ld
,
3665 char *errmsg
, int errmsg_len
, capture_src
*pcap_src
)
3668 int packet_count_before
;
3671 packet_count_before
= ld
->packets_captured
;
3672 if (pcap_src
->from_cap_pipe
) {
3673 /* dispatch from capture pipe */
3674 #ifdef LOG_CAPTURE_VERBOSE
3675 ws_debug("capture_loop_dispatch: from capture pipe");
3678 if (pcap_src
->from_cap_socket
) {
3680 sel_ret
= cap_pipe_select(pcap_src
->cap_pipe_fd
);
3682 if (sel_ret
< 0 && errno
!= EINTR
) {
3683 snprintf(errmsg
, errmsg_len
,
3684 "Unexpected error from select: %s", g_strerror(errno
));
3685 report_capture_error(errmsg
, please_report_bug());
3691 /* Windows does not have select() for pipes. */
3692 /* Proceed with _dispatch() which waits for cap_pipe_done_q
3693 * notification from cap_thread_read() when ReadFile() on
3694 * the pipe has read enough bytes. */
3700 * "select()" says we can read from the pipe without blocking
3702 inpkts
= pcap_src
->cap_pipe_dispatch(ld
, pcap_src
, errmsg
, errmsg_len
);
3704 ws_debug("%s: src %u pipe reached EOF or err, rcv: %u drop: %u flush: %u",
3705 G_STRFUNC
, pcap_src
->interface_id
, pcap_src
->received
, pcap_src
->dropped
, pcap_src
->flushed
);
3706 ws_assert(pcap_src
->cap_pipe_err
!= PIPOK
);
3712 /* dispatch from pcap */
3713 #ifdef MUST_DO_SELECT
3715 * If we have "pcap_get_selectable_fd()", we use it to get the
3716 * descriptor on which to select; if that's -1, it means there
3717 * is no descriptor on which you can do a "select()" (perhaps
3718 * because you're capturing on a special device, and that device's
3719 * driver unfortunately doesn't support "select()", in which case
3720 * we don't do the select - which means it might not be possible
3721 * to stop a capture until a packet arrives. If that's unacceptable,
3722 * plead with whoever supplies the software for that device to add
3723 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3724 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3725 * later, so it can use pcap_breakloop().
3727 #ifdef LOG_CAPTURE_VERBOSE
3728 ws_debug("capture_loop_dispatch: from pcap_dispatch with select");
3730 if (pcap_src
->pcap_fd
!= -1) {
3731 sel_ret
= cap_pipe_select(pcap_src
->pcap_fd
);
3734 * "select()" says we can read from it without blocking; go for
3737 * We don't have pcap_breakloop(), so we only process one packet
3738 * per pcap_dispatch() call, to allow a signal to stop the
3739 * processing immediately, rather than processing all packets
3740 * in a batch before quitting.
3743 inpkts
= pcap_dispatch(pcap_src
->pcap_h
, 1, capture_loop_queue_packet_cb
, (uint8_t *)pcap_src
);
3745 inpkts
= pcap_dispatch(pcap_src
->pcap_h
, 1, capture_loop_write_packet_cb
, (uint8_t *)pcap_src
);
3749 /* Error, rather than pcap_breakloop(). */
3750 pcap_src
->pcap_err
= true;
3752 ld
->go
= false; /* error or pcap_breakloop() - stop capturing */
3755 if (sel_ret
< 0 && errno
!= EINTR
) {
3756 snprintf(errmsg
, errmsg_len
,
3757 "Unexpected error from select: %s", g_strerror(errno
));
3758 report_capture_error(errmsg
, please_report_bug());
3764 #endif /* MUST_DO_SELECT */
3766 /* dispatch from pcap without select */
3768 #ifdef LOG_CAPTURE_VERBOSE
3769 ws_debug("capture_loop_dispatch: from pcap_dispatch");
3773 * On Windows, we don't support asynchronously telling a process to
3774 * stop capturing; instead, we check for an indication on a pipe
3775 * after processing packets. We therefore process only one packet
3776 * at a time, so that we can check the pipe after every packet.
3779 inpkts
= pcap_dispatch(pcap_src
->pcap_h
, 1, capture_loop_queue_packet_cb
, (uint8_t *)pcap_src
);
3781 inpkts
= pcap_dispatch(pcap_src
->pcap_h
, 1, capture_loop_write_packet_cb
, (uint8_t *)pcap_src
);
3785 inpkts
= pcap_dispatch(pcap_src
->pcap_h
, -1, capture_loop_queue_packet_cb
, (uint8_t *)pcap_src
);
3787 inpkts
= pcap_dispatch(pcap_src
->pcap_h
, -1, capture_loop_write_packet_cb
, (uint8_t *)pcap_src
);
3792 /* Error, rather than pcap_breakloop(). */
3793 pcap_src
->pcap_err
= true;
3795 ld
->go
= false; /* error or pcap_breakloop() - stop capturing */
3797 #else /* pcap_next_ex */
3798 #ifdef LOG_CAPTURE_VERBOSE
3799 ws_debug("capture_loop_dispatch: from pcap_next_ex");
3801 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3804 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3805 * see https://gitlab.com/wireshark/wireshark/-/wikis/CaptureSetup/WinPcapRemote
3806 * This should be fixed in the WinPcap 4.0 alpha release.
3808 * For reference, an example remote interface:
3809 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3812 /* emulate dispatch from pcap */
3815 struct pcap_pkthdr
*pkt_header
;
3820 (in
= pcap_next_ex(pcap_src
->pcap_h
, &pkt_header
, &pkt_data
)) == 1) {
3822 capture_loop_queue_packet_cb((uint8_t *)pcap_src
, pkt_header
, pkt_data
);
3824 capture_loop_write_packet_cb((uint8_t *)pcap_src
, pkt_header
, pkt_data
);
3829 pcap_src
->pcap_err
= true;
3833 #endif /* pcap_next_ex */
3837 #ifdef LOG_CAPTURE_VERBOSE
3838 ws_debug("capture_loop_dispatch: %d new packet%s", inpkts
, plurality(inpkts
, "", "s"));
3841 return ld
->packets_captured
- packet_count_before
;
3845 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3846 * want to grab only the characters between the '{' and '}' delimiters.
3848 * Returns a GString that must be freed with g_string_free(). */
3850 isolate_uuid(const char *iface
)
3855 ptr
= strchr(iface
, '{');
3857 return g_string_new(iface
);
3858 gstr
= g_string_new(ptr
+ 1);
3860 ptr
= strchr(gstr
->str
, '}');
3864 gstr
= g_string_truncate(gstr
, ptr
- gstr
->str
);
3869 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3870 /* Returns true if the file opened successfully, false otherwise. */
3872 capture_loop_open_output(capture_options
*capture_opts
, int *save_file_fd
,
3873 char *errmsg
, int errmsg_len
)
3875 char *capfile_name
= NULL
;
3876 char *prefix
, *suffix
;
3878 GError
*err_tempfile
= NULL
;
3880 ws_debug("capture_loop_open_output: %s",
3881 (capture_opts
->save_file
) ? capture_opts
->save_file
: "(not specified)");
3883 if (capture_opts
->save_file
!= NULL
) {
3884 /* We return to the caller while the capture is in progress.
3885 * Therefore we need to take a copy of save_file in
3886 * case the caller destroys it after we return.
3888 capfile_name
= g_strdup(capture_opts
->save_file
);
3890 if (capture_opts
->output_to_pipe
== true) { /* either "-" or named pipe */
3891 if (capture_opts
->multi_files_on
) {
3892 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3893 snprintf(errmsg
, errmsg_len
,
3894 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3895 g_free(capfile_name
);
3898 if (strcmp(capfile_name
, "-") == 0) {
3899 /* write to stdout */
3902 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3903 _setmode(1, O_BINARY
);
3906 /* Try to open the specified FIFO for use as a capture buffer.
3907 Do *not* create it if it doesn't exist. There's nothing
3908 to truncate. If we need to read it, We Have A Problem. */
3909 *save_file_fd
= ws_open(capfile_name
, O_WRONLY
|O_BINARY
, 0);
3911 } /* if (...output_to_pipe ... */
3914 if (capture_opts
->multi_files_on
) {
3915 /* ringbuffer is enabled */
3916 *save_file_fd
= ringbuf_init(capfile_name
,
3917 (capture_opts
->has_ring_num_files
) ? capture_opts
->ring_num_files
: 0,
3918 capture_opts
->group_read_access
,
3919 capture_opts
->compress_type
,
3920 capture_opts
->has_nametimenum
);
3922 /* capfile_name is unused as the ringbuffer provides its own filename. */
3923 if (*save_file_fd
!= -1) {
3924 g_free(capfile_name
);
3925 capfile_name
= NULL
;
3927 if (capture_opts
->print_file_names
) {
3928 if (!ringbuf_set_print_name(capture_opts
->print_name_to
, NULL
)) {
3929 snprintf(errmsg
, errmsg_len
, "Could not write filenames to %s: %s.\n",
3930 capture_opts
->print_name_to
,
3932 g_free(capfile_name
);
3933 ringbuf_error_cleanup();
3938 /* Try to open/create the specified file for use as a capture buffer. */
3939 *save_file_fd
= ws_open(capfile_name
, O_WRONLY
|O_BINARY
|O_TRUNC
|O_CREAT
,
3940 (capture_opts
->group_read_access
) ? 0640 : 0600);
3943 is_tempfile
= false;
3945 /* Choose a random name for the temporary capture buffer */
3946 if (global_capture_opts
.ifaces
->len
> 1) {
3948 * More than one interface; just use the number of interfaces
3949 * to generate the temporary file name prefix.
3951 prefix
= ws_strdup_printf("wireshark_%d_interfaces", global_capture_opts
.ifaces
->len
);
3954 * One interface; use its description, if it has one, to generate
3955 * the temporary file name, otherwise use its name.
3958 const interface_options
*interface_opts
;
3960 interface_opts
= &g_array_index(global_capture_opts
.ifaces
, interface_options
, 0);
3963 * Do we have a description?
3965 if (interface_opts
->descr
) {
3969 * Strip off any stuff we shouldn't use in the file name,
3970 * by getting the last component of what would be a file
3973 basename
= g_path_get_basename(interface_opts
->descr
);
3976 * No - use the name.
3978 * Strip off any stuff we shouldn't use in the file name,
3979 * by getting the last component of what would be a file
3982 basename
= g_path_get_basename(interface_opts
->name
);
3985 * This is Windows, where we might have an ugly GUID-based
3988 * If it's an ugly GUID-based name, use the generic portion
3989 * of the interface GUID to form the basis of the filename.
3991 if (strncmp("NPF_{", basename
, 5) == 0) {
3993 * We have a GUID-based name; extract the GUID digits
3994 * as the basis of the filename.
3997 iface
= isolate_uuid(basename
);
3999 basename
= g_strdup(iface
->str
);
4000 g_string_free(iface
, TRUE
);
4004 /* generate the temp file name prefix */
4005 prefix
= g_strconcat("wireshark_", basename
, NULL
);
4009 /* Generate the appropriate suffix. */
4010 if (capture_opts
->use_pcapng
) {
4015 *save_file_fd
= create_tempfile(capture_opts
->temp_dir
, &capfile_name
, prefix
, suffix
, &err_tempfile
);
4020 /* did we fail to open the output file? */
4021 if (*save_file_fd
== -1) {
4023 snprintf(errmsg
, errmsg_len
,
4024 "The temporary file to which the capture would be saved "
4025 "could not be opened: %s.", err_tempfile
->message
);
4026 g_error_free(err_tempfile
);
4028 if (capture_opts
->multi_files_on
) {
4029 /* Ensures that the ringbuffer is not used. This ensures that
4030 * !ringbuf_is_initialized() is equivalent to
4031 * capture_opts->save_file not being part of ringbuffer. */
4032 ringbuf_error_cleanup();
4035 snprintf(errmsg
, errmsg_len
,
4036 "The file to which the capture would be saved (\"%s\") "
4037 "could not be opened: %s.", capfile_name
,
4040 g_free(capfile_name
);
4044 g_free(capture_opts
->save_file
);
4045 if (!is_tempfile
&& capture_opts
->multi_files_on
) {
4046 /* In ringbuffer mode, save_file points to a filename from ringbuffer.c.
4047 * capfile_name was already freed before. */
4048 capture_opts
->save_file
= (char *)ringbuf_current_filename();
4050 /* capture_opts_cleanup will g_free(capture_opts->save_file). */
4051 capture_opts
->save_file
= capfile_name
;
4057 static time_t get_next_time_interval(int interval_s
) {
4058 time_t next_time
= time(NULL
);
4059 next_time
-= next_time
% interval_s
;
4060 next_time
+= interval_s
;
4064 /* Do the work of handling either the file size or file duration capture
4065 conditions being reached, and switching files or stopping. */
4067 do_file_switch_or_stop(capture_options
*capture_opts
)
4071 if (capture_opts
->multi_files_on
) {
4072 if (capture_opts
->has_autostop_files
&&
4073 ++global_ld
.file_count
>= capture_opts
->autostop_files
) {
4074 /* no files left: stop here */
4075 global_ld
.go
= false;
4079 /* Switch to the next ringbuffer file */
4080 if (ringbuf_switch_file(&global_ld
.pdh
, &capture_opts
->save_file
,
4081 &global_ld
.save_file_fd
, &global_ld
.err
)) {
4083 /* File switch succeeded: reset the conditions */
4084 global_ld
.bytes_written
= 0;
4085 global_ld
.packets_written
= 0;
4086 if (capture_opts
->use_pcapng
) {
4087 successful
= capture_loop_init_pcapng_output(capture_opts
, &global_ld
, &global_ld
.err
);
4089 capture_src
*pcap_src
;
4090 pcap_src
= g_array_index(global_ld
.pcaps
, capture_src
*, 0);
4091 successful
= libpcap_write_file_header(global_ld
.pdh
, pcap_src
->linktype
, pcap_src
->snaplen
,
4092 pcap_src
->ts_nsec
, &global_ld
.bytes_written
, &global_ld
.err
);
4096 fclose(global_ld
.pdh
);
4097 global_ld
.pdh
= NULL
;
4098 global_ld
.go
= false;
4099 g_free(global_ld
.io_buffer
);
4100 global_ld
.io_buffer
= NULL
;
4103 if (global_ld
.file_duration_timer
) {
4104 g_timer_reset(global_ld
.file_duration_timer
);
4106 if (global_ld
.next_interval_time
) {
4107 global_ld
.next_interval_time
= get_next_time_interval(global_ld
.interval_s
);
4109 fflush(global_ld
.pdh
);
4110 if (global_ld
.inpkts_to_sync_pipe
) {
4112 report_packet_count(global_ld
.inpkts_to_sync_pipe
);
4113 global_ld
.inpkts_to_sync_pipe
= 0;
4115 report_new_capture_file(capture_opts
->save_file
);
4117 /* File switch failed: stop here */
4118 global_ld
.go
= false;
4122 /* single file, stop now */
4123 global_ld
.go
= false;
4130 pcap_read_handler(void* arg
)
4132 capture_src
*pcap_src
= (capture_src
*)arg
;
4133 char errmsg
[MSG_MAX_LENGTH
+1];
4135 ws_info("Started thread for interface %d.", pcap_src
->interface_id
);
4137 /* If this is a pipe input it might finish early. */
4138 while (global_ld
.go
&& pcap_src
->cap_pipe_err
== PIPOK
) {
4139 /* dispatch incoming packets */
4140 capture_loop_dispatch(&global_ld
, errmsg
, sizeof(errmsg
), pcap_src
);
4143 ws_info("Stopped thread for interface %d.", pcap_src
->interface_id
);
4144 g_thread_exit(NULL
);
4148 /* Try to pop an item off the packet queue and if it exists, write it */
4150 capture_loop_dequeue_packet(void) {
4151 pcap_queue_element
*queue_element
;
4153 g_async_queue_lock(pcap_queue
);
4154 queue_element
= (pcap_queue_element
*)g_async_queue_timeout_pop_unlocked(pcap_queue
, WRITER_THREAD_TIMEOUT
);
4155 if (queue_element
) {
4156 if (queue_element
->pcap_src
->from_pcapng
) {
4157 pcap_queue_bytes
-= queue_element
->u
.bh
.block_total_length
;
4159 pcap_queue_bytes
-= queue_element
->u
.phdr
.caplen
;
4161 pcap_queue_packets
-= 1;
4163 g_async_queue_unlock(pcap_queue
);
4164 if (queue_element
) {
4165 if (queue_element
->pcap_src
->from_pcapng
) {
4166 ws_info("Dequeued a block of type 0x%08x of length %d captured on interface %d.",
4167 queue_element
->u
.bh
.block_type
, queue_element
->u
.bh
.block_total_length
,
4168 queue_element
->pcap_src
->interface_id
);
4170 capture_loop_write_pcapng_cb(queue_element
->pcap_src
,
4171 &queue_element
->u
.bh
,
4174 ws_info("Dequeued a packet of length %d captured on interface %d.",
4175 queue_element
->u
.phdr
.caplen
, queue_element
->pcap_src
->interface_id
);
4177 capture_loop_write_packet_cb((uint8_t *) queue_element
->pcap_src
,
4178 &queue_element
->u
.phdr
,
4181 g_free(queue_element
->pd
);
4182 g_free(queue_element
);
4189 * Note: this code will never be run on any OS other than Windows.
4191 * We keep the arguments in case there's something in the future
4192 * that needs to be reported as an NPCAP bug.
4195 handle_npcap_bug(char *adapter_name _U_
, char *cap_err_str _U_
)
4197 bool have_npcap
= false;
4200 have_npcap
= caplibs_have_npcap();
4205 * We're not using Npcap, so don't recomment a user
4206 * file a bug against Npcap.
4208 return g_strdup("");
4211 return ws_strdup_printf("If you have not removed that adapter, this "
4212 "is probably a known issue in Npcap resulting from "
4213 "the behavior of the Windows networking stack. "
4214 "Work is being done in Npcap to improve the "
4215 "handling of this issue; it does not need to "
4216 "be reported as a Wireshark or Npcap bug.");
4219 /* Do the low-level work of a capture.
4220 Returns true if it succeeds, false otherwise. */
4222 capture_loop_start(capture_options
*capture_opts
, bool *stats_known
, struct pcap_stat
*stats
)
4225 ULONGLONG upd_time
, cur_time
; /* GetTickCount64() returns a "ULONGLONG" */
4227 struct timeval upd_time
, cur_time
;
4231 GTimer
*autostop_duration_timer
= NULL
;
4234 bool cfilter_error
= false;
4235 char errmsg
[MSG_MAX_LENGTH
+1];
4236 char secondary_errmsg
[MSG_MAX_LENGTH
+1];
4237 capture_src
*pcap_src
;
4238 interface_options
*interface_opts
;
4239 unsigned i
, error_index
= 0;
4242 *secondary_errmsg
= '\0';
4244 /* init the loop data */
4245 global_ld
.go
= true;
4246 global_ld
.packets_captured
= 0;
4248 global_ld
.report_packet_count
= false;
4250 global_ld
.inpkts_to_sync_pipe
= 0;
4251 global_ld
.err
= 0; /* no error seen yet */
4252 global_ld
.pdh
= NULL
;
4253 global_ld
.save_file_fd
= -1;
4254 global_ld
.io_buffer
= NULL
;
4255 global_ld
.file_count
= 0;
4256 global_ld
.file_duration_timer
= NULL
;
4257 global_ld
.next_interval_time
= 0;
4258 global_ld
.interval_s
= 0;
4260 /* We haven't yet gotten the capture statistics. */
4261 *stats_known
= false;
4263 ws_info("Capture loop starting ...");
4264 capture_opts_log(LOG_DOMAIN_CAPCHILD
, LOG_LEVEL_DEBUG
, capture_opts
);
4266 /* open the "input file" from network interface or capture pipe */
4267 if (!capture_loop_open_input(capture_opts
, &global_ld
, errmsg
, sizeof(errmsg
),
4268 secondary_errmsg
, sizeof(secondary_errmsg
))) {
4271 for (i
= 0; i
< capture_opts
->ifaces
->len
; i
++) {
4272 pcap_src
= g_array_index(global_ld
.pcaps
, capture_src
*, i
);
4273 interface_opts
= &g_array_index(capture_opts
->ifaces
, interface_options
, i
);
4274 /* init the input filter from the network interface (capture pipe will do nothing) */
4276 * When remote capturing WinPCap crashes when the capture filter
4277 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
4280 switch (capture_loop_init_filter(pcap_src
->pcap_h
, pcap_src
->from_cap_pipe
,
4281 interface_opts
->name
,
4282 interface_opts
->cfilter
?interface_opts
->cfilter
:"")) {
4284 case INITFILTER_NO_ERROR
:
4287 case INITFILTER_BAD_FILTER
:
4288 cfilter_error
= true;
4290 snprintf(errmsg
, sizeof(errmsg
), "%s", pcap_geterr(pcap_src
->pcap_h
));
4293 case INITFILTER_OTHER_ERROR
:
4294 snprintf(errmsg
, sizeof(errmsg
), "Can't install filter (%s).",
4295 pcap_geterr(pcap_src
->pcap_h
));
4296 snprintf(secondary_errmsg
, sizeof(secondary_errmsg
), "%s", please_report_bug());
4301 /* If we're supposed to write to a capture file, open it for output
4302 (temporary/specified name/ringbuffer) */
4303 if (capture_opts
->saving_to_file
) {
4304 if (!capture_loop_open_output(capture_opts
, &global_ld
.save_file_fd
,
4305 errmsg
, sizeof(errmsg
))) {
4309 /* set up to write to the already-opened capture output file/files */
4310 if (!capture_loop_init_output(capture_opts
, &global_ld
, errmsg
,
4315 /* XXX - capture SIGTERM and close the capture, in case we're on a
4316 Linux 2.0[.x] system and you have to explicitly close the capture
4317 stream in order to turn promiscuous mode off? We need to do that
4318 in other places as well - and I don't think that works all the
4319 time in any case, due to libpcap bugs. */
4321 /* Well, we should be able to start capturing.
4323 Sync out the capture file, so the header makes it to the file system,
4324 and send a "capture started successfully and capture file created"
4325 message to our parent so that they'll open the capture file and
4326 update its windows to indicate that we have a live capture in
4328 fflush(global_ld
.pdh
);
4329 report_new_capture_file(capture_opts
->save_file
);
4332 if (capture_opts
->has_file_interval
) {
4333 global_ld
.interval_s
= capture_opts
->file_interval
;
4334 global_ld
.next_interval_time
= get_next_time_interval(global_ld
.interval_s
);
4336 /* create stop conditions */
4337 if (capture_opts
->has_autostop_filesize
) {
4338 if (capture_opts
->autostop_filesize
> UINT32_C(2000000000)) {
4339 capture_opts
->autostop_filesize
= UINT32_C(2000000000);
4342 if (capture_opts
->has_autostop_duration
) {
4343 autostop_duration_timer
= g_timer_new();
4346 if (capture_opts
->multi_files_on
) {
4347 if (capture_opts
->has_file_duration
) {
4348 global_ld
.file_duration_timer
= g_timer_new();
4352 /* init the time values */
4354 upd_time
= GetTickCount64();
4356 gettimeofday(&upd_time
, NULL
);
4358 start_time
= create_timestamp();
4359 ws_info("Capture loop running.");
4360 capture_opts_log(LOG_DOMAIN_CAPCHILD
, LOG_LEVEL_DEBUG
, capture_opts
);
4362 /* WOW, everything is prepared! */
4363 /* please fasten your seat belts, we will enter now the actual capture loop */
4365 pcap_queue
= g_async_queue_new();
4366 pcap_queue_bytes
= 0;
4367 pcap_queue_packets
= 0;
4368 for (i
= 0; i
< global_ld
.pcaps
->len
; i
++) {
4369 pcap_src
= g_array_index(global_ld
.pcaps
, capture_src
*, i
);
4370 /* XXX - Add an interface name here? */
4371 pcap_src
->tid
= g_thread_new("Capture read", pcap_read_handler
, pcap_src
);
4374 while (global_ld
.go
) {
4375 /* dispatch incoming packets */
4377 bool dequeued
= capture_loop_dequeue_packet();
4385 pcap_src
= g_array_index(global_ld
.pcaps
, capture_src
*, 0);
4386 inpkts
= capture_loop_dispatch(&global_ld
, errmsg
,
4387 sizeof(errmsg
), pcap_src
);
4390 /* Stop capturing if all of our sources are pipes and none of them are open. */
4391 bool open_interfaces
= false;
4392 for (i
= 0; i
< global_ld
.pcaps
->len
; i
++) {
4393 pcap_src
= g_array_index(global_ld
.pcaps
, capture_src
*, i
);
4394 if (pcap_src
->cap_pipe_err
== PIPOK
) {
4395 /* True for both non-pipes and open pipes. */
4396 open_interfaces
= true;
4399 if (!open_interfaces
) {
4400 global_ld
.go
= false;
4404 /* Were we asked to print packet counts by the SIGINFO handler? */
4405 if (global_ld
.report_packet_count
) {
4406 fprintf(stderr
, "%u packet%s captured\n", global_ld
.packets_captured
,
4407 plurality(global_ld
.packets_captured
, "", "s"));
4408 global_ld
.report_packet_count
= false;
4413 /* any news from our parent (signal pipe)? -> just stop the capture */
4414 if (!signal_pipe_check_running()) {
4415 global_ld
.go
= false;
4420 if (capture_opts
->output_to_pipe
) {
4421 fflush(global_ld
.pdh
);
4425 /* Only update after an interval so as not to overload slow displays.
4426 * This also prevents too much context-switching between the dumpcap
4427 * and wireshark processes.
4428 * XXX: Should we send updates sooner if there have been lots of
4429 * packets we haven't notified the parent about, such as on fast links?
4432 cur_time
= GetTickCount64();
4433 if ((cur_time
- upd_time
) > capture_opts
->update_interval
)
4435 gettimeofday(&cur_time
, NULL
);
4436 if (((uint64_t)cur_time
.tv_sec
* 1000000 + cur_time
.tv_usec
) >
4437 ((uint64_t)upd_time
.tv_sec
* 1000000 + upd_time
.tv_usec
+ capture_opts
->update_interval
*1000))
4441 upd_time
= cur_time
;
4444 if (pcap_stats(pch
, stats
) >= 0) {
4445 *stats_known
= true;
4448 /* Let the parent process know. */
4449 if (global_ld
.inpkts_to_sync_pipe
) {
4451 fflush(global_ld
.pdh
);
4453 /* Send our parent a message saying we've written out
4454 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
4456 report_packet_count(global_ld
.inpkts_to_sync_pipe
);
4458 global_ld
.inpkts_to_sync_pipe
= 0;
4461 /* check capture duration condition */
4462 if (autostop_duration_timer
!= NULL
&& g_timer_elapsed(autostop_duration_timer
, NULL
) >= capture_opts
->autostop_duration
) {
4463 /* The maximum capture time has elapsed; stop the capture. */
4464 global_ld
.go
= false;
4468 /* check capture file duration condition */
4469 if (global_ld
.file_duration_timer
!= NULL
&& g_timer_elapsed(global_ld
.file_duration_timer
, NULL
) >= capture_opts
->file_duration
) {
4470 /* duration limit reached, do we have another file? */
4471 if (!do_file_switch_or_stop(capture_opts
))
4473 } /* cnd_file_duration */
4475 /* check capture file interval condition */
4476 if (global_ld
.interval_s
&& time(NULL
) >= global_ld
.next_interval_time
) {
4477 /* end of interval reached, do we have another file? */
4478 if (!do_file_switch_or_stop(capture_opts
))
4480 } /* cnd_file_interval */
4484 ws_info("Capture loop stopping ...");
4487 for (i
= 0; i
< global_ld
.pcaps
->len
; i
++) {
4488 pcap_src
= g_array_index(global_ld
.pcaps
, capture_src
*, i
);
4489 ws_info("Waiting for thread of interface %u...", pcap_src
->interface_id
);
4490 g_thread_join(pcap_src
->tid
);
4491 ws_info("Thread of interface %u terminated.", pcap_src
->interface_id
);
4494 bool dequeued
= capture_loop_dequeue_packet();
4498 if (capture_opts
->output_to_pipe
) {
4499 fflush(global_ld
.pdh
);
4505 /* delete stop conditions */
4506 if (global_ld
.file_duration_timer
!= NULL
)
4507 g_timer_destroy(global_ld
.file_duration_timer
);
4508 if (autostop_duration_timer
!= NULL
)
4509 g_timer_destroy(autostop_duration_timer
);
4511 /* did we have a pcap (input) error? */
4512 for (i
= 0; i
< capture_opts
->ifaces
->len
; i
++) {
4513 pcap_src
= g_array_index(global_ld
.pcaps
, capture_src
*, i
);
4514 if (pcap_src
->pcap_err
) {
4515 /* On Linux, if an interface goes down while you're capturing on it,
4516 you'll get "recvfrom: Network is down".
4517 (At least you will if g_strerror() doesn't show a local translation
4520 Newer versions of libpcap maps that to just
4521 "The interface went down".
4523 On FreeBSD, DragonFly BSD, and macOS, if a network adapter
4524 disappears while you're capturing on it, you'll get
4525 "read: Device not configured" error (ENXIO). (See previous
4526 parenthetical note.)
4528 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
4530 With WinPcap and Npcap, you'll get
4531 "read error: PacketReceivePacket failed" or
4532 "PacketReceivePacket error: The device has been removed. (1617)".
4534 Newer versions of libpcap map some or all of those to just
4535 "The interface disappeared" or something beginning with
4536 "The interface disappeared".
4538 These should *not* be reported to the Wireshark developers,
4539 although, with Npcap, "The interface disappeared" messages
4540 should perhaps be reported to the Npcap developers, at least
4541 until errors of that sort that shouldn't happen are fixed,
4542 if that's possible. */
4545 char *secondary_msg
;
4547 interface_opts
= &g_array_index(capture_opts
->ifaces
, interface_options
, i
);
4548 cap_err_str
= pcap_geterr(pcap_src
->pcap_h
);
4549 if (strcmp(cap_err_str
, "The interface went down") == 0 ||
4550 strcmp(cap_err_str
, "recvfrom: Network is down") == 0) {
4551 primary_msg
= ws_strdup_printf("The network adapter \"%s\" "
4552 "is no longer running; the "
4553 "capture has stopped.",
4554 interface_opts
->display_name
);
4555 secondary_msg
= g_strdup("");
4556 } else if (strcmp(cap_err_str
, "The interface disappeared") == 0 ||
4557 strcmp(cap_err_str
, "read: Device not configured") == 0 ||
4558 strcmp(cap_err_str
, "read: I/O error") == 0 ||
4559 strcmp(cap_err_str
, "read error: PacketReceivePacket failed") == 0) {
4560 primary_msg
= ws_strdup_printf("The network adapter \"%s\" "
4561 "is no longer attached; the "
4562 "capture has stopped.",
4563 interface_opts
->display_name
);
4564 secondary_msg
= g_strdup("");
4565 } else if (g_str_has_prefix(cap_err_str
, "The interface disappeared ")) {
4567 * Npcap, if it picks up a recent commit to libpcap, will
4568 * report an error *beginning* with "The interface
4569 * disappeared", with the name of the Windows status code,
4570 * and the corresponding NT status code, after it.
4572 * Those should be reported as Npcap issues.
4574 primary_msg
= ws_strdup_printf("The network adapter \"%s\" "
4575 "is no longer attached; the "
4576 "capture has stopped.",
4577 interface_opts
->display_name
);
4578 secondary_msg
= handle_npcap_bug(interface_opts
->display_name
,
4580 } else if (g_str_has_prefix(cap_err_str
, "PacketReceivePacket error:") &&
4581 g_str_has_suffix(cap_err_str
, "(1617)")) {
4583 * "PacketReceivePacket error: {message in arbitrary language} (1617)",
4584 * which is ERROR_DEVICE_REMOVED.
4586 * Current libpcap/Npcap treat ERROR_GEN_FAILURE as
4587 * "the device is no longer attached"; users are also
4588 * getting ERROR_DEVICE_REMOVED.
4590 * For now, some users appear to be getg ERROR_DEVICE_REMOVED
4591 * in cases where the device *wasn't* removed, so tell
4592 * them to report this as an Npcap issue; I seem to
4593 * remember some discussion between Daniel and somebody
4594 * at Microsoft about the Windows 10 network stack setup/
4595 * teardown code being modified to try to prevent those
4596 * sort of problems popping up, but I can't find that
4599 primary_msg
= ws_strdup_printf("The network adapter \"%s\" "
4600 "is no longer attached; the "
4601 "capture has stopped.",
4602 interface_opts
->display_name
);
4603 secondary_msg
= handle_npcap_bug(interface_opts
->display_name
,
4604 "The interface disappeared (error code ERROR_DEVICE_REMOVED/STATUS_DEVICE_REMOVED)");
4605 } else if (strcmp(cap_err_str
, "The other host terminated the connection.") == 0 ||
4606 g_str_has_prefix(cap_err_str
, "Is the server properly installed?")) {
4608 * Networking error for a remote capture.
4610 primary_msg
= g_strdup(cap_err_str
);
4611 secondary_msg
= g_strdup("This may be a problem with the "
4612 "remote host on which you are "
4613 "capturing packets.");
4615 primary_msg
= ws_strdup_printf("Error while capturing packets: %s",
4617 secondary_msg
= g_strdup(please_report_bug());
4619 report_capture_error(primary_msg
, secondary_msg
);
4620 g_free(primary_msg
);
4621 g_free(secondary_msg
);
4623 } else if (pcap_src
->from_cap_pipe
&& pcap_src
->cap_pipe_err
== PIPERR
) {
4624 report_capture_error(errmsg
, "");
4628 /* did we have an output error while capturing? */
4629 if (global_ld
.err
== 0) {
4632 capture_loop_get_errmsg(errmsg
, sizeof(errmsg
), secondary_errmsg
,
4633 sizeof(secondary_errmsg
),
4634 capture_opts
->save_file
, global_ld
.err
, false);
4635 report_capture_error(errmsg
, secondary_errmsg
);
4639 if (capture_opts
->saving_to_file
) {
4640 /* close the output file */
4641 close_ok
= capture_loop_close_output(capture_opts
, &global_ld
, &err_close
);
4645 /* there might be packets not yet notified to the parent */
4646 /* (do this after closing the file, so all packets are already flushed) */
4647 if (global_ld
.inpkts_to_sync_pipe
) {
4649 report_packet_count(global_ld
.inpkts_to_sync_pipe
);
4650 global_ld
.inpkts_to_sync_pipe
= 0;
4653 /* If we've displayed a message about a write error, there's no point
4654 in displaying another message about an error on close. */
4655 if (!close_ok
&& write_ok
) {
4656 capture_loop_get_errmsg(errmsg
, sizeof(errmsg
), secondary_errmsg
,
4657 sizeof(secondary_errmsg
),
4658 capture_opts
->save_file
, err_close
, true);
4659 report_capture_error(errmsg
, secondary_errmsg
);
4663 * XXX We exhibit different behaviour between normal mode and sync mode
4664 * when the pipe is stdin and not already at EOF. If we're a child, the
4665 * parent's stdin isn't closed, so if the user starts another capture,
4666 * cap_pipe_open_live() will very likely not see the expected magic bytes and
4667 * will say "Unrecognized libpcap format". On the other hand, in normal
4668 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
4671 report_capture_count(!really_quiet
);
4673 /* get packet drop statistics from pcap */
4674 for (i
= 0; i
< capture_opts
->ifaces
->len
; i
++) {
4676 uint32_t pcap_dropped
= 0;
4678 pcap_src
= g_array_index(global_ld
.pcaps
, capture_src
*, i
);
4679 interface_opts
= &g_array_index(capture_opts
->ifaces
, interface_options
, i
);
4680 received
= pcap_src
->received
;
4681 if (pcap_src
->pcap_h
!= NULL
) {
4682 ws_assert(!pcap_src
->from_cap_pipe
);
4683 /* Get the capture statistics, so we know how many packets were dropped. */
4684 if (pcap_stats(pcap_src
->pcap_h
, stats
) >= 0) {
4685 *stats_known
= true;
4686 /* Let the parent process know. */
4687 pcap_dropped
+= stats
->ps_drop
;
4689 snprintf(errmsg
, sizeof(errmsg
),
4690 "Can't get packet-drop statistics: %s",
4691 pcap_geterr(pcap_src
->pcap_h
));
4692 report_capture_error(errmsg
, please_report_bug());
4695 report_packet_drops(received
, pcap_dropped
, pcap_src
->dropped
, pcap_src
->flushed
, stats
->ps_ifdrop
, interface_opts
->display_name
);
4698 /* close the input file (pcap or capture pipe) */
4699 capture_loop_close_input(&global_ld
);
4701 ws_info("Capture loop stopped.");
4703 /* ok, if the write and the close were successful. */
4704 return write_ok
&& close_ok
;
4707 if (capture_opts
->multi_files_on
) {
4708 /* cleanup ringbuffer */
4709 ringbuf_error_cleanup();
4711 /* We can't use the save file, and we have no FILE * for the stream
4712 to close in order to close it, so close the FD directly. */
4713 if (global_ld
.save_file_fd
!= -1) {
4714 ws_close(global_ld
.save_file_fd
);
4717 /* We couldn't even start the capture, so get rid of the capture
4719 if (capture_opts
->save_file
!= NULL
) {
4720 ws_unlink(capture_opts
->save_file
);
4724 report_cfilter_error(capture_opts
, error_index
, errmsg
);
4726 report_capture_error(errmsg
, secondary_errmsg
);
4728 /* close the input file (pcap or cap_pipe) */
4729 capture_loop_close_input(&global_ld
);
4731 ws_info("Capture loop stopped with error");
4738 capture_loop_stop(void)
4741 capture_src
*pcap_src
;
4743 for (i
= 0; i
< global_ld
.pcaps
->len
; i
++) {
4744 pcap_src
= g_array_index(global_ld
.pcaps
, capture_src
*, i
);
4745 if (pcap_src
->pcap_h
!= NULL
)
4746 pcap_breakloop(pcap_src
->pcap_h
);
4748 global_ld
.go
= false;
4753 capture_loop_get_errmsg(char *errmsg
, size_t errmsglen
, char *secondary_errmsg
,
4754 size_t secondary_errmsglen
, const char *fname
,
4755 int err
, bool is_close
)
4757 static const char find_space
[] =
4758 "You will need to free up space on that file system"
4759 " or put the capture file on a different file system.";
4764 snprintf(errmsg
, errmsglen
,
4765 "Not all the packets could be written to the file"
4766 " to which the capture was being saved\n"
4767 "(\"%s\") because there is no space left on the file system\n"
4768 "on which that file resides.",
4770 snprintf(secondary_errmsg
, secondary_errmsglen
, "%s", find_space
);
4775 snprintf(errmsg
, errmsglen
,
4776 "Not all the packets could be written to the file"
4777 " to which the capture was being saved\n"
4778 "(\"%s\") because you are too close to, or over,"
4779 " your disk quota\n"
4780 "on the file system on which that file resides.",
4782 snprintf(secondary_errmsg
, secondary_errmsglen
, "%s", find_space
);
4788 snprintf(errmsg
, errmsglen
,
4789 "The file to which the capture was being saved\n"
4790 "(\"%s\") could not be closed: %s.",
4791 fname
, g_strerror(err
));
4793 snprintf(errmsg
, errmsglen
,
4794 "An error occurred while writing to the file"
4795 " to which the capture was being saved\n"
4797 fname
, g_strerror(err
));
4799 snprintf(secondary_errmsg
, secondary_errmsglen
,
4800 "%s", please_report_bug());
4806 * We wrote one packet. Update some statistics and check if we've met any
4807 * autostop or ring buffer conditions.
4810 capture_loop_wrote_one_packet(capture_src
*pcap_src
) {
4811 global_ld
.packets_captured
++;
4812 global_ld
.packets_written
++;
4813 global_ld
.inpkts_to_sync_pipe
++;
4816 pcap_src
->received
++;
4820 if (global_capture_opts
.has_autostop_packets
&& global_ld
.packets_captured
>= global_capture_opts
.autostop_packets
) {
4821 fflush(global_ld
.pdh
);
4822 global_ld
.go
= false;
4825 /* check -a packets:NUM (treat like -c NUM) */
4826 if (global_capture_opts
.has_autostop_written_packets
&& global_ld
.packets_captured
>= global_capture_opts
.autostop_written_packets
) {
4827 fflush(global_ld
.pdh
);
4828 global_ld
.go
= false;
4831 /* check -b packets:NUM */
4832 if (global_capture_opts
.has_file_packets
&& global_ld
.packets_written
>= global_capture_opts
.file_packets
) {
4833 do_file_switch_or_stop(&global_capture_opts
);
4836 /* check -a filesize:NUM */
4837 if (global_capture_opts
.has_autostop_filesize
&&
4838 global_capture_opts
.autostop_filesize
> 0 &&
4839 global_ld
.bytes_written
/ 1000 >= global_capture_opts
.autostop_filesize
) {
4840 /* Capture size limit reached, do we have another file? */
4841 do_file_switch_or_stop(&global_capture_opts
);
4846 /* one pcapng block was captured, process it */
4848 capture_loop_write_pcapng_cb(capture_src
*pcap_src
, const pcapng_block_header_t
*bh
, uint8_t *pd
)
4853 * This should never be called if we're not writing pcapng.
4855 ws_assert(global_capture_opts
.use_pcapng
);
4857 /* We may be called multiple times from pcap_dispatch(); if we've set
4858 the "stop capturing" flag, ignore this packet, as we're not
4859 supposed to be saving any more packets. */
4860 if (!global_ld
.go
) {
4861 pcap_src
->flushed
++;
4865 if (!pcapng_adjust_block(pcap_src
, bh
, pd
)) {
4866 ws_info("%s failed to adjust pcapng block.", G_STRFUNC
);
4867 ws_assert_not_reached();
4871 if (bh
->block_type
== BLOCK_TYPE_SHB
&& !global_ld
.pcapng_passthrough
) {
4873 * capture_loop_init_pcapng_output should've handled this. We need
4874 * to write ISBs when they're initially read so we shouldn't skip
4880 if (global_ld
.pdh
) {
4883 /* We're supposed to write the packet to a file; do so.
4884 If this fails, set "ld->go" to false, to stop the capture, and set
4885 "ld->err" to the error. */
4886 successful
= pcapng_write_block(global_ld
.pdh
,
4888 bh
->block_total_length
,
4889 &global_ld
.bytes_written
, &err
);
4891 fflush(global_ld
.pdh
);
4893 global_ld
.go
= false;
4894 global_ld
.err
= err
;
4895 pcap_src
->dropped
++;
4896 } else if (is_data_block(bh
->block_type
)) {
4897 /* Count packets for block types that should be dissected, i.e. ones that show up in the packet list. */
4898 ws_debug("Wrote a pcapng block type 0x%04x of length %d captured on interface %u.",
4899 bh
->block_type
, bh
->block_total_length
, pcap_src
->interface_id
);
4900 capture_loop_wrote_one_packet(pcap_src
);
4901 } else if (bh
->block_type
== BLOCK_TYPE_SHB
&& report_capture_filename
) {
4902 ws_debug("Sending SP_FILE on first SHB");
4903 /* SHB is now ready for capture parent to read on SP_FILE message */
4904 sync_pipe_write_string_msg(sync_pipe_fd
, SP_FILE
, report_capture_filename
);
4905 report_capture_filename
= NULL
;
4910 /* one pcap packet was captured, process it */
4912 capture_loop_write_packet_cb(uint8_t *pcap_src_p
, const struct pcap_pkthdr
*phdr
,
4915 capture_src
*pcap_src
= (capture_src
*) (void *) pcap_src_p
;
4917 unsigned ts_mul
= pcap_src
->ts_nsec
? 1000000000 : 1000000;
4919 ws_debug("capture_loop_write_packet_cb");
4921 /* We may be called multiple times from pcap_dispatch(); if we've set
4922 the "stop capturing" flag, ignore this packet, as we're not
4923 supposed to be saving any more packets. */
4924 if (!global_ld
.go
) {
4925 pcap_src
->flushed
++;
4929 if (global_ld
.pdh
) {
4932 /* We're supposed to write the packet to a file; do so.
4933 If this fails, set "ld->go" to false, to stop the capture, and set
4934 "ld->err" to the error. */
4935 if (global_capture_opts
.use_pcapng
) {
4936 successful
= pcapng_write_enhanced_packet_block(global_ld
.pdh
,
4938 phdr
->ts
.tv_sec
, (int32_t)phdr
->ts
.tv_usec
,
4939 phdr
->caplen
, phdr
->len
,
4943 &global_ld
.bytes_written
, &err
);
4945 successful
= libpcap_write_packet(global_ld
.pdh
,
4946 phdr
->ts
.tv_sec
, (int32_t)phdr
->ts
.tv_usec
,
4947 phdr
->caplen
, phdr
->len
,
4949 &global_ld
.bytes_written
, &err
);
4952 global_ld
.go
= false;
4953 global_ld
.err
= err
;
4954 pcap_src
->dropped
++;
4956 ws_debug("Wrote a pcap packet of length %d captured on interface %u.",
4957 phdr
->caplen
, pcap_src
->interface_id
);
4958 capture_loop_wrote_one_packet(pcap_src
);
4963 /* one packet was captured, queue it */
4965 capture_loop_queue_packet_cb(uint8_t *pcap_src_p
, const struct pcap_pkthdr
*phdr
,
4968 capture_src
*pcap_src
= (capture_src
*) (void *) pcap_src_p
;
4969 pcap_queue_element
*queue_element
;
4972 /* We may be called multiple times from pcap_dispatch(); if we've set
4973 the "stop capturing" flag, ignore this packet, as we're not
4974 supposed to be saving any more packets. */
4975 if (!global_ld
.go
) {
4976 pcap_src
->flushed
++;
4980 queue_element
= g_new(pcap_queue_element
, 1);
4981 if (queue_element
== NULL
) {
4982 pcap_src
->dropped
++;
4985 queue_element
->pcap_src
= pcap_src
;
4986 queue_element
->u
.phdr
= *phdr
;
4987 queue_element
->pd
= (uint8_t *)g_malloc(phdr
->caplen
);
4988 if (queue_element
->pd
== NULL
) {
4989 pcap_src
->dropped
++;
4990 g_free(queue_element
);
4993 memcpy(queue_element
->pd
, pd
, phdr
->caplen
);
4994 g_async_queue_lock(pcap_queue
);
4995 if (((pcap_queue_byte_limit
== 0) || (pcap_queue_bytes
< pcap_queue_byte_limit
)) &&
4996 ((pcap_queue_packet_limit
== 0) || (pcap_queue_packets
< pcap_queue_packet_limit
))) {
4997 limit_reached
= false;
4998 g_async_queue_push_unlocked(pcap_queue
, queue_element
);
4999 pcap_queue_bytes
+= phdr
->caplen
;
5000 pcap_queue_packets
+= 1;
5002 limit_reached
= true;
5004 g_async_queue_unlock(pcap_queue
);
5005 if (limit_reached
) {
5006 pcap_src
->dropped
++;
5007 g_free(queue_element
->pd
);
5008 g_free(queue_element
);
5009 ws_info("Dropped a packet of length %d captured on interface %u.",
5010 phdr
->caplen
, pcap_src
->interface_id
);
5012 pcap_src
->received
++;
5013 ws_info("Queued a packet of length %d captured on interface %u.",
5014 phdr
->caplen
, pcap_src
->interface_id
);
5016 /* I don't want to hold the mutex over the debug output. So the
5017 output may be wrong */
5018 ws_info("Queue size is now %" PRId64
" bytes (%" PRId64
" packets)",
5019 pcap_queue_bytes
, pcap_queue_packets
);
5022 /* one pcapng block was captured, queue it */
5024 capture_loop_queue_pcapng_cb(capture_src
*pcap_src
, const pcapng_block_header_t
*bh
, uint8_t *pd
)
5026 pcap_queue_element
*queue_element
;
5029 /* We may be called multiple times from pcap_dispatch(); if we've set
5030 the "stop capturing" flag, ignore this packet, as we're not
5031 supposed to be saving any more packets. */
5032 if (!global_ld
.go
) {
5033 pcap_src
->flushed
++;
5037 queue_element
= g_new(pcap_queue_element
, 1);
5038 if (queue_element
== NULL
) {
5039 pcap_src
->dropped
++;
5042 queue_element
->pcap_src
= pcap_src
;
5043 queue_element
->u
.bh
= *bh
;
5044 queue_element
->pd
= (uint8_t *)g_malloc(bh
->block_total_length
);
5045 if (queue_element
->pd
== NULL
) {
5046 pcap_src
->dropped
++;
5047 g_free(queue_element
);
5050 memcpy(queue_element
->pd
, pd
, bh
->block_total_length
);
5051 g_async_queue_lock(pcap_queue
);
5052 if (((pcap_queue_byte_limit
== 0) || (pcap_queue_bytes
< pcap_queue_byte_limit
)) &&
5053 ((pcap_queue_packet_limit
== 0) || (pcap_queue_packets
< pcap_queue_packet_limit
))) {
5054 limit_reached
= false;
5055 g_async_queue_push_unlocked(pcap_queue
, queue_element
);
5056 pcap_queue_bytes
+= bh
->block_total_length
;
5057 pcap_queue_packets
+= 1;
5059 limit_reached
= true;
5061 g_async_queue_unlock(pcap_queue
);
5062 if (limit_reached
) {
5063 pcap_src
->dropped
++;
5064 g_free(queue_element
->pd
);
5065 g_free(queue_element
);
5066 ws_info("Dropped a packet of length %d captured on interface %u.",
5067 bh
->block_total_length
, pcap_src
->interface_id
);
5069 pcap_src
->received
++;
5070 ws_info("Queued a block of type 0x%08x of length %d captured on interface %u.",
5071 bh
->block_type
, bh
->block_total_length
, pcap_src
->interface_id
);
5073 /* I don't want to hold the mutex over the debug output. So the
5074 output may be wrong */
5075 ws_info("Queue size is now %" PRId64
" bytes (%" PRId64
" packets)",
5076 pcap_queue_bytes
, pcap_queue_packets
);
5080 set_80211_channel(const char *iface
, const char *opt
)
5084 uint32_t center_freq1
= 0;
5085 uint32_t center_freq2
= 0;
5088 char **options
= NULL
;
5090 options
= g_strsplit_set(opt
, ",", 4);
5091 for (args
= 0; options
[args
]; args
++)
5094 ret
= ws80211_init();
5095 if (ret
!= WS80211_INIT_OK
) {
5096 if (ret
== WS80211_INIT_NOT_SUPPORTED
)
5097 cmdarg_err("Setting 802.11 channels is not supported on this platform");
5099 cmdarg_err("Failed to init ws80211: %s", g_strerror(abs(ret
)));
5105 freq
= get_nonzero_uint32(options
[0], "802.11 channel frequency");
5107 if (args
>= 1 && options
[1]) {
5108 type
= ws80211_str_to_chan_type(options
[1]);
5110 cmdarg_err("\"%s\" is not a valid 802.11 channel type", options
[1]);
5116 if (args
>= 2 && options
[2])
5117 center_freq1
= get_nonzero_uint32(options
[2], "VHT center frequency");
5119 if (args
>= 3 && options
[3])
5120 center_freq2
= get_nonzero_uint32(options
[3], "VHT center frequency 2");
5122 ret
= ws80211_set_freq(iface
, freq
, type
, center_freq1
, center_freq2
);
5125 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret
), g_strerror(abs(ret
)));
5131 sync_pipe_write_string_msg(sync_pipe_fd
, SP_SUCCESS
, NULL
);
5134 g_strfreev(options
);
5139 gather_dumpcap_compiled_info(feature_list l
)
5141 /* Capture libraries */
5142 gather_caplibs_compile_info(l
);
5146 gather_dumpcap_runtime_info(feature_list l
)
5148 /* Capture libraries */
5149 gather_caplibs_runtime_info(l
);
5152 #define LONGOPT_IFNAME LONGOPT_BASE_APPLICATION+1
5153 #define LONGOPT_IFDESCR LONGOPT_BASE_APPLICATION+2
5154 #define LONGOPT_CAPTURE_COMMENT LONGOPT_BASE_APPLICATION+3
5156 #define LONGOPT_SIGNAL_PIPE LONGOPT_BASE_APPLICATION+4
5159 /* And now our feature presentation... [ fade to music ] */
5161 main(int argc
, char *argv
[])
5165 static const struct ws_option long_options
[] = {
5166 {"help", ws_no_argument
, NULL
, 'h'},
5167 {"version", ws_no_argument
, NULL
, 'v'},
5168 LONGOPT_CAPTURE_COMMON
5169 {"ifname", ws_required_argument
, NULL
, LONGOPT_IFNAME
},
5170 {"ifdescr", ws_required_argument
, NULL
, LONGOPT_IFDESCR
},
5171 {"capture-comment", ws_required_argument
, NULL
, LONGOPT_CAPTURE_COMMENT
},
5173 {"signal-pipe", ws_required_argument
, NULL
, LONGOPT_SIGNAL_PIPE
},
5178 bool arg_error
= false;
5181 struct sigaction action
, oldaction
;
5185 struct pcap_stat stats
= {0};
5186 bool list_interfaces
= false;
5187 int caps_queries
= 0;
5188 bool print_bpf_code
= false;
5189 bool set_chan
= false;
5190 char *set_chan_arg
= NULL
;
5191 bool machine_readable
= false;
5192 bool print_statistics
= false;
5193 int status
, run_once_args
= 0;
5196 #if defined(__APPLE__) && defined(__LP64__)
5197 struct utsname osinfo
;
5202 * Determine if dumpcap is being requested to run in a special
5203 * capture_child mode by going thru the command line args to see if
5204 * a -Z is present. (-Z is a hidden option).
5206 * The primary result of running in capture_child mode is that
5207 * all messages sent out on stderr are in a special type/len/string
5208 * format to allow message processing by type. These messages include
5209 * error messages if dumpcap fails to start the operation it was
5210 * requested to do, as well as various "status" messages which are sent
5211 * when an actual capture is in progress, and a "success" message sent
5212 * if dumpcap was requested to perform an operation other than a
5215 * Capture_child mode would normally be requested by a parent process
5216 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
5217 * to which dumpcap stderr has been redirected. It might also have
5218 * another pipe to obtain dumpcap stdout output; for operations other
5219 * than a capture, that information is formatted specially for easier
5220 * parsing by the parent process.
5222 * Capture_child mode needs to be determined immediately upon
5223 * startup so that any messages generated by dumpcap in this mode
5224 * (eg: during initialization) will be formatted properly.
5227 for (i
=1; i
<argc
; i
++) {
5228 if (strcmp("-Z", argv
[i
]) == 0) {
5229 capture_child
= true;
5230 machine_readable
= true; /* request machine-readable output */
5236 if (strcmp(argv
[i
], SIGNAL_PIPE_CTRL_ID_NONE
) != 0) {
5237 // get_positive_int calls cmdarg_err
5238 if (!ws_strtoi(argv
[i
], NULL
, &sync_pipe_fd
) || sync_pipe_fd
<= 0) {
5242 /* On UN*X the fd is the same when we fork + exec.
5243 * On Windows the HANDLE value is the same for inherited
5244 * handles in the child process and the parent, although
5245 * not necessarily the fd value from _open_osfhandle.
5246 * https://learn.microsoft.com/en-us/windows/win32/procthread/inheritance
5247 * Also, "64-bit versions of Windows use 32-bit handles for
5248 * interoperability... only the lower 32 bits are significant,
5249 * so it is safe to truncate... or sign-extend the handle."
5250 * https://learn.microsoft.com/en-us/windows/win32/winprog64/interprocess-communication
5252 /* set output pipe to binary mode, avoid ugly text conversions */
5253 sync_pipe_fd
= _open_osfhandle( (intptr_t) sync_pipe_fd
, _O_BINARY
);
5259 cmdarg_err_init(dumpcap_cmdarg_err
, dumpcap_cmdarg_err_cont
);
5261 /* Initialize log handler early so we can have proper logging during startup. */
5262 ws_log_init_with_writer("dumpcap", dumpcap_log_writer
, vcmdarg_err
);
5264 /* Early logging command-line initialization. */
5265 ws_log_parse_args(&argc
, argv
, vcmdarg_err
, 1);
5267 #if DEBUG_CHILD_DUMPCAP
5268 /* Assume that if we're specially compiled with dumpcap debugging
5269 * then we want maximum debugging.
5271 if (capture_child
) {
5272 ws_log_set_level(LOG_LEVEL_NOISY
);
5275 if ((debug_log
= ws_fopen("dumpcap_debug_log.tmp","w")) == NULL
) {
5276 fprintf (stderr
, "Unable to open debug log file .\n");
5281 ws_noisy("Finished log init and parsing command line log arguments");
5284 create_app_running_mutex();
5287 * Initialize our DLL search path. MUST be called before LoadLibrary
5290 ws_init_dll_search_path();
5292 /* Load wpcap if possible. Do this before collecting the run-time version information */
5296 /* Initialize the version information. */
5297 ws_init_version_info("Dumpcap", gather_dumpcap_compiled_info
,
5298 gather_dumpcap_runtime_info
);
5300 #ifdef HAVE_PCAP_REMOTE
5301 #define OPTSTRING_r "r"
5302 #define OPTSTRING_u "u"
5308 #ifdef HAVE_PCAP_SETSAMPLING
5309 #define OPTSTRING_m "m:"
5314 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:dghk:" OPTSTRING_m "MN:nPqQ" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
5316 #if defined(__APPLE__) && defined(__LP64__)
5318 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
5319 * a bug workaround - timeouts less than 1 second don't work with libpcap
5320 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
5321 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
5322 * The problem is extremely unlikely to be reintroduced in a future
5325 if (uname(&osinfo
) == 0) {
5327 * {Mac} OS X/macOS 10.x uses Darwin {x+4}.0.0; 10.x.y uses Darwin
5328 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
5329 * number of 10.0.0, not 10.1.0 - go figure).
5331 if (strcmp(osinfo
.release
, "10.0.0") == 0 || /* 10.6, 10.6.1 */
5332 strcmp(osinfo
.release
, "10.3.0") == 0 || /* 10.6.3 */
5333 strcmp(osinfo
.release
, "10.4.0") == 0) /* 10.6.4 */
5334 need_timeout_workaround
= true;
5338 /* Initialize the pcaps list and IDBs */
5339 global_ld
.pcaps
= g_array_new(FALSE
, FALSE
, sizeof(capture_src
*));
5340 global_ld
.pcapng_passthrough
= false;
5341 global_ld
.saved_shb
= NULL
;
5342 global_ld
.saved_idbs
= g_array_new(FALSE
, TRUE
, sizeof(saved_idb_t
));
5344 err_msg
= ws_init_sockets();
5345 if (err_msg
!= NULL
)
5347 ws_log(LOG_DOMAIN_CAPCHILD
, LOG_LEVEL_ERROR
,
5348 "ERROR: %s", err_msg
);
5350 ws_log(LOG_DOMAIN_CAPCHILD
, LOG_LEVEL_ERROR
,
5351 "%s", please_report_bug());
5356 /* Set handler for Ctrl+C key */
5357 SetConsoleCtrlHandler(capture_cleanup_handler
, true);
5359 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
5360 and exit. Do the same with SIGPIPE, in case, for example,
5361 we're writing to our standard output and it's a pipe.
5362 Do the same with SIGHUP if it's not being ignored (if we're
5363 being run under nohup, it might be ignored, in which case we
5364 should leave it ignored).
5366 XXX - apparently, Coverity complained that part of action
5367 wasn't initialized. Perhaps it's running on Linux, where
5368 struct sigaction has an ignored "sa_restorer" element and
5369 where "sa_handler" and "sa_sigaction" might not be two
5370 members of a union. */
5371 memset(&action
, 0, sizeof(action
));
5372 action
.sa_handler
= capture_cleanup_handler
;
5374 * Arrange that system calls not get restarted, because when
5375 * our signal handler returns we don't want to restart
5376 * a call that was waiting for packets to arrive.
5378 action
.sa_flags
= 0;
5379 sigemptyset(&action
.sa_mask
);
5380 sigaction(SIGTERM
, &action
, NULL
);
5381 sigaction(SIGINT
, &action
, NULL
);
5382 sigaction(SIGPIPE
, &action
, NULL
);
5383 sigaction(SIGHUP
, NULL
, &oldaction
);
5384 if (oldaction
.sa_handler
== SIG_DFL
)
5385 sigaction(SIGHUP
, &action
, NULL
);
5388 /* Catch SIGINFO and, if we get it and we're capturing in
5389 quiet mode, report the number of packets we've captured. */
5390 action
.sa_handler
= report_counts_siginfo
;
5391 action
.sa_flags
= SA_RESTART
;
5392 sigemptyset(&action
.sa_mask
);
5393 sigaction(SIGINFO
, &action
, NULL
);
5394 #endif /* SIGINFO */
5397 /* ----------------------------------------------------------------- */
5398 /* Privilege and capability handling */
5400 /* 1. Running not as root or suid root; no special capabilities. */
5403 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
5406 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
5408 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
5409 /* capabilities; Drop all other capabilities; */
5410 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5411 /* else: after pcap_open_live() in capture_loop_open_input() */
5412 /* drop all capabilities (NET_RAW and NET_ADMIN); */
5413 /* (Note: this means that the process, although logged in */
5414 /* as root, does not have various permissions such as the */
5415 /* ability to bypass file access permissions). */
5416 /* XXX: Should we just leave capabilities alone in this case */
5417 /* so that user gets expected effect that root can do */
5420 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
5422 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5423 /* else: after pcap_open_live() in capture_loop_open_input() */
5424 /* drop suid root (set euid=ruid).(ie: keep suid until after */
5425 /* pcap_open_live). */
5427 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
5429 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
5430 /* capabilities; Drop all other capabilities; */
5431 /* Drop suid privileges (euid=ruid); */
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 all capabilities (NET_RAW and NET_ADMIN). */
5436 /* XXX: For some Linux versions/distros with capabilities */
5437 /* a 'normal' process with any capabilities cannot be */
5438 /* 'killed' (signaled) from another (same uid) non-privileged */
5440 /* For example: If (non-suid) Wireshark forks a */
5441 /* child suid dumpcap which acts as described here (case 5), */
5442 /* Wireshark will be unable to kill (signal) the child */
5443 /* dumpcap process until the capabilities have been dropped */
5444 /* (after pcap_open_live()). */
5445 /* This behaviour will apparently be changed in the kernel */
5446 /* to allow the kill (signal) in this case. */
5447 /* See the following for details: */
5448 /* https://www.mail-archive.com/ [wrapped] */
5449 /* linux-security-module@vger.kernel.org/msg02913.html */
5451 /* It is therefore conceivable that if dumpcap somehow hangs */
5452 /* in pcap_open_live or before that wireshark will not */
5453 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
5454 /* In this case, exiting wireshark will kill the child */
5455 /* dumpcap process. */
5457 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
5458 /* capabilities; Using libcap. Note: capset cmd (which see) */
5459 /* used to assign capabilities to file. */
5461 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5462 /* else: after pcap_open_live() in capture_loop_open_input() */
5463 /* drop all capabilities (NET_RAW and NET_ADMIN) */
5465 /* ToDo: -S (stats) should drop privileges/capabilities when no */
5466 /* longer required (similar to capture). */
5468 /* ----------------------------------------------------------------- */
5470 init_process_policies();
5473 /* If 'started with special privileges' (and using libcap) */
5474 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
5475 /* Set euid/egid = ruid/rgid to remove suid privileges */
5476 relinquish_privs_except_capture();
5479 /* Set the initial values in the capture options. This might be overwritten
5480 by the command line parameters. */
5481 capture_opts_init(&global_capture_opts
, get_interface_list
);
5482 /* We always save to a file - if no file was specified, we save to a
5484 global_capture_opts
.saving_to_file
= true;
5485 global_capture_opts
.has_ring_num_files
= true;
5487 /* Pass on capture_child mode for capture_opts */
5488 global_capture_opts
.capture_child
= capture_child
;
5490 /* Now get our args */
5491 while ((opt
= ws_getopt_long(argc
, argv
, OPTSTRING
, long_options
, NULL
)) != -1) {
5493 case 'h': /* Print help and exit */
5494 show_help_header("Capture network packets and dump them into a pcapng or pcap file.");
5495 print_usage(stdout
);
5498 case 'v': /* Show version and exit */
5502 /*** capture option specific ***/
5503 case 'a': /* autostop criteria */
5504 case 'b': /* Ringbuffer option */
5505 case 'c': /* Capture x packets */
5506 case 'f': /* capture filter */
5507 case 'F': /* capture file type */
5508 case 'g': /* enable group read access on file(s) */
5509 case 'i': /* Use interface x */
5510 case LONGOPT_SET_TSTAMP_TYPE
: /* Set capture timestamp type */
5511 case 'n': /* Use pcapng format */
5512 case 'p': /* Don't capture in promiscuous mode */
5513 case 'P': /* Use pcap format */
5514 case 's': /* Set the snapshot (capture) length */
5515 case 'w': /* Write to capture file x */
5516 case 'y': /* Set the pcap data link type */
5517 #ifdef HAVE_PCAP_REMOTE
5518 case 'u': /* Use UDP for data transfer */
5519 case 'r': /* Capture own RPCAP traffic too */
5520 case 'A': /* Authentication */
5522 #ifdef HAVE_PCAP_SETSAMPLING
5523 case 'm': /* Sampling */
5525 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
5526 case 'B': /* Buffer size */
5528 #ifdef HAVE_PCAP_CREATE
5529 case 'I': /* Monitor mode */
5531 case LONGOPT_COMPRESS_TYPE
: /* compress type */
5532 case LONGOPT_CAPTURE_TMPDIR
: /* capture temp directory */
5533 case LONGOPT_UPDATE_INTERVAL
: /* sync pipe update interval */
5534 status
= capture_opts_add_opt(&global_capture_opts
, opt
, ws_optarg
);
5539 /*** hidden option: Wireshark child mode (using binary output messages) ***/
5540 case LONGOPT_IFNAME
:
5541 if (global_capture_opts
.ifaces
->len
> 0) {
5542 interface_options
*interface_opts
;
5544 interface_opts
= &g_array_index(global_capture_opts
.ifaces
, interface_options
, global_capture_opts
.ifaces
->len
- 1);
5545 interface_opts
->ifname
= g_strdup(ws_optarg
);
5547 cmdarg_err("--ifname must be specified after a -i option");
5551 case LONGOPT_IFDESCR
:
5552 if (global_capture_opts
.ifaces
->len
> 0) {
5553 interface_options
*interface_opts
;
5555 interface_opts
= &g_array_index(global_capture_opts
.ifaces
, interface_options
, global_capture_opts
.ifaces
->len
- 1);
5556 interface_opts
->descr
= g_strdup(ws_optarg
);
5558 cmdarg_err("--ifdescr must be specified after a -i option");
5562 case LONGOPT_CAPTURE_COMMENT
: /* capture comment */
5563 if (capture_comments
== NULL
) {
5564 capture_comments
= g_ptr_array_new_with_free_func(g_free
);
5566 g_ptr_array_add(capture_comments
, g_strdup(ws_optarg
));
5569 capture_child
= true;
5575 case LONGOPT_SIGNAL_PIPE
:
5576 if (!capture_child
) {
5577 /* We have already checked for -Z at the very beginning. */
5578 cmdarg_err("--signal-pipe may only be specified with -Z");
5582 * ws_optarg = the control ID, aka the PPID, currently used for the
5585 if (strcmp(ws_optarg
, SIGNAL_PIPE_CTRL_ID_NONE
) != 0) {
5586 sig_pipe_name
= ws_strdup_printf(SIGNAL_PIPE_FORMAT
, ws_optarg
);
5587 sig_pipe_handle
= CreateFile(utf_8to16(sig_pipe_name
),
5588 GENERIC_READ
, 0, NULL
, OPEN_EXISTING
, 0, NULL
);
5590 if (sig_pipe_handle
== INVALID_HANDLE_VALUE
) {
5591 ws_info("Signal pipe: Unable to open %s. Dead parent?",
5598 case 'q': /* Quiet */
5601 case 'Q': /* Really quiet */
5603 really_quiet
= true;
5608 /*** all non capture option specific ***/
5609 case 'D': /* Print a list of capture devices and exit */
5610 if (!list_interfaces
&& !caps_queries
& !print_statistics
) {
5613 list_interfaces
= true;
5615 case 'L': /* Print list of link-layer types and exit */
5616 if (!list_interfaces
&& !caps_queries
& !print_statistics
) {
5619 caps_queries
|= CAPS_QUERY_LINK_TYPES
;
5621 case LONGOPT_LIST_TSTAMP_TYPES
:
5622 if (!list_interfaces
&& !caps_queries
& !print_statistics
) {
5625 caps_queries
|= CAPS_QUERY_TIMESTAMP_TYPES
;
5627 case 'd': /* Print BPF code for capture filter and exit */
5628 if (!print_bpf_code
) {
5629 print_bpf_code
= true;
5633 case 'S': /* Print interface statistics once a second */
5634 if (!list_interfaces
&& !caps_queries
& !print_statistics
) {
5637 print_statistics
= true;
5639 case 'k': /* Set wireless channel */
5642 set_chan_arg
= ws_optarg
;
5645 cmdarg_err("Only one -k flag may be specified");
5649 case 'M': /* For -D, -L, and -S, print machine-readable output */
5650 machine_readable
= true;
5653 pcap_queue_byte_limit
= get_positive_int(ws_optarg
, "byte_limit");
5656 pcap_queue_packet_limit
= get_positive_int(ws_optarg
, "packet_limit");
5659 cmdarg_err("Invalid Option: %s", argv
[ws_optind
-1]);
5661 case '?': /* Bad flag - print usage message */
5670 /* user specified file name as regular command-line argument */
5671 /* XXX - use it as the capture file name (or something else)? */
5677 * Extra command line arguments were specified; complain.
5678 * XXX - interpret as capture filter, as tcpdump and tshark do?
5680 cmdarg_err("Invalid argument: %s", argv
[0]);
5685 if ((pcap_queue_byte_limit
> 0) || (pcap_queue_packet_limit
> 0)) {
5688 if ((pcap_queue_byte_limit
== 0) && (pcap_queue_packet_limit
== 0)) {
5689 /* Use some default if the user hasn't specified some */
5690 /* XXX: Are these defaults good enough? */
5691 pcap_queue_byte_limit
= 1000 * 1000;
5692 pcap_queue_packet_limit
= 1000;
5695 if (ws_optopt
== 'F') {
5696 capture_opts_list_file_types();
5699 print_usage(stderr
);
5703 if (run_once_args
> 1) {
5704 cmdarg_err("Only one of -D, -L, -d, -k or -S may be supplied.");
5706 } else if (run_once_args
== 1) {
5707 /* We're supposed to print some information, rather than
5708 to capture traffic; did they specify a ring buffer option? */
5709 if (global_capture_opts
.multi_files_on
) {
5710 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
5714 /* We're supposed to capture traffic; */
5716 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
5717 if (global_capture_opts
.ifaces
->len
> 1) {
5719 global_capture_opts
.use_pcapng
= true;
5722 if (capture_comments
&&
5723 (!global_capture_opts
.use_pcapng
|| global_capture_opts
.multi_files_on
)) {
5724 /* XXX - for ringbuffer, should we apply the comments to each file? */
5725 cmdarg_err("Capture comments can only be set if we capture into a single pcapng file.");
5729 /* Was the ring buffer option specified and, if so, does it make sense? */
5730 if (global_capture_opts
.multi_files_on
) {
5731 /* Ring buffer works only under certain conditions:
5732 a) ring buffer does not work with temporary files;
5733 b) it makes no sense to enable the ring buffer if the maximum
5734 file size is set to "infinite". */
5735 if (global_capture_opts
.save_file
== NULL
) {
5736 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
5737 global_capture_opts
.multi_files_on
= false;
5739 if (!global_capture_opts
.has_autostop_filesize
&&
5740 !global_capture_opts
.has_file_duration
&&
5741 !global_capture_opts
.has_file_interval
&&
5742 !global_capture_opts
.has_file_packets
) {
5743 cmdarg_err("Ring buffer requested, but no maximum capture file size, duration "
5744 "interval, or packets were specified.");
5746 /* XXX - this must be redesigned as the conditions changed */
5747 global_capture_opts
.multi_files_on
= false;
5750 if (global_capture_opts
.has_file_duration
&& global_capture_opts
.has_file_interval
) {
5751 cmdarg_err("Ring buffer file duration and interval can't be used at the same time.");
5758 * "-D" requires no interface to be selected; it's supposed to list
5761 if (list_interfaces
) {
5762 /* Get the list of interfaces */
5767 if_list
= get_interface_list(&err
, &err_str
);
5768 if (if_list
== NULL
) {
5771 * If we're being run by another program, just give them
5772 * an empty list of interfaces, don't report this as
5773 * an error; that lets them decide whether to report
5774 * this as an error or not.
5776 if (!machine_readable
) {
5777 cmdarg_err("There are no interfaces on which a capture can be done");
5781 cmdarg_err("%s", err_str
);
5787 if (!machine_readable
) {
5789 capture_opts_print_interfaces(if_list
);
5794 interface_options
*interface_opts
;
5795 cap_device_open_status open_status
;
5796 char *open_status_str
;
5797 for (GList
*if_entry
= if_list
; if_entry
!= NULL
; if_entry
= g_list_next(if_entry
)) {
5798 if_info
= (if_info_t
*)if_entry
->data
;
5801 * XXX - If on the command line we had the options -i <interface> -I,
5802 * we should retrieve the link-types for the interface in monitor mode.
5803 * We've already copied that information to global_capture_opts, but
5804 * the below statement wipes it away.
5806 interface_opts
= interface_opts_from_if_info(&global_capture_opts
, if_info
);
5808 if_info
->caps
= get_if_capabilities(interface_opts
, &open_status
, &open_status_str
);
5810 if (!machine_readable
) {
5811 if (if_info
->caps
== NULL
) {
5812 cmdarg_err("The capabilities of the capture device "
5813 "\"%s\" could not be obtained (%s).\n%s",
5814 interface_opts
->name
, open_status_str
,
5815 get_pcap_failure_secondary_error_message(open_status
, open_status_str
));
5816 g_free(open_status_str
);
5817 /* Break after one error, as when printing selected
5818 * interface capabilities. (XXX: We could print all
5819 * the primary status strings, and only the unique
5820 * set of secondary messages / suggestions; printing
5821 * the same long secondary error is a lot.)
5823 interface_opts_free(interface_opts
);
5824 g_free(interface_opts
);
5827 status
= capture_opts_print_if_capabilities(if_info
->caps
, interface_opts
, caps_queries
);
5829 interface_opts_free(interface_opts
);
5830 g_free(interface_opts
);
5835 if (if_info
->caps
== NULL
) {
5836 if_info
->caps
= g_new0(if_capabilities_t
, 1);
5837 if_info
->caps
->primary_msg
= open_status_str
;
5838 if_info
->caps
->secondary_msg
= get_pcap_failure_secondary_error_message(open_status
, open_status_str
);
5840 if_info
->caps
->status
= open_status
;
5843 interface_opts_free(interface_opts
);
5844 g_free(interface_opts
);
5848 if (machine_readable
) {
5849 status
= print_machine_readable_interfaces(if_list
, caps_queries
, print_statistics
);
5851 free_interface_list(if_list
);
5852 if (!print_statistics
) {
5858 * "-S" requires no interface to be selected; it gives statistics
5859 * for all interfaces.
5861 if (print_statistics
) {
5862 status
= print_statistics_loop(machine_readable
);
5867 interface_options
*interface_opts
;
5869 if (global_capture_opts
.ifaces
->len
!= 1) {
5870 cmdarg_err("Need one interface");
5874 interface_opts
= &g_array_index(global_capture_opts
.ifaces
, interface_options
, 0);
5875 status
= set_80211_channel(interface_opts
->name
, set_chan_arg
);
5880 * "-L", "-d", and capturing act on a particular interface, so we have to
5881 * have an interface; if none was specified, pick a default.
5883 status
= capture_opts_default_iface_if_necessary(&global_capture_opts
, NULL
);
5885 /* cmdarg_err() already called .... */
5890 /* Get the list of link-layer and/or timestamp types for the capture device. */
5891 if_capabilities_t
*caps
;
5892 cap_device_open_status open_status
;
5893 char *open_status_str
;
5896 if (machine_readable
) {
5897 json_dumper dumper
= {
5898 .output_file
= stdout
,
5899 .flags
= JSON_DUMPER_FLAGS_NO_DEBUG
,
5900 // Don't abort on failure
5902 json_dumper_begin_array(&dumper
);
5903 for (ii
= 0; ii
< global_capture_opts
.ifaces
->len
; ii
++) {
5904 interface_options
*interface_opts
;
5906 interface_opts
= &g_array_index(global_capture_opts
.ifaces
, interface_options
, ii
);
5908 json_dumper_begin_object(&dumper
);
5909 json_dumper_set_member_name(&dumper
, interface_opts
->name
);
5911 json_dumper_begin_object(&dumper
);
5913 open_status
= CAP_DEVICE_OPEN_NO_ERR
;
5914 caps
= get_if_capabilities(interface_opts
, &open_status
, &open_status_str
);
5916 json_dumper_set_member_name(&dumper
, "status");
5917 json_dumper_value_anyf(&dumper
, "%i", open_status
);
5918 json_dumper_set_member_name(&dumper
, "primary_msg");
5919 json_dumper_value_string(&dumper
, open_status_str
);
5920 g_free(open_status_str
);
5922 caps
->status
= open_status
;
5923 print_machine_readable_if_capabilities(&dumper
, caps
, caps_queries
);
5924 free_if_capabilities(caps
);
5926 json_dumper_end_object(&dumper
);
5927 json_dumper_end_object(&dumper
);
5929 json_dumper_end_array(&dumper
);
5930 if (json_dumper_finish(&dumper
)) {
5932 if (capture_child
) {
5933 /* Let our parent know we succeeded. */
5934 sync_pipe_write_string_msg(sync_pipe_fd
, SP_SUCCESS
, NULL
);
5938 if (capture_child
) {
5939 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd
, "Unexpected JSON error", "");
5943 for (ii
= 0; ii
< global_capture_opts
.ifaces
->len
; ii
++) {
5944 interface_options
*interface_opts
;
5946 interface_opts
= &g_array_index(global_capture_opts
.ifaces
, interface_options
, ii
);
5948 caps
= get_if_capabilities(interface_opts
, &open_status
, &open_status_str
);
5950 if (capture_child
) {
5951 char *error_msg
= ws_strdup_printf("The capabilities of the capture device "
5952 "\"%s\" could not be obtained (%s)",
5953 interface_opts
->name
, open_status_str
);
5954 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd
, error_msg
,
5955 get_pcap_failure_secondary_error_message(open_status
, open_status_str
));
5959 cmdarg_err("The capabilities of the capture device "
5960 "\"%s\" could not be obtained (%s).\n%s",
5961 interface_opts
->name
, open_status_str
,
5962 get_pcap_failure_secondary_error_message(open_status
, open_status_str
));
5964 g_free(open_status_str
);
5968 /* XXX: We might want to print also the interface name */
5969 status
= capture_opts_print_if_capabilities(caps
,
5972 free_if_capabilities(caps
);
5980 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
5981 for (j
= 0; j
< global_capture_opts
.ifaces
->len
; j
++) {
5982 interface_options
*interface_opts
;
5984 interface_opts
= &g_array_index(global_capture_opts
.ifaces
, interface_options
, j
);
5985 if (interface_opts
->timestamp_type
) {
5986 interface_opts
->timestamp_type_id
= pcap_tstamp_type_name_to_val(interface_opts
->timestamp_type
);
5987 if (interface_opts
->timestamp_type_id
< 0) {
5988 cmdarg_err("Invalid argument to option: --time-stamp-type=%s", interface_opts
->timestamp_type
);
5995 /* We're supposed to do a capture, or print the BPF code for a filter. */
5997 /* Let the user know what interfaces were chosen. */
5998 if (capture_child
) {
5999 for (j
= 0; j
< global_capture_opts
.ifaces
->len
; j
++) {
6000 interface_options
*interface_opts
;
6002 interface_opts
= &g_array_index(global_capture_opts
.ifaces
, interface_options
, j
);
6003 ws_debug("Interface: %s\n", interface_opts
->name
);
6006 str
= g_string_new("");
6008 if (global_capture_opts
.ifaces
->len
< 2)
6010 if (global_capture_opts
.ifaces
->len
< 4)
6013 for (j
= 0; j
< global_capture_opts
.ifaces
->len
; j
++) {
6014 interface_options
*interface_opts
;
6016 interface_opts
= &g_array_index(global_capture_opts
.ifaces
, interface_options
, j
);
6018 if (global_capture_opts
.ifaces
->len
> 2) {
6019 g_string_append_printf(str
, ",");
6021 g_string_append_printf(str
, " ");
6022 if (j
== global_capture_opts
.ifaces
->len
- 1) {
6023 g_string_append_printf(str
, "and ");
6026 if (interface_opts
->ifname
!= NULL
) {
6028 * Re-generate the display name based on the strins
6031 g_free(interface_opts
->display_name
);
6032 if (interface_opts
->descr
!= NULL
) {
6034 interface_opts
->display_name
= ws_strdup_printf("%s",
6035 interface_opts
->descr
);
6037 interface_opts
->display_name
= ws_strdup_printf("%s: %s",
6038 interface_opts
->descr
, interface_opts
->ifname
);
6041 interface_opts
->display_name
= ws_strdup_printf("%s",
6042 interface_opts
->ifname
);
6045 g_string_append_printf(str
, "'%s'", interface_opts
->display_name
);
6048 g_string_append_printf(str
, "%u interfaces", global_capture_opts
.ifaces
->len
);
6051 fprintf(stderr
, "Capturing on %s\n", str
->str
);
6052 g_string_free(str
, TRUE
);
6055 /* Process the snapshot length, as that affects the generated BPF code. */
6056 capture_opts_trim_snaplen(&global_capture_opts
, MIN_PACKET_SIZE
);
6058 if (print_bpf_code
) {
6059 show_filter_code(&global_capture_opts
);
6063 /* We're supposed to do a capture. Process the ring buffer arguments. */
6064 capture_opts_trim_ring_num_files(&global_capture_opts
);
6066 /* flush stderr prior to starting the main capture loop */
6069 /* Now start the capture. */
6070 if (capture_loop_start(&global_capture_opts
, &stats_known
, &stats
) == true) {
6074 /* capture failed */
6077 return 0; /* never here, make compiler happy */
6081 dumpcap_log_writer(const char *domain
, enum ws_log_level level
,
6082 const char *file
, long line
, const char *func
,
6083 const char *fatal_msg _U_
,
6084 ws_log_manifest_t
*mft
,
6085 const char *user_format
, va_list user_ap
,
6086 void *user_data _U_
)
6088 if (ws_log_msg_is_active(domain
, level
)) {
6089 /* log messages go to stderr or */
6090 /* to parent especially formatted if dumpcap running as child. */
6091 #ifdef DEBUG_CHILD_DUMPCAP
6092 va_list user_ap_copy
;
6093 va_copy(user_ap_copy
, user_ap
);
6095 if (capture_child
) {
6096 /* Format the log mesage as the numeric level, followed
6097 * by a colon and then a string matching the standard log
6098 * string. In the future perhaps we serialize file, line,
6099 * and func (which can be NULL) instead.
6101 GString
*msg
= g_string_new(NULL
);
6102 g_string_append_printf(msg
, "%u:", level
);
6104 g_string_append_printf(msg
, "%s", file
);
6106 g_string_append_printf(msg
, ":%ld", line
);
6109 g_string_append(msg
, " --");
6111 g_string_append_printf(msg
, " %s():", func
);
6113 g_string_append_c(msg
, ' ');
6114 g_string_append_vprintf(msg
, user_format
, user_ap
);
6116 sync_pipe_write_string_msg(sync_pipe_fd
, SP_LOG_MSG
, msg
->str
);
6117 g_string_free(msg
, TRUE
);
6119 ws_log_console_writer(domain
, level
, file
, line
, func
, mft
, user_format
, user_ap
);
6121 #ifdef DEBUG_CHILD_DUMPCAP
6122 ws_log_file_writer(debug_log
, domain
, level
, file
, line
, func
, mft
, user_format
, user_ap_copy
);
6123 va_end(user_ap_copy
);
6129 /****************************************************************************************************************/
6130 /* indication report routines */
6134 report_packet_count(unsigned int packet_count
)
6136 static unsigned int count
= 0;
6138 if (capture_child
) {
6139 ws_debug("Packets: %u", packet_count
);
6140 sync_pipe_write_uint_msg(sync_pipe_fd
, SP_PACKET_COUNT
, packet_count
);
6142 count
+= packet_count
;
6143 fprintf(stderr
, "\rPackets: %u ", count
);
6144 /* stderr could be line buffered */
6150 report_new_capture_file(const char *filename
)
6152 if (capture_child
) {
6153 ws_debug("File: %s", filename
);
6154 if (global_ld
.pcapng_passthrough
) {
6155 /* Save filename for sending SP_FILE to capture parent after SHB is passed-through */
6156 ws_debug("Delaying SP_FILE until first SHB");
6157 report_capture_filename
= filename
;
6159 sync_pipe_write_string_msg(sync_pipe_fd
, SP_FILE
, filename
);
6164 * Prevent a SIGINFO handler from writing to the standard error
6165 * while we're doing so; instead, have it just set a flag telling
6166 * us to print that information when we're done.
6169 #endif /* SIGINFO */
6170 if (!really_quiet
) {
6171 fprintf(stderr
, "File: %s\n", filename
);
6172 /* stderr could be line buffered */
6178 * Allow SIGINFO handlers to write.
6183 * If a SIGINFO handler asked us to write out capture counts, do so.
6186 report_counts_for_siginfo();
6187 #endif /* SIGINFO */
6192 report_cfilter_error(capture_options
*capture_opts
, unsigned i
, const char *errmsg
)
6194 interface_options
*interface_opts
;
6195 char tmp
[MSG_MAX_LENGTH
+1+6];
6197 if (i
< capture_opts
->ifaces
->len
) {
6198 if (capture_child
) {
6199 snprintf(tmp
, sizeof(tmp
), "%u:%s", i
, errmsg
);
6200 ws_debug("Capture filter error: %s", errmsg
);
6201 sync_pipe_write_string_msg(sync_pipe_fd
, SP_BAD_FILTER
, tmp
);
6204 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
6205 * the error message below.
6207 interface_opts
= &g_array_index(capture_opts
->ifaces
, interface_options
, i
);
6209 "Invalid capture filter \"%s\" for interface '%s'.\n"
6211 "That string isn't a valid capture filter (%s).\n"
6212 "See the User's Guide for a description of the capture filter syntax.",
6213 interface_opts
->cfilter
, interface_opts
->name
, errmsg
);
6219 report_capture_error(const char *error_msg
, const char *secondary_error_msg
)
6221 if (capture_child
) {
6222 ws_debug("Primary Error: %s", error_msg
);
6223 ws_debug("Secondary Error: %s", secondary_error_msg
);
6224 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd
, error_msg
, secondary_error_msg
);
6226 cmdarg_err("%s", error_msg
);
6227 if (secondary_error_msg
[0] != '\0')
6228 cmdarg_err_cont("%s", secondary_error_msg
);
6233 report_packet_drops(uint32_t received
, uint32_t pcap_drops
, uint32_t drops
, uint32_t flushed
, uint32_t ps_ifdrop
, char *name
)
6235 uint32_t total_drops
= pcap_drops
+ drops
+ flushed
;
6237 if (capture_child
) {
6238 char* tmp
= ws_strdup_printf("%u:%s", total_drops
, name
);
6240 ws_debug("Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
6241 name
, received
, total_drops
, pcap_drops
, drops
, flushed
, ps_ifdrop
);
6242 sync_pipe_write_string_msg(sync_pipe_fd
, SP_DROPS
, tmp
);
6245 if (!really_quiet
) {
6247 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
6248 name
, received
, total_drops
, pcap_drops
, drops
, flushed
, ps_ifdrop
,
6249 received
? 100.0 * received
/ (received
+ total_drops
) : 0.0);
6250 /* stderr could be line buffered */
6257 /************************************************************************************************/
6258 /* signal_pipe handling */
6263 signal_pipe_check_running(void)
6265 /* any news from our parent? -> just stop the capture */
6269 /* if we are running standalone, no check required */
6270 if (!capture_child
) {
6274 if (!sig_pipe_name
|| !sig_pipe_handle
) {
6275 /* This shouldn't happen */
6276 ws_info("Signal pipe: No name or handle");
6281 * XXX - We should have the process ID of the parent (from the "-Z" flag)
6282 * at this point. Should we check to see if the parent is still alive,
6283 * e.g. by using OpenProcess?
6286 result
= PeekNamedPipe(sig_pipe_handle
, NULL
, 0, NULL
, &avail
, NULL
);
6288 if (!result
|| avail
> 0) {
6289 /* peek failed or some bytes really available */
6290 /* (if not piping from stdin this would fail) */
6291 ws_info("Signal pipe: Stop capture: %s", sig_pipe_name
);
6292 ws_debug("Signal pipe: %s (%p) result: %u avail: %lu", sig_pipe_name
,
6293 sig_pipe_handle
, result
, avail
);
6296 /* pipe ok and no bytes available */
6303 * Editor modelines - https://www.wireshark.org/tools/modelines.html
6308 * indent-tabs-mode: nil
6311 * vi: set shiftwidth=4 tabstop=8 expandtab:
6312 * :indentSize=4:tabSize=8:noTabs=true: