update epan/dissectors/pidl/drsuapi/drsuapi.idl from samba
[wireshark-sm.git] / dumpcap.c
blob58ba8b2694313ec19d360fd122ee485fed0fde41
1 /* dumpcap.c
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
8 */
10 #include <config.h>
11 #define WS_LOG_DOMAIN LOG_DOMAIN_CAPCHILD
13 #include <stdio.h>
14 #include <stdlib.h> /* for exit() */
15 #include <glib.h>
17 #include <string.h>
19 #include <ws_exit_codes.h>
21 #include <sys/types.h>
23 #ifdef HAVE_NETINET_IN_H
24 #include <netinet/in.h>
25 #endif
27 #include <wsutil/ws_getopt.h>
29 #if defined(__APPLE__) && defined(__LP64__)
30 #include <sys/utsname.h>
31 #endif
33 #include <signal.h>
34 #include <errno.h>
36 #include <wsutil/array.h>
37 #include <wsutil/cmdarg_err.h>
38 #include <wsutil/strtoi.h>
39 #include <cli_main.h>
40 #include <wsutil/version_info.h>
42 #include <wsutil/socket.h>
43 #include <wsutil/wslog.h>
44 #include <wsutil/file_util.h>
46 #ifdef HAVE_LIBCAP
47 # include <sys/prctl.h>
48 # include <sys/capability.h>
49 #endif
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"
56 #ifdef _WIN32
57 #include "capture/capture-wpcap.h"
58 #endif /* _WIN32 */
60 #include "writecap/pcapio.h"
62 #ifndef _WIN32
63 #include <sys/un.h>
64 #endif
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"
89 #include "extcap.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 */
110 #ifdef _WIN32
111 #include "wsutil/win32-utils.h"
112 #ifdef DEBUG_DUMPCAP
113 #include <conio.h> /* _getch() */
114 #endif
115 #endif
117 #ifdef DEBUG_CHILD_DUMPCAP
118 FILE *debug_log; /* for logging debug messages to */
119 /* a file if DEBUG_CHILD_DUMPCAP */
120 /* is defined */
121 #include <stdarg.h> /* va_copy */
122 #endif
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 */
132 #ifdef _WIN32
133 static char *sig_pipe_name;
134 static HANDLE sig_pipe_handle;
135 static bool signal_pipe_check_running(void);
136 #endif
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.
143 WS_DLL_PUBLIC int
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
148 * the sync pipe.
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()
153 if (capture_child) {
154 return 1;
156 #ifdef HAVE_LIBCAP
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");
198 return 1;
200 #endif
201 return 0;
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.
211 return "exitcode=0";
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.
221 return "exitcode=0";
223 #endif
225 #ifdef SIGINFO
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 */
228 #endif /* SIGINFO */
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
245 #endif
247 /** init the capture filter */
248 typedef enum {
249 INITFILTER_NO_ERROR,
250 INITFILTER_BAD_FILTER,
251 INITFILTER_OTHER_ERROR
252 } initfilter_status_t;
254 typedef enum {
255 STATE_EXPECT_REC_HDR,
256 STATE_READ_REC_HDR,
257 STATE_EXPECT_DATA,
258 STATE_READ_DATA
259 } cap_pipe_state_t;
261 typedef enum {
262 PIPOK,
263 PIPEOF,
264 PIPERR,
265 PIPNEXIST
266 } cap_pipe_err_t;
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 */
272 } pcap_pipe_info_t;
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 {
285 uint32_t received;
286 uint32_t dropped;
287 uint32_t flushed;
288 pcap_t *pcap_h;
289 #ifdef MUST_DO_SELECT
290 int pcap_fd; /**< pcap file descriptor */
291 #endif
292 bool pcap_err;
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. */
295 GThread *tid;
296 int snaplen;
297 int linktype;
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 */
303 union {
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 */
306 } cap_pipe_info;
307 #ifdef _WIN32
308 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
309 #endif
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 */
315 #if defined(_WIN32)
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 */
319 #else
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 */
322 #endif
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;
327 #if defined(_WIN32)
328 GMutex *cap_pipe_read_mtx;
329 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
330 #endif
331 } capture_src;
333 typedef struct _saved_idb {
334 bool deleted;
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. */
337 unsigned idb_len;
338 } saved_idb_t;
341 * Global capture loop state.
343 typedef struct _loop_data {
344 /* common */
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 */
349 #ifdef SIGINFO
350 bool report_packet_count; /**< Set by SIGINFO handler; print packet count */
351 #endif
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 */
357 /* output file(s) */
358 FILE *pdh;
359 int save_file_fd;
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. */
364 int file_count;
365 /* ring buffer conditions */
366 GTimer *file_duration_timer;
367 time_t next_interval_time;
368 int interval_s;
369 } loop_data;
371 typedef struct _pcap_queue_element {
372 capture_src *pcap_src;
373 union {
374 struct pcap_pkthdr phdr;
375 pcapng_block_header_t bh;
376 } u;
377 uint8_t *pd;
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)
398 #else
399 #define CAP_READ_TIMEOUT 250
400 #endif
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.
413 #if defined(_WIN32)
414 #define PIPE_READ_TIMEOUT 100000
415 #else
416 #define PIPE_READ_TIMEOUT 250000
417 #endif
419 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
421 static void
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,
426 void *user_data);
428 /* capture related options */
429 static capture_options global_capture_opts;
430 static GPtrArray *capture_comments;
431 static bool quiet;
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,
437 const uint8_t *pd);
438 static void capture_loop_queue_packet_cb(uint8_t *pcap_src_p, const struct pcap_pkthdr *phdr,
439 const uint8_t *pd);
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,
446 bool is_close);
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
458 static void
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"
469 #else
470 " or for remote capturing, use this format:\n"
471 #endif
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");
482 #else
483 fprintf(output, " packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
484 #endif
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");
489 #endif
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);
493 #endif
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");
517 #endif
518 #endif
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");
560 #ifdef __linux__
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");
566 #endif
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
576 * just print it.
578 static void
579 dumpcap_cmdarg_err(const char *fmt, va_list ap)
581 if (capture_child) {
582 char *msg;
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, "");
586 g_free(msg);
587 } else {
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
597 * just print it.
599 static void
600 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
602 if (capture_child) {
603 char *msg;
604 msg = ws_strdup_vprintf(fmt, ap);
605 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, msg, "");
606 g_free(msg);
607 } else {
608 vfprintf(stderr, fmt, ap);
609 fprintf(stderr, "\n");
613 #ifdef HAVE_LIBCAP
614 static void
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 */
618 /* .... */
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);
624 cap_free(caps_text);
625 cap_free(caps);
629 static void
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");
640 cap_free(caps);
642 #endif
644 static void
645 get_capture_device_open_failure_messages(cap_device_open_status open_status,
646 const char *open_status_str,
647 const char *iface,
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);
658 break;
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);
664 break;
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);
670 break;
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);
676 break;
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);
682 break;
684 case CAP_DEVICE_OPEN_ERROR_OTHER:
685 default:
686 snprintf(errmsg, errmsg_len,
687 "The capture session could not be initiated on capture device \"%s\".\n(%s)",
688 iface, open_status_str);
689 break;
691 snprintf(secondary_errmsg, secondary_errmsg_len, "%s",
692 get_pcap_failure_secondary_error_message(open_status, open_status_str));
695 static bool
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
710 * use the netmask).
712 /*cmdarg_err(
713 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
714 netmask = 0;
718 * Sigh. Older versions of libpcap don't properly declare the
719 * third argument to pcap_compile() as a const pointer. Cast
720 * away the warning.
722 DIAG_OFF(cast-qual)
723 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
724 return false;
725 DIAG_ON(cast-qual)
726 return true;
729 static bool
730 show_filter_code(capture_options *capture_opts)
732 interface_options *interface_opts;
733 pcap_t *pcap_h;
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;
740 u_int i;
741 unsigned j;
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,
752 secondary_errmsg,
753 sizeof secondary_errmsg);
754 /* And report them */
755 report_capture_error(errmsg, secondary_errmsg);
756 return false;
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)) {
763 pcap_close(pcap_h);
764 report_capture_error(errmsg, secondary_errmsg);
765 return false;
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));
772 pcap_close(pcap_h);
773 report_cfilter_error(capture_opts, j, errmsg);
774 return false;
776 pcap_close(pcap_h);
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. */
793 #ifndef HAVE_LIBCAP
794 relinquish_special_privs_perm();
795 #else
796 relinquish_all_capabilities();
797 #endif
798 if (capture_child) {
799 /* Let our parent know we succeeded. */
800 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
802 return true;
805 static void
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"
813 static int
814 print_machine_readable_interfaces(GList *if_list, int caps_queries, bool print_statistics)
816 GList *if_entry;
817 if_info_t *if_info;
818 GSList *addr;
819 if_addr_t *if_addr;
820 char addr_str[WS_INET6_ADDRSTRLEN];
821 int status;
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) {
859 case IF_AT_IPv4:
860 json_dumper_value_string(&dumper, ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str, sizeof(addr_str)));
861 break;
862 case IF_AT_IPv6:
863 json_dumper_value_string(&dumper, ws_inet_ntop6(&if_addr->addr.ip6_addr, addr_str, sizeof(addr_str)));
864 break;
865 default:
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)) {
888 status = 0;
889 if (capture_child) {
890 if (print_statistics) {
891 sync_pipe_write_string_msg(sync_pipe_fd, SP_IFACE_LIST, dumper.output_string->str);
892 } else {
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);
897 } else {
898 printf("%s", dumper.output_string->str);
900 } else {
901 status = 2;
902 if (capture_child) {
903 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, "Unexpected JSON error", "");
904 } else {
905 cmdarg_err("Unexpected JSON error");
908 g_string_free(dumper.output_string, TRUE);
909 return status;
913 * If you change the machine-readable output format of this function,
914 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
916 static void
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;
939 else
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;
959 else
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;
980 else
981 desc_str = "(none)";
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);
993 typedef struct {
994 char *name;
995 pcap_t *pch;
996 } if_stat_t;
998 /* Print the number of packets captured for each interface until we're killed. */
999 static int
1000 print_statistics_loop(bool machine_readable)
1002 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1003 if_info_t *if_info;
1004 if_stat_t *if_stat;
1005 int err;
1006 char *err_str;
1007 pcap_t *pch;
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) {
1013 if (err == 0) {
1014 cmdarg_err("There are no interfaces on which a capture can be done");
1015 err = WS_EXIT_NO_INTERFACES;
1017 else {
1018 cmdarg_err("%s", err_str);
1019 g_free(err_str);
1021 return err;
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;
1027 #ifdef __linux__
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);
1033 continue;
1035 #endif
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);
1044 else
1045 #endif
1046 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1048 if (pch) {
1049 if_stat = g_new(if_stat_t, 1);
1050 if_stat->name = g_strdup(if_info->name);
1051 if_stat->pch = pch;
1052 stat_list = g_list_append(stat_list, if_stat);
1056 if (!stat_list) {
1057 cmdarg_err("There are no interfaces on which a capture can be done");
1058 return 2;
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",
1068 "Dropped");
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);
1080 } else {
1081 printf("%s\t%u\t%u\n", if_stat->name,
1082 ps.ps_recv, ps.ps_drop);
1083 fflush(stdout);
1087 #ifdef _WIN32
1088 /* If we have a dummy signal pipe check it */
1089 if (!signal_pipe_check_running()) {
1090 global_ld.go = false;
1092 Sleep(1 * 1000);
1093 #else
1094 sleep(1);
1095 #endif
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);
1103 g_free(if_stat);
1105 g_list_free(stat_list);
1106 free_interface_list(if_list);
1108 return 0;
1112 #ifdef _WIN32
1113 static BOOL WINAPI
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();
1137 return true;
1138 } else {
1139 return false;
1142 #else
1143 static void
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();
1152 #endif
1155 static void
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 */
1162 fflush(stderr);
1167 #ifdef SIGINFO
1168 static void
1169 report_counts_for_siginfo(void)
1171 report_capture_count(quiet);
1172 infoprint = false; /* we just reported it */
1175 static void
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). */
1183 if (infodelay)
1184 infoprint = true;
1185 else
1186 report_counts_for_siginfo();
1187 errno = sav_errno;
1189 #endif /* SIGINFO */
1191 static void
1192 exit_main(int status)
1194 ws_cleanup_sockets();
1196 #ifdef _WIN32
1197 /* can be helpful for debugging */
1198 #ifdef DEBUG_DUMPCAP
1199 printf("Press any key\n");
1200 _getch();
1201 #endif
1203 #endif /* _WIN32 */
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'. */
1208 ringbuf_free();
1209 global_capture_opts.save_file = NULL;
1212 capture_opts_cleanup(&global_capture_opts);
1213 exit(status);
1216 #ifdef HAVE_LIBCAP
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)
1222 static void
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
1233 * suid privileges.
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);
1313 cap_free(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
1328 all platforms. */
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
1343 static int
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)
1350 return (dlt);
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);
1362 #endif
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);
1375 #endif
1377 /* For all other DLT_s with values beyond 104, the value
1378 of the corresponding LINKTYPE_ is the same. */
1379 if (dlt >= 104)
1380 return (dlt);
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);
1401 #endif
1402 #ifdef DLT_RAW
1403 if (dlt == DLT_RAW)
1404 return (LINKTYPE_RAW);
1405 #endif
1406 #ifdef DLT_SLIP_BSDOS
1407 if (dlt == DLT_SLIP_BSDOS)
1408 return (LINKTYPE_SLIP_BSDOS);
1409 #endif
1410 #ifdef DLT_PPP_BSDOS
1411 if (dlt == DLT_PPP_BSDOS)
1412 return (LINKTYPE_PPP_BSDOS);
1413 #endif
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
1422 platform.
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
1427 LINKTYPE_.
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. */
1433 #ifdef DLT_FR
1434 /* BSD/OS Frame Relay */
1435 if (dlt == DLT_FR)
1436 return (LINKTYPE_FRELAY);
1437 #endif
1438 #if defined(DLT_HDLC) && DLT_HDLC != LINKTYPE_NETBSD_HDLC
1439 /* NetBSD HDLC */
1440 if (dlt == DLT_HDLC)
1441 return (LINKTYPE_NETBSD_HDLC);
1442 #endif
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);
1447 #endif
1448 #if defined(DLT_LOOP) && DLT_LOOP != LINKTYPE_LOOP
1449 /* OpenBSD DLT_LOOP */
1450 if (dlt == DLT_LOOP)
1451 return (LINKTYPE_LOOP);
1452 #endif
1453 #if defined(DLT_ENC) && DLT_ENC != LINKTYPE_ENC
1454 /* OpenBSD DLT_ENC */
1455 if (dlt == DLT_ENC)
1456 return (LINKTYPE_ENC);
1457 #endif
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. */
1463 #ifdef DLT_ATM_CLIP
1464 /* Linux ATM Classical IP */
1465 if (dlt == DLT_ATM_CLIP)
1466 return (LINKTYPE_ATM_CLIP);
1467 #endif
1469 /* Treat all other DLT_s as having the same value as the
1470 corresponding LINKTYPE_. */
1471 return (dlt);
1474 /* Take care of byte order in the libpcap headers read from pipes.
1475 * (function taken from wiretap/libpcap.c) */
1476 static void
1477 cap_pipe_adjust_pcap_header(bool byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1479 if (byte_swapped) {
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))) {
1497 uint32_t temp;
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,
1506 * or just read().
1508 static ssize_t
1509 cap_pipe_read(int pipe_fd, char *buf, size_t sz, bool from_socket _U_)
1511 #ifdef _WIN32
1512 if (from_socket) {
1513 return recv(pipe_fd, buf, (int)sz, 0);
1514 } else {
1515 return -1;
1517 #else
1518 return ws_read(pipe_fd, buf, sz);
1519 #endif
1522 #if defined(_WIN32)
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;
1542 #ifdef _WIN32
1543 BOOL res;
1544 DWORD last_err, bytes_read;
1545 #else /* _WIN32 */
1546 size_t bytes_read;
1547 #endif /* _WIN32 */
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);
1553 bytes_read = 0;
1554 while (bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1555 if ((pcap_src->from_cap_socket)
1556 #ifndef _WIN32
1557 || 1
1558 #endif
1561 ssize_t b;
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);
1564 if (b <= 0) {
1565 if (b == 0) {
1566 pcap_src->cap_pipe_err = PIPEOF;
1567 bytes_read = 0;
1568 break;
1569 } else {
1570 pcap_src->cap_pipe_err = PIPERR;
1571 bytes_read = -1;
1572 break;
1574 } else {
1575 bytes_read += (DWORD)b;
1578 #ifdef _WIN32
1579 else
1581 /* If we try to use read() on a named pipe on Windows with partial
1582 * data it appears to return EOF.
1584 DWORD b;
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,
1587 &b, NULL);
1589 bytes_read += b;
1590 if (!res) {
1591 last_err = GetLastError();
1592 if (last_err == ERROR_MORE_DATA) {
1593 continue;
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;
1596 bytes_read = 0;
1597 break;
1599 pcap_src->cap_pipe_err = PIPERR;
1600 bytes_read = -1;
1601 break;
1602 } else if (b == 0 && pcap_src->cap_pipe_bytes_to_read > 0) {
1603 pcap_src->cap_pipe_err = PIPEOF;
1604 bytes_read = 0;
1605 break;
1608 #endif /*_WIN32 */
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);
1623 return NULL;
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
1633 * sockets.
1635 void
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);
1645 #endif
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.
1652 static int
1653 cap_pipe_select(int pipe_fd)
1655 fd_set rfds;
1656 struct timeval timeout;
1658 FD_ZERO(&rfds);
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
1669 static int
1670 cap_open_socket(char *pipename, capture_src *pcap_src, char *errmsg, size_t errmsgl)
1672 struct sockaddr_storage sa;
1673 socklen_t sa_len;
1674 int fd;
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;
1682 return -1;
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"
1689 #ifdef _WIN32
1690 " %s", win32strerror(WSAGetLastError()));
1691 #else
1692 " %d: %s", errno, g_strerror(errno));
1693 #endif
1694 pcap_src->cap_pipe_err = PIPERR;
1695 return -1;
1698 if (sa.ss_family == AF_INET6)
1699 sa_len = sizeof(struct sockaddr_in6);
1700 else
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"
1706 #ifdef _WIN32
1707 " %s", win32strerror(WSAGetLastError()));
1708 #else
1709 " %d: %s", errno, g_strerror(errno));
1710 #endif
1711 pcap_src->cap_pipe_err = PIPERR;
1713 cap_pipe_close(fd, true);
1714 return -1;
1717 pcap_src->from_cap_socket = true;
1718 return fd;
1721 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1722 * otherwise.
1724 static void
1725 cap_pipe_close(int pipe_fd, bool from_socket)
1727 #ifdef _WIN32
1728 if (from_socket) {
1729 closesocket(pipe_fd);
1731 #else
1732 (void) from_socket; /* Mark unused, similar to Q_UNUSED */
1733 ws_close(pipe_fd);
1734 #endif
1737 /** Read bytes from a capture source, which is assumed to be a pipe or
1738 * socket.
1740 * Returns -1, or the number of bytes read similar to read(2).
1741 * Sets pcap_src->cap_pipe_err on error or EOF.
1743 static ssize_t
1744 cap_pipe_read_data_bytes(capture_src *pcap_src, char *errmsg, size_t errmsgl)
1746 int sel_ret;
1747 int fd = pcap_src->cap_pipe_fd;
1748 #ifdef _WIN32
1749 DWORD sz, bytes_read = 0;
1750 #else /* _WIN32 */
1751 ssize_t sz, bytes_read = 0;
1752 #endif /* _WIN32 */
1753 ssize_t b;
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);
1758 #endif
1759 sz = pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read;
1760 while (bytes_read < sz) {
1761 if (fd == -1) {
1762 snprintf(errmsg, errmsgl, "Invalid file descriptor.");
1763 pcap_src->cap_pipe_err = PIPNEXIST;
1764 return -1;
1767 sel_ret = cap_pipe_select(fd);
1768 if (sel_ret < 0) {
1769 snprintf(errmsg, errmsgl,
1770 "Unexpected error from select: %s.", g_strerror(errno));
1771 pcap_src->cap_pipe_err = PIPERR;
1772 return -1;
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);
1776 if (b <= 0) {
1777 if (b == 0) {
1778 snprintf(errmsg, errmsgl,
1779 "End of file reading from pipe or socket.");
1780 pcap_src->cap_pipe_err = PIPEOF;
1781 } else {
1782 #ifdef _WIN32
1784 * On Windows, we only do this for sockets.
1786 DWORD lastError = WSAGetLastError();
1787 errno = lastError;
1788 snprintf(errmsg, errmsgl,
1789 "Error reading from pipe or socket: %s.",
1790 win32strerror(lastError));
1791 #else
1792 snprintf(errmsg, errmsgl,
1793 "Error reading from pipe or socket: %s.",
1794 g_strerror(errno));
1795 #endif
1796 pcap_src->cap_pipe_err = PIPERR;
1798 return -1;
1800 #ifdef _WIN32
1801 bytes_read += (DWORD)b;
1802 #else
1803 bytes_read += b;
1804 #endif
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);
1811 #endif
1812 return bytes_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) */
1836 static void
1837 cap_pipe_open_live(char *pipename,
1838 capture_src *pcap_src,
1839 void *hdr,
1840 char *errmsg, size_t errmsgl,
1841 char *secondary_errmsg, size_t secondary_errmsgl)
1843 #ifndef _WIN32
1844 ws_statb64 pipe_stat;
1845 struct sockaddr_un sa;
1846 #else /* _WIN32 */
1847 uintptr_t extcap_pipe_handle;
1848 #endif
1849 bool extcap_pipe = false;
1850 ssize_t b;
1851 int fd = -1, sel_ret;
1852 size_t bytes_read;
1853 uint32_t magic = 0;
1854 pcap_src->cap_pipe_fd = -1;
1855 #ifdef _WIN32
1856 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1857 #endif
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) {
1866 #ifndef _WIN32
1867 fd = 0; /* read from stdin */
1868 #else /* _WIN32 */
1869 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1870 #endif /* _WIN32 */
1871 } else if (!strncmp(pipename, "TCP@", 4)) {
1872 if ((fd = cap_open_socket(pipename, pcap_src, errmsg, errmsgl)) < 0) {
1873 return;
1875 } else {
1876 #ifndef _WIN32
1877 if ( g_strrstr(pipename, EXTCAP_PIPE_PREFIX) != NULL )
1878 extcap_pipe = true;
1880 if (ws_stat64(pipename, &pipe_stat) < 0) {
1881 if (errno == ENOENT || errno == ENOTDIR)
1882 pcap_src->cap_pipe_err = PIPNEXIST;
1883 else {
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;
1889 return;
1891 if (S_ISFIFO(pipe_stat.st_mode)) {
1892 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1893 if (fd == -1) {
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;
1898 return;
1900 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1901 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1902 if (fd == -1) {
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;
1907 return;
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).
1922 * It also says
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;
1939 ws_close(fd);
1940 return;
1942 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1943 if (b == -1) {
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;
1948 ws_close(fd);
1949 return;
1951 } else {
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;
1958 } else {
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;
1964 return;
1967 #else /* _WIN32 */
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.
1973 extcap_pipe = true;
1974 pcap_src->cap_pipe_h = (HANDLE)extcap_pipe_handle;
1976 else
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;
1983 return;
1986 /* Wait for the pipe to appear */
1987 while (1) {
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)
1992 break;
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;
2000 return;
2003 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
2004 snprintf(errmsg, errmsgl,
2005 "The capture session on \"%s\" timed out during "
2006 "pipe open: %s.",
2007 pipename, win32strerror(GetLastError()));
2008 pcap_src->cap_pipe_err = PIPERR;
2009 return;
2013 #endif /* _WIN32 */
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.
2035 #ifdef _WIN32
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)
2045 #endif
2047 bytes_read = 0;
2048 while (bytes_read < sizeof magic) {
2049 sel_ret = cap_pipe_select(fd);
2050 if (sel_ret < 0) {
2051 snprintf(errmsg, errmsgl,
2052 "Unexpected error from select: %s.",
2053 g_strerror(errno));
2054 goto error;
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)
2061 goto error;
2063 if (b <= 0) {
2064 if (b == 0)
2065 snprintf(errmsg, errmsgl,
2066 "End of file on pipe magic during open.");
2067 else
2068 snprintf(errmsg, errmsgl,
2069 "Error on pipe magic during open: %s.",
2070 g_strerror(errno));
2071 goto error;
2073 bytes_read += b;
2077 #ifdef _WIN32
2078 else {
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)
2085 goto error;
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.");
2091 else
2092 snprintf(errmsg, errmsgl,
2093 "Error on pipe magic during open: %s.",
2094 g_strerror(errno));
2095 goto error;
2098 #endif
2100 switch (magic) {
2101 case PCAP_MAGIC:
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;
2109 break;
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;
2116 break;
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;
2126 break;
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;
2134 break;
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 */
2141 break;
2142 default:
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",
2148 not_our_bug);
2149 goto error;
2152 if (pcap_src->from_pcapng)
2153 pcapng_pipe_open_live(fd, pcap_src, errmsg, errmsgl);
2154 else
2155 pcap_pipe_open_live(fd, pcap_src, (struct pcap_hdr *) hdr, errmsg, errmsgl,
2156 secondary_errmsg, secondary_errmsgl);
2158 return;
2160 error:
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;
2165 #ifdef _WIN32
2166 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2167 #endif
2171 * Read the part of the pcap file header that follows the magic
2172 * number (we've already read the magic number).
2174 static void
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)
2181 size_t bytes_read;
2182 ssize_t b;
2183 int sel_ret;
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.)
2193 #ifdef _WIN32
2194 if (pcap_src->from_cap_socket)
2195 #endif
2197 /* Keep reading until we get the rest of the header. */
2198 bytes_read = 0;
2199 while (bytes_read < sizeof(struct pcap_hdr)) {
2200 sel_ret = cap_pipe_select(fd);
2201 if (sel_ret < 0) {
2202 snprintf(errmsg, errmsgl,
2203 "Unexpected error from select: %s.",
2204 g_strerror(errno));
2205 goto error;
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);
2210 if (b <= 0) {
2211 if (b == 0)
2212 snprintf(errmsg, errmsgl,
2213 "End of file on pipe header during open.");
2214 else
2215 snprintf(errmsg, errmsgl,
2216 "Error on pipe header during open: %s.",
2217 g_strerror(errno));
2218 snprintf(secondary_errmsg, secondary_errmsgl,
2219 "%s", not_our_bug);
2220 goto error;
2222 bytes_read += b;
2226 #ifdef _WIN32
2227 else {
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.");
2233 else
2234 snprintf(errmsg, errmsgl,
2235 "Error on pipe header header during open: %s.",
2236 g_strerror(errno));
2237 snprintf(secondary_errmsg, secondary_errmsgl, "%s",
2238 not_our_bug);
2239 goto error;
2242 #endif
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
2255 * are the same.
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;
2269 break;
2271 case 279: /* DLT_EBHSCR */
2272 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_EBHSCR;
2273 break;
2275 case 249: /* DLT_USBPCAP */
2276 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_USBPCAP;
2277 break;
2279 default:
2280 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
2281 break;
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",
2289 not_our_bug);
2290 goto error;
2293 pcap_src->cap_pipe_fd = fd;
2294 return;
2296 error:
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;
2301 #ifdef _WIN32
2302 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2303 #endif
2307 * Synchronously read the fixed portion of the pcapng section header block
2308 * (we've already read the pcapng block header).
2310 static int
2311 pcapng_read_shb(capture_src *pcap_src,
2312 char *errmsg,
2313 size_t errmsgl)
2315 pcapng_section_header_block_t shb;
2317 #ifdef _WIN32
2318 if (pcap_src->from_cap_socket)
2319 #endif
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) {
2323 return -1;
2326 #ifdef _WIN32
2327 else {
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.");
2334 else
2335 snprintf(errmsg, errmsgl,
2336 "Error reading from pipe or socket: %s.",
2337 g_strerror(errno));
2338 return -1;
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);
2343 #endif
2344 memcpy(&shb, pcap_src->cap_pipe_databuf + sizeof(pcapng_block_header_t), sizeof(pcapng_section_header_block_t));
2345 switch (shb.magic)
2347 case PCAPNG_MAGIC:
2348 ws_debug("pcapng SHB MAGIC");
2349 break;
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
2356 * elsewhere.
2358 * XXX - punting means that the Wireshark test suite must be
2359 * modified to:
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
2366 * being run;
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"
2381 #else
2382 #define OUR_ENDIAN "little"
2383 #define IFACE_ENDIAN "big"
2384 #endif
2385 snprintf(errmsg, errmsgl,
2386 "Interface %u is " IFACE_ENDIAN " endian but we're " OUR_ENDIAN " endian.",
2387 pcap_src->interface_id);
2388 return -1;
2389 default:
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.");
2393 return -1;
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;
2401 return 0;
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.
2409 static bool
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
2420 * buffer files.
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);
2434 } else {
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);
2452 break;
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);
2469 break;
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. */
2475 break;
2477 /* The interface ID is the first 32-bit field after the BH for both EPBs and ISBs. */
2478 uint32_t iface_id;
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);
2483 } else {
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);
2485 return false;
2488 break;
2489 default:
2490 break;
2493 return true;
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) {
2504 case BLOCK_TYPE_PB:
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:
2511 return true;
2512 default:
2513 break;
2515 return false;
2519 * Read the part of the initial pcapng SHB following the block type
2520 * (we've already read the block type).
2522 static void
2523 pcapng_pipe_open_live(int fd,
2524 capture_src *pcap_src,
2525 char *errmsg,
2526 size_t errmsgl)
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
2536 * block length.
2538 #ifdef _WIN32
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)
2548 #endif
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) {
2555 goto error;
2557 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(pcapng_block_header_t));
2559 #ifdef _WIN32
2560 else {
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.");
2570 else
2571 snprintf(errmsg, errmsgl,
2572 "Error reading from pipe or socket: %s.",
2573 g_strerror(errno));
2574 goto error;
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;
2580 #endif
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);
2585 goto error;
2587 if (pcapng_read_shb(pcap_src, errmsg, errmsgl)) {
2588 goto error;
2591 return;
2593 error:
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;
2598 #ifdef _WIN32
2599 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2600 #endif
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. */
2605 static int
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,
2610 PD_ERR } result;
2611 #ifdef _WIN32
2612 void * q_status;
2613 #endif
2614 ssize_t b;
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");
2620 #endif
2622 switch (pcap_src->cap_pipe_state) {
2624 case STATE_EXPECT_REC_HDR:
2625 #ifdef _WIN32
2626 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2627 #endif
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;
2634 #ifdef _WIN32
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);
2639 #endif
2640 /* Fall through */
2642 case STATE_READ_REC_HDR:
2643 #ifdef _WIN32
2644 if (pcap_src->from_cap_socket)
2645 #endif
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);
2649 if (b <= 0) {
2650 if (b == 0)
2651 result = PD_PIPE_EOF;
2652 else
2653 result = PD_PIPE_ERR;
2654 break;
2656 #ifdef _WIN32
2657 pcap_src->cap_pipe_bytes_read += (DWORD)b;
2658 #else
2659 pcap_src->cap_pipe_bytes_read += b;
2660 #endif
2662 #ifdef _WIN32
2663 else {
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;
2667 break;
2668 } else if (pcap_src->cap_pipe_err == PIPERR) {
2669 result = PD_PIPE_ERR;
2670 break;
2672 if (!q_status) {
2673 return 0;
2676 #endif
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. */
2679 return 0;
2681 result = PD_REC_HDR_READ;
2682 break;
2684 case STATE_EXPECT_DATA:
2685 #ifdef _WIN32
2686 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2687 #endif
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;
2693 #ifdef _WIN32
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);
2698 #endif
2699 /* Fall through */
2701 case STATE_READ_DATA:
2702 #ifdef _WIN32
2703 if (pcap_src->from_cap_socket)
2704 #endif
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);
2710 if (b <= 0) {
2711 if (b == 0)
2712 result = PD_PIPE_EOF;
2713 else
2714 result = PD_PIPE_ERR;
2715 break;
2717 #ifdef _WIN32
2718 pcap_src->cap_pipe_bytes_read += (DWORD)b;
2719 #else
2720 pcap_src->cap_pipe_bytes_read += b;
2721 #endif
2723 #ifdef _WIN32
2724 else {
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;
2729 break;
2730 } else if (pcap_src->cap_pipe_err == PIPERR) {
2731 result = PD_PIPE_ERR;
2732 break;
2734 if (!q_status) {
2735 return 0;
2738 #endif /* _WIN32 */
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. */
2741 return 0;
2743 result = PD_DATA_READ;
2744 break;
2746 default:
2747 snprintf(errmsg, errmsgl,
2748 "pcap_pipe_dispatch: invalid state");
2749 result = PD_ERR;
2751 } /* switch (pcap_src->cap_pipe_state) */
2754 * We've now read as much data as we were expecting, so process it.
2756 switch (result) {
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);
2774 break;
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
2780 * 2.
2782 new_bufsize = pcap_info->rechdr.hdr.incl_len;
2784 * https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2786 new_bufsize--;
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;
2792 new_bufsize++;
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;
2803 return 0;
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.
2810 /* FALLTHROUGH */
2812 case PD_DATA_READ:
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;
2822 if (use_threads) {
2823 capture_loop_queue_packet_cb((uint8_t *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2824 } else {
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;
2832 return 1;
2834 case PD_PIPE_EOF:
2835 pcap_src->cap_pipe_err = PIPEOF;
2836 return -1;
2838 case PD_PIPE_ERR:
2839 snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2840 #ifdef _WIN32
2841 win32strerror(GetLastError()));
2842 #else
2843 g_strerror(errno));
2844 #endif
2845 /* Fall through */
2846 case PD_ERR:
2847 break;
2850 pcap_src->cap_pipe_err = PIPERR;
2851 /* Return here rather than inside the switch to prevent GCC warning */
2852 return -1;
2855 static int
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,
2859 PD_ERR } result;
2860 #ifdef _WIN32
2861 void * q_status;
2862 #endif
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");
2868 #endif
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");
2875 #endif
2876 #ifdef _WIN32
2877 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2878 #endif
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;
2884 #ifdef _WIN32
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);
2891 #endif
2892 /* Fall through */
2894 case STATE_READ_REC_HDR:
2895 #ifdef LOG_CAPTURE_VERBOSE
2896 ws_debug("pcapng_pipe_dispatch STATE_READ_REC_HDR");
2897 #endif
2898 #ifdef _WIN32
2899 if (pcap_src->from_cap_socket) {
2900 #endif
2901 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2902 return -1;
2904 #ifdef _WIN32
2905 } else {
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;
2909 break;
2910 } else if (pcap_src->cap_pipe_err == PIPERR) {
2911 result = PD_PIPE_ERR;
2912 break;
2914 if (!q_status) {
2915 return 0;
2918 #endif
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. */
2921 return 0;
2923 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(pcapng_block_header_t));
2924 result = PD_REC_HDR_READ;
2925 break;
2927 case STATE_EXPECT_DATA:
2928 #ifdef LOG_CAPTURE_VERBOSE
2929 ws_debug("pcapng_pipe_dispatch STATE_EXPECT_DATA");
2930 #endif
2931 #ifdef _WIN32
2932 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2933 #endif
2934 pcap_src->cap_pipe_state = STATE_READ_DATA;
2935 pcap_src->cap_pipe_bytes_to_read = bh->block_total_length;
2937 #ifdef _WIN32
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);
2946 #endif
2947 /* Fall through */
2949 case STATE_READ_DATA:
2950 #ifdef LOG_CAPTURE_VERBOSE
2951 ws_debug("pcapng_pipe_dispatch STATE_READ_DATA");
2952 #endif
2953 #ifdef _WIN32
2954 if (pcap_src->from_cap_socket) {
2955 #endif
2956 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2957 return -1;
2959 #ifdef _WIN32
2960 } else {
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;
2965 break;
2966 } else if (pcap_src->cap_pipe_err == PIPERR) {
2967 result = PD_PIPE_ERR;
2968 break;
2970 if (!q_status) {
2971 return 0;
2974 #endif /* _WIN32 */
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. */
2977 return 0;
2979 result = PD_DATA_READ;
2980 break;
2982 default:
2983 snprintf(errmsg, errmsgl,
2984 "pcapng_pipe_dispatch: invalid state");
2985 result = PD_ERR;
2987 } /* switch (pcap_src->cap_pipe_state) */
2990 * We've now read as much data as we were expecting, so process it.
2992 switch (result) {
2994 case PD_REC_HDR_READ:
2996 * We've read the pcapng block header, so we know the block type
2997 * and length.
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
3005 * the section.)
3007 * Continue the read process.
3009 pcapng_read_shb(pcap_src, errmsg, errmsgl);
3010 return 1;
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);
3017 break;
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);
3028 break;
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
3034 * 2.
3036 new_bufsize = bh->block_total_length;
3038 * https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
3040 new_bufsize--;
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;
3046 new_bufsize++;
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;
3056 return -1;
3060 * Now we want to read the block contents.
3062 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
3063 return 0;
3065 case PD_DATA_READ:
3067 * We've read the full contents of the block.
3068 * Process the block.
3070 if (use_threads) {
3071 capture_loop_queue_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
3072 } else {
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;
3080 return 1;
3082 case PD_PIPE_EOF:
3083 pcap_src->cap_pipe_err = PIPEOF;
3084 return -1;
3086 case PD_PIPE_ERR:
3087 snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
3088 #ifdef _WIN32
3089 win32strerror(GetLastError()));
3090 #else
3091 g_strerror(errno));
3092 #endif
3093 /* Fall through */
3094 case PD_ERR:
3095 break;
3098 pcap_src->cap_pipe_err = PIPERR;
3099 /* Return here rather than inside the switch to prevent GCC warning */
3100 return -1;
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. */
3106 static bool
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];
3113 char *sync_msg_str;
3114 interface_options *interface_opts;
3115 capture_src *pcap_src;
3116 unsigned i;
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.");
3122 return false;
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.");
3132 return false;
3135 #ifdef MUST_DO_SELECT
3136 pcap_src->pcap_fd = -1;
3137 #endif
3138 pcap_src->interface_id = i;
3139 pcap_src->linktype = -1;
3140 #ifdef _WIN32
3141 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
3142 #endif
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;
3147 #ifdef _WIN32
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();
3152 #endif
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);
3165 #endif
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;
3175 break;
3177 case CAPTURE_SAMP_BY_TIMER:
3178 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
3179 break;
3181 default:
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;
3191 } else {
3192 report_capture_error("Couldn't set the capture sampling",
3193 "Cannot get packet sampling data structure");
3196 #endif
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,
3201 errmsg, errmsg_len,
3202 secondary_errmsg, secondary_errmsg_len)) {
3203 return false;
3205 pcap_src->linktype = dlt_to_linktype(get_pcap_datalink(pcap_src->pcap_h, interface_opts->name));
3206 } else {
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,
3212 errmsg, errmsg_len,
3213 secondary_errmsg, secondary_errmsg_len);
3215 #ifdef _WIN32
3216 if (pcap_src->from_cap_socket) {
3217 #endif
3218 if (pcap_src->cap_pipe_fd == -1) {
3219 pipe_err = true;
3221 #ifdef _WIN32
3222 } else {
3223 if (pcap_src->cap_pipe_h == INVALID_HANDLE_VALUE) {
3224 pipe_err = true;
3227 #endif
3229 if (pipe_err) {
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
3235 * the interface.
3237 get_capture_device_open_failure_messages(open_status,
3238 open_status_str,
3239 interface_opts->name,
3240 errmsg,
3241 errmsg_len,
3242 secondary_errmsg,
3243 secondary_errmsg_len);
3246 * Else pipe (or file) does exist and cap_pipe_open_live() has
3247 * filled in errmsg
3249 return false;
3250 } else {
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);
3264 #endif
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.)
3279 pcapng_src_count++;
3280 } else {
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
3297 * information?
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) */
3316 #ifndef HAVE_LIBCAP
3317 relinquish_special_privs_perm();
3318 #else
3319 relinquish_all_capabilities();
3320 #endif
3321 return true;
3324 /* close the capture input file (pcap or capture pipe) */
3325 static void capture_loop_close_input(loop_data *ld)
3327 unsigned i;
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;
3341 #ifdef _WIN32
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;
3346 #endif
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;
3356 } else {
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;
3366 ld->go = false;
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);
3391 #endif
3392 return INITFILTER_OTHER_ERROR;
3394 #ifdef HAVE_PCAP_FREECODE
3395 pcap_freecode(&fcode);
3396 #endif
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.
3406 static bool
3407 capture_loop_init_pcapng_output(capture_options *capture_opts, loop_data *ld,
3408 int *err)
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);
3416 return true;
3419 bool successful = true;
3420 GString *os_info_str = g_string_new("");
3422 *err = 0;
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);
3435 } else {
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 */
3445 &ld->bytes_written,
3446 err);
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
3457 * IDBs like so:
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 */
3479 &global_ld.err);
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;
3490 } else {
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 */
3500 pcap_src->linktype,
3501 pcap_src->snaplen,
3502 &(global_ld.bytes_written),
3503 0, /* IDB_IF_SPEED 8 */
3504 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3505 &global_ld.err);
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);
3513 return successful;
3516 /* set up to write to the already-opened capture output file/files */
3517 static bool
3518 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
3520 int err = 0;
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.");
3528 return false;
3531 /* Set up to write to the capture file. */
3532 if (capture_opts->multi_files_on) {
3533 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
3534 } else {
3535 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
3536 if (ld->pdh == NULL) {
3537 err = errno;
3538 } else {
3539 size_t buffsize = IO_BUF_SIZE;
3540 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
3541 ws_statb64 statb;
3543 if (ws_fstat64(ld->save_file_fd, &statb) == 0) {
3544 if (statb.st_blksize > IO_BUF_SIZE) {
3545 buffsize = statb.st_blksize;
3548 #endif
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);
3555 if (ld->pdh) {
3556 bool successful;
3557 if (capture_opts->use_pcapng) {
3558 successful = capture_loop_init_pcapng_output(capture_opts, ld, &err);
3559 } else {
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;
3564 } else {
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);
3570 if (!successful) {
3571 fclose(ld->pdh);
3572 ld->pdh = NULL;
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? */
3581 if (err < 0) {
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);
3586 } else {
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));
3592 return false;
3595 return true;
3598 static bool
3599 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
3602 unsigned int i;
3603 capture_src *pcap_src;
3604 uint64_t end_time = create_timestamp();
3605 bool success;
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);
3611 } else {
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;
3622 } else {
3623 isb_ifrecv = UINT64_MAX;
3624 isb_ifdrop = UINT64_MAX;
3626 pcapng_write_interface_statistics_block(ld->pdh,
3628 &ld->bytes_written,
3629 "Counters provided by dumpcap",
3630 start_time,
3631 end_time,
3632 isb_ifrecv,
3633 isb_ifdrop,
3634 err_close);
3638 if (fclose(ld->pdh) == EOF) {
3639 if (err_close != NULL) {
3640 *err_close = errno;
3642 success = false;
3643 } else {
3644 success = true;
3646 g_free(ld->io_buffer);
3647 ld->io_buffer = NULL;
3648 return success;
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
3661 * indefinitely.
3663 static int
3664 capture_loop_dispatch(loop_data *ld,
3665 char *errmsg, int errmsg_len, capture_src *pcap_src)
3667 int inpkts = 0;
3668 int packet_count_before;
3669 int sel_ret;
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");
3676 #endif
3677 #ifdef _WIN32
3678 if (pcap_src->from_cap_socket) {
3679 #endif
3680 sel_ret = cap_pipe_select(pcap_src->cap_pipe_fd);
3681 if (sel_ret <= 0) {
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());
3686 ld->go = false;
3689 #ifdef _WIN32
3690 } else {
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. */
3695 sel_ret = 1;
3697 #endif
3698 if (sel_ret > 0) {
3700 * "select()" says we can read from the pipe without blocking
3702 inpkts = pcap_src->cap_pipe_dispatch(ld, pcap_src, errmsg, errmsg_len);
3703 if (inpkts < 0) {
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);
3710 else
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");
3729 #endif
3730 if (pcap_src->pcap_fd != -1) {
3731 sel_ret = cap_pipe_select(pcap_src->pcap_fd);
3732 if (sel_ret > 0) {
3734 * "select()" says we can read from it without blocking; go for
3735 * it.
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.
3742 if (use_threads) {
3743 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (uint8_t *)pcap_src);
3744 } else {
3745 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (uint8_t *)pcap_src);
3747 if (inpkts < 0) {
3748 if (inpkts == -1) {
3749 /* Error, rather than pcap_breakloop(). */
3750 pcap_src->pcap_err = true;
3752 ld->go = false; /* error or pcap_breakloop() - stop capturing */
3754 } else {
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());
3759 ld->go = false;
3763 else
3764 #endif /* MUST_DO_SELECT */
3766 /* dispatch from pcap without select */
3767 #if 1
3768 #ifdef LOG_CAPTURE_VERBOSE
3769 ws_debug("capture_loop_dispatch: from pcap_dispatch");
3770 #endif
3771 #ifdef _WIN32
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.
3778 if (use_threads) {
3779 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (uint8_t *)pcap_src);
3780 } else {
3781 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (uint8_t *)pcap_src);
3783 #else
3784 if (use_threads) {
3785 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_queue_packet_cb, (uint8_t *)pcap_src);
3786 } else {
3787 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_write_packet_cb, (uint8_t *)pcap_src);
3789 #endif
3790 if (inpkts < 0) {
3791 if (inpkts == -1) {
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");
3800 #endif
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 */
3814 int in;
3815 struct pcap_pkthdr *pkt_header;
3816 uint8_t *pkt_data;
3818 in = 0;
3819 while(ld->go &&
3820 (in = pcap_next_ex(pcap_src->pcap_h, &pkt_header, &pkt_data)) == 1) {
3821 if (use_threads) {
3822 capture_loop_queue_packet_cb((uint8_t *)pcap_src, pkt_header, pkt_data);
3823 } else {
3824 capture_loop_write_packet_cb((uint8_t *)pcap_src, pkt_header, pkt_data);
3828 if (in < 0) {
3829 pcap_src->pcap_err = true;
3830 ld->go = false;
3833 #endif /* pcap_next_ex */
3837 #ifdef LOG_CAPTURE_VERBOSE
3838 ws_debug("capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3839 #endif
3841 return ld->packets_captured - packet_count_before;
3844 #ifdef _WIN32
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(). */
3849 static GString *
3850 isolate_uuid(const char *iface)
3852 char *ptr;
3853 GString *gstr;
3855 ptr = strchr(iface, '{');
3856 if (ptr == NULL)
3857 return g_string_new(iface);
3858 gstr = g_string_new(ptr + 1);
3860 ptr = strchr(gstr->str, '}');
3861 if (ptr == NULL)
3862 return gstr;
3864 gstr = g_string_truncate(gstr, ptr - gstr->str);
3865 return gstr;
3867 #endif
3869 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3870 /* Returns true if the file opened successfully, false otherwise. */
3871 static bool
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;
3877 bool is_tempfile;
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);
3896 return false;
3898 if (strcmp(capfile_name, "-") == 0) {
3899 /* write to stdout */
3900 *save_file_fd = 1;
3901 #ifdef _WIN32
3902 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3903 _setmode(1, O_BINARY);
3904 #endif
3905 } else {
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 ... */
3913 else {
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,
3931 g_strerror(errno));
3932 g_free(capfile_name);
3933 ringbuf_error_cleanup();
3934 return false;
3937 } else {
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;
3944 } else {
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);
3952 } else {
3954 * One interface; use its description, if it has one, to generate
3955 * the temporary file name, otherwise use its name.
3957 char *basename;
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) {
3967 * Yes - use it.
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
3971 * name.
3973 basename = g_path_get_basename(interface_opts->descr);
3974 } else {
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
3980 * name.
3982 basename = g_path_get_basename(interface_opts->name);
3983 #ifdef _WIN32
3985 * This is Windows, where we might have an ugly GUID-based
3986 * interface name.
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.
3996 GString *iface;
3997 iface = isolate_uuid(basename);
3998 g_free(basename);
3999 basename = g_strdup(iface->str);
4000 g_string_free(iface, TRUE);
4002 #endif
4004 /* generate the temp file name prefix */
4005 prefix = g_strconcat("wireshark_", basename, NULL);
4006 g_free(basename);
4009 /* Generate the appropriate suffix. */
4010 if (capture_opts->use_pcapng) {
4011 suffix = ".pcapng";
4012 } else {
4013 suffix = ".pcap";
4015 *save_file_fd = create_tempfile(capture_opts->temp_dir, &capfile_name, prefix, suffix, &err_tempfile);
4016 g_free(prefix);
4017 is_tempfile = true;
4020 /* did we fail to open the output file? */
4021 if (*save_file_fd == -1) {
4022 if (is_tempfile) {
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);
4027 } else {
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,
4038 g_strerror(errno));
4040 g_free(capfile_name);
4041 return false;
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();
4049 } else {
4050 /* capture_opts_cleanup will g_free(capture_opts->save_file). */
4051 capture_opts->save_file = capfile_name;
4054 return true;
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;
4061 return next_time;
4064 /* Do the work of handling either the file size or file duration capture
4065 conditions being reached, and switching files or stopping. */
4066 static bool
4067 do_file_switch_or_stop(capture_options *capture_opts)
4069 bool successful;
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;
4076 return 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);
4088 } else {
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);
4095 if (!successful) {
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;
4101 return false;
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) {
4111 if (!quiet)
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);
4116 } else {
4117 /* File switch failed: stop here */
4118 global_ld.go = false;
4119 return false;
4121 } else {
4122 /* single file, stop now */
4123 global_ld.go = false;
4124 return false;
4126 return true;
4129 static void *
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);
4145 return (NULL);
4148 /* Try to pop an item off the packet queue and if it exists, write it */
4149 static bool
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;
4158 } else {
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,
4172 queue_element->pd);
4173 } else {
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,
4179 queue_element->pd);
4181 g_free(queue_element->pd);
4182 g_free(queue_element);
4183 return true;
4185 return false;
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.
4194 static char *
4195 handle_npcap_bug(char *adapter_name _U_, char *cap_err_str _U_)
4197 bool have_npcap = false;
4199 #ifdef _WIN32
4200 have_npcap = caplibs_have_npcap();
4201 #endif
4203 if (!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. */
4221 static bool
4222 capture_loop_start(capture_options *capture_opts, bool *stats_known, struct pcap_stat *stats)
4224 #ifdef _WIN32
4225 ULONGLONG upd_time, cur_time; /* GetTickCount64() returns a "ULONGLONG" */
4226 #else
4227 struct timeval upd_time, cur_time;
4228 #endif
4229 int err_close;
4230 int inpkts;
4231 GTimer *autostop_duration_timer = NULL;
4232 bool write_ok;
4233 bool close_ok;
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;
4241 *errmsg = '\0';
4242 *secondary_errmsg = '\0';
4244 /* init the loop data */
4245 global_ld.go = true;
4246 global_ld.packets_captured = 0;
4247 #ifdef SIGINFO
4248 global_ld.report_packet_count = false;
4249 #endif
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))) {
4269 goto error;
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
4278 * string.
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:
4285 break;
4287 case INITFILTER_BAD_FILTER:
4288 cfilter_error = true;
4289 error_index = i;
4290 snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_src->pcap_h));
4291 goto error;
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());
4297 goto error;
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))) {
4306 goto error;
4309 /* set up to write to the already-opened capture output file/files */
4310 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
4311 sizeof(errmsg))) {
4312 goto error;
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
4327 progress. */
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 */
4353 #ifdef _WIN32
4354 upd_time = GetTickCount64();
4355 #else
4356 gettimeofday(&upd_time, NULL);
4357 #endif
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 */
4364 if (use_threads) {
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 */
4376 if (use_threads) {
4377 bool dequeued = capture_loop_dequeue_packet();
4379 if (dequeued) {
4380 inpkts = 1;
4381 } else {
4382 inpkts = 0;
4384 } else {
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);
4389 if (inpkts == 0) {
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;
4403 #ifdef SIGINFO
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;
4410 #endif
4412 #ifdef _WIN32
4413 /* any news from our parent (signal pipe)? -> just stop the capture */
4414 if (!signal_pipe_check_running()) {
4415 global_ld.go = false;
4417 #endif
4419 if (inpkts > 0) {
4420 if (capture_opts->output_to_pipe) {
4421 fflush(global_ld.pdh);
4423 } /* inpkts */
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?
4431 #ifdef _WIN32
4432 cur_time = GetTickCount64();
4433 if ((cur_time - upd_time) > capture_opts->update_interval)
4434 #else
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))
4438 #endif
4441 upd_time = cur_time;
4443 #if 0
4444 if (pcap_stats(pch, stats) >= 0) {
4445 *stats_known = true;
4447 #endif
4448 /* Let the parent process know. */
4449 if (global_ld.inpkts_to_sync_pipe) {
4450 /* do sync here */
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. */
4455 if (!quiet)
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;
4465 continue;
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))
4472 continue;
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))
4479 continue;
4480 } /* cnd_file_interval */
4484 ws_info("Capture loop stopping ...");
4485 if (use_threads) {
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);
4493 while (1) {
4494 bool dequeued = capture_loop_dequeue_packet();
4495 if (!dequeued) {
4496 break;
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
4518 of the error.)
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. */
4543 char *cap_err_str;
4544 char *primary_msg;
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,
4579 cap_err_str);
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
4597 * discussion.
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.");
4614 } else {
4615 primary_msg = ws_strdup_printf("Error while capturing packets: %s",
4616 cap_err_str);
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);
4622 break;
4623 } else if (pcap_src->from_cap_pipe && pcap_src->cap_pipe_err == PIPERR) {
4624 report_capture_error(errmsg, "");
4625 break;
4628 /* did we have an output error while capturing? */
4629 if (global_ld.err == 0) {
4630 write_ok = true;
4631 } else {
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);
4636 write_ok = false;
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);
4642 } else
4643 close_ok = true;
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) {
4648 if (!quiet)
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++) {
4675 uint32_t received;
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;
4688 } else {
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;
4706 error:
4707 if (capture_opts->multi_files_on) {
4708 /* cleanup ringbuffer */
4709 ringbuf_error_cleanup();
4710 } else {
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
4718 file. */
4719 if (capture_opts->save_file != NULL) {
4720 ws_unlink(capture_opts->save_file);
4723 if (cfilter_error)
4724 report_cfilter_error(capture_opts, error_index, errmsg);
4725 else
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");
4733 return false;
4737 static void
4738 capture_loop_stop(void)
4740 unsigned i;
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;
4752 static void
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.";
4761 switch (err) {
4763 case ENOSPC:
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.",
4769 fname);
4770 snprintf(secondary_errmsg, secondary_errmsglen, "%s", find_space);
4771 break;
4773 #ifdef EDQUOT
4774 case EDQUOT:
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.",
4781 fname);
4782 snprintf(secondary_errmsg, secondary_errmsglen, "%s", find_space);
4783 break;
4784 #endif
4786 default:
4787 if (is_close) {
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));
4792 } else {
4793 snprintf(errmsg, errmsglen,
4794 "An error occurred while writing to the file"
4795 " to which the capture was being saved\n"
4796 "(\"%s\"): %s.",
4797 fname, g_strerror(err));
4799 snprintf(secondary_errmsg, secondary_errmsglen,
4800 "%s", please_report_bug());
4801 break;
4806 * We wrote one packet. Update some statistics and check if we've met any
4807 * autostop or ring buffer conditions.
4809 static void
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++;
4815 if (!use_threads) {
4816 pcap_src->received++;
4819 /* check -c NUM */
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;
4823 return;
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;
4829 return;
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);
4834 return;
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);
4842 return;
4846 /* one pcapng block was captured, process it */
4847 static void
4848 capture_loop_write_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, uint8_t *pd)
4850 int err;
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++;
4862 return;
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();
4868 return;
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
4875 * them here.
4877 return;
4880 if (global_ld.pdh) {
4881 bool successful;
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);
4892 if (!successful) {
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 */
4911 static void
4912 capture_loop_write_packet_cb(uint8_t *pcap_src_p, const struct pcap_pkthdr *phdr,
4913 const uint8_t *pd)
4915 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4916 int err;
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++;
4926 return;
4929 if (global_ld.pdh) {
4930 bool successful;
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,
4937 NULL,
4938 phdr->ts.tv_sec, (int32_t)phdr->ts.tv_usec,
4939 phdr->caplen, phdr->len,
4940 pcap_src->idb_id,
4941 ts_mul,
4942 pd, 0,
4943 &global_ld.bytes_written, &err);
4944 } else {
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);
4951 if (!successful) {
4952 global_ld.go = false;
4953 global_ld.err = err;
4954 pcap_src->dropped++;
4955 } else {
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 */
4964 static void
4965 capture_loop_queue_packet_cb(uint8_t *pcap_src_p, const struct pcap_pkthdr *phdr,
4966 const uint8_t *pd)
4968 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4969 pcap_queue_element *queue_element;
4970 bool limit_reached;
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++;
4977 return;
4980 queue_element = g_new(pcap_queue_element, 1);
4981 if (queue_element == NULL) {
4982 pcap_src->dropped++;
4983 return;
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);
4991 return;
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;
5001 } else {
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);
5011 } else {
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 */
5023 static void
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;
5027 bool limit_reached;
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++;
5034 return;
5037 queue_element = g_new(pcap_queue_element, 1);
5038 if (queue_element == NULL) {
5039 pcap_src->dropped++;
5040 return;
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);
5048 return;
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;
5058 } else {
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);
5068 } else {
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);
5079 static int
5080 set_80211_channel(const char *iface, const char *opt)
5082 uint32_t freq = 0;
5083 int type = -1;
5084 uint32_t center_freq1 = 0;
5085 uint32_t center_freq2 = 0;
5086 int args;
5087 int ret = 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");
5098 else
5099 cmdarg_err("Failed to init ws80211: %s", g_strerror(abs(ret)));
5100 ret = 2;
5101 goto out;
5104 if (options[0])
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]);
5109 if (type == -1) {
5110 cmdarg_err("\"%s\" is not a valid 802.11 channel type", options[1]);
5111 ret = EINVAL;
5112 goto out;
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);
5124 if (ret) {
5125 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
5126 ret = 2;
5127 goto out;
5130 if (capture_child)
5131 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
5133 out:
5134 g_strfreev(options);
5135 return ret;
5138 static void
5139 gather_dumpcap_compiled_info(feature_list l)
5141 /* Capture libraries */
5142 gather_caplibs_compile_info(l);
5145 static void
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
5155 #ifdef _WIN32
5156 #define LONGOPT_SIGNAL_PIPE LONGOPT_BASE_APPLICATION+4
5157 #endif
5159 /* And now our feature presentation... [ fade to music ] */
5161 main(int argc, char *argv[])
5163 char *err_msg;
5164 int opt;
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},
5172 #ifdef _WIN32
5173 {"signal-pipe", ws_required_argument, NULL, LONGOPT_SIGNAL_PIPE},
5174 #endif
5175 {0, 0, 0, 0 }
5178 bool arg_error = false;
5180 #ifndef _WIN32
5181 struct sigaction action, oldaction;
5182 #endif
5184 bool stats_known;
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;
5194 int i;
5195 unsigned j;
5196 #if defined(__APPLE__) && defined(__LP64__)
5197 struct utsname osinfo;
5198 #endif
5199 GString *str;
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
5213 * capture.
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 */
5231 i++;
5232 if (i >= argc) {
5233 exit_main(1);
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) {
5239 exit_main(1);
5241 #ifdef _WIN32
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);
5254 #endif
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");
5277 exit (1);
5279 #endif
5281 ws_noisy("Finished log init and parsing command line log arguments");
5283 #ifdef _WIN32
5284 create_app_running_mutex();
5287 * Initialize our DLL search path. MUST be called before LoadLibrary
5288 * or g_module_open.
5290 ws_init_dll_search_path();
5292 /* Load wpcap if possible. Do this before collecting the run-time version information */
5293 load_wpcap();
5294 #endif
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"
5303 #else
5304 #define OPTSTRING_r
5305 #define OPTSTRING_u
5306 #endif
5308 #ifdef HAVE_PCAP_SETSAMPLING
5309 #define OPTSTRING_m "m:"
5310 #else
5311 #define OPTSTRING_m
5312 #endif
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
5323 * release.)
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;
5336 #endif
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);
5349 g_free(err_msg);
5350 ws_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_ERROR,
5351 "%s", please_report_bug());
5352 exit_main(1);
5355 #ifdef _WIN32
5356 /* Set handler for Ctrl+C key */
5357 SetConsoleCtrlHandler(capture_cleanup_handler, true);
5358 #else
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);
5387 #ifdef SIGINFO
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 */
5395 #endif /* _WIN32 */
5397 /* ----------------------------------------------------------------- */
5398 /* Privilege and capability handling */
5399 /* Cases: */
5400 /* 1. Running not as root or suid root; no special capabilities. */
5401 /* Action: none */
5402 /* */
5403 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
5404 /* Action: none */
5405 /* */
5406 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
5407 /* Action: */
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 */
5418 /* anything ?? */
5419 /* */
5420 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
5421 /* Action: */
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). */
5426 /* */
5427 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
5428 /* Action: */
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). */
5435 /* */
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 */
5439 /* process. */
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 */
5450 /* */
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. */
5456 /* */
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. */
5460 /* Action: */
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) */
5464 /* */
5465 /* ToDo: -S (stats) should drop privileges/capabilities when no */
5466 /* longer required (similar to capture). */
5467 /* */
5468 /* ----------------------------------------------------------------- */
5470 init_process_policies();
5472 #ifdef HAVE_LIBCAP
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();
5477 #endif
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
5483 temporary file. */
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) {
5492 switch (opt) {
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);
5496 exit_main(0);
5497 break;
5498 case 'v': /* Show version and exit */
5499 show_version();
5500 exit_main(0);
5501 break;
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 */
5521 #endif
5522 #ifdef HAVE_PCAP_SETSAMPLING
5523 case 'm': /* Sampling */
5524 #endif
5525 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
5526 case 'B': /* Buffer size */
5527 #endif
5528 #ifdef HAVE_PCAP_CREATE
5529 case 'I': /* Monitor mode */
5530 #endif
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);
5535 if (status != 0) {
5536 exit_main(status);
5538 break;
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);
5546 } else {
5547 cmdarg_err("--ifname must be specified after a -i option");
5548 exit_main(1);
5550 break;
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);
5557 } else {
5558 cmdarg_err("--ifdescr must be specified after a -i option");
5559 exit_main(1);
5561 break;
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));
5567 break;
5568 case 'Z':
5569 capture_child = true;
5571 * Handled above
5573 break;
5574 #ifdef _WIN32
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");
5579 exit_main(1);
5582 * ws_optarg = the control ID, aka the PPID, currently used for the
5583 * signal pipe name.
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?",
5592 sig_pipe_name);
5593 exit_main(1);
5596 break;
5597 #endif
5598 case 'q': /* Quiet */
5599 quiet = true;
5600 break;
5601 case 'Q': /* Really quiet */
5602 quiet = true;
5603 really_quiet = true;
5604 break;
5605 case 't':
5606 use_threads = true;
5607 break;
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) {
5611 run_once_args++;
5613 list_interfaces = true;
5614 break;
5615 case 'L': /* Print list of link-layer types and exit */
5616 if (!list_interfaces && !caps_queries & !print_statistics) {
5617 run_once_args++;
5619 caps_queries |= CAPS_QUERY_LINK_TYPES;
5620 break;
5621 case LONGOPT_LIST_TSTAMP_TYPES:
5622 if (!list_interfaces && !caps_queries & !print_statistics) {
5623 run_once_args++;
5625 caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
5626 break;
5627 case 'd': /* Print BPF code for capture filter and exit */
5628 if (!print_bpf_code) {
5629 print_bpf_code = true;
5630 run_once_args++;
5632 break;
5633 case 'S': /* Print interface statistics once a second */
5634 if (!list_interfaces && !caps_queries & !print_statistics) {
5635 run_once_args++;
5637 print_statistics = true;
5638 break;
5639 case 'k': /* Set wireless channel */
5640 if (!set_chan) {
5641 set_chan = true;
5642 set_chan_arg = ws_optarg;
5643 run_once_args++;
5644 } else {
5645 cmdarg_err("Only one -k flag may be specified");
5646 arg_error = true;
5648 break;
5649 case 'M': /* For -D, -L, and -S, print machine-readable output */
5650 machine_readable = true;
5651 break;
5652 case 'C':
5653 pcap_queue_byte_limit = get_positive_int(ws_optarg, "byte_limit");
5654 break;
5655 case 'N':
5656 pcap_queue_packet_limit = get_positive_int(ws_optarg, "packet_limit");
5657 break;
5658 default:
5659 cmdarg_err("Invalid Option: %s", argv[ws_optind-1]);
5660 /* FALLTHROUGH */
5661 case '?': /* Bad flag - print usage message */
5662 arg_error = true;
5663 break;
5666 if (!arg_error) {
5667 argc -= ws_optind;
5668 argv += ws_optind;
5669 if (argc >= 1) {
5670 /* user specified file name as regular command-line argument */
5671 /* XXX - use it as the capture file name (or something else)? */
5672 argc--;
5673 argv++;
5675 if (argc != 0) {
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]);
5681 arg_error = true;
5685 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
5686 use_threads = true;
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;
5694 if (arg_error) {
5695 if (ws_optopt == 'F') {
5696 capture_opts_list_file_types();
5697 exit_main(1);
5699 print_usage(stderr);
5700 exit_main(1);
5703 if (run_once_args > 1) {
5704 cmdarg_err("Only one of -D, -L, -d, -k or -S may be supplied.");
5705 exit_main(1);
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.");
5711 exit_main(1);
5713 } else {
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) {
5718 use_threads = true;
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.");
5726 exit_main(1);
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.");
5745 #if 0
5746 /* XXX - this must be redesigned as the conditions changed */
5747 global_capture_opts.multi_files_on = false;
5748 #endif
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.");
5752 exit_main(1);
5758 * "-D" requires no interface to be selected; it's supposed to list
5759 * all interfaces.
5761 if (list_interfaces) {
5762 /* Get the list of interfaces */
5763 GList *if_list;
5764 int err;
5765 char *err_str;
5767 if_list = get_interface_list(&err, &err_str);
5768 if (if_list == NULL) {
5769 if (err == 0) {
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");
5778 exit_main(2);
5780 } else {
5781 cmdarg_err("%s", err_str);
5782 g_free(err_str);
5783 exit_main(2);
5787 if (!machine_readable) {
5788 status = 0;
5789 capture_opts_print_interfaces(if_list);
5792 if (caps_queries) {
5793 if_info_t *if_info;
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);
5825 break;
5826 } else {
5827 status = capture_opts_print_if_capabilities(if_info->caps, interface_opts, caps_queries);
5828 if (status != 0) {
5829 interface_opts_free(interface_opts);
5830 g_free(interface_opts);
5831 break;
5834 } else {
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) {
5853 exit_main(status);
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);
5863 exit_main(status);
5866 if (set_chan) {
5867 interface_options *interface_opts;
5869 if (global_capture_opts.ifaces->len != 1) {
5870 cmdarg_err("Need one interface");
5871 exit_main(2);
5874 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
5875 status = set_80211_channel(interface_opts->name, set_chan_arg);
5876 exit_main(status);
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);
5884 if (status != 0) {
5885 /* cmdarg_err() already called .... */
5886 exit_main(status);
5889 if (caps_queries) {
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;
5894 unsigned ii;
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);
5915 if (caps == NULL) {
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);
5921 } else {
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)) {
5931 status = 0;
5932 if (capture_child) {
5933 /* Let our parent know we succeeded. */
5934 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
5936 } else {
5937 status = 2;
5938 if (capture_child) {
5939 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, "Unexpected JSON error", "");
5942 } else {
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);
5949 if (caps == NULL) {
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));
5956 g_free(error_msg);
5958 else {
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);
5965 exit_main(2);
5968 /* XXX: We might want to print also the interface name */
5969 status = capture_opts_print_if_capabilities(caps,
5970 interface_opts,
5971 caps_queries);
5972 free_if_capabilities(caps);
5973 if (status != 0)
5974 break;
5977 exit_main(status);
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);
5989 exit_main(1);
5993 #endif
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);
6005 } else {
6006 str = g_string_new("");
6007 #ifdef _WIN32
6008 if (global_capture_opts.ifaces->len < 2)
6009 #else
6010 if (global_capture_opts.ifaces->len < 4)
6011 #endif
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);
6017 if (j > 0) {
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
6029 * we were handed.
6031 g_free(interface_opts->display_name);
6032 if (interface_opts->descr != NULL) {
6033 #ifdef _WIN32
6034 interface_opts->display_name = ws_strdup_printf("%s",
6035 interface_opts->descr);
6036 #else
6037 interface_opts->display_name = ws_strdup_printf("%s: %s",
6038 interface_opts->descr, interface_opts->ifname);
6039 #endif
6040 } else {
6041 interface_opts->display_name = ws_strdup_printf("%s",
6042 interface_opts->ifname);
6045 g_string_append_printf(str, "'%s'", interface_opts->display_name);
6047 } else {
6048 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
6050 if (!really_quiet)
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);
6060 exit_main(0);
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 */
6067 fflush(stderr);
6069 /* Now start the capture. */
6070 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == true) {
6071 /* capture ok */
6072 exit_main(0);
6073 } else {
6074 /* capture failed */
6075 exit_main(1);
6077 return 0; /* never here, make compiler happy */
6080 static void
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);
6094 #endif
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);
6103 if (file != NULL) {
6104 g_string_append_printf(msg, "%s", file);
6105 if (line >= 0) {
6106 g_string_append_printf(msg, ":%ld", line);
6109 g_string_append(msg, " --");
6110 if (func != NULL) {
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);
6118 } else {
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);
6124 #endif
6129 /****************************************************************************************************************/
6130 /* indication report routines */
6133 static void
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);
6141 } else {
6142 count += packet_count;
6143 fprintf(stderr, "\rPackets: %u ", count);
6144 /* stderr could be line buffered */
6145 fflush(stderr);
6149 static void
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;
6158 } else {
6159 sync_pipe_write_string_msg(sync_pipe_fd, SP_FILE, filename);
6161 } else {
6162 #ifdef SIGINFO
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.
6168 infodelay = true;
6169 #endif /* SIGINFO */
6170 if (!really_quiet) {
6171 fprintf(stderr, "File: %s\n", filename);
6172 /* stderr could be line buffered */
6173 fflush(stderr);
6176 #ifdef SIGINFO
6178 * Allow SIGINFO handlers to write.
6180 infodelay = false;
6183 * If a SIGINFO handler asked us to write out capture counts, do so.
6185 if (infoprint)
6186 report_counts_for_siginfo();
6187 #endif /* SIGINFO */
6191 static void
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);
6202 } else {
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);
6208 cmdarg_err(
6209 "Invalid capture filter \"%s\" for interface '%s'.\n"
6210 "\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);
6218 static void
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);
6225 } else {
6226 cmdarg_err("%s", error_msg);
6227 if (secondary_error_msg[0] != '\0')
6228 cmdarg_err_cont("%s", secondary_error_msg);
6232 static void
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);
6243 g_free(tmp);
6244 } else {
6245 if (!really_quiet) {
6246 fprintf(stderr,
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 */
6251 fflush(stderr);
6257 /************************************************************************************************/
6258 /* signal_pipe handling */
6261 #ifdef _WIN32
6262 static bool
6263 signal_pipe_check_running(void)
6265 /* any news from our parent? -> just stop the capture */
6266 DWORD avail = 0;
6267 bool result;
6269 /* if we are running standalone, no check required */
6270 if (!capture_child) {
6271 return true;
6274 if (!sig_pipe_name || !sig_pipe_handle) {
6275 /* This shouldn't happen */
6276 ws_info("Signal pipe: No name or handle");
6277 return false;
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);
6294 return false;
6295 } else {
6296 /* pipe ok and no bytes available */
6297 return true;
6300 #endif
6303 * Editor modelines - https://www.wireshark.org/tools/modelines.html
6305 * Local variables:
6306 * c-basic-offset: 4
6307 * tab-width: 8
6308 * indent-tabs-mode: nil
6309 * End:
6311 * vi: set shiftwidth=4 tabstop=8 expandtab:
6312 * :indentSize=4:tabSize=8:noTabs=true: