sync epan/dissectors/pidl/drsuapi/drsuapi.idl
[wireshark-sm.git] / dumpcap.c
blob16236b831c715611bc62bd8a9641933b994a7925
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/application_flavor.h>
37 #include <wsutil/array.h>
38 #include <wsutil/cmdarg_err.h>
39 #include <wsutil/report_message.h>
40 #include <wsutil/failure_message_simple.h>
41 #include <wsutil/strtoi.h>
42 #include <cli_main.h>
43 #include <wsutil/version_info.h>
45 #include <wsutil/socket.h>
46 #include <wsutil/wslog.h>
47 #include <wsutil/file_util.h>
49 #ifdef HAVE_LIBCAP
50 # include <sys/prctl.h>
51 # include <sys/capability.h>
52 #endif
54 #include "ringbuffer.h"
56 #include "capture/capture_ifinfo.h"
57 #include "capture/capture-pcap-util.h"
58 #include "capture/capture-pcap-util-int.h"
59 #ifdef _WIN32
60 #include "capture/capture-wpcap.h"
61 #endif /* _WIN32 */
63 #include "writecap/pcapio.h"
65 #ifndef _WIN32
66 #include <sys/un.h>
67 #endif
69 #include <wsutil/clopts_common.h>
70 #include <wsutil/privileges.h>
72 #include "sync_pipe.h"
74 #include "ui/capture_opts.h"
75 #include <capture/capture_session.h>
76 #include <capture/capture_sync.h>
78 #include "wsutil/tempfile.h"
79 #include "wsutil/file_util.h"
80 #include "wsutil/cpu_info.h"
81 #include "wsutil/os_version_info.h"
82 #include "wsutil/str_util.h"
83 #include "wsutil/inet_addr.h"
84 #include "wsutil/time_util.h"
85 #include "wsutil/please_report_bug.h"
86 #include "wsutil/glib-compat.h"
87 #include <wsutil/json_dumper.h>
88 #include <wsutil/ws_assert.h>
90 #include "capture/ws80211_utils.h"
92 #include "extcap.h"
95 * Get information about libpcap format from "wiretap/libpcap.h".
96 * Get information about pcapng format from "wiretap/pcapng_module.h".
97 * XXX - can we just use pcap_open_offline() to read the pipe?
99 #include "wiretap/libpcap.h"
100 #include "wiretap/pcapng_module.h"
101 #include "wiretap/pcapng.h"
104 * Define these for extra logging. Note that when dumpcap is spawned as
105 * a child process, logs are sent to the parent via the sync pipe.
106 * The parent will pass along the Capchild domain log level settings,
107 * so "--log-debug Capchild" or "--log-level debug" can be used to get
108 * debugging from dumpcap sent to the parent.
110 //#define DEBUG_DUMPCAP /* Waits for keypress on quitting on Windows */
111 //#define DEBUG_CHILD_DUMPCAP /* Writes logs to file */
113 #ifdef _WIN32
114 #include "wsutil/win32-utils.h"
115 #ifdef DEBUG_DUMPCAP
116 #include <conio.h> /* _getch() */
117 #endif
118 #endif
120 #ifdef DEBUG_CHILD_DUMPCAP
121 FILE *debug_log; /* for logging debug messages to */
122 /* a file if DEBUG_CHILD_DUMPCAP */
123 /* is defined */
124 #include <stdarg.h> /* va_copy */
125 #endif
127 static GAsyncQueue *pcap_queue;
128 static int64_t pcap_queue_bytes;
129 static int64_t pcap_queue_packets;
130 static int64_t pcap_queue_byte_limit;
131 static int64_t pcap_queue_packet_limit;
133 static bool capture_child; /* false: standalone call, true: this is an Wireshark capture child */
134 static const char *report_capture_filename; /* capture child file name */
135 #ifdef _WIN32
136 static char *sig_pipe_name;
137 static HANDLE sig_pipe_handle;
138 static bool signal_pipe_check_running(void);
139 #endif
140 static int sync_pipe_fd = 2;
142 #if defined (ENABLE_ASAN) || defined (ENABLE_LSAN)
143 /* This has public visibility so that if compiled with shared libasan (the
144 * gcc default) function interposition occurs.
146 WS_DLL_PUBLIC int
147 __lsan_is_turned_off(void)
149 /* If we're in capture child mode, don't run a LSan report and
150 * send it to stderr, because it isn't properly formatted for
151 * the sync pipe.
152 * We could, if debugging variables are set, send the reports
153 * elsewhere instead, by calling __sanitizer_set_report_path()
154 * or __sanitizer_set_report_fd()
156 if (capture_child) {
157 return 1;
159 #ifdef HAVE_LIBCAP
160 /* LSan dies with a fatal error without explanation if it can't ptrace.
161 * Normally, the "dumpable" attribute (which also controls ptracing)
162 * is set to 1 (SUID_DUMP_USER, process is dumpable.) However, it is
163 * reset to the current value in /proc/sys/fs/suid_dumpable in the
164 * following circumstances: euid/egid changes, fsuid/fsgid changes,
165 * execve of a setuid or setgid program that changes the euid or egid,
166 * execve of a program with capabilities exceeding those already
167 * permitted for the process.
169 * Unless we're running as root, one of those applies to dumpcap.
171 * The default value of /proc/sys/fs/suid_dumpable is 0, SUID_DUMP_DISABLE.
172 * In such a case, LeakSanitizer temporarily sets the value to 1 to
173 * allow ptracing, and then sets it back to 0.
175 * Another possible value, used by Ubuntu, Fedora, etc., is 2,
176 * which creates dumps readable by root only. For security reasons,
177 * unprivileged programs are not allowed to change the value to 2.
178 * (See https://nvd.nist.gov/vuln/detail/CVE-2006-2451 )
180 * LSan does not check for the value 2 and change dumpable to 1 in that
181 * case, possibly because if it did it could not change it back to 2
182 * and would have to either leave the process dumpable or change it to 0.
184 * The usual way to control the family of sanitizers is through environment
185 * variables. However, complicating things, changing the dumpable attribute
186 * to 0 or 2 changes the ownership of files in /proc/[pid] (including
187 * /proc/self ) to root:root, in particular /proc/[pid]/environ, and so
188 * ASAN_OPTIONS=detect_leaks=0 has no effect. (Unless the process has
189 * CAP_SYS_PTRACE, which allows tracing of any process, but that's also
190 * a security risk and we'll have dropped that with other privileges.)
192 * So if prctl(PR_GET_DUMPABLE) returns 2, we know that the process will
193 * die with a fatal error if it attempts to run LSan, so don't.
195 * See proc(5), prctl(2), ptrace(2), and
196 * https://github.com/google/sanitizers/issues/1306
197 * https://github.com/llvm/llvm-project/issues/55944
199 if (prctl(PR_GET_DUMPABLE) == 2) {
200 ws_debug("Not running LeakSanitizer because /proc/sys/fs/suid_dumpable is 2");
201 return 1;
203 #endif
204 return 0;
207 WS_DLL_PUBLIC const char*
208 __asan_default_options(void)
210 /* By default don't override our exit code if there's a leak or error.
211 * We particularly don't want to do this if running as a capture child,
212 * because capture/capture_sync doesn't expect the ASan exit codes.
214 return "exitcode=0";
217 WS_DLL_PUBLIC const char*
218 __lsan_default_options(void)
220 /* By default don't override our exit code if there's a leak or error.
221 * We particularly don't want to do this if running as a capture child,
222 * because capture/capture_sync doesn't expect the LSan exit codes.
224 return "exitcode=0";
226 #endif
228 #ifdef SIGINFO
229 static bool infodelay; /* if true, don't print capture info in SIGINFO handler */
230 static bool infoprint; /* if true, print capture info after clearing infodelay */
231 #endif /* SIGINFO */
233 /** Stop a low-level capture (stops the capture child). */
234 static void capture_loop_stop(void);
235 /** Close a pipe, or socket if \a from_socket is true */
236 static void cap_pipe_close(int pipe_fd, bool from_socket);
238 #if defined (__linux__)
239 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
240 * in pcap_dispatch(); on the other hand, select() works just fine there.
241 * Hence we use a select for that come what may.
243 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
244 * internally, and, with TPACKET_V3, once that's supported, it'll
245 * support timeouts, at least as I understand the way the code works.
247 #define MUST_DO_SELECT
248 #endif
250 /** init the capture filter */
251 typedef enum {
252 INITFILTER_NO_ERROR,
253 INITFILTER_BAD_FILTER,
254 INITFILTER_OTHER_ERROR
255 } initfilter_status_t;
257 typedef enum {
258 STATE_EXPECT_REC_HDR,
259 STATE_READ_REC_HDR,
260 STATE_EXPECT_DATA,
261 STATE_READ_DATA
262 } cap_pipe_state_t;
264 typedef enum {
265 PIPOK,
266 PIPEOF,
267 PIPERR,
268 PIPNEXIST
269 } cap_pipe_err_t;
271 typedef struct _pcap_pipe_info {
272 bool byte_swapped; /**< true if data in the pipe is byte swapped. */
273 struct pcap_hdr hdr; /**< Pcap header when capturing from a pipe */
274 struct pcaprec_modified_hdr rechdr; /**< Pcap record header when capturing from a pipe */
275 } pcap_pipe_info_t;
277 typedef struct _pcapng_pipe_info {
278 pcapng_block_header_t bh; /**< Pcapng general block header when capturing from a pipe */
279 GArray *src_iface_to_global; /**< Int array mapping local IDB numbers to global_ld.interface_data */
280 } pcapng_pipe_info_t;
282 struct _loop_data; /* forward declaration so we can use it in the cap_pipe_dispatch function pointer */
285 * A source of packets from which we're capturing.
287 typedef struct _capture_src {
288 uint32_t received;
289 uint32_t dropped;
290 uint32_t flushed;
291 pcap_t *pcap_h;
292 #ifdef MUST_DO_SELECT
293 int pcap_fd; /**< pcap file descriptor */
294 #endif
295 bool pcap_err;
296 unsigned interface_id;
297 unsigned idb_id; /**< If from_pcapng is false, the output IDB interface ID. Otherwise the mapping in src_iface_to_global is used. */
298 GThread *tid;
299 int snaplen;
300 int linktype;
301 bool ts_nsec; /**< true if we're using nanosecond precision. */
302 /**< capture pipe (unix only "input file") */
303 bool from_cap_pipe; /**< true if we are capturing data from a capture pipe */
304 bool from_cap_socket; /**< true if we're capturing from socket */
305 bool from_pcapng; /**< true if we're capturing from pcapng format */
306 union {
307 pcap_pipe_info_t pcap; /**< Pcap info when capturing from a pipe */
308 pcapng_pipe_info_t pcapng; /**< Pcapng info when capturing from a pipe */
309 } cap_pipe_info;
310 #ifdef _WIN32
311 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
312 #endif
313 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
314 bool cap_pipe_modified; /**< true if data in the pipe uses modified pcap headers */
315 char * cap_pipe_databuf; /**< Pointer to the data buffer we've allocated */
316 size_t cap_pipe_databuf_size; /**< Current size of the data buffer */
317 unsigned cap_pipe_max_pkt_size; /**< Maximum packet size allowed */
318 #if defined(_WIN32)
319 char * cap_pipe_buf; /**< Pointer to the buffer we read into */
320 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
321 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
322 #else
323 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
324 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
325 #endif
326 int (*cap_pipe_dispatch)(struct _loop_data *, struct _capture_src *, char *, size_t);
327 cap_pipe_state_t cap_pipe_state;
328 cap_pipe_err_t cap_pipe_err;
330 #if defined(_WIN32)
331 GMutex *cap_pipe_read_mtx;
332 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
333 #endif
334 } capture_src;
336 typedef struct _saved_idb {
337 bool deleted;
338 unsigned interface_id; /* capture_src->interface_id for the associated SHB */
339 uint8_t *idb; /* If non-NULL, IDB read from capture_src. This is an interface specified on the command line otherwise. */
340 unsigned idb_len;
341 } saved_idb_t;
344 * Global capture loop state.
346 typedef struct _loop_data {
347 /* common */
348 bool go; /**< true as long as we're supposed to keep capturing */
349 int err; /**< if non-zero, error seen while capturing */
350 int packets_captured; /**< Number of packets we have already captured */
351 unsigned inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
352 #ifdef SIGINFO
353 bool report_packet_count; /**< Set by SIGINFO handler; print packet count */
354 #endif
355 GArray *pcaps; /**< Array of capture_src's on which we're capturing */
356 bool pcapng_passthrough; /**< We have one source and it's pcapng. Pass its SHB and IDBs through. */
357 uint8_t *saved_shb; /**< SHB to write when we have one pcapng input */
358 GArray *saved_idbs; /**< Array of saved_idb_t, written when we have a new section or output file. */
359 GRWLock saved_shb_idb_lock; /**< Saved IDB RW mutex */
360 /* output file(s) */
361 pcapio_writer* pdh;
362 int save_file_fd;
363 uint64_t bytes_written; /**< Bytes written for the current file. */
364 /* autostop conditions */
365 int packets_written; /**< Packets written for the current file. */
366 int file_count;
367 /* ring buffer conditions */
368 GTimer *file_duration_timer;
369 time_t next_interval_time;
370 int interval_s;
371 } loop_data;
373 typedef struct _pcap_queue_element {
374 capture_src *pcap_src;
375 union {
376 struct pcap_pkthdr phdr;
377 pcapng_block_header_t bh;
378 } u;
379 uint8_t *pd;
380 } pcap_queue_element;
383 * This needs to be static, so that the SIGINT handler can clear the "go"
384 * flag and for saved_shb_idb_lock.
386 static loop_data global_ld;
389 * Timeout, in milliseconds, for reads from the stream of captured packets
390 * from a capture device.
392 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
393 * 64-bit applications, with sub-second timeouts not to work. The bug is
394 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
396 #if defined(__APPLE__) && defined(__LP64__)
397 static bool need_timeout_workaround;
399 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
400 #else
401 #define CAP_READ_TIMEOUT 250
402 #endif
405 * Timeout, in microseconds, for reads from the stream of captured packets
406 * from a pipe. Pipes don't have the same problem that BPF devices do
407 * in Mac OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
408 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
409 * of the offending versions of Snow Leopard.
411 * On Windows this value is converted to milliseconds and passed to
412 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
413 * will return immediately.
415 #if defined(_WIN32)
416 #define PIPE_READ_TIMEOUT 100000
417 #else
418 #define PIPE_READ_TIMEOUT 250000
419 #endif
421 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
423 static void
424 dumpcap_log_writer(const char *domain, enum ws_log_level level,
425 const char *file, long line, const char *func,
426 const char *fatal_msg, ws_log_manifest_t *mft,
427 const char *user_format, va_list user_ap,
428 void *user_data);
430 /* capture related options */
431 static capture_options global_capture_opts;
432 static GPtrArray *capture_comments;
433 static bool quiet;
434 static bool really_quiet;
435 static bool use_threads;
436 static uint64_t start_time;
438 static void capture_loop_write_packet_cb(uint8_t *pcap_src_p, const struct pcap_pkthdr *phdr,
439 const uint8_t *pd);
440 static void capture_loop_queue_packet_cb(uint8_t *pcap_src_p, const struct pcap_pkthdr *phdr,
441 const uint8_t *pd);
442 static void capture_loop_write_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, uint8_t *pd);
443 static void capture_loop_queue_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, uint8_t *pd);
444 static void capture_loop_get_errmsg(char *errmsg, size_t errmsglen,
445 char *secondary_errmsg,
446 size_t secondary_errmsglen,
447 const char *fname, int err,
448 bool is_close);
450 WS_NORETURN static void exit_main(int err);
452 static void report_new_capture_file(const char *filename);
453 static void report_packet_count(unsigned int packet_count);
454 static void report_packet_drops(uint32_t received, uint32_t pcap_drops, uint32_t drops, uint32_t flushed, uint32_t ps_ifdrop, char *name);
455 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
456 static void report_cfilter_error(capture_options *capture_opts, unsigned i, const char *errmsg);
458 #define MSG_MAX_LENGTH 4096
460 static void
461 print_usage(FILE *output)
463 fprintf(output, "\nUsage: dumpcap [options] ...\n");
464 fprintf(output, "\n");
465 fprintf(output, "Capture interface:\n");
466 fprintf(output, " -i <interface>, --interface <interface>\n");
467 fprintf(output, " name or idx of interface (def: first non-loopback)\n"
468 #ifdef HAVE_PCAP_REMOTE
469 " or for remote capturing, use one of these formats:\n"
470 " rpcap://<host>/<interface>\n"
471 #else
472 " or for remote capturing, use this format:\n"
473 #endif
474 " TCP@<host>:<port>\n");
475 fprintf(output, " --ifname <name> name to use in the capture file for a pipe from which\n");
476 fprintf(output, " we're capturing\n");
477 fprintf(output, " --ifdescr <description>\n");
478 fprintf(output, " description to use in the capture file for a pipe\n");
479 fprintf(output, " from which we're capturing\n");
480 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
481 fprintf(output, " -s <snaplen>, --snapshot-length <snaplen>\n");
482 fprintf(output, " packet snapshot length (def: appropriate maximum)\n");
483 fprintf(output, " -p, --no-promiscuous-mode\n");
484 fprintf(output, " don't capture in promiscuous mode\n");
485 fprintf(output, " -I, --monitor-mode capture in monitor mode, if available\n");
486 fprintf(output, " -B <buffer size>, --buffer-size <buffer size>\n");
487 fprintf(output, " size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
488 fprintf(output, " -y <link type>, --linktype <link type>\n");
489 fprintf(output, " link layer type (def: first appropriate)\n");
490 fprintf(output, " --time-stamp-type <type> timestamp method for interface\n");
491 fprintf(output, " -D, --list-interfaces print list of interfaces and exit\n");
492 fprintf(output, " -L, --list-data-link-types\n");
493 fprintf(output, " print list of link-layer types of iface and exit\n");
494 fprintf(output, " --list-time-stamp-types print list of timestamp types for iface and exit\n");
495 fprintf(output, " --update-interval interval between updates with new packets, in milliseconds (def: %dms)\n", DEFAULT_UPDATE_INTERVAL);
496 fprintf(output, " -d print generated BPF code for capture filter\n");
497 fprintf(output, " -k <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
498 fprintf(output, " set channel on wifi interface\n");
499 fprintf(output, " -S print statistics for each interface once per second\n");
500 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
501 fprintf(output, "\n");
502 #ifdef HAVE_PCAP_REMOTE
503 fprintf(output, "RPCAP options:\n");
504 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
505 fprintf(output, " -u use UDP for RPCAP data transfer\n");
506 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
507 #ifdef HAVE_PCAP_SETSAMPLING
508 fprintf(output, " -m <sampling type> use packet sampling\n");
509 fprintf(output, " count:NUM - capture one packet of every NUM\n");
510 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
511 #endif
512 #endif
513 fprintf(output, "Stop conditions:\n");
514 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
515 fprintf(output, " -a <autostop cond.> ..., --autostop <autostop cond.> ...\n");
516 fprintf(output, " duration:NUM - stop after NUM seconds\n");
517 fprintf(output, " filesize:NUM - stop this file after NUM kB\n");
518 fprintf(output, " files:NUM - stop after NUM files\n");
519 fprintf(output, " packets:NUM - stop after NUM packets\n");
520 /*fprintf(output, "\n");*/
521 fprintf(output, "Output (files):\n");
522 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
523 fprintf(output, " -g enable group read access on the output file(s)\n");
524 fprintf(output, " -b <ringbuffer opt.> ..., --ring-buffer <ringbuffer opt.>\n");
525 fprintf(output, " duration:NUM - switch to next file after NUM secs\n");
526 fprintf(output, " filesize:NUM - switch to next file after NUM kB\n");
527 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
528 fprintf(output, " packets:NUM - ringbuffer: replace after NUM packets\n");
529 fprintf(output, " interval:NUM - switch to next file when the time is\n");
530 fprintf(output, " an exact multiple of NUM secs\n");
531 fprintf(output, " printname:FILE - print filename to FILE when written\n");
532 fprintf(output, " (can use 'stdout' or 'stderr')\n");
533 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
534 fprintf(output, " -P use libpcap format instead of pcapng\n");
535 fprintf(output, " --capture-comment <comment>\n");
536 fprintf(output, " add a capture comment to the output file\n");
537 fprintf(output, " (only for pcapng)\n");
538 fprintf(output, " --temp-dir <directory> write temporary files to this directory\n");
539 fprintf(output, " (default: %s)\n", g_get_tmp_dir());
540 fprintf(output, "\n");
542 ws_log_print_usage(output);
543 fprintf(output, "\n");
545 fprintf(output, "Miscellaneous:\n");
546 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
547 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
548 fprintf(output, " within dumpcap\n");
549 fprintf(output, " -t use a separate thread per interface\n");
550 fprintf(output, " -q don't report packet capture counts\n");
551 fprintf(output, " --application-flavor <flavor>\n");
552 fprintf(output, " set the application flavor\n");
553 fprintf(output, " -v, --version print version information and exit\n");
554 fprintf(output, " -h, --help display this help and exit\n");
555 fprintf(output, "\n");
556 #ifdef __linux__
557 fprintf(output, "Dumpcap can benefit from an enabled BPF JIT compiler if available.\n");
558 fprintf(output, "You might want to enable it by executing:\n");
559 fprintf(output, " \"echo 1 > /proc/sys/net/core/bpf_jit_enable\"\n");
560 fprintf(output, "Note that this can make your system less secure!\n");
561 fprintf(output, "\n");
562 #endif
563 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
564 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
565 fprintf(output, "\n");
566 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
570 * Report an error in command-line arguments.
571 * If we're a capture child, send a message back to the parent, otherwise
572 * just print it.
574 static void
575 dumpcap_cmdarg_err(const char *fmt, va_list ap)
577 if (capture_child) {
578 char *msg;
579 /* Generate a 'special format' message back to parent */
580 msg = ws_strdup_vprintf(fmt, ap);
581 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, msg, "");
582 g_free(msg);
583 } else {
584 fprintf(stderr, "dumpcap: ");
585 vfprintf(stderr, fmt, ap);
586 fprintf(stderr, "\n");
591 * Report additional information for an error in command-line arguments.
592 * If we're a capture child, send a message back to the parent, otherwise
593 * just print it.
595 static void
596 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
598 if (capture_child) {
599 char *msg;
600 msg = ws_strdup_vprintf(fmt, ap);
601 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, msg, "");
602 g_free(msg);
603 } else {
604 vfprintf(stderr, fmt, ap);
605 fprintf(stderr, "\n");
609 #ifdef HAVE_LIBCAP
610 static void
611 /* see 'man cap_to_text()' for explanation of output */
612 /* '=' means 'all= ' ie: no capabilities */
613 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
614 /* .... */
615 print_caps(const char *pfx) {
616 if (ws_log_msg_is_active(WS_LOG_DOMAIN, LOG_LEVEL_NOISY)) {
617 cap_t caps = cap_get_proc();
618 char *caps_text = cap_to_text(caps, NULL);
619 ws_noisy("%s: EUID: %d Capabilities: %s", pfx, geteuid(), caps_text);
620 cap_free(caps_text);
621 cap_free(caps);
625 static void
626 relinquish_all_capabilities(void)
628 /* Drop any and all capabilities this process may have. */
629 /* Allowed whether or not process has any privileges. */
630 cap_t caps = cap_init(); /* all capabilities initialized to off */
631 print_caps("Pre-clear");
632 if (cap_set_proc(caps)) {
633 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
635 print_caps("Post-clear");
636 cap_free(caps);
638 #endif
640 static void
641 get_capture_device_open_failure_messages(cap_device_open_status open_status,
642 const char *open_status_str,
643 const char *iface,
644 char *errmsg, size_t errmsg_len,
645 char *secondary_errmsg,
646 size_t secondary_errmsg_len)
648 switch (open_status) {
650 case CAP_DEVICE_OPEN_ERROR_NO_SUCH_DEVICE:
651 snprintf(errmsg, errmsg_len,
652 "There is no device named \"%s\".\n(%s)",
653 iface, open_status_str);
654 break;
656 case CAP_DEVICE_OPEN_ERROR_RFMON_NOTSUP:
657 snprintf(errmsg, errmsg_len,
658 "Capturing in monitor mode is not supported on device \"%s\".\n(%s)",
659 iface, open_status_str);
660 break;
662 case CAP_DEVICE_OPEN_ERROR_PERM_DENIED:
663 snprintf(errmsg, errmsg_len,
664 "You do not have permission to capture on device \"%s\".\n(%s)",
665 iface, open_status_str);
666 break;
668 case CAP_DEVICE_OPEN_ERROR_IFACE_NOT_UP:
669 snprintf(errmsg, errmsg_len,
670 "Device \"%s\" is not up.\n(%s)",
671 iface, open_status_str);
672 break;
674 case CAP_DEVICE_OPEN_ERROR_PROMISC_PERM_DENIED:
675 snprintf(errmsg, errmsg_len,
676 "You do not have permission to capture in promiscuous mode on device \"%s\".\n(%s)",
677 iface, open_status_str);
678 break;
680 case CAP_DEVICE_OPEN_ERROR_OTHER:
681 default:
682 snprintf(errmsg, errmsg_len,
683 "The capture session could not be initiated on capture device \"%s\".\n(%s)",
684 iface, open_status_str);
685 break;
687 snprintf(secondary_errmsg, secondary_errmsg_len, "%s",
688 get_pcap_failure_secondary_error_message(open_status, open_status_str));
691 static bool
692 compile_capture_filter(const char *iface, pcap_t *pcap_h,
693 struct bpf_program *fcode, const char *cfilter)
695 bpf_u_int32 netnum, netmask;
696 char lookup_net_err_str[PCAP_ERRBUF_SIZE];
698 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
700 * Well, we can't get the netmask for this interface; it's used
701 * only for filters that check for broadcast IP addresses, so
702 * we just punt and use 0. It might be nice to warn the user,
703 * but that's a pain in a GUI application, as it'd involve popping
704 * up a message box, and it's not clear how often this would make
705 * a difference (only filters that check for IP broadcast addresses
706 * use the netmask).
708 /*cmdarg_err(
709 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
710 netmask = 0;
714 * Sigh. Older versions of libpcap don't properly declare the
715 * third argument to pcap_compile() as a const pointer. Cast
716 * away the warning.
718 DIAG_OFF(cast-qual)
719 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
720 return false;
721 DIAG_ON(cast-qual)
722 return true;
725 static bool
726 show_filter_code(capture_options *capture_opts)
728 interface_options *interface_opts;
729 pcap_t *pcap_h;
730 cap_device_open_status open_status;
731 char open_status_str[PCAP_ERRBUF_SIZE];
732 char errmsg[MSG_MAX_LENGTH+1];
733 char secondary_errmsg[MSG_MAX_LENGTH+1];
734 struct bpf_program fcode;
735 struct bpf_insn *insn;
736 u_int i;
737 unsigned j;
739 for (j = 0; j < capture_opts->ifaces->len; j++) {
740 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, j);
741 pcap_h = open_capture_device(capture_opts, interface_opts,
742 CAP_READ_TIMEOUT, &open_status, &open_status_str);
743 if (pcap_h == NULL) {
744 /* Open failed; get messages */
745 get_capture_device_open_failure_messages(open_status, open_status_str,
746 interface_opts->name,
747 errmsg, sizeof errmsg,
748 secondary_errmsg,
749 sizeof secondary_errmsg);
750 /* And report them */
751 report_capture_error(errmsg, secondary_errmsg);
752 return false;
755 /* Set the link-layer type. */
756 if (!set_pcap_datalink(pcap_h, interface_opts->linktype, interface_opts->name,
757 errmsg, sizeof errmsg,
758 secondary_errmsg, sizeof secondary_errmsg)) {
759 pcap_close(pcap_h);
760 report_capture_error(errmsg, secondary_errmsg);
761 return false;
764 /* OK, try to compile the capture filter. */
765 if (!compile_capture_filter(interface_opts->name, pcap_h, &fcode,
766 interface_opts->cfilter)) {
767 snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_h));
768 pcap_close(pcap_h);
769 report_cfilter_error(capture_opts, j, errmsg);
770 return false;
772 pcap_close(pcap_h);
774 /* Now print the filter code. */
775 insn = fcode.bf_insns;
777 for (i = 0; i < fcode.bf_len; insn++, i++)
778 printf("%s\n", bpf_image(insn, i));
780 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
781 /* to remove any suid privileges. */
782 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
783 /* (euid/egid have already previously been set to ruid/rgid. */
784 /* (See comment in main() for details) */
785 /* XXX - On Linux, if we're capturing on a mac80211 device and enabling */
786 /* rfmon via libpcap with libnl support, that creates a new monitor mode */
787 /* device that libpcap will attempt to delete when capture is done. That */
788 /* will fail with EPERM because we dropped privileges. */
789 #ifndef HAVE_LIBCAP
790 relinquish_special_privs_perm();
791 #else
792 relinquish_all_capabilities();
793 #endif
794 if (capture_child) {
795 /* Let our parent know we succeeded. */
796 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
798 return true;
801 static void
802 print_machine_readable_if_capabilities(json_dumper *dumper, if_capabilities_t *caps, int queries);
805 * Output a machine readable list of the interfaces
806 * This list is retrieved by the sync_interface_list_open() function
807 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
809 static int
810 print_machine_readable_interfaces(GList *if_list, int caps_queries, bool print_statistics)
812 GList *if_entry;
813 if_info_t *if_info;
814 GSList *addr;
815 if_addr_t *if_addr;
816 char addr_str[WS_INET6_ADDRSTRLEN];
817 int status;
819 json_dumper dumper = {
820 .output_string = g_string_new(NULL),
821 .flags = JSON_DUMPER_FLAGS_NO_DEBUG,
822 // Don't abort on failure
824 json_dumper_begin_array(&dumper);
827 * Print the contents of the if_entry struct in a parseable format (JSON)
829 for (if_entry = g_list_first(if_list); if_entry != NULL;
830 if_entry = g_list_next(if_entry)) {
831 if_info = (if_info_t *)if_entry->data;
833 json_dumper_begin_object(&dumper);
834 json_dumper_set_member_name(&dumper, if_info->name);
836 json_dumper_begin_object(&dumper);
838 json_dumper_set_member_name(&dumper, "friendly_name");
839 json_dumper_value_string(&dumper, if_info->friendly_name);
841 json_dumper_set_member_name(&dumper, "vendor_description");
842 json_dumper_value_string(&dumper, if_info->vendor_description);
844 json_dumper_set_member_name(&dumper, "type");
845 json_dumper_value_anyf(&dumper, "%i", if_info->type);
847 json_dumper_set_member_name(&dumper, "addrs");
849 json_dumper_begin_array(&dumper);
850 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
851 addr = g_slist_next(addr)) {
853 if_addr = (if_addr_t *)addr->data;
854 switch(if_addr->ifat_type) {
855 case IF_AT_IPv4:
856 json_dumper_value_string(&dumper, ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str, sizeof(addr_str)));
857 break;
858 case IF_AT_IPv6:
859 json_dumper_value_string(&dumper, ws_inet_ntop6(&if_addr->addr.ip6_addr, addr_str, sizeof(addr_str)));
860 break;
861 default:
862 json_dumper_value_anyf(&dumper, "<type unknown %i>", if_addr->ifat_type);
865 json_dumper_end_array(&dumper);
867 json_dumper_set_member_name(&dumper, "loopback");
868 json_dumper_value_anyf(&dumper, "%s", if_info->loopback ? "true" : "false");
870 json_dumper_set_member_name(&dumper, "extcap");
871 json_dumper_value_string(&dumper, if_info->extcap);
873 if (if_info->caps && caps_queries) {
874 json_dumper_set_member_name(&dumper, "caps");
875 json_dumper_begin_object(&dumper);
876 print_machine_readable_if_capabilities(&dumper, if_info->caps, caps_queries);
877 json_dumper_end_object(&dumper);
879 json_dumper_end_object(&dumper);
880 json_dumper_end_object(&dumper);
882 json_dumper_end_array(&dumper);
883 if (json_dumper_finish(&dumper)) {
884 status = 0;
885 if (capture_child) {
886 if (print_statistics) {
887 sync_pipe_write_string_msg(sync_pipe_fd, SP_IFACE_LIST, dumper.output_string->str);
888 } else {
889 /* Let our parent know we succeeded. */
890 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
891 printf("%s", dumper.output_string->str);
893 } else {
894 printf("%s", dumper.output_string->str);
896 } else {
897 status = 2;
898 if (capture_child) {
899 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, "Unexpected JSON error", "");
900 } else {
901 cmdarg_err("Unexpected JSON error");
904 g_string_free(dumper.output_string, TRUE);
905 return status;
909 * If you change the machine-readable output format of this function,
910 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
912 static void
913 print_machine_readable_if_capabilities(json_dumper *dumper, if_capabilities_t *caps, int queries)
915 GList *lt_entry, *ts_entry;
916 const char *desc_str;
918 json_dumper_set_member_name(dumper, "status");
919 json_dumper_value_anyf(dumper, "%i", caps->status);
920 if (caps->primary_msg) {
921 json_dumper_set_member_name(dumper, "primary_msg");
922 json_dumper_value_string(dumper, caps->primary_msg);
925 if (queries & CAPS_QUERY_LINK_TYPES) {
926 json_dumper_set_member_name(dumper, "rfmon");
927 json_dumper_value_anyf(dumper, "%s", caps->can_set_rfmon ? "true" : "false");
928 json_dumper_set_member_name(dumper, "data_link_types");
929 json_dumper_begin_array(dumper);
930 for (lt_entry = caps->data_link_types; lt_entry != NULL;
931 lt_entry = g_list_next(lt_entry)) {
932 data_link_info_t *data_link_info = (data_link_info_t *)lt_entry->data;
933 if (data_link_info->description != NULL)
934 desc_str = data_link_info->description;
935 else
936 desc_str = "(not supported)";
937 json_dumper_begin_object(dumper);
938 json_dumper_set_member_name(dumper, "dlt");
939 json_dumper_value_anyf(dumper, "%d", data_link_info->dlt);
940 json_dumper_set_member_name(dumper, "name");
941 json_dumper_value_string(dumper, data_link_info->name);
942 json_dumper_set_member_name(dumper, "description");
943 json_dumper_value_string(dumper, desc_str);
944 json_dumper_end_object(dumper);
946 json_dumper_end_array(dumper);
948 json_dumper_set_member_name(dumper, "data_link_types_rfmon");
949 json_dumper_begin_array(dumper);
950 for (lt_entry = caps->data_link_types_rfmon; lt_entry != NULL;
951 lt_entry = g_list_next(lt_entry)) {
952 data_link_info_t *data_link_info = (data_link_info_t *)lt_entry->data;
953 if (data_link_info->description != NULL)
954 desc_str = data_link_info->description;
955 else
956 desc_str = "(not supported)";
957 json_dumper_begin_object(dumper);
958 json_dumper_set_member_name(dumper, "dlt");
959 json_dumper_value_anyf(dumper, "%d", data_link_info->dlt);
960 json_dumper_set_member_name(dumper, "name");
961 json_dumper_value_string(dumper, data_link_info->name);
962 json_dumper_set_member_name(dumper, "description");
963 json_dumper_value_string(dumper, desc_str);
964 json_dumper_end_object(dumper);
966 json_dumper_end_array(dumper);
968 if (queries & CAPS_QUERY_TIMESTAMP_TYPES) {
969 json_dumper_set_member_name(dumper, "timestamp_types");
970 json_dumper_begin_array(dumper);
971 for (ts_entry = caps->timestamp_types; ts_entry != NULL;
972 ts_entry = g_list_next(ts_entry)) {
973 timestamp_info_t *timestamp = (timestamp_info_t *)ts_entry->data;
974 if (timestamp->description != NULL)
975 desc_str = timestamp->description;
976 else
977 desc_str = "(none)";
978 json_dumper_begin_object(dumper);
979 json_dumper_set_member_name(dumper, "name");
980 json_dumper_value_string(dumper, timestamp->name);
981 json_dumper_set_member_name(dumper, "description");
982 json_dumper_value_string(dumper, desc_str);
983 json_dumper_end_object(dumper);
985 json_dumper_end_array(dumper);
989 typedef struct {
990 char *name;
991 pcap_t *pch;
992 } if_stat_t;
994 /* Print the number of packets captured for each interface until we're killed. */
995 static int
996 print_statistics_loop(bool machine_readable)
998 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
999 if_info_t *if_info;
1000 if_stat_t *if_stat;
1001 int err;
1002 char *err_str;
1003 pcap_t *pch;
1004 char errbuf[PCAP_ERRBUF_SIZE];
1005 struct pcap_stat ps;
1007 if_list = get_interface_list(&err, &err_str);
1008 if (if_list == NULL) {
1009 if (err == 0) {
1010 cmdarg_err("There are no interfaces on which a capture can be done");
1011 err = WS_EXIT_NO_INTERFACES;
1013 else {
1014 cmdarg_err("%s", err_str);
1015 g_free(err_str);
1017 return err;
1020 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1021 if_info = (if_info_t *)if_entry->data;
1023 #ifdef __linux__
1024 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
1025 * connections. We avoid collecting stats on them.
1027 if (!strncmp(if_info->name, "nf", 2)) {
1028 ws_debug("Skipping interface %s for stats", if_info->name);
1029 continue;
1031 #endif
1033 #ifdef HAVE_PCAP_OPEN
1035 * If we're opening a remote device, use pcap_open(); that's currently
1036 * the only open routine that supports remote devices.
1038 if (strncmp(if_info->name, "rpcap://", 8) == 0)
1039 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1040 else
1041 #endif
1042 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1044 if (pch) {
1045 if_stat = g_new(if_stat_t, 1);
1046 if_stat->name = g_strdup(if_info->name);
1047 if_stat->pch = pch;
1048 stat_list = g_list_append(stat_list, if_stat);
1052 if (!stat_list) {
1053 cmdarg_err("There are no interfaces on which a capture can be done");
1054 return 2;
1057 if (capture_child) {
1058 /* Let our parent know we succeeded. */
1059 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
1062 if (!machine_readable) {
1063 printf("%-15s %10s %10s\n", "Interface", "Received",
1064 "Dropped");
1067 global_ld.go = true;
1068 while (global_ld.go) {
1069 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1070 if_stat = (if_stat_t *)stat_entry->data;
1071 /* XXX - what if this fails? */
1072 if (pcap_stats(if_stat->pch, &ps) == 0) {
1073 if (!machine_readable) {
1074 printf("%-15s %10u %10u\n", if_stat->name,
1075 ps.ps_recv, ps.ps_drop);
1076 } else {
1077 printf("%s\t%u\t%u\n", if_stat->name,
1078 ps.ps_recv, ps.ps_drop);
1079 fflush(stdout);
1083 #ifdef _WIN32
1084 /* If we have a dummy signal pipe check it */
1085 if (!signal_pipe_check_running()) {
1086 global_ld.go = false;
1088 Sleep(1 * 1000);
1089 #else
1090 sleep(1);
1091 #endif
1094 /* XXX - Not reached. Should we look for 'q' in stdin? */
1095 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1096 if_stat = (if_stat_t *)stat_entry->data;
1097 pcap_close(if_stat->pch);
1098 g_free(if_stat->name);
1099 g_free(if_stat);
1101 g_list_free(stat_list);
1102 free_interface_list(if_list);
1104 return 0;
1108 #ifdef _WIN32
1109 static BOOL WINAPI
1110 capture_cleanup_handler(DWORD dwCtrlType)
1112 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1113 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1114 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1115 like SIGTERM at least when the machine's shutting down.
1117 For now, if we're running as a command rather than a capture child,
1118 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1119 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1120 in that way on UN*X.
1122 If we're not running as a capture child, we might be running as
1123 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1124 user logs out. (XXX - can we explicitly check whether we're
1125 running as a service?) */
1127 ws_info("Console: Control signal");
1128 ws_debug("Console: Control signal, CtrlType: %lu", dwCtrlType);
1130 /* Keep capture running if we're a service and a user logs off */
1131 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1132 capture_loop_stop();
1133 return true;
1134 } else {
1135 return false;
1138 #else
1139 static void
1140 capture_cleanup_handler(int signum _U_)
1142 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1143 SIGTERM. We assume that if the user wanted it to keep running
1144 after they logged out, they'd have nohupped it. */
1146 capture_loop_stop();
1148 #endif
1151 static void
1152 report_capture_count(bool reportit)
1154 /* Don't print this if we're a capture child. */
1155 if (!capture_child && reportit) {
1156 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packets_captured);
1157 /* stderr could be line buffered */
1158 fflush(stderr);
1163 #ifdef SIGINFO
1164 static void
1165 report_counts_for_siginfo(void)
1167 report_capture_count(quiet);
1168 infoprint = false; /* we just reported it */
1171 static void
1172 report_counts_siginfo(int signum _U_)
1174 int sav_errno = errno;
1176 /* If we've been told to delay printing, just set a flag asking
1177 that we print counts (if we're supposed to), otherwise print
1178 the count of packets captured (if we're supposed to). */
1179 if (infodelay)
1180 infoprint = true;
1181 else
1182 report_counts_for_siginfo();
1183 errno = sav_errno;
1185 #endif /* SIGINFO */
1187 static void
1188 exit_main(int status)
1190 ws_cleanup_sockets();
1192 #ifdef _WIN32
1193 /* can be helpful for debugging */
1194 #ifdef DEBUG_DUMPCAP
1195 printf("Press any key\n");
1196 _getch();
1197 #endif
1199 #endif /* _WIN32 */
1201 if (ringbuf_is_initialized()) {
1202 /* save_file is managed by ringbuffer, be sure to release the memory and
1203 * avoid capture_opts_cleanup from double-freeing 'save_file'. */
1204 ringbuf_free();
1205 global_capture_opts.save_file = NULL;
1208 capture_opts_cleanup(&global_capture_opts);
1209 exit(status);
1212 #ifdef HAVE_LIBCAP
1214 * If we were linked with libcap (not related to libpcap), make sure we have
1215 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1216 * (See comment in main() for details)
1218 static void
1219 relinquish_privs_except_capture(void)
1222 * Drop any capabilities other than NET_ADMIN and NET_RAW:
1224 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1225 * stuff we don't need (and shouldn't have).
1226 * CAP_NET_RAW: Packet capture (raw sockets).
1228 * If 'started_with_special_privs' (ie: suid) then drop our
1229 * suid privileges.
1232 cap_t current_caps = cap_get_proc();
1233 print_caps("Pre set");
1235 cap_t caps = cap_init(); /* all capabilities initialized to off */
1238 * We can only set capabilities that are in the permitted set.
1239 * If the real or effective user ID is 0 (root), then the file
1240 * inherited and permitted sets are ignored, and our permitted
1241 * set should be all ones - unless the effective ID is 0, the
1242 * real ID is not zero, and the binary has file capabilities,
1243 * in which case the permitted set is only that of the file.
1244 * (E.g., set-user-ID-root + file capabilities.)
1246 * If one or more of the euid, ruid, and saved set user ID are
1247 * all zero and all change to nonzero, then all capabilities are
1248 * cleared from the permitted, effective, and ambient sets.
1249 * PR_SET_KEEPCAPS causes the permitted set to be retained, so
1250 * we can relinquish our changed user ID.
1252 * All capabilities are always cleared from the effective set
1253 * when the euid is changed from 0 to nonzero.
1255 * See capabilities(7).
1257 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1258 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1261 if (started_with_special_privs()) {
1262 relinquish_special_privs_perm();
1266 * If cap_set_proc() fails, it leaves the capabilities unchanged.
1267 * So the only way to guarantee that we've dropped all other
1268 * capabilities is to ensure that cap_set_proc() succeeds.
1269 * One option might be to exit if cap_set_proc() fails - but some
1270 * captures will work with CAP_NET_RAW but not CAP_NET_ADMIN.
1273 cap_value_t cap_list[1] = { CAP_NET_ADMIN };
1274 int cl_len = array_length(cap_list);
1275 cap_flag_value_t value;
1277 cap_get_flag(current_caps, cap_list[0], CAP_PERMITTED, &value);
1279 if (value != CAP_SET) {
1280 // XXX - Should we warn here? Some captures will still work.
1282 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, value);
1283 // XXX - Do we really need CAP_INHERITABLE?
1284 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, value);
1285 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, value);
1287 cap_list[0] = CAP_NET_RAW;
1288 cap_get_flag(current_caps, cap_list[0], CAP_PERMITTED, &value);
1290 if (value != CAP_SET) {
1291 // XXX - Should we warn here?
1293 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, value);
1294 // XXX - Do we really need CAP_INHERITABLE?
1295 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, value);
1296 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, value);
1298 if (cap_set_proc(caps)) {
1300 * This shouldn't happen, we're only trying to set capabilities
1301 * already in the permitted set.
1303 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1306 print_caps("Post set");
1308 cap_free(current_caps);
1309 cap_free(caps);
1312 #endif /* HAVE_LIBCAP */
1314 /* Map DLT_ values, as returned by pcap_datalink(), to LINKTYPE_ values,
1315 as are written to capture files.
1317 Most of the time, a DLT_ value and the corresponding LINKYPE_ value
1318 are the same, but there are some cases, where a numeric value as
1319 a DLT_ doesn't uniquely identify a particular link-layer header type,
1320 where they differ, so that the values in files *do* identify
1321 particular link-layer header types. */
1323 /* LINKTYPE_ values that don't match corresponding DLT_ values on
1324 all platforms. */
1325 #define LINKTYPE_ATM_RFC1483 100
1326 #define LINKTYPE_RAW 101
1327 #define LINKTYPE_SLIP_BSDOS 102
1328 #define LINKTYPE_PPP_BSDOS 103
1329 #define LINKTYPE_C_HDLC 104
1330 #define LINKTYPE_IEEE802_11 105
1331 #define LINKTYPE_ATM_CLIP 106
1332 #define LINKTYPE_FRELAY 107
1333 #define LINKTYPE_LOOP 108
1334 #define LINKTYPE_ENC 109
1335 #define LINKTYPE_NETBSD_HDLC 112
1336 #define LINKTYPE_PFSYNC 246
1337 #define LINKTYPE_PKTAP 258
1339 static int
1340 dlt_to_linktype(int dlt)
1342 /* DLT_NULL through DLT_FDDI have the same numeric value on
1343 all platforms, so the corresponding LINKTYPE_s have the
1344 same numeric values. */
1345 if (dlt >= DLT_NULL && dlt <= DLT_FDDI)
1346 return (dlt);
1348 #if defined(DLT_PFSYNC) && DLT_PFSYNC != LINKTYPE_PFSYNC
1349 /* DLT_PFSYNC has a value on several platforms that's in the
1350 non-matching range, a value on FreeBSD that's in the high
1351 matching range and that's *not* equal to LINKTYPE_PFSYNC,
1352 and has a value on the rmaining platforms that's equal
1353 to LINKTYPE_PFSYNC, which is in the high matching range.
1355 Map it to LINKTYPE_PFSYNC if it's not equal to LINKTYPE_PFSYNC. */
1356 if (dlt == DLT_PFSYNC)
1357 return (LINKTYPE_PFSYNC);
1358 #endif
1360 /* DLT_PKTAP is defined as DLT_USER2 - which is in the high
1361 matching range - on Darwin because Apple used DLT_USER2
1362 on systems that users ran, not just as an internal thing.
1364 We map it to LINKTYPE_PKTAP if it's not equal to LINKTYPE_PKTAP
1365 so that DLT_PKTAP captures from Apple machines can be read by
1366 software that either doesn't handle DLT_USER2 or that handles it
1367 as something other than Apple PKTAP. */
1368 #if defined(DLT_PKTAP) && DLT_PKTAP != LINKTYPE_PKTAP
1369 if (dlt == DLT_PKTAP)
1370 return (LINKTYPE_PKTAP);
1371 #endif
1373 /* For all other DLT_s with values beyond 104, the value
1374 of the corresponding LINKTYPE_ is the same. */
1375 if (dlt >= 104)
1376 return (dlt);
1378 /* These DLT_ values have different values on different
1379 platforms, so we assigned them LINKTYPE_ values just
1380 below the lower bound of the high matchig range;
1381 those values should never be equal to any DLT_
1382 values, so that should avoid collisions.
1384 That way, for example, "raw IP" packets will have
1385 LINKTYPE_RAW as the code in all savefiles for
1386 which the code that writes them maps to that
1387 value, regardless of the platform on which they
1388 were written, so they should be readable on all
1389 platforms without having to determine on which
1390 platform they were written.
1392 We map the DLT_ values on this platform, whatever
1393 it might be, to the corresponding LINKTYPE_ values. */
1394 #ifdef DLT_ATM_RFC1483
1395 if (dlt == DLT_ATM_RFC1483)
1396 return (LINKTYPE_ATM_RFC1483);
1397 #endif
1398 #ifdef DLT_RAW
1399 if (dlt == DLT_RAW)
1400 return (LINKTYPE_RAW);
1401 #endif
1402 #ifdef DLT_SLIP_BSDOS
1403 if (dlt == DLT_SLIP_BSDOS)
1404 return (LINKTYPE_SLIP_BSDOS);
1405 #endif
1406 #ifdef DLT_PPP_BSDOS
1407 if (dlt == DLT_PPP_BSDOS)
1408 return (LINKTYPE_PPP_BSDOS);
1409 #endif
1411 /* These DLT_ values were originally defined on some platform,
1412 and weren't defined on other platforms.
1414 At least some of those values, on at least one platform,
1415 collide with the values of other DLT_s on other platforms,
1416 e.g. DLT_LOOP, so we don't just define them, on all
1417 platforms, as having the same value as on the original
1418 platform.
1420 Therefore, we assigned new LINKTYPE_ values to them, and,
1421 on the platforms where they weren't originally defined,
1422 define the DLT_s to have the same value as the corresponding
1423 LINKTYPE_.
1425 This means that, for capture files with the original
1426 platform's DLT_ value rather than the LINKTYPE_ value
1427 as a link-layer type, we will recognize those types
1428 on that platform, but not on other platforms. */
1429 #ifdef DLT_FR
1430 /* BSD/OS Frame Relay */
1431 if (dlt == DLT_FR)
1432 return (LINKTYPE_FRELAY);
1433 #endif
1434 #if defined(DLT_HDLC) && DLT_HDLC != LINKTYPE_NETBSD_HDLC
1435 /* NetBSD HDLC */
1436 if (dlt == DLT_HDLC)
1437 return (LINKTYPE_NETBSD_HDLC);
1438 #endif
1439 #if defined(DLT_C_HDLC) && DLT_C_HDLC != LINKTYPE_C_HDLC
1440 /* BSD/OS Cisco HDLC */
1441 if (dlt == DLT_C_HDLC)
1442 return (LINKTYPE_C_HDLC);
1443 #endif
1444 #if defined(DLT_LOOP) && DLT_LOOP != LINKTYPE_LOOP
1445 /* OpenBSD DLT_LOOP */
1446 if (dlt == DLT_LOOP)
1447 return (LINKTYPE_LOOP);
1448 #endif
1449 #if defined(DLT_ENC) && DLT_ENC != LINKTYPE_ENC
1450 /* OpenBSD DLT_ENC */
1451 if (dlt == DLT_ENC)
1452 return (LINKTYPE_ENC);
1453 #endif
1455 /* These DLT_ values are not on all platforms, but, so far,
1456 there don't appear to be any platforms that define
1457 other DLT_s with those values; we map them to
1458 different LINKTYPE_ values anyway, just in case. */
1459 #ifdef DLT_ATM_CLIP
1460 /* Linux ATM Classical IP */
1461 if (dlt == DLT_ATM_CLIP)
1462 return (LINKTYPE_ATM_CLIP);
1463 #endif
1465 /* Treat all other DLT_s as having the same value as the
1466 corresponding LINKTYPE_. */
1467 return (dlt);
1470 /* Take care of byte order in the libpcap headers read from pipes.
1471 * (function taken from wiretap/libpcap.c) */
1472 static void
1473 cap_pipe_adjust_pcap_header(bool byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1475 if (byte_swapped) {
1476 /* Byte-swap the record header fields. */
1477 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1478 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1479 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1480 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1483 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1484 swapped, in order to match the BPF header layout.
1486 Unfortunately, some files were, according to a comment in the "libpcap"
1487 source, written with version 2.3 in their headers but without the
1488 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1489 would make no sense - we assume that we need to swap them. */
1490 if (hdr->version_major == 2 &&
1491 (hdr->version_minor < 3 ||
1492 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1493 uint32_t temp;
1495 temp = rechdr->orig_len;
1496 rechdr->orig_len = rechdr->incl_len;
1497 rechdr->incl_len = temp;
1501 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1502 * or just read().
1504 static ssize_t
1505 cap_pipe_read(int pipe_fd, char *buf, size_t sz, bool from_socket _U_)
1507 #ifdef _WIN32
1508 if (from_socket) {
1509 return recv(pipe_fd, buf, (int)sz, 0);
1510 } else {
1511 return -1;
1513 #else
1514 return ws_read(pipe_fd, buf, sz);
1515 #endif
1518 #if defined(_WIN32)
1520 * Thread function that reads from a pipe and pushes the data
1521 * to the main application thread.
1524 * XXX Right now we use async queues for basic signaling. The main thread
1525 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1526 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1527 * Iff the read is successful cap_pipe_read pushes an item onto
1528 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1529 * the queues themselves (yet).
1531 * We might want to move some of the cap_pipe_dispatch logic here so that
1532 * we can let cap_thread_read run independently, queuing up multiple reads
1533 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1535 static void *cap_thread_read(void *arg)
1537 capture_src *pcap_src;
1538 #ifdef _WIN32
1539 BOOL res;
1540 DWORD last_err, bytes_read;
1541 #else /* _WIN32 */
1542 size_t bytes_read;
1543 #endif /* _WIN32 */
1545 pcap_src = (capture_src *)arg;
1546 while (pcap_src->cap_pipe_err == PIPOK) {
1547 g_async_queue_pop(pcap_src->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1548 g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1549 bytes_read = 0;
1550 while (bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1551 if ((pcap_src->from_cap_socket)
1552 #ifndef _WIN32
1553 || 1
1554 #endif
1557 ssize_t b;
1558 b = cap_pipe_read(pcap_src->cap_pipe_fd, pcap_src->cap_pipe_buf+bytes_read,
1559 pcap_src->cap_pipe_bytes_to_read - bytes_read, pcap_src->from_cap_socket);
1560 if (b <= 0) {
1561 if (b == 0) {
1562 pcap_src->cap_pipe_err = PIPEOF;
1563 bytes_read = 0;
1564 break;
1565 } else {
1566 pcap_src->cap_pipe_err = PIPERR;
1567 bytes_read = -1;
1568 break;
1570 } else {
1571 bytes_read += (DWORD)b;
1574 #ifdef _WIN32
1575 else
1577 /* If we try to use read() on a named pipe on Windows with partial
1578 * data it appears to return EOF.
1580 DWORD b;
1581 res = ReadFile(pcap_src->cap_pipe_h, pcap_src->cap_pipe_buf+bytes_read,
1582 pcap_src->cap_pipe_bytes_to_read - bytes_read,
1583 &b, NULL);
1585 bytes_read += b;
1586 if (!res) {
1587 last_err = GetLastError();
1588 if (last_err == ERROR_MORE_DATA) {
1589 continue;
1590 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1591 pcap_src->cap_pipe_err = PIPEOF;
1592 bytes_read = 0;
1593 break;
1595 pcap_src->cap_pipe_err = PIPERR;
1596 bytes_read = -1;
1597 break;
1598 } else if (b == 0 && pcap_src->cap_pipe_bytes_to_read > 0) {
1599 pcap_src->cap_pipe_err = PIPEOF;
1600 bytes_read = 0;
1601 break;
1604 #endif /*_WIN32 */
1606 pcap_src->cap_pipe_bytes_read = bytes_read;
1607 if (pcap_src->cap_pipe_bytes_read >= pcap_src->cap_pipe_bytes_to_read) {
1608 g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1610 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1612 /* Post to queue if we didn't read enough data as the main thread waits for the message */
1613 g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1614 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1615 /* There's still more of the record to read. */
1616 g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1618 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1619 return NULL;
1623 * Do a blocking read from a pipe within the main thread, by pushing
1624 * the read onto the pipe queue and then popping it off that queue;
1625 * the pipe will block until the pushed read completes.
1627 * We do it with another thread because we can't use select() on
1628 * pipes on Windows, as we can on UN*Xes, we can only use it on
1629 * sockets.
1631 void
1632 pipe_read_sync(capture_src *pcap_src, void *buf, DWORD nbytes)
1634 pcap_src->cap_pipe_buf = (char *) buf;
1635 pcap_src->cap_pipe_bytes_read = 0;
1636 pcap_src->cap_pipe_bytes_to_read = nbytes;
1637 /* We don't have to worry about cap_pipe_read_mtx here */
1638 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1639 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1641 #endif
1643 /* Provide select() functionality for a single file descriptor
1644 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1646 * Returns the same values as select.
1648 static int
1649 cap_pipe_select(int pipe_fd)
1651 fd_set rfds;
1652 struct timeval timeout;
1654 FD_ZERO(&rfds);
1655 FD_SET(pipe_fd, &rfds);
1657 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1658 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1660 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1663 #define DEF_TCP_PORT 19000
1665 static int
1666 cap_open_socket(char *pipename, capture_src *pcap_src, char *errmsg, size_t errmsgl)
1668 struct sockaddr_storage sa;
1669 socklen_t sa_len;
1670 int fd;
1672 /* Skip the initial "TCP@" in the pipename. */
1673 if (ws_socket_ptoa(&sa, pipename + 4, DEF_TCP_PORT) < 0) {
1674 snprintf(errmsg, errmsgl,
1675 "The capture session could not be initiated because"
1676 "\"%s\" is not a valid socket specification", pipename);
1677 pcap_src->cap_pipe_err = PIPERR;
1678 return -1;
1681 if ((fd = (int)socket(sa.ss_family, SOCK_STREAM, 0)) < 0) {
1682 snprintf(errmsg, errmsgl,
1683 "The capture session could not be initiated because"
1684 " the socket couldn't be created due to the socket error: \n"
1685 #ifdef _WIN32
1686 " %s", win32strerror(WSAGetLastError()));
1687 #else
1688 " %d: %s", errno, g_strerror(errno));
1689 #endif
1690 pcap_src->cap_pipe_err = PIPERR;
1691 return -1;
1694 if (sa.ss_family == AF_INET6)
1695 sa_len = sizeof(struct sockaddr_in6);
1696 else
1697 sa_len = sizeof(struct sockaddr_in);
1698 if (connect(fd, (struct sockaddr *)&sa, sa_len) < 0) {
1699 snprintf(errmsg, errmsgl,
1700 "The capture session could not be initiated because"
1701 " the socket couldn't be connected due to the socket error: \n"
1702 #ifdef _WIN32
1703 " %s", win32strerror(WSAGetLastError()));
1704 #else
1705 " %d: %s", errno, g_strerror(errno));
1706 #endif
1707 pcap_src->cap_pipe_err = PIPERR;
1709 cap_pipe_close(fd, true);
1710 return -1;
1713 pcap_src->from_cap_socket = true;
1714 return fd;
1717 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1718 * otherwise.
1720 static void
1721 cap_pipe_close(int pipe_fd, bool from_socket)
1723 #ifdef _WIN32
1724 if (from_socket) {
1725 closesocket(pipe_fd);
1727 #else
1728 (void) from_socket; /* Mark unused, similar to Q_UNUSED */
1729 ws_close(pipe_fd);
1730 #endif
1733 /** Read bytes from a capture source, which is assumed to be a pipe or
1734 * socket.
1736 * Returns -1, or the number of bytes read similar to read(2).
1737 * Sets pcap_src->cap_pipe_err on error or EOF.
1739 static ssize_t
1740 cap_pipe_read_data_bytes(capture_src *pcap_src, char *errmsg, size_t errmsgl)
1742 int sel_ret;
1743 int fd = pcap_src->cap_pipe_fd;
1744 #ifdef _WIN32
1745 DWORD sz, bytes_read = 0;
1746 #else /* _WIN32 */
1747 ssize_t sz, bytes_read = 0;
1748 #endif /* _WIN32 */
1749 ssize_t b;
1751 #ifdef LOG_CAPTURE_VERBOSE
1752 ws_debug("cap_pipe_read_data_bytes read %lu of %lu",
1753 pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1754 #endif
1755 sz = pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read;
1756 while (bytes_read < sz) {
1757 if (fd == -1) {
1758 snprintf(errmsg, errmsgl, "Invalid file descriptor.");
1759 pcap_src->cap_pipe_err = PIPNEXIST;
1760 return -1;
1763 sel_ret = cap_pipe_select(fd);
1764 if (sel_ret < 0) {
1765 snprintf(errmsg, errmsgl,
1766 "Unexpected error from select: %s.", g_strerror(errno));
1767 pcap_src->cap_pipe_err = PIPERR;
1768 return -1;
1769 } else if (sel_ret > 0) {
1770 b = cap_pipe_read(fd, pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read+bytes_read,
1771 sz-bytes_read, pcap_src->from_cap_socket);
1772 if (b <= 0) {
1773 if (b == 0) {
1774 snprintf(errmsg, errmsgl,
1775 "End of file reading from pipe or socket.");
1776 pcap_src->cap_pipe_err = PIPEOF;
1777 } else {
1778 #ifdef _WIN32
1780 * On Windows, we only do this for sockets.
1782 DWORD lastError = WSAGetLastError();
1783 errno = lastError;
1784 snprintf(errmsg, errmsgl,
1785 "Error reading from pipe or socket: %s.",
1786 win32strerror(lastError));
1787 #else
1788 snprintf(errmsg, errmsgl,
1789 "Error reading from pipe or socket: %s.",
1790 g_strerror(errno));
1791 #endif
1792 pcap_src->cap_pipe_err = PIPERR;
1794 return -1;
1796 #ifdef _WIN32
1797 bytes_read += (DWORD)b;
1798 #else
1799 bytes_read += b;
1800 #endif
1803 pcap_src->cap_pipe_bytes_read += bytes_read;
1804 #ifdef LOG_CAPTURE_VERBOSE
1805 ws_debug("cap_pipe_read_data_bytes read %lu of %lu",
1806 pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1807 #endif
1808 return bytes_read;
1811 /* Some forward declarations for breaking up cap_pipe_open_live for pcap and pcapng formats */
1812 static void pcap_pipe_open_live(int fd, capture_src *pcap_src,
1813 struct pcap_hdr *hdr,
1814 char *errmsg, size_t errmsgl,
1815 char *secondary_errmsg, size_t secondary_errmsgl);
1816 static void pcapng_pipe_open_live(int fd, capture_src *pcap_src,
1817 char *errmsg, size_t errmsgl);
1818 static int pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src,
1819 char *errmsg, size_t errmsgl);
1821 /* For problems that are probably Not Our Fault. */
1822 static char not_our_bug[] =
1823 "Please report this to the developers of the program writing to the pipe.";
1825 /* Mimic pcap_open_live() for pipe captures
1827 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1828 * open it, and read the header.
1830 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1831 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1832 static void
1833 cap_pipe_open_live(char *pipename,
1834 capture_src *pcap_src,
1835 void *hdr,
1836 char *errmsg, size_t errmsgl,
1837 char *secondary_errmsg, size_t secondary_errmsgl)
1839 #ifndef _WIN32
1840 ws_statb64 pipe_stat;
1841 struct sockaddr_un sa;
1842 #else /* _WIN32 */
1843 uintptr_t extcap_pipe_handle;
1844 #endif
1845 bool extcap_pipe = false;
1846 ssize_t b;
1847 int fd = -1, sel_ret;
1848 size_t bytes_read;
1849 uint32_t magic = 0;
1850 pcap_src->cap_pipe_fd = -1;
1851 #ifdef _WIN32
1852 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1853 #endif
1855 ws_debug("cap_pipe_open_live: %s", pipename);
1858 * XXX - this blocks until a pcap per-file header has been written to
1859 * the pipe, so it could block indefinitely.
1861 if (strcmp(pipename, "-") == 0) {
1862 #ifndef _WIN32
1863 fd = 0; /* read from stdin */
1864 #else /* _WIN32 */
1865 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1866 #endif /* _WIN32 */
1867 } else if (!strncmp(pipename, "TCP@", 4)) {
1868 if ((fd = cap_open_socket(pipename, pcap_src, errmsg, errmsgl)) < 0) {
1869 return;
1871 } else {
1872 #ifndef _WIN32
1873 if ( g_strrstr(pipename, EXTCAP_PIPE_PREFIX) != NULL )
1874 extcap_pipe = true;
1876 if (ws_stat64(pipename, &pipe_stat) < 0) {
1877 if (errno == ENOENT || errno == ENOTDIR)
1878 pcap_src->cap_pipe_err = PIPNEXIST;
1879 else {
1880 snprintf(errmsg, errmsgl,
1881 "The capture session could not be initiated "
1882 "due to error getting information on pipe or socket: %s.", g_strerror(errno));
1883 pcap_src->cap_pipe_err = PIPERR;
1885 return;
1887 if (S_ISFIFO(pipe_stat.st_mode)) {
1888 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1889 if (fd == -1) {
1890 snprintf(errmsg, errmsgl,
1891 "The capture session could not be initiated "
1892 "due to error on pipe open: %s.", g_strerror(errno));
1893 pcap_src->cap_pipe_err = PIPERR;
1894 return;
1896 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1897 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1898 if (fd == -1) {
1899 snprintf(errmsg, errmsgl,
1900 "The capture session could not be initiated "
1901 "due to error on socket create: %s.", g_strerror(errno));
1902 pcap_src->cap_pipe_err = PIPERR;
1903 return;
1905 sa.sun_family = AF_UNIX;
1907 * The Single UNIX Specification says:
1909 * The size of sun_path has intentionally been left undefined.
1910 * This is because different implementations use different sizes.
1911 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1912 * of 104. Since most implementations originate from BSD versions,
1913 * the size is typically in the range 92 to 108.
1915 * Applications should not assume a particular length for sun_path
1916 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1918 * It also says
1920 * The <sys/un.h> header shall define the sockaddr_un structure,
1921 * which shall include at least the following members:
1923 * sa_family_t sun_family Address family.
1924 * char sun_path[] Socket pathname.
1926 * so we assume that it's an array, with a specified size,
1927 * and that the size reflects the maximum path length.
1929 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1930 /* Path name too long */
1931 snprintf(errmsg, errmsgl,
1932 "The capture session could not be initiated "
1933 "due to error on socket connect: Path name too long.");
1934 pcap_src->cap_pipe_err = PIPERR;
1935 ws_close(fd);
1936 return;
1938 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1939 if (b == -1) {
1940 snprintf(errmsg, errmsgl,
1941 "The capture session could not be initiated "
1942 "due to error on socket connect: %s.", g_strerror(errno));
1943 pcap_src->cap_pipe_err = PIPERR;
1944 ws_close(fd);
1945 return;
1947 } else {
1948 if (S_ISCHR(pipe_stat.st_mode)) {
1950 * Assume the user specified an interface on a system where
1951 * interfaces are in /dev. Pretend we haven't seen it.
1953 pcap_src->cap_pipe_err = PIPNEXIST;
1954 } else {
1955 snprintf(errmsg, errmsgl,
1956 "The capture session could not be initiated because\n"
1957 "\"%s\" is neither an interface nor a socket nor a pipe.", pipename);
1958 pcap_src->cap_pipe_err = PIPERR;
1960 return;
1963 #else /* _WIN32 */
1964 if (sscanf(pipename, EXTCAP_PIPE_PREFIX "%" SCNuPTR, &extcap_pipe_handle) == 1)
1966 /* The client is already connected to extcap pipe.
1967 * We have inherited the handle from parent process.
1969 extcap_pipe = true;
1970 pcap_src->cap_pipe_h = (HANDLE)extcap_pipe_handle;
1972 else
1974 if (!win32_is_pipe_name(pipename)) {
1975 snprintf(errmsg, errmsgl,
1976 "The capture session could not be initiated because\n"
1977 "\"%s\" is neither an interface nor a pipe.", pipename);
1978 pcap_src->cap_pipe_err = PIPNEXIST;
1979 return;
1982 /* Wait for the pipe to appear */
1983 while (1) {
1984 pcap_src->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1985 OPEN_EXISTING, 0, NULL);
1987 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE)
1988 break;
1990 if (GetLastError() != ERROR_PIPE_BUSY) {
1991 snprintf(errmsg, errmsgl,
1992 "The capture session on \"%s\" could not be started "
1993 "due to error on pipe open: %s.",
1994 pipename, win32strerror(GetLastError()));
1995 pcap_src->cap_pipe_err = PIPERR;
1996 return;
1999 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
2000 snprintf(errmsg, errmsgl,
2001 "The capture session on \"%s\" timed out during "
2002 "pipe open: %s.",
2003 pipename, win32strerror(GetLastError()));
2004 pcap_src->cap_pipe_err = PIPERR;
2005 return;
2009 #endif /* _WIN32 */
2012 pcap_src->from_cap_pipe = true;
2015 * We start with a 2KB buffer for packet data, which should be
2016 * large enough for most regular network packets. We increase it,
2017 * up to the maximum size we allow, as necessary.
2019 pcap_src->cap_pipe_databuf = (char*)g_malloc(2048);
2020 pcap_src->cap_pipe_databuf_size = 2048;
2023 * Read the first 4 bytes of data from the pipe.
2025 * If a pcap file is being written to it, that will be
2026 * the pcap magic number.
2028 * If a pcapng file is being written to it, that will be
2029 * the block type of the initial SHB.
2031 #ifdef _WIN32
2033 * On UN*X, we can use select() on pipes or sockets.
2035 * On Windows, we can only use it on sockets; to do non-blocking
2036 * reads from pipes, we currently do reads in a separate thread
2037 * and use GLib asynchronous queues from the main thread to start
2038 * read operations and to wait for them to complete.
2040 if (pcap_src->from_cap_socket)
2041 #endif
2043 bytes_read = 0;
2044 while (bytes_read < sizeof magic) {
2045 sel_ret = cap_pipe_select(fd);
2046 if (sel_ret < 0) {
2047 snprintf(errmsg, errmsgl,
2048 "Unexpected error from select: %s.",
2049 g_strerror(errno));
2050 goto error;
2051 } else if (sel_ret > 0) {
2052 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
2053 sizeof magic-bytes_read,
2054 pcap_src->from_cap_socket);
2055 /* jump messaging, if extcap had an error, stderr will provide the correct message */
2056 if (extcap_pipe && b <= 0)
2057 goto error;
2059 if (b <= 0) {
2060 if (b == 0)
2061 snprintf(errmsg, errmsgl,
2062 "End of file on pipe magic during open.");
2063 else
2064 snprintf(errmsg, errmsgl,
2065 "Error on pipe magic during open: %s.",
2066 g_strerror(errno));
2067 goto error;
2069 bytes_read += b;
2073 #ifdef _WIN32
2074 else {
2075 /* Create a thread to read from this pipe */
2076 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
2078 pipe_read_sync(pcap_src, &magic, sizeof(magic));
2079 /* jump messaging, if extcap had an error, stderr will provide the correct message */
2080 if (pcap_src->cap_pipe_bytes_read <= 0 && extcap_pipe)
2081 goto error;
2083 if (pcap_src->cap_pipe_bytes_read <= 0) {
2084 if (pcap_src->cap_pipe_bytes_read == 0)
2085 snprintf(errmsg, errmsgl,
2086 "End of file on pipe magic during open.");
2087 else
2088 snprintf(errmsg, errmsgl,
2089 "Error on pipe magic during open: %s.",
2090 g_strerror(errno));
2091 goto error;
2094 #endif
2096 switch (magic) {
2097 case PCAP_MAGIC:
2098 case PCAP_NSEC_MAGIC:
2099 /* This is a pcap file.
2100 The host that wrote it has our byte order, and was running
2101 a program using either standard or ss990417 libpcap. */
2102 pcap_src->cap_pipe_info.pcap.byte_swapped = false;
2103 pcap_src->cap_pipe_modified = false;
2104 pcap_src->ts_nsec = magic == PCAP_NSEC_MAGIC;
2105 break;
2106 case PCAP_MODIFIED_MAGIC:
2107 /* This is a pcap file.
2108 The host that wrote it has our byte order, but was running
2109 a program using either ss990915 or ss991029 libpcap. */
2110 pcap_src->cap_pipe_info.pcap.byte_swapped = false;
2111 pcap_src->cap_pipe_modified = true;
2112 break;
2113 case PCAP_SWAPPED_MAGIC:
2114 case PCAP_SWAPPED_NSEC_MAGIC:
2115 /* This is a pcap file.
2116 The host that wrote it has a byte order opposite to ours,
2117 and was running a program using either standard or
2118 ss990417 libpcap. */
2119 pcap_src->cap_pipe_info.pcap.byte_swapped = true;
2120 pcap_src->cap_pipe_modified = false;
2121 pcap_src->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
2122 break;
2123 case PCAP_SWAPPED_MODIFIED_MAGIC:
2124 /* This is a pcap file.
2125 The host that wrote it out has a byte order opposite to
2126 ours, and was running a program using either ss990915
2127 or ss991029 libpcap. */
2128 pcap_src->cap_pipe_info.pcap.byte_swapped = true;
2129 pcap_src->cap_pipe_modified = true;
2130 break;
2131 case BLOCK_TYPE_SHB:
2132 /* This is a pcapng file. */
2133 pcap_src->from_pcapng = true;
2134 pcap_src->cap_pipe_dispatch = pcapng_pipe_dispatch;
2135 pcap_src->cap_pipe_info.pcapng.src_iface_to_global = g_array_new(FALSE, FALSE, sizeof(uint32_t));
2136 global_capture_opts.use_pcapng = true; /* we can only output in pcapng format */
2137 break;
2138 default:
2139 /* Not a pcapng file, and either not a pcap type we know about
2140 or not a pcap file, either. */
2141 snprintf(errmsg, errmsgl,
2142 "File type is neither a supported pcap nor pcapng format. (magic = 0x%08x)", magic);
2143 snprintf(secondary_errmsg, secondary_errmsgl, "%s",
2144 not_our_bug);
2145 goto error;
2148 if (pcap_src->from_pcapng)
2149 pcapng_pipe_open_live(fd, pcap_src, errmsg, errmsgl);
2150 else
2151 pcap_pipe_open_live(fd, pcap_src, (struct pcap_hdr *) hdr, errmsg, errmsgl,
2152 secondary_errmsg, secondary_errmsgl);
2154 return;
2156 error:
2157 ws_debug("cap_pipe_open_live: error %s", errmsg);
2158 pcap_src->cap_pipe_err = PIPERR;
2159 cap_pipe_close(fd, pcap_src->from_cap_socket);
2160 pcap_src->cap_pipe_fd = -1;
2161 #ifdef _WIN32
2162 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2163 #endif
2167 * Read the part of the pcap file header that follows the magic
2168 * number (we've already read the magic number).
2170 static void
2171 pcap_pipe_open_live(int fd,
2172 capture_src *pcap_src,
2173 struct pcap_hdr *hdr,
2174 char *errmsg, size_t errmsgl,
2175 char *secondary_errmsg, size_t secondary_errmsgl)
2177 size_t bytes_read;
2178 ssize_t b;
2179 int sel_ret;
2182 * We're reading from a pcap file. We've already read the magic
2183 * number; read the rest of the header.
2185 * (Note that struct pcap_hdr is a structure for the part of a
2186 * pcap file header *following the magic number*; it does not
2187 * include the magic number itself.)
2189 #ifdef _WIN32
2190 if (pcap_src->from_cap_socket)
2191 #endif
2193 /* Keep reading until we get the rest of the header. */
2194 bytes_read = 0;
2195 while (bytes_read < sizeof(struct pcap_hdr)) {
2196 sel_ret = cap_pipe_select(fd);
2197 if (sel_ret < 0) {
2198 snprintf(errmsg, errmsgl,
2199 "Unexpected error from select: %s.",
2200 g_strerror(errno));
2201 goto error;
2202 } else if (sel_ret > 0) {
2203 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
2204 sizeof(struct pcap_hdr) - bytes_read,
2205 pcap_src->from_cap_socket);
2206 if (b <= 0) {
2207 if (b == 0)
2208 snprintf(errmsg, errmsgl,
2209 "End of file on pipe header during open.");
2210 else
2211 snprintf(errmsg, errmsgl,
2212 "Error on pipe header during open: %s.",
2213 g_strerror(errno));
2214 snprintf(secondary_errmsg, secondary_errmsgl,
2215 "%s", not_our_bug);
2216 goto error;
2218 bytes_read += b;
2222 #ifdef _WIN32
2223 else {
2224 pipe_read_sync(pcap_src, hdr, sizeof(struct pcap_hdr));
2225 if (pcap_src->cap_pipe_bytes_read <= 0) {
2226 if (pcap_src->cap_pipe_bytes_read == 0)
2227 snprintf(errmsg, errmsgl,
2228 "End of file on pipe header during open.");
2229 else
2230 snprintf(errmsg, errmsgl,
2231 "Error on pipe header header during open: %s.",
2232 g_strerror(errno));
2233 snprintf(secondary_errmsg, secondary_errmsgl, "%s",
2234 not_our_bug);
2235 goto error;
2238 #endif
2240 if (pcap_src->cap_pipe_info.pcap.byte_swapped) {
2241 /* Byte-swap the header fields about which we care. */
2242 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
2243 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
2244 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
2245 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
2248 * The link-layer header type field of the pcap header is
2249 * probably a LINKTYPE_ value, as the vast majority of
2250 * LINKTYPE_ values and their corresponding DLT_ values
2251 * are the same.
2253 * However, in case the file was written by a program
2254 * that used a DLT_ value, rather than a LINKTYPE_ value,
2255 * in one of the cases where the two differ, use dlt_to_linktype()
2256 * to map to a LINKTYPE_ value, just as we use it to map
2257 * the result of pcap_datalink() to a LINKTYPE_ value.
2259 pcap_src->linktype = dlt_to_linktype(hdr->network);
2260 /* Pick the appropriate maximum packet size for the link type */
2261 switch (pcap_src->linktype) {
2263 case 231: /* DLT_DBUS */
2264 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_DBUS;
2265 break;
2267 case 279: /* DLT_EBHSCR */
2268 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_EBHSCR;
2269 break;
2271 case 249: /* DLT_USBPCAP */
2272 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_USBPCAP;
2273 break;
2275 default:
2276 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
2277 break;
2280 if (hdr->version_major < 2) {
2281 snprintf(errmsg, errmsgl,
2282 "The old pcap format version %d.%d is not supported.",
2283 hdr->version_major, hdr->version_minor);
2284 snprintf(secondary_errmsg, secondary_errmsgl, "%s",
2285 not_our_bug);
2286 goto error;
2289 pcap_src->cap_pipe_fd = fd;
2290 return;
2292 error:
2293 ws_debug("pcap_pipe_open_live: error %s", errmsg);
2294 pcap_src->cap_pipe_err = PIPERR;
2295 cap_pipe_close(fd, pcap_src->from_cap_socket);
2296 pcap_src->cap_pipe_fd = -1;
2297 #ifdef _WIN32
2298 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2299 #endif
2303 * Synchronously read the fixed portion of the pcapng section header block
2304 * (we've already read the pcapng block header).
2306 static int
2307 pcapng_read_shb(capture_src *pcap_src,
2308 char *errmsg,
2309 size_t errmsgl)
2311 pcapng_section_header_block_t shb;
2313 #ifdef _WIN32
2314 if (pcap_src->from_cap_socket)
2315 #endif
2317 pcap_src->cap_pipe_bytes_to_read = sizeof(pcapng_block_header_t) + sizeof(pcapng_section_header_block_t);
2318 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2319 return -1;
2322 #ifdef _WIN32
2323 else {
2324 pipe_read_sync(pcap_src, pcap_src->cap_pipe_databuf + sizeof(pcapng_block_header_t),
2325 sizeof(pcapng_section_header_block_t));
2326 if (pcap_src->cap_pipe_bytes_read <= 0) {
2327 if (pcap_src->cap_pipe_bytes_read == 0)
2328 snprintf(errmsg, errmsgl,
2329 "End of file reading from pipe or socket.");
2330 else
2331 snprintf(errmsg, errmsgl,
2332 "Error reading from pipe or socket: %s.",
2333 g_strerror(errno));
2334 return -1;
2336 /* Continuing with STATE_EXPECT_DATA requires reading into cap_pipe_databuf at offset cap_pipe_bytes_read */
2337 pcap_src->cap_pipe_bytes_read = sizeof(pcapng_block_header_t) + sizeof(pcapng_section_header_block_t);
2339 #endif
2340 memcpy(&shb, pcap_src->cap_pipe_databuf + sizeof(pcapng_block_header_t), sizeof(pcapng_section_header_block_t));
2341 switch (shb.magic)
2343 case PCAPNG_MAGIC:
2344 ws_debug("pcapng SHB MAGIC");
2345 break;
2346 case PCAPNG_SWAPPED_MAGIC:
2347 ws_debug("pcapng SHB SWAPPED MAGIC");
2349 * pcapng sources can contain all sorts of block types.
2350 * Rather than add a bunch of complexity to this code (which is
2351 * often privileged), punt and tell the user to swap bytes
2352 * elsewhere.
2354 * XXX - punting means that the Wireshark test suite must be
2355 * modified to:
2357 * 1) have both little-endian and big-endian versions of
2358 * all pcapng files piped to dumpcap;
2360 * 2) pipe the appropriate file to dumpcap, depending on
2361 * the byte order of the host on which the tests are
2362 * being run;
2364 * as per comments in bug 15772 and 15754.
2366 * Are we *really* certain that the complexity added would be
2367 * significant enough to make adding it a security risk? And
2368 * why would this code even be running with any elevated
2369 * privileges if you're capturing from a pipe? We should not
2370 * only have given up all additional privileges if we're reading
2371 * from a pipe, we should give them up in such a fashion that
2372 * we can't reclaim them.
2374 #if G_BYTE_ORDER == G_BIG_ENDIAN
2375 #define OUR_ENDIAN "big"
2376 #define IFACE_ENDIAN "little"
2377 #else
2378 #define OUR_ENDIAN "little"
2379 #define IFACE_ENDIAN "big"
2380 #endif
2381 snprintf(errmsg, errmsgl,
2382 "Interface %u is " IFACE_ENDIAN " endian but we're " OUR_ENDIAN " endian.",
2383 pcap_src->interface_id);
2384 return -1;
2385 default:
2386 /* Not a pcapng type we know about, or not pcapng at all. */
2387 snprintf(errmsg, errmsgl,
2388 "Unrecognized pcapng format or not pcapng data.");
2389 return -1;
2392 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
2394 /* Setup state to capture any options following the section header block */
2395 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2397 return 0;
2401 * Save IDB blocks for playback whenever we change output files, and
2402 * fix LINKTYPE_ values that are really platform-dependent DLT_ values.
2403 * Rewrite EPB and ISB interface IDs.
2405 static bool
2406 pcapng_adjust_block(capture_src *pcap_src, const pcapng_block_header_t *bh, uint8_t *pd)
2408 switch(bh->block_type) {
2409 case BLOCK_TYPE_SHB:
2411 if (global_ld.pcapng_passthrough) {
2413 * We have a single pcapng input. We pass the SHB through when
2414 * writing a single output file and for the first ring buffer
2415 * file. We need to save it for the second and subsequent ring
2416 * buffer files.
2418 g_free(global_ld.saved_shb);
2419 global_ld.saved_shb = (uint8_t *) g_memdup2(pd, bh->block_total_length);
2422 * We're dealing with one section at a time, so we can (and must)
2423 * get rid of our old IDBs.
2425 for (unsigned i = 0; i < global_ld.saved_idbs->len; i++) {
2426 saved_idb_t *idb_source = &g_array_index(global_ld.saved_idbs, saved_idb_t, i);
2427 g_free(idb_source->idb);
2429 g_array_set_size(global_ld.saved_idbs, 0);
2430 } else {
2432 * We have a new SHB from this capture source. We need to keep
2433 * global_ld.saved_idbs intact, so we mark IDBs we previously
2434 * collected from this source as deleted.
2436 for (unsigned i = 0; i < pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len; i++) {
2437 uint32_t iface_id = g_array_index(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, uint32_t, i);
2438 saved_idb_t *idb_source = &g_array_index(global_ld.saved_idbs, saved_idb_t, iface_id);
2439 ws_assert(idb_source->interface_id == pcap_src->interface_id);
2440 g_free(idb_source->idb);
2441 memset(idb_source, 0, sizeof(saved_idb_t));
2442 idb_source->deleted = true;
2443 ws_debug("%s: deleted pcapng IDB %u", G_STRFUNC, iface_id);
2446 g_array_set_size(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, 0);
2448 break;
2449 case BLOCK_TYPE_IDB:
2452 * Always gather IDBs. We can remove them or mark them as deleted
2453 * when we get a new SHB.
2455 saved_idb_t idb_source = { 0 };
2456 idb_source.interface_id = pcap_src->interface_id;
2457 idb_source.idb_len = bh->block_total_length;
2458 idb_source.idb = (uint8_t *) g_memdup2(pd, idb_source.idb_len);
2459 g_array_append_val(global_ld.saved_idbs, idb_source);
2460 uint32_t iface_id = global_ld.saved_idbs->len - 1;
2461 g_array_append_val(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, iface_id);
2462 ws_debug("%s: mapped pcapng IDB %u -> %u from source %u",
2463 G_STRFUNC, pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len - 1, iface_id, pcap_src->interface_id);
2465 break;
2466 case BLOCK_TYPE_EPB:
2467 case BLOCK_TYPE_ISB:
2469 if (global_ld.pcapng_passthrough) {
2470 /* Our input and output interface IDs are the same. */
2471 break;
2473 /* The interface ID is the first 32-bit field after the BH for both EPBs and ISBs. */
2474 uint32_t iface_id;
2475 memcpy(&iface_id, pd + sizeof(pcapng_block_header_t), 4);
2476 if (iface_id < pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len) {
2477 memcpy(pd + sizeof(pcapng_block_header_t),
2478 &g_array_index(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, uint32_t, iface_id), 4);
2479 } else {
2480 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);
2481 return false;
2484 break;
2485 default:
2486 break;
2489 return true;
2493 * Return true if the block contains packet, event, or log data. Return false otherwise.
2495 static bool is_data_block(uint32_t block_type)
2497 // Any block types that lead to calling wtap_read_bytes_buffer in
2498 // wiretap/pcapng.c should be listed here.
2499 switch (block_type) {
2500 case BLOCK_TYPE_PB:
2501 case BLOCK_TYPE_EPB:
2502 case BLOCK_TYPE_SPB:
2503 case BLOCK_TYPE_SYSTEMD_JOURNAL_EXPORT:
2504 case BLOCK_TYPE_SYSDIG_EVENT:
2505 case BLOCK_TYPE_SYSDIG_EVENT_V2:
2506 case BLOCK_TYPE_SYSDIG_EVENT_V2_LARGE:
2507 return true;
2508 default:
2509 break;
2511 return false;
2515 * Read the part of the initial pcapng SHB following the block type
2516 * (we've already read the block type).
2518 static void
2519 pcapng_pipe_open_live(int fd,
2520 capture_src *pcap_src,
2521 char *errmsg,
2522 size_t errmsgl)
2524 uint32_t type = BLOCK_TYPE_SHB;
2525 pcapng_block_header_t *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2527 ws_debug("pcapng_pipe_open_live: fd %d", fd);
2530 * A pcapng block begins with the block type followed by the block
2531 * total length; we've already read the block type, now read the
2532 * block length.
2534 #ifdef _WIN32
2536 * On UN*X, we can use select() on pipes or sockets.
2538 * On Windows, we can only use it on sockets; to do non-blocking
2539 * reads from pipes, we currently do reads in a separate thread
2540 * and use GLib asynchronous queues from the main thread to start
2541 * read operations and to wait for them to complete.
2543 if (pcap_src->from_cap_socket)
2544 #endif
2546 memcpy(pcap_src->cap_pipe_databuf, &type, sizeof(uint32_t));
2547 pcap_src->cap_pipe_bytes_read = sizeof(uint32_t);
2548 pcap_src->cap_pipe_bytes_to_read = sizeof(pcapng_block_header_t);
2549 pcap_src->cap_pipe_fd = fd;
2550 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2551 goto error;
2553 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(pcapng_block_header_t));
2555 #ifdef _WIN32
2556 else {
2557 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
2559 bh->block_type = type;
2560 pipe_read_sync(pcap_src, &bh->block_total_length,
2561 sizeof(bh->block_total_length));
2562 if (pcap_src->cap_pipe_bytes_read <= 0) {
2563 if (pcap_src->cap_pipe_bytes_read == 0)
2564 snprintf(errmsg, errmsgl,
2565 "End of file reading from pipe or socket.");
2566 else
2567 snprintf(errmsg, errmsgl,
2568 "Error reading from pipe or socket: %s.",
2569 g_strerror(errno));
2570 goto error;
2572 pcap_src->cap_pipe_bytes_read = sizeof(pcapng_block_header_t);
2573 memcpy(pcap_src->cap_pipe_databuf, bh, sizeof(pcapng_block_header_t));
2574 pcap_src->cap_pipe_fd = fd;
2576 #endif
2577 if ((bh->block_total_length & 0x03) != 0) {
2578 snprintf(errmsg, errmsgl,
2579 "block_total_length read from pipe is %u, which is not a multiple of 4.",
2580 bh->block_total_length);
2581 goto error;
2583 if (pcapng_read_shb(pcap_src, errmsg, errmsgl)) {
2584 goto error;
2587 return;
2589 error:
2590 ws_debug("pcapng_pipe_open_live: error %s", errmsg);
2591 pcap_src->cap_pipe_err = PIPERR;
2592 cap_pipe_close(fd, pcap_src->from_cap_socket);
2593 pcap_src->cap_pipe_fd = -1;
2594 #ifdef _WIN32
2595 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2596 #endif
2599 /* We read one record from the pipe, take care of byte order in the record
2600 * header, write the record to the capture file, and update capture statistics. */
2601 static int
2602 pcap_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, size_t errmsgl)
2604 struct pcap_pkthdr phdr;
2605 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2606 PD_ERR } result;
2607 #ifdef _WIN32
2608 void * q_status;
2609 #endif
2610 ssize_t b;
2611 unsigned new_bufsize;
2612 pcap_pipe_info_t *pcap_info = &pcap_src->cap_pipe_info.pcap;
2614 #ifdef LOG_CAPTURE_VERBOSE
2615 ws_debug("pcap_pipe_dispatch");
2616 #endif
2618 switch (pcap_src->cap_pipe_state) {
2620 case STATE_EXPECT_REC_HDR:
2621 #ifdef _WIN32
2622 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2623 #endif
2625 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2626 pcap_src->cap_pipe_bytes_to_read = pcap_src->cap_pipe_modified ?
2627 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2628 pcap_src->cap_pipe_bytes_read = 0;
2630 #ifdef _WIN32
2631 pcap_src->cap_pipe_buf = (char *) &pcap_info->rechdr;
2632 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2633 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2635 #endif
2636 /* Fall through */
2638 case STATE_READ_REC_HDR:
2639 #ifdef _WIN32
2640 if (pcap_src->from_cap_socket)
2641 #endif
2643 b = cap_pipe_read(pcap_src->cap_pipe_fd, ((char *)&pcap_info->rechdr)+pcap_src->cap_pipe_bytes_read,
2644 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read, pcap_src->from_cap_socket);
2645 if (b <= 0) {
2646 if (b == 0)
2647 result = PD_PIPE_EOF;
2648 else
2649 result = PD_PIPE_ERR;
2650 break;
2652 #ifdef _WIN32
2653 pcap_src->cap_pipe_bytes_read += (DWORD)b;
2654 #else
2655 pcap_src->cap_pipe_bytes_read += b;
2656 #endif
2658 #ifdef _WIN32
2659 else {
2660 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2661 if (pcap_src->cap_pipe_err == PIPEOF) {
2662 result = PD_PIPE_EOF;
2663 break;
2664 } else if (pcap_src->cap_pipe_err == PIPERR) {
2665 result = PD_PIPE_ERR;
2666 break;
2668 if (!q_status) {
2669 return 0;
2672 #endif
2673 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2674 /* There's still more of the pcap packet header to read. */
2675 return 0;
2677 result = PD_REC_HDR_READ;
2678 break;
2680 case STATE_EXPECT_DATA:
2681 #ifdef _WIN32
2682 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2683 #endif
2685 pcap_src->cap_pipe_state = STATE_READ_DATA;
2686 pcap_src->cap_pipe_bytes_to_read = pcap_info->rechdr.hdr.incl_len;
2687 pcap_src->cap_pipe_bytes_read = 0;
2689 #ifdef _WIN32
2690 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2691 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2692 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2694 #endif
2695 /* Fall through */
2697 case STATE_READ_DATA:
2698 #ifdef _WIN32
2699 if (pcap_src->from_cap_socket)
2700 #endif
2702 b = cap_pipe_read(pcap_src->cap_pipe_fd,
2703 pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read,
2704 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read,
2705 pcap_src->from_cap_socket);
2706 if (b <= 0) {
2707 if (b == 0)
2708 result = PD_PIPE_EOF;
2709 else
2710 result = PD_PIPE_ERR;
2711 break;
2713 #ifdef _WIN32
2714 pcap_src->cap_pipe_bytes_read += (DWORD)b;
2715 #else
2716 pcap_src->cap_pipe_bytes_read += b;
2717 #endif
2719 #ifdef _WIN32
2720 else {
2722 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2723 if (pcap_src->cap_pipe_err == PIPEOF) {
2724 result = PD_PIPE_EOF;
2725 break;
2726 } else if (pcap_src->cap_pipe_err == PIPERR) {
2727 result = PD_PIPE_ERR;
2728 break;
2730 if (!q_status) {
2731 return 0;
2734 #endif /* _WIN32 */
2735 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2736 /* There's still more of the pcap packet data to read. */
2737 return 0;
2739 result = PD_DATA_READ;
2740 break;
2742 default:
2743 snprintf(errmsg, errmsgl,
2744 "pcap_pipe_dispatch: invalid state");
2745 result = PD_ERR;
2747 } /* switch (pcap_src->cap_pipe_state) */
2750 * We've now read as much data as we were expecting, so process it.
2752 switch (result) {
2754 case PD_REC_HDR_READ:
2756 * We've read the packet header, so we know the captured length,
2757 * and thus the number of packet data bytes. Take care of byte order.
2759 cap_pipe_adjust_pcap_header(pcap_src->cap_pipe_info.pcap.byte_swapped, &pcap_info->hdr,
2760 &pcap_info->rechdr.hdr);
2761 if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_max_pkt_size) {
2763 * The record contains more data than the advertised/allowed in the
2764 * pcap header, do not try to read more data (do not change to
2765 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2766 * instead stop with an error.
2768 snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2769 ld->packets_captured+1, pcap_info->rechdr.hdr.incl_len);
2770 break;
2773 if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_databuf_size) {
2775 * Grow the buffer to the packet size, rounded up to a power of
2776 * 2.
2778 new_bufsize = pcap_info->rechdr.hdr.incl_len;
2780 * https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2782 new_bufsize--;
2783 new_bufsize |= new_bufsize >> 1;
2784 new_bufsize |= new_bufsize >> 2;
2785 new_bufsize |= new_bufsize >> 4;
2786 new_bufsize |= new_bufsize >> 8;
2787 new_bufsize |= new_bufsize >> 16;
2788 new_bufsize++;
2789 pcap_src->cap_pipe_databuf = (char*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2790 pcap_src->cap_pipe_databuf_size = new_bufsize;
2793 if (pcap_info->rechdr.hdr.incl_len) {
2795 * The record has some data following the header, try
2796 * to read it next time.
2798 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2799 return 0;
2803 * No data following the record header? Then no more data needs to be
2804 * read and we will fallthrough and emit an empty packet.
2806 /* FALLTHROUGH */
2808 case PD_DATA_READ:
2810 * We've read the full contents of the packet record.
2811 * Fill in a "struct pcap_pkthdr", and process the packet.
2813 phdr.ts.tv_sec = pcap_info->rechdr.hdr.ts_sec;
2814 phdr.ts.tv_usec = pcap_info->rechdr.hdr.ts_usec;
2815 phdr.caplen = pcap_info->rechdr.hdr.incl_len;
2816 phdr.len = pcap_info->rechdr.hdr.orig_len;
2818 if (use_threads) {
2819 capture_loop_queue_packet_cb((uint8_t *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2820 } else {
2821 capture_loop_write_packet_cb((uint8_t *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2825 * Now we want to read the next packet's header.
2827 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2828 return 1;
2830 case PD_PIPE_EOF:
2831 pcap_src->cap_pipe_err = PIPEOF;
2832 return -1;
2834 case PD_PIPE_ERR:
2835 snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2836 #ifdef _WIN32
2837 win32strerror(GetLastError()));
2838 #else
2839 g_strerror(errno));
2840 #endif
2841 /* Fall through */
2842 case PD_ERR:
2843 break;
2846 pcap_src->cap_pipe_err = PIPERR;
2847 /* Return here rather than inside the switch to prevent GCC warning */
2848 return -1;
2851 static int
2852 pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, size_t errmsgl)
2854 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2855 PD_ERR } result;
2856 #ifdef _WIN32
2857 void * q_status;
2858 #endif
2859 unsigned new_bufsize;
2860 pcapng_block_header_t *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2862 #ifdef LOG_CAPTURE_VERBOSE
2863 ws_debug("pcapng_pipe_dispatch");
2864 #endif
2866 switch (pcap_src->cap_pipe_state) {
2868 case STATE_EXPECT_REC_HDR:
2869 #ifdef LOG_CAPTURE_VERBOSE
2870 ws_debug("pcapng_pipe_dispatch STATE_EXPECT_REC_HDR");
2871 #endif
2872 #ifdef _WIN32
2873 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2874 #endif
2876 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2877 pcap_src->cap_pipe_bytes_to_read = sizeof(pcapng_block_header_t);
2878 pcap_src->cap_pipe_bytes_read = 0;
2880 #ifdef _WIN32
2881 if (!pcap_src->from_cap_socket) {
2882 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2883 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2885 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2887 #endif
2888 /* Fall through */
2890 case STATE_READ_REC_HDR:
2891 #ifdef LOG_CAPTURE_VERBOSE
2892 ws_debug("pcapng_pipe_dispatch STATE_READ_REC_HDR");
2893 #endif
2894 #ifdef _WIN32
2895 if (pcap_src->from_cap_socket) {
2896 #endif
2897 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2898 return -1;
2900 #ifdef _WIN32
2901 } else {
2902 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2903 if (pcap_src->cap_pipe_err == PIPEOF) {
2904 result = PD_PIPE_EOF;
2905 break;
2906 } else if (pcap_src->cap_pipe_err == PIPERR) {
2907 result = PD_PIPE_ERR;
2908 break;
2910 if (!q_status) {
2911 return 0;
2914 #endif
2915 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2916 /* There's still more of the pcapng block header to read. */
2917 return 0;
2919 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(pcapng_block_header_t));
2920 result = PD_REC_HDR_READ;
2921 break;
2923 case STATE_EXPECT_DATA:
2924 #ifdef LOG_CAPTURE_VERBOSE
2925 ws_debug("pcapng_pipe_dispatch STATE_EXPECT_DATA");
2926 #endif
2927 #ifdef _WIN32
2928 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2929 #endif
2930 pcap_src->cap_pipe_state = STATE_READ_DATA;
2931 pcap_src->cap_pipe_bytes_to_read = bh->block_total_length;
2933 #ifdef _WIN32
2934 if (!pcap_src->from_cap_socket) {
2935 pcap_src->cap_pipe_bytes_to_read -= pcap_src->cap_pipe_bytes_read;
2936 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf + pcap_src->cap_pipe_bytes_read;
2937 pcap_src->cap_pipe_bytes_read = 0;
2938 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2940 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2942 #endif
2943 /* Fall through */
2945 case STATE_READ_DATA:
2946 #ifdef LOG_CAPTURE_VERBOSE
2947 ws_debug("pcapng_pipe_dispatch STATE_READ_DATA");
2948 #endif
2949 #ifdef _WIN32
2950 if (pcap_src->from_cap_socket) {
2951 #endif
2952 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2953 return -1;
2955 #ifdef _WIN32
2956 } else {
2958 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2959 if (pcap_src->cap_pipe_err == PIPEOF) {
2960 result = PD_PIPE_EOF;
2961 break;
2962 } else if (pcap_src->cap_pipe_err == PIPERR) {
2963 result = PD_PIPE_ERR;
2964 break;
2966 if (!q_status) {
2967 return 0;
2970 #endif /* _WIN32 */
2971 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2972 /* There's still more of the pcap block contents to read. */
2973 return 0;
2975 result = PD_DATA_READ;
2976 break;
2978 default:
2979 snprintf(errmsg, errmsgl,
2980 "pcapng_pipe_dispatch: invalid state");
2981 result = PD_ERR;
2983 } /* switch (pcap_src->cap_pipe_state) */
2986 * We've now read as much data as we were expecting, so process it.
2988 switch (result) {
2990 case PD_REC_HDR_READ:
2992 * We've read the pcapng block header, so we know the block type
2993 * and length.
2995 if (bh->block_type == BLOCK_TYPE_SHB) {
2997 * We need to read the fixed portion of the SHB before to
2998 * get the endianness before we can interpret the block length.
2999 * (The block type of the SHB is byte-order-independent, so that
3000 * an SHB can be recognized before we know the endianness of
3001 * the section.)
3003 * Continue the read process.
3005 pcapng_read_shb(pcap_src, errmsg, errmsgl);
3006 return 1;
3009 if ((bh->block_total_length & 0x03) != 0) {
3010 snprintf(errmsg, errmsgl,
3011 "Total length of pcapng block read from pipe is %u, which is not a multiple of 4.",
3012 bh->block_total_length);
3013 break;
3015 if (is_data_block(bh->block_type) && bh->block_total_length > pcap_src->cap_pipe_max_pkt_size) {
3017 * The record contains more data than the advertised/allowed in the
3018 * pcapng header, do not try to read more data (do not change to
3019 * STATE_EXPECT_DATA) as that would not fit in the buffer and
3020 * instead stop with an error.
3022 snprintf(errmsg, errmsgl, "Block %u type 0x%08x too long (%d bytes)",
3023 ld->packets_captured+1, bh->block_type, bh->block_total_length);
3024 break;
3027 if (bh->block_total_length > pcap_src->cap_pipe_databuf_size) {
3029 * Grow the buffer to the packet size, rounded up to a power of
3030 * 2.
3032 new_bufsize = bh->block_total_length;
3034 * https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
3036 new_bufsize--;
3037 new_bufsize |= new_bufsize >> 1;
3038 new_bufsize |= new_bufsize >> 2;
3039 new_bufsize |= new_bufsize >> 4;
3040 new_bufsize |= new_bufsize >> 8;
3041 new_bufsize |= new_bufsize >> 16;
3042 new_bufsize++;
3043 pcap_src->cap_pipe_databuf = (unsigned char*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
3044 pcap_src->cap_pipe_databuf_size = new_bufsize;
3047 /* The record always has at least the block total length following the header */
3048 if (bh->block_total_length < sizeof(pcapng_block_header_t)+sizeof(uint32_t)) {
3049 snprintf(errmsg, errmsgl,
3050 "malformed pcapng block_total_length < minimum");
3051 pcap_src->cap_pipe_err = PIPEOF;
3052 return -1;
3056 * Now we want to read the block contents.
3058 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
3059 return 0;
3061 case PD_DATA_READ:
3063 * We've read the full contents of the block.
3064 * Process the block.
3066 if (use_threads) {
3067 capture_loop_queue_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
3068 } else {
3069 capture_loop_write_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
3073 * Now we want to read the next block's header.
3075 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
3076 return 1;
3078 case PD_PIPE_EOF:
3079 pcap_src->cap_pipe_err = PIPEOF;
3080 return -1;
3082 case PD_PIPE_ERR:
3083 snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
3084 #ifdef _WIN32
3085 win32strerror(GetLastError()));
3086 #else
3087 g_strerror(errno));
3088 #endif
3089 /* Fall through */
3090 case PD_ERR:
3091 break;
3094 pcap_src->cap_pipe_err = PIPERR;
3095 /* Return here rather than inside the switch to prevent GCC warning */
3096 return -1;
3099 /** Open the capture input sources; each one is either a pcap device,
3100 * a capture pipe, or a capture socket.
3101 * Returns true if it succeeds, false otherwise. */
3102 static bool
3103 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
3104 char *errmsg, size_t errmsg_len,
3105 char *secondary_errmsg, size_t secondary_errmsg_len)
3107 cap_device_open_status open_status;
3108 char open_status_str[PCAP_ERRBUF_SIZE];
3109 char *sync_msg_str;
3110 interface_options *interface_opts;
3111 capture_src *pcap_src;
3112 unsigned i;
3114 if ((use_threads == false) &&
3115 (capture_opts->ifaces->len > 1)) {
3116 snprintf(errmsg, errmsg_len,
3117 "Using threads is required for capturing on multiple interfaces.");
3118 return false;
3121 int pcapng_src_count = 0;
3122 for (i = 0; i < capture_opts->ifaces->len; i++) {
3123 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
3124 pcap_src = g_new0(capture_src, 1);
3125 if (pcap_src == NULL) {
3126 snprintf(errmsg, errmsg_len,
3127 "Could not allocate memory.");
3128 return false;
3131 #ifdef MUST_DO_SELECT
3132 pcap_src->pcap_fd = -1;
3133 #endif
3134 pcap_src->interface_id = i;
3135 pcap_src->linktype = -1;
3136 #ifdef _WIN32
3137 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
3138 #endif
3139 pcap_src->cap_pipe_fd = -1;
3140 pcap_src->cap_pipe_dispatch = pcap_pipe_dispatch;
3141 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
3142 pcap_src->cap_pipe_err = PIPOK;
3143 #ifdef _WIN32
3144 pcap_src->cap_pipe_read_mtx = g_new(GMutex, 1);
3145 g_mutex_init(pcap_src->cap_pipe_read_mtx);
3146 pcap_src->cap_pipe_pending_q = g_async_queue_new();
3147 pcap_src->cap_pipe_done_q = g_async_queue_new();
3148 #endif
3149 g_array_append_val(ld->pcaps, pcap_src);
3151 ws_debug("capture_loop_open_input : %s", interface_opts->name);
3152 pcap_src->pcap_h = open_capture_device(capture_opts, interface_opts,
3153 CAP_READ_TIMEOUT, &open_status, &open_status_str);
3155 if (pcap_src->pcap_h != NULL) {
3156 /* we've opened "iface" as a network device */
3158 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
3159 /* Find out if we're getting nanosecond-precision time stamps */
3160 pcap_src->ts_nsec = have_high_resolution_timestamp(pcap_src->pcap_h);
3161 #endif
3163 #if defined(HAVE_PCAP_SETSAMPLING)
3164 if (interface_opts->sampling_method != CAPTURE_SAMP_NONE) {
3165 struct pcap_samp *samp;
3167 if ((samp = pcap_setsampling(pcap_src->pcap_h)) != NULL) {
3168 switch (interface_opts->sampling_method) {
3169 case CAPTURE_SAMP_BY_COUNT:
3170 samp->method = PCAP_SAMP_1_EVERY_N;
3171 break;
3173 case CAPTURE_SAMP_BY_TIMER:
3174 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
3175 break;
3177 default:
3178 sync_msg_str = ws_strdup_printf(
3179 "Unknown sampling method %d specified,\n"
3180 "continue without packet sampling",
3181 interface_opts->sampling_method);
3182 report_capture_error("Couldn't set the capture "
3183 "sampling", sync_msg_str);
3184 g_free(sync_msg_str);
3186 samp->value = interface_opts->sampling_param;
3187 } else {
3188 report_capture_error("Couldn't set the capture sampling",
3189 "Cannot get packet sampling data structure");
3192 #endif
3194 /* setting the data link type only works on real interfaces */
3195 if (!set_pcap_datalink(pcap_src->pcap_h, interface_opts->linktype,
3196 interface_opts->name,
3197 errmsg, errmsg_len,
3198 secondary_errmsg, secondary_errmsg_len)) {
3199 return false;
3201 pcap_src->linktype = dlt_to_linktype(get_pcap_datalink(pcap_src->pcap_h, interface_opts->name));
3202 } else {
3203 /* We couldn't open "iface" as a network device. */
3204 /* Try to open it as a pipe */
3205 bool pipe_err = false;
3206 cap_pipe_open_live(interface_opts->name, pcap_src,
3207 &pcap_src->cap_pipe_info.pcap.hdr,
3208 errmsg, errmsg_len,
3209 secondary_errmsg, secondary_errmsg_len);
3211 #ifdef _WIN32
3212 if (pcap_src->from_cap_socket) {
3213 #endif
3214 if (pcap_src->cap_pipe_fd == -1) {
3215 pipe_err = true;
3217 #ifdef _WIN32
3218 } else {
3219 if (pcap_src->cap_pipe_h == INVALID_HANDLE_VALUE) {
3220 pipe_err = true;
3223 #endif
3225 if (pipe_err) {
3226 if (pcap_src->cap_pipe_err == PIPNEXIST) {
3228 * We tried opening as an interface, and that failed,
3229 * so we tried to open it as a pipe, but the pipe
3230 * doesn't exist. Report the error message for
3231 * the interface.
3233 get_capture_device_open_failure_messages(open_status,
3234 open_status_str,
3235 interface_opts->name,
3236 errmsg,
3237 errmsg_len,
3238 secondary_errmsg,
3239 secondary_errmsg_len);
3242 * Else pipe (or file) does exist and cap_pipe_open_live() has
3243 * filled in errmsg
3245 return false;
3246 } else {
3248 * We tried opening as an interface, and that failed,
3249 * so we tried to open it as a pipe, and that succeeded.
3251 open_status = CAP_DEVICE_OPEN_NO_ERR;
3255 /* XXX - will this work for tshark? */
3256 #ifdef MUST_DO_SELECT
3257 if (!pcap_src->from_cap_pipe) {
3258 pcap_src->pcap_fd = pcap_get_selectable_fd(pcap_src->pcap_h);
3260 #endif
3262 /* Is "open_status" something other than CAP_DEVICE_OPEN_NO_ERR?
3263 If so, "open_capture_device()" returned a warning; print it,
3264 but keep capturing. */
3265 if (open_status != CAP_DEVICE_OPEN_NO_ERR) {
3266 sync_msg_str = ws_strdup_printf("%s.", open_status_str);
3267 report_capture_error(sync_msg_str, "");
3268 g_free(sync_msg_str);
3270 if (pcap_src->from_pcapng) {
3272 * We will use the IDBs from the source (but rewrite the
3273 * interface IDs if there's more than one source.)
3275 pcapng_src_count++;
3276 } else {
3278 * Add our pcapng interface entry.
3280 saved_idb_t idb_source = { 0 };
3281 idb_source.interface_id = i;
3282 g_rw_lock_writer_lock (&ld->saved_shb_idb_lock);
3283 pcap_src->idb_id = global_ld.saved_idbs->len;
3284 g_array_append_val(global_ld.saved_idbs, idb_source);
3285 g_rw_lock_writer_unlock (&ld->saved_shb_idb_lock);
3286 ws_debug("%s: saved capture_opts %u to IDB %u",
3287 G_STRFUNC, i, pcap_src->idb_id);
3292 * Are we capturing from one source that is providing pcapng
3293 * information?
3295 if (capture_opts->ifaces->len == 1 && pcapng_src_count == 1) {
3297 * Yes; pass through SHBs and IDBs from the source, rather
3298 * than generating our own.
3300 ld->pcapng_passthrough = true;
3301 g_rw_lock_writer_lock (&ld->saved_shb_idb_lock);
3302 ws_assert(global_ld.saved_idbs->len == 0);
3303 ws_debug("%s: Pass through SHBs and IDBs directly", G_STRFUNC);
3304 g_rw_lock_writer_unlock (&ld->saved_shb_idb_lock);
3307 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
3308 /* to remove any suid privileges. */
3309 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
3310 /* (euid/egid have already previously been set to ruid/rgid. */
3311 /* (See comment in main() for details) */
3312 #ifndef HAVE_LIBCAP
3313 relinquish_special_privs_perm();
3314 #else
3315 relinquish_all_capabilities();
3316 #endif
3317 return true;
3320 /* close the capture input file (pcap or capture pipe) */
3321 static void capture_loop_close_input(loop_data *ld)
3323 unsigned i;
3324 capture_src *pcap_src;
3326 ws_debug("capture_loop_close_input");
3328 for (i = 0; i < ld->pcaps->len; i++) {
3329 pcap_src = g_array_index(ld->pcaps, capture_src *, i);
3330 /* Pipe, or capture device? */
3331 if (pcap_src->from_cap_pipe) {
3332 /* Pipe. If open, close the capture pipe "input file". */
3333 if (pcap_src->cap_pipe_fd >= 0) {
3334 cap_pipe_close(pcap_src->cap_pipe_fd, pcap_src->from_cap_socket);
3335 pcap_src->cap_pipe_fd = -1;
3337 #ifdef _WIN32
3338 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE) {
3339 CloseHandle(pcap_src->cap_pipe_h);
3340 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
3342 #endif
3343 if (pcap_src->cap_pipe_databuf != NULL) {
3344 /* Free the buffer. */
3345 g_free(pcap_src->cap_pipe_databuf);
3346 pcap_src->cap_pipe_databuf = NULL;
3348 if (pcap_src->from_pcapng) {
3349 g_array_free(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, TRUE);
3350 pcap_src->cap_pipe_info.pcapng.src_iface_to_global = NULL;
3352 } else {
3353 /* Capture device. If open, close the pcap_t. */
3354 if (pcap_src->pcap_h != NULL) {
3355 ws_debug("capture_loop_close_input: closing %p", (void *)pcap_src->pcap_h);
3356 pcap_close(pcap_src->pcap_h);
3357 pcap_src->pcap_h = NULL;
3362 ld->go = false;
3366 /* init the capture filter */
3367 static initfilter_status_t
3368 capture_loop_init_filter(pcap_t *pcap_h, bool from_cap_pipe,
3369 const char * name, const char * cfilter)
3371 struct bpf_program fcode;
3373 ws_debug("capture_loop_init_filter: %s", cfilter);
3375 /* capture filters only work on real interfaces */
3376 if (cfilter && !from_cap_pipe) {
3377 /* A capture filter was specified; set it up. */
3378 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
3379 /* Treat this specially - our caller might try to compile this
3380 as a display filter and, if that succeeds, warn the user that
3381 the display and capture filter syntaxes are different. */
3382 return INITFILTER_BAD_FILTER;
3384 if (pcap_setfilter(pcap_h, &fcode) < 0) {
3385 pcap_freecode(&fcode);
3386 return INITFILTER_OTHER_ERROR;
3388 pcap_freecode(&fcode);
3391 return INITFILTER_NO_ERROR;
3395 * Write the dumpcap pcapng SHB and IDBs if needed.
3396 * Called from capture_loop_init_output and do_file_switch_or_stop.
3398 static bool
3399 capture_loop_init_pcapng_output(capture_options *capture_opts, loop_data *ld,
3400 int *err)
3402 g_rw_lock_reader_lock (&ld->saved_shb_idb_lock);
3404 if (ld->pcapng_passthrough && !ld->saved_shb) {
3405 /* We have a single pcapng capture interface and this is the first or only output file. */
3406 ws_debug("%s: skipping dumpcap SHB and IDBs in favor of source", G_STRFUNC);
3407 g_rw_lock_reader_unlock (&ld->saved_shb_idb_lock);
3408 return true;
3411 bool successful = true;
3412 GString *os_info_str = g_string_new("");
3414 *err = 0;
3415 get_os_version_info(os_info_str);
3417 if (ld->saved_shb) {
3418 /* We have a single pcapng capture interface and multiple output files. */
3420 pcapng_block_header_t bh;
3422 memcpy(&bh, ld->saved_shb, sizeof(pcapng_block_header_t));
3424 successful = pcapng_write_block(ld->pdh, ld->saved_shb, bh.block_total_length, &ld->bytes_written, err);
3426 ws_debug("%s: wrote saved passthrough SHB %d", G_STRFUNC, successful);
3427 } else {
3428 GString *cpu_info_str = g_string_new("");
3429 get_cpu_info(cpu_info_str);
3431 successful = pcapng_write_section_header_block(ld->pdh,
3432 capture_comments, /* Comments */
3433 cpu_info_str->str, /* HW */
3434 os_info_str->str, /* OS */
3435 get_appname_and_version(),
3436 -1, /* section_length */
3437 &ld->bytes_written,
3438 err);
3439 ws_debug("%s: wrote dumpcap SHB %d", G_STRFUNC, successful);
3440 g_string_free(cpu_info_str, TRUE);
3443 for (unsigned i = 0; successful && (i < ld->saved_idbs->len); i++) {
3444 saved_idb_t idb_source = g_array_index(ld->saved_idbs, saved_idb_t, i);
3445 if (idb_source.deleted) {
3447 * Our interface is out of scope. Suppose we're writing multiple
3448 * files and a source switches sections. We currently write dummy
3449 * IDBs like so:
3451 * File 1: IDB0, IDB1, IDB2
3452 * [ The source of IDBs 1 and 2 writes an SHB with two new IDBs ]
3453 * [ We switch output files ]
3454 * File 2: IDB0, dummy IDB, dummy IDB, IDB3, IDB4
3456 * It might make more sense to write the original data so that
3457 * so that our IDB lists are more consistent across files.
3459 successful = pcapng_write_interface_description_block(global_ld.pdh,
3460 "Interface went out of scope", /* OPT_COMMENT 1 */
3461 "dummy", /* IDB_NAME 2 */
3462 "Dumpcap dummy interface", /* IDB_DESCRIPTION 3 */
3463 NULL, /* IDB_FILTER 11 */
3464 os_info_str->str, /* IDB_OS 12 */
3465 NULL, /* IDB_HARDWARE 15 */
3468 &(global_ld.bytes_written),
3469 0, /* IDB_IF_SPEED 8 */
3470 6, /* IDB_TSRESOL 9 */
3471 &global_ld.err);
3472 ws_debug("%s: skipping deleted pcapng IDB %u", G_STRFUNC, i);
3473 } else if (idb_source.idb && idb_source.idb_len) {
3474 successful = pcapng_write_block(global_ld.pdh, idb_source.idb, idb_source.idb_len, &ld->bytes_written, err);
3475 ws_debug("%s: wrote pcapng IDB %d", G_STRFUNC, successful);
3476 } else if (idb_source.interface_id < capture_opts->ifaces->len) {
3477 unsigned if_id = idb_source.interface_id;
3478 interface_options *interface_opts = &g_array_index(capture_opts->ifaces, interface_options, if_id);
3479 capture_src *pcap_src = g_array_index(ld->pcaps, capture_src *, if_id);
3480 if (pcap_src->from_cap_pipe) {
3481 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
3482 } else {
3483 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
3485 successful = pcapng_write_interface_description_block(global_ld.pdh,
3486 NULL, /* OPT_COMMENT 1 */
3487 (interface_opts->ifname != NULL) ? interface_opts->ifname : interface_opts->name, /* IDB_NAME 2 */
3488 interface_opts->descr, /* IDB_DESCRIPTION 3 */
3489 interface_opts->cfilter, /* IDB_FILTER 11 */
3490 os_info_str->str, /* IDB_OS 12 */
3491 interface_opts->hardware, /* IDB_HARDWARE 15 */
3492 pcap_src->linktype,
3493 pcap_src->snaplen,
3494 &(global_ld.bytes_written),
3495 0, /* IDB_IF_SPEED 8 */
3496 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3497 &global_ld.err);
3498 ws_debug("%s: wrote capture_opts IDB %d: %d", G_STRFUNC, if_id, successful);
3501 g_rw_lock_reader_unlock (&ld->saved_shb_idb_lock);
3503 g_string_free(os_info_str, TRUE);
3505 return successful;
3508 /* set up to write to the already-opened capture output file/files */
3509 static bool
3510 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
3512 int err = 0;
3514 ws_debug("capture_loop_init_output");
3516 if ((capture_opts->use_pcapng == false) &&
3517 (capture_opts->ifaces->len > 1)) {
3518 snprintf(errmsg, errmsg_len,
3519 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
3520 return false;
3523 /* Set up to write to the capture file. */
3524 if (capture_opts->multi_files_on) {
3525 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
3526 } else {
3527 ld->pdh = writecap_fdopen(ld->save_file_fd, wtap_name_to_compression_type(capture_opts->compress_type), &err);
3529 if (ld->pdh) {
3530 bool successful;
3531 if (capture_opts->use_pcapng) {
3532 successful = capture_loop_init_pcapng_output(capture_opts, ld, &err);
3533 } else {
3534 capture_src *pcap_src;
3535 pcap_src = g_array_index(ld->pcaps, capture_src *, 0);
3536 if (pcap_src->from_cap_pipe) {
3537 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
3538 } else {
3539 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
3541 successful = libpcap_write_file_header(ld->pdh, pcap_src->linktype, pcap_src->snaplen,
3542 pcap_src->ts_nsec, &ld->bytes_written, &err);
3544 if (!successful) {
3545 writecap_close(ld->pdh, NULL);
3546 ld->pdh = NULL;
3550 if (ld->pdh == NULL) {
3551 /* We couldn't set up to write to the capture file. */
3552 /* XXX - use cf_open_error_message from tshark instead? */
3553 if (err < 0) {
3554 snprintf(errmsg, errmsg_len,
3555 "The file to which the capture would be"
3556 " saved (\"%s\") could not be opened: Error %d.",
3557 capture_opts->save_file, err);
3558 } else {
3559 snprintf(errmsg, errmsg_len,
3560 "The file to which the capture would be"
3561 " saved (\"%s\") could not be opened: %s.",
3562 capture_opts->save_file, g_strerror(err));
3564 return false;
3567 return true;
3570 static bool
3571 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
3574 unsigned int i;
3575 capture_src *pcap_src;
3576 uint64_t end_time = create_timestamp();
3577 bool success;
3579 ws_debug("capture_loop_close_output");
3581 if (capture_opts->multi_files_on) {
3582 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
3583 } else {
3584 if (capture_opts->use_pcapng) {
3585 for (i = 0; i < global_ld.pcaps->len; i++) {
3586 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3587 if (!pcap_src->from_cap_pipe) {
3588 uint64_t isb_ifrecv, isb_ifdrop;
3589 struct pcap_stat stats;
3591 if (pcap_stats(pcap_src->pcap_h, &stats) >= 0) {
3592 isb_ifrecv = pcap_src->received;
3593 isb_ifdrop = stats.ps_drop + pcap_src->dropped + pcap_src->flushed;
3594 } else {
3595 isb_ifrecv = UINT64_MAX;
3596 isb_ifdrop = UINT64_MAX;
3598 pcapng_write_interface_statistics_block(ld->pdh,
3600 &ld->bytes_written,
3601 "Counters provided by dumpcap",
3602 start_time,
3603 end_time,
3604 isb_ifrecv,
3605 isb_ifdrop,
3606 err_close);
3610 success = writecap_close(ld->pdh, err_close);
3611 return success;
3615 /* dispatch incoming packets (pcap or capture pipe)
3617 * Waits for incoming packets to be available, and calls pcap_dispatch()
3618 * to cause them to be processed.
3620 * Returns the number of packets which were processed.
3622 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3623 * packet-batching behaviour does not cause packets to get held back
3624 * indefinitely.
3626 static int
3627 capture_loop_dispatch(loop_data *ld,
3628 char *errmsg, int errmsg_len, capture_src *pcap_src)
3630 int inpkts = 0;
3631 int packet_count_before;
3632 int sel_ret;
3634 packet_count_before = ld->packets_captured;
3635 if (pcap_src->from_cap_pipe) {
3636 /* dispatch from capture pipe */
3637 #ifdef LOG_CAPTURE_VERBOSE
3638 ws_debug("capture_loop_dispatch: from capture pipe");
3639 #endif
3640 #ifdef _WIN32
3641 if (pcap_src->from_cap_socket) {
3642 #endif
3643 sel_ret = cap_pipe_select(pcap_src->cap_pipe_fd);
3644 if (sel_ret <= 0) {
3645 if (sel_ret < 0 && errno != EINTR) {
3646 snprintf(errmsg, errmsg_len,
3647 "Unexpected error from select: %s", g_strerror(errno));
3648 report_capture_error(errmsg, please_report_bug());
3649 ld->go = false;
3652 #ifdef _WIN32
3653 } else {
3654 /* Windows does not have select() for pipes. */
3655 /* Proceed with _dispatch() which waits for cap_pipe_done_q
3656 * notification from cap_thread_read() when ReadFile() on
3657 * the pipe has read enough bytes. */
3658 sel_ret = 1;
3660 #endif
3661 if (sel_ret > 0) {
3663 * "select()" says we can read from the pipe without blocking
3665 inpkts = pcap_src->cap_pipe_dispatch(ld, pcap_src, errmsg, errmsg_len);
3666 if (inpkts < 0) {
3667 ws_debug("%s: src %u pipe reached EOF or err, rcv: %u drop: %u flush: %u",
3668 G_STRFUNC, pcap_src->interface_id, pcap_src->received, pcap_src->dropped, pcap_src->flushed);
3669 ws_assert(pcap_src->cap_pipe_err != PIPOK);
3673 else
3675 /* dispatch from pcap */
3676 #ifdef MUST_DO_SELECT
3678 * If we have "pcap_get_selectable_fd()", we use it to get the
3679 * descriptor on which to select; if that's -1, it means there
3680 * is no descriptor on which you can do a "select()" (perhaps
3681 * because you're capturing on a special device, and that device's
3682 * driver unfortunately doesn't support "select()", in which case
3683 * we don't do the select - which means it might not be possible
3684 * to stop a capture until a packet arrives. If that's unacceptable,
3685 * plead with whoever supplies the software for that device to add
3686 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3687 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3688 * later, so it can use pcap_breakloop().
3690 #ifdef LOG_CAPTURE_VERBOSE
3691 ws_debug("capture_loop_dispatch: from pcap_dispatch with select");
3692 #endif
3693 if (pcap_src->pcap_fd != -1) {
3694 sel_ret = cap_pipe_select(pcap_src->pcap_fd);
3695 if (sel_ret > 0) {
3697 * "select()" says we can read from it without blocking; go for
3698 * it.
3700 * We don't have pcap_breakloop(), so we only process one packet
3701 * per pcap_dispatch() call, to allow a signal to stop the
3702 * processing immediately, rather than processing all packets
3703 * in a batch before quitting.
3705 if (use_threads) {
3706 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (uint8_t *)pcap_src);
3707 } else {
3708 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (uint8_t *)pcap_src);
3710 if (inpkts < 0) {
3711 if (inpkts == -1) {
3712 /* Error, rather than pcap_breakloop(). */
3713 pcap_src->pcap_err = true;
3715 ld->go = false; /* error or pcap_breakloop() - stop capturing */
3717 } else {
3718 if (sel_ret < 0 && errno != EINTR) {
3719 snprintf(errmsg, errmsg_len,
3720 "Unexpected error from select: %s", g_strerror(errno));
3721 report_capture_error(errmsg, please_report_bug());
3722 ld->go = false;
3726 else
3727 #endif /* MUST_DO_SELECT */
3729 /* dispatch from pcap without select */
3730 #if 1
3731 #ifdef LOG_CAPTURE_VERBOSE
3732 ws_debug("capture_loop_dispatch: from pcap_dispatch");
3733 #endif
3734 #ifdef _WIN32
3736 * On Windows, we don't support asynchronously telling a process to
3737 * stop capturing; instead, we check for an indication on a pipe
3738 * after processing packets. We therefore process only one packet
3739 * at a time, so that we can check the pipe after every packet.
3741 if (use_threads) {
3742 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (uint8_t *)pcap_src);
3743 } else {
3744 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (uint8_t *)pcap_src);
3746 #else
3747 if (use_threads) {
3748 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_queue_packet_cb, (uint8_t *)pcap_src);
3749 } else {
3750 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_write_packet_cb, (uint8_t *)pcap_src);
3752 #endif
3753 if (inpkts < 0) {
3754 if (inpkts == -1) {
3755 /* Error, rather than pcap_breakloop(). */
3756 pcap_src->pcap_err = true;
3758 ld->go = false; /* error or pcap_breakloop() - stop capturing */
3760 #else /* pcap_next_ex */
3761 #ifdef LOG_CAPTURE_VERBOSE
3762 ws_debug("capture_loop_dispatch: from pcap_next_ex");
3763 #endif
3764 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3767 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3768 * see https://gitlab.com/wireshark/wireshark/-/wikis/CaptureSetup/WinPcapRemote
3769 * This should be fixed in the WinPcap 4.0 alpha release.
3771 * For reference, an example remote interface:
3772 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3775 /* emulate dispatch from pcap */
3777 int in;
3778 struct pcap_pkthdr *pkt_header;
3779 uint8_t *pkt_data;
3781 in = 0;
3782 while(ld->go &&
3783 (in = pcap_next_ex(pcap_src->pcap_h, &pkt_header, &pkt_data)) == 1) {
3784 if (use_threads) {
3785 capture_loop_queue_packet_cb((uint8_t *)pcap_src, pkt_header, pkt_data);
3786 } else {
3787 capture_loop_write_packet_cb((uint8_t *)pcap_src, pkt_header, pkt_data);
3791 if (in < 0) {
3792 pcap_src->pcap_err = true;
3793 ld->go = false;
3796 #endif /* pcap_next_ex */
3800 #ifdef LOG_CAPTURE_VERBOSE
3801 ws_debug("capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3802 #endif
3804 return ld->packets_captured - packet_count_before;
3807 #ifdef _WIN32
3808 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3809 * want to grab only the characters between the '{' and '}' delimiters.
3811 * Returns a GString that must be freed with g_string_free(). */
3812 static GString *
3813 isolate_uuid(const char *iface)
3815 char *ptr;
3816 GString *gstr;
3818 ptr = strchr(iface, '{');
3819 if (ptr == NULL)
3820 return g_string_new(iface);
3821 gstr = g_string_new(ptr + 1);
3823 ptr = strchr(gstr->str, '}');
3824 if (ptr == NULL)
3825 return gstr;
3827 gstr = g_string_truncate(gstr, ptr - gstr->str);
3828 return gstr;
3830 #endif
3832 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3833 /* Returns true if the file opened successfully, false otherwise. */
3834 static bool
3835 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3836 char *errmsg, int errmsg_len)
3838 char *capfile_name = NULL;
3839 char *prefix, *suffix;
3840 bool is_tempfile;
3841 GError *err_tempfile = NULL;
3843 ws_debug("capture_loop_open_output: %s",
3844 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3846 if (capture_opts->save_file != NULL) {
3847 /* We return to the caller while the capture is in progress.
3848 * Therefore we need to take a copy of save_file in
3849 * case the caller destroys it after we return.
3851 capfile_name = g_strdup(capture_opts->save_file);
3853 if (capture_opts->output_to_pipe == true) { /* either "-" or named pipe */
3854 if (capture_opts->multi_files_on) {
3855 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3856 snprintf(errmsg, errmsg_len,
3857 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3858 g_free(capfile_name);
3859 return false;
3861 if (strcmp(capfile_name, "-") == 0) {
3862 /* write to stdout */
3863 *save_file_fd = 1;
3864 #ifdef _WIN32
3865 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3866 _setmode(1, O_BINARY);
3867 #endif
3868 } else {
3869 /* Try to open the specified FIFO for use as a capture buffer.
3870 Do *not* create it if it doesn't exist. There's nothing
3871 to truncate. If we need to read it, We Have A Problem. */
3872 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY, 0);
3874 } /* if (...output_to_pipe ... */
3876 else {
3877 if (capture_opts->multi_files_on) {
3878 /* ringbuffer is enabled */
3879 *save_file_fd = ringbuf_init(capfile_name,
3880 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3881 capture_opts->group_read_access,
3882 capture_opts->compress_type,
3883 capture_opts->has_nametimenum);
3885 /* capfile_name is unused as the ringbuffer provides its own filename. */
3886 if (*save_file_fd != -1) {
3887 g_free(capfile_name);
3888 capfile_name = NULL;
3890 if (capture_opts->print_file_names) {
3891 if (!ringbuf_set_print_name(capture_opts->print_name_to, NULL)) {
3892 snprintf(errmsg, errmsg_len, "Could not write filenames to %s: %s.\n",
3893 capture_opts->print_name_to,
3894 g_strerror(errno));
3895 g_free(capfile_name);
3896 ringbuf_error_cleanup();
3897 return false;
3900 } else {
3901 /* Try to open/create the specified file for use as a capture buffer. */
3902 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY|O_TRUNC|O_CREAT,
3903 (capture_opts->group_read_access) ? 0640 : 0600);
3906 is_tempfile = false;
3907 } else {
3908 /* Choose a random name for the temporary capture buffer */
3909 if (global_capture_opts.ifaces->len > 1) {
3911 * More than one interface; just use the number of interfaces
3912 * to generate the temporary file name prefix.
3914 prefix = ws_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3915 } else {
3917 * One interface; use its description, if it has one, to generate
3918 * the temporary file name, otherwise use its name.
3920 char *basename;
3921 const interface_options *interface_opts;
3923 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
3926 * Do we have a description?
3928 if (interface_opts->descr) {
3930 * Yes - use it.
3932 * Strip off any stuff we shouldn't use in the file name,
3933 * by getting the last component of what would be a file
3934 * name.
3936 basename = g_path_get_basename(interface_opts->descr);
3937 } else {
3939 * No - use the name.
3941 * Strip off any stuff we shouldn't use in the file name,
3942 * by getting the last component of what would be a file
3943 * name.
3945 basename = g_path_get_basename(interface_opts->name);
3946 #ifdef _WIN32
3948 * This is Windows, where we might have an ugly GUID-based
3949 * interface name.
3951 * If it's an ugly GUID-based name, use the generic portion
3952 * of the interface GUID to form the basis of the filename.
3954 if (strncmp("NPF_{", basename, 5) == 0) {
3956 * We have a GUID-based name; extract the GUID digits
3957 * as the basis of the filename.
3959 GString *iface;
3960 iface = isolate_uuid(basename);
3961 g_free(basename);
3962 basename = g_strdup(iface->str);
3963 g_string_free(iface, TRUE);
3965 #endif
3967 /* generate the temp file name prefix */
3968 prefix = g_strconcat("wireshark_", basename, NULL);
3969 g_free(basename);
3972 /* Generate the appropriate suffix. */
3973 if (capture_opts->use_pcapng) {
3974 suffix = ".pcapng";
3975 } else {
3976 suffix = ".pcap";
3978 const char* compression_suffix = wtap_compression_type_extension(wtap_name_to_compression_type(capture_opts->compress_type));
3979 /* If not compressed, compression_suffix is NULL and g_strjoin
3980 * handles the string list terminating early correctly.
3982 suffix = g_strjoin(".", suffix, compression_suffix, NULL);
3983 *save_file_fd = create_tempfile(capture_opts->temp_dir, &capfile_name, prefix, suffix, &err_tempfile);
3984 g_free(prefix);
3985 g_free(suffix);
3986 is_tempfile = true;
3989 /* did we fail to open the output file? */
3990 if (*save_file_fd == -1) {
3991 if (is_tempfile) {
3992 snprintf(errmsg, errmsg_len,
3993 "The temporary file to which the capture would be saved "
3994 "could not be opened: %s.", err_tempfile->message);
3995 g_error_free(err_tempfile);
3996 } else {
3997 if (capture_opts->multi_files_on) {
3998 /* Ensures that the ringbuffer is not used. This ensures that
3999 * !ringbuf_is_initialized() is equivalent to
4000 * capture_opts->save_file not being part of ringbuffer. */
4001 ringbuf_error_cleanup();
4004 snprintf(errmsg, errmsg_len,
4005 "The file to which the capture would be saved (\"%s\") "
4006 "could not be opened: %s.", capfile_name,
4007 g_strerror(errno));
4009 g_free(capfile_name);
4010 return false;
4013 g_free(capture_opts->save_file);
4014 if (!is_tempfile && capture_opts->multi_files_on) {
4015 /* In ringbuffer mode, save_file points to a filename from ringbuffer.c.
4016 * capfile_name was already freed before. */
4017 capture_opts->save_file = (char *)ringbuf_current_filename();
4018 } else {
4019 /* capture_opts_cleanup will g_free(capture_opts->save_file). */
4020 capture_opts->save_file = capfile_name;
4023 return true;
4026 static time_t get_next_time_interval(int interval_s) {
4027 time_t next_time = time(NULL);
4028 next_time -= next_time % interval_s;
4029 next_time += interval_s;
4030 return next_time;
4033 /* Do the work of handling either the file size or file duration capture
4034 conditions being reached, and switching files or stopping. */
4035 static bool
4036 do_file_switch_or_stop(capture_options *capture_opts)
4038 bool successful;
4040 if (capture_opts->multi_files_on) {
4041 if (capture_opts->has_autostop_files &&
4042 ++global_ld.file_count >= capture_opts->autostop_files) {
4043 /* no files left: stop here */
4044 global_ld.go = false;
4045 return false;
4048 /* Switch to the next ringbuffer file */
4049 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
4050 &global_ld.save_file_fd, &global_ld.err)) {
4052 /* File switch succeeded: reset the conditions */
4053 global_ld.bytes_written = 0;
4054 global_ld.packets_written = 0;
4055 if (capture_opts->use_pcapng) {
4056 successful = capture_loop_init_pcapng_output(capture_opts, &global_ld, &global_ld.err);
4057 } else {
4058 capture_src *pcap_src;
4059 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
4060 successful = libpcap_write_file_header(global_ld.pdh, pcap_src->linktype, pcap_src->snaplen,
4061 pcap_src->ts_nsec, &global_ld.bytes_written, &global_ld.err);
4064 if (!successful) {
4065 writecap_close(global_ld.pdh, NULL);
4066 global_ld.pdh = NULL;
4067 global_ld.go = false;
4068 return false;
4070 if (global_ld.file_duration_timer) {
4071 g_timer_reset(global_ld.file_duration_timer);
4073 if (global_ld.next_interval_time) {
4074 global_ld.next_interval_time = get_next_time_interval(global_ld.interval_s);
4076 writecap_flush(global_ld.pdh, NULL);
4077 if (global_ld.inpkts_to_sync_pipe) {
4078 if (!quiet)
4079 report_packet_count(global_ld.inpkts_to_sync_pipe);
4080 global_ld.inpkts_to_sync_pipe = 0;
4082 report_new_capture_file(capture_opts->save_file);
4083 } else {
4084 /* File switch failed: stop here */
4085 global_ld.go = false;
4086 return false;
4088 } else {
4089 /* single file, stop now */
4090 global_ld.go = false;
4091 return false;
4093 return true;
4096 static void *
4097 pcap_read_handler(void* arg)
4099 capture_src *pcap_src = (capture_src *)arg;
4100 char errmsg[MSG_MAX_LENGTH+1];
4102 ws_info("Started thread for interface %d.", pcap_src->interface_id);
4104 /* If this is a pipe input it might finish early. */
4105 while (global_ld.go && pcap_src->cap_pipe_err == PIPOK) {
4106 /* dispatch incoming packets */
4107 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_src);
4110 ws_info("Stopped thread for interface %d.", pcap_src->interface_id);
4111 g_thread_exit(NULL);
4112 return (NULL);
4115 /* Try to pop an item off the packet queue and if it exists, write it */
4116 static bool
4117 capture_loop_dequeue_packet(void) {
4118 pcap_queue_element *queue_element;
4120 g_async_queue_lock(pcap_queue);
4121 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
4122 if (queue_element) {
4123 if (queue_element->pcap_src->from_pcapng) {
4124 pcap_queue_bytes -= queue_element->u.bh.block_total_length;
4125 } else {
4126 pcap_queue_bytes -= queue_element->u.phdr.caplen;
4128 pcap_queue_packets -= 1;
4130 g_async_queue_unlock(pcap_queue);
4131 if (queue_element) {
4132 if (queue_element->pcap_src->from_pcapng) {
4133 ws_info("Dequeued a block of type 0x%08x of length %d captured on interface %d.",
4134 queue_element->u.bh.block_type, queue_element->u.bh.block_total_length,
4135 queue_element->pcap_src->interface_id);
4137 capture_loop_write_pcapng_cb(queue_element->pcap_src,
4138 &queue_element->u.bh,
4139 queue_element->pd);
4140 } else {
4141 ws_info("Dequeued a packet of length %d captured on interface %d.",
4142 queue_element->u.phdr.caplen, queue_element->pcap_src->interface_id);
4144 capture_loop_write_packet_cb((uint8_t *) queue_element->pcap_src,
4145 &queue_element->u.phdr,
4146 queue_element->pd);
4148 g_free(queue_element->pd);
4149 g_free(queue_element);
4150 return true;
4152 return false;
4156 * Note: this code will never be run on any OS other than Windows.
4158 * We keep the arguments in case there's something in the future
4159 * that needs to be reported as an NPCAP bug.
4161 static char *
4162 handle_npcap_bug(char *adapter_name _U_, char *cap_err_str _U_)
4164 bool have_npcap = false;
4166 #ifdef _WIN32
4167 have_npcap = caplibs_have_npcap();
4168 #endif
4170 if (!have_npcap) {
4172 * We're not using Npcap, so don't recommend a user
4173 * file a bug against Npcap.
4175 return g_strdup("");
4178 return ws_strdup_printf("If you have not removed that adapter, this "
4179 "is probably a known issue in Npcap resulting from "
4180 "the behavior of the Windows networking stack. "
4181 "Work is being done in Npcap to improve the "
4182 "handling of this issue; it does not need to "
4183 "be reported as a Wireshark or Npcap bug.");
4186 /* Do the low-level work of a capture.
4187 Returns true if it succeeds, false otherwise. */
4188 static bool
4189 capture_loop_start(capture_options *capture_opts, bool *stats_known, struct pcap_stat *stats)
4191 #ifdef _WIN32
4192 ULONGLONG upd_time, cur_time; /* GetTickCount64() returns a "ULONGLONG" */
4193 #else
4194 struct timeval upd_time, cur_time;
4195 #endif
4196 int err_close;
4197 int inpkts;
4198 GTimer *autostop_duration_timer = NULL;
4199 bool write_ok;
4200 bool close_ok;
4201 bool cfilter_error = false;
4202 char errmsg[MSG_MAX_LENGTH+1];
4203 char secondary_errmsg[MSG_MAX_LENGTH+1];
4204 capture_src *pcap_src;
4205 interface_options *interface_opts;
4206 unsigned i, error_index = 0;
4208 *errmsg = '\0';
4209 *secondary_errmsg = '\0';
4211 /* init the loop data */
4212 global_ld.go = true;
4213 global_ld.packets_captured = 0;
4214 #ifdef SIGINFO
4215 global_ld.report_packet_count = false;
4216 #endif
4217 global_ld.inpkts_to_sync_pipe = 0;
4218 global_ld.err = 0; /* no error seen yet */
4219 global_ld.pdh = NULL;
4220 global_ld.save_file_fd = -1;
4221 global_ld.file_count = 0;
4222 global_ld.file_duration_timer = NULL;
4223 global_ld.next_interval_time = 0;
4224 global_ld.interval_s = 0;
4226 /* We haven't yet gotten the capture statistics. */
4227 *stats_known = false;
4229 ws_info("Capture loop starting ...");
4230 capture_opts_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_DEBUG, capture_opts);
4232 /* open the "input file" from network interface or capture pipe */
4233 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
4234 secondary_errmsg, sizeof(secondary_errmsg))) {
4235 goto error;
4237 for (i = 0; i < capture_opts->ifaces->len; i++) {
4238 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4239 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
4240 /* init the input filter from the network interface (capture pipe will do nothing) */
4242 * When remote capturing WinPCap crashes when the capture filter
4243 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
4244 * string.
4246 switch (capture_loop_init_filter(pcap_src->pcap_h, pcap_src->from_cap_pipe,
4247 interface_opts->name,
4248 interface_opts->cfilter?interface_opts->cfilter:"")) {
4250 case INITFILTER_NO_ERROR:
4251 break;
4253 case INITFILTER_BAD_FILTER:
4254 cfilter_error = true;
4255 error_index = i;
4256 snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_src->pcap_h));
4257 goto error;
4259 case INITFILTER_OTHER_ERROR:
4260 snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
4261 pcap_geterr(pcap_src->pcap_h));
4262 snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report_bug());
4263 goto error;
4267 /* If we're supposed to write to a capture file, open it for output
4268 (temporary/specified name/ringbuffer) */
4269 if (capture_opts->saving_to_file) {
4270 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
4271 errmsg, sizeof(errmsg))) {
4272 goto error;
4275 /* set up to write to the already-opened capture output file/files */
4276 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
4277 sizeof(errmsg))) {
4278 goto error;
4281 /* XXX - capture SIGTERM and close the capture, in case we're on a
4282 Linux 2.0[.x] system and you have to explicitly close the capture
4283 stream in order to turn promiscuous mode off? We need to do that
4284 in other places as well - and I don't think that works all the
4285 time in any case, due to libpcap bugs. */
4287 /* Well, we should be able to start capturing.
4289 Sync out the capture file, so the header makes it to the file system,
4290 and send a "capture started successfully and capture file created"
4291 message to our parent so that they'll open the capture file and
4292 update its windows to indicate that we have a live capture in
4293 progress. */
4294 writecap_flush(global_ld.pdh, NULL);
4295 report_new_capture_file(capture_opts->save_file);
4298 if (capture_opts->has_file_interval) {
4299 global_ld.interval_s = capture_opts->file_interval;
4300 global_ld.next_interval_time = get_next_time_interval(global_ld.interval_s);
4302 /* create stop conditions */
4303 if (capture_opts->has_autostop_filesize) {
4304 if (capture_opts->autostop_filesize > UINT32_C(2000000000)) {
4305 capture_opts->autostop_filesize = UINT32_C(2000000000);
4308 if (capture_opts->has_autostop_duration) {
4309 autostop_duration_timer = g_timer_new();
4312 if (capture_opts->multi_files_on) {
4313 if (capture_opts->has_file_duration) {
4314 global_ld.file_duration_timer = g_timer_new();
4318 /* init the time values */
4319 #ifdef _WIN32
4320 upd_time = GetTickCount64();
4321 #else
4322 gettimeofday(&upd_time, NULL);
4323 #endif
4324 start_time = create_timestamp();
4325 ws_info("Capture loop running.");
4326 capture_opts_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_DEBUG, capture_opts);
4328 /* WOW, everything is prepared! */
4329 /* please fasten your seat belts, we will enter now the actual capture loop */
4330 if (use_threads) {
4331 pcap_queue = g_async_queue_new();
4332 pcap_queue_bytes = 0;
4333 pcap_queue_packets = 0;
4334 for (i = 0; i < global_ld.pcaps->len; i++) {
4335 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4336 /* XXX - Add an interface name here? */
4337 pcap_src->tid = g_thread_new("Capture read", pcap_read_handler, pcap_src);
4340 while (global_ld.go) {
4341 /* dispatch incoming packets */
4342 if (use_threads) {
4343 bool dequeued = capture_loop_dequeue_packet();
4345 if (dequeued) {
4346 inpkts = 1;
4347 } else {
4348 inpkts = 0;
4350 } else {
4351 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
4352 inpkts = capture_loop_dispatch(&global_ld, errmsg,
4353 sizeof(errmsg), pcap_src);
4355 if (inpkts == 0) {
4356 /* Stop capturing if all of our sources are pipes and none of them are open. */
4357 bool open_interfaces = false;
4358 for (i = 0; i < global_ld.pcaps->len; i++) {
4359 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4360 if (pcap_src->cap_pipe_err == PIPOK) {
4361 /* True for both non-pipes and open pipes. */
4362 open_interfaces = true;
4365 if (!open_interfaces) {
4366 global_ld.go = false;
4369 #ifdef SIGINFO
4370 /* Were we asked to print packet counts by the SIGINFO handler? */
4371 if (global_ld.report_packet_count) {
4372 fprintf(stderr, "%u packet%s captured\n", global_ld.packets_captured,
4373 plurality(global_ld.packets_captured, "", "s"));
4374 global_ld.report_packet_count = false;
4376 #endif
4378 #ifdef _WIN32
4379 /* any news from our parent (signal pipe)? -> just stop the capture */
4380 if (!signal_pipe_check_running()) {
4381 global_ld.go = false;
4383 #endif
4385 if (inpkts > 0) {
4386 if (capture_opts->output_to_pipe) {
4387 writecap_flush(global_ld.pdh, NULL);
4389 } /* inpkts */
4391 /* Only update after an interval so as not to overload slow displays.
4392 * This also prevents too much context-switching between the dumpcap
4393 * and wireshark processes.
4394 * XXX: Should we send updates sooner if there have been lots of
4395 * packets we haven't notified the parent about, such as on fast links?
4397 #ifdef _WIN32
4398 cur_time = GetTickCount64();
4399 if ((cur_time - upd_time) > capture_opts->update_interval)
4400 #else
4401 gettimeofday(&cur_time, NULL);
4402 if (((uint64_t)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
4403 ((uint64_t)upd_time.tv_sec * 1000000 + upd_time.tv_usec + capture_opts->update_interval*1000))
4404 #endif
4407 upd_time = cur_time;
4409 #if 0
4410 if (pcap_stats(pch, stats) >= 0) {
4411 *stats_known = true;
4413 #endif
4414 /* Let the parent process know. */
4415 if (global_ld.inpkts_to_sync_pipe) {
4416 /* do sync here */
4417 writecap_flush(global_ld.pdh, NULL);
4419 /* Send our parent a message saying we've written out
4420 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
4421 if (!quiet)
4422 report_packet_count(global_ld.inpkts_to_sync_pipe);
4424 global_ld.inpkts_to_sync_pipe = 0;
4427 /* check capture duration condition */
4428 if (autostop_duration_timer != NULL && g_timer_elapsed(autostop_duration_timer, NULL) >= capture_opts->autostop_duration) {
4429 /* The maximum capture time has elapsed; stop the capture. */
4430 global_ld.go = false;
4431 continue;
4434 /* check capture file duration condition */
4435 if (global_ld.file_duration_timer != NULL && g_timer_elapsed(global_ld.file_duration_timer, NULL) >= capture_opts->file_duration) {
4436 /* duration limit reached, do we have another file? */
4437 if (!do_file_switch_or_stop(capture_opts))
4438 continue;
4439 } /* cnd_file_duration */
4441 /* check capture file interval condition */
4442 if (global_ld.interval_s && time(NULL) >= global_ld.next_interval_time) {
4443 /* end of interval reached, do we have another file? */
4444 if (!do_file_switch_or_stop(capture_opts))
4445 continue;
4446 } /* cnd_file_interval */
4450 ws_info("Capture loop stopping ...");
4451 if (use_threads) {
4453 for (i = 0; i < global_ld.pcaps->len; i++) {
4454 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4455 ws_info("Waiting for thread of interface %u...", pcap_src->interface_id);
4456 g_thread_join(pcap_src->tid);
4457 ws_info("Thread of interface %u terminated.", pcap_src->interface_id);
4459 while (1) {
4460 bool dequeued = capture_loop_dequeue_packet();
4461 if (!dequeued) {
4462 break;
4464 if (capture_opts->output_to_pipe) {
4465 writecap_flush(global_ld.pdh, NULL);
4471 /* delete stop conditions */
4472 if (global_ld.file_duration_timer != NULL)
4473 g_timer_destroy(global_ld.file_duration_timer);
4474 if (autostop_duration_timer != NULL)
4475 g_timer_destroy(autostop_duration_timer);
4477 /* did we have a pcap (input) error? */
4478 for (i = 0; i < capture_opts->ifaces->len; i++) {
4479 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4480 if (pcap_src->pcap_err) {
4481 /* On Linux, if an interface goes down while you're capturing on it,
4482 you'll get "recvfrom: Network is down".
4483 (At least you will if g_strerror() doesn't show a local translation
4484 of the error.)
4486 Newer versions of libpcap maps that to just
4487 "The interface went down".
4489 On FreeBSD, DragonFly BSD, and macOS, if a network adapter
4490 disappears while you're capturing on it, you'll get
4491 "read: Device not configured" error (ENXIO). (See previous
4492 parenthetical note.)
4494 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
4496 With WinPcap and Npcap, you'll get
4497 "read error: PacketReceivePacket failed" or
4498 "PacketReceivePacket error: The device has been removed. (1617)".
4500 Newer versions of libpcap map some or all of those to just
4501 "The interface disappeared" or something beginning with
4502 "The interface disappeared".
4504 These should *not* be reported to the Wireshark developers,
4505 although, with Npcap, "The interface disappeared" messages
4506 should perhaps be reported to the Npcap developers, at least
4507 until errors of that sort that shouldn't happen are fixed,
4508 if that's possible. */
4509 char *cap_err_str;
4510 char *primary_msg;
4511 char *secondary_msg;
4513 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
4514 cap_err_str = pcap_geterr(pcap_src->pcap_h);
4515 if (strcmp(cap_err_str, "The interface went down") == 0 ||
4516 strcmp(cap_err_str, "recvfrom: Network is down") == 0) {
4517 primary_msg = ws_strdup_printf("The network adapter \"%s\" "
4518 "is no longer running; the "
4519 "capture has stopped.",
4520 interface_opts->display_name);
4521 secondary_msg = g_strdup("");
4522 } else if (strcmp(cap_err_str, "The interface disappeared") == 0 ||
4523 strcmp(cap_err_str, "read: Device not configured") == 0 ||
4524 strcmp(cap_err_str, "read: I/O error") == 0 ||
4525 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
4526 primary_msg = ws_strdup_printf("The network adapter \"%s\" "
4527 "is no longer attached; the "
4528 "capture has stopped.",
4529 interface_opts->display_name);
4530 secondary_msg = g_strdup("");
4531 } else if (g_str_has_prefix(cap_err_str, "The interface disappeared ")) {
4533 * Npcap, if it picks up a recent commit to libpcap, will
4534 * report an error *beginning* with "The interface
4535 * disappeared", with the name of the Windows status code,
4536 * and the corresponding NT status code, after it.
4538 * Those should be reported as Npcap issues.
4540 primary_msg = ws_strdup_printf("The network adapter \"%s\" "
4541 "is no longer attached; the "
4542 "capture has stopped.",
4543 interface_opts->display_name);
4544 secondary_msg = handle_npcap_bug(interface_opts->display_name,
4545 cap_err_str);
4546 } else if (g_str_has_prefix(cap_err_str, "PacketReceivePacket error:") &&
4547 g_str_has_suffix(cap_err_str, "(1617)")) {
4549 * "PacketReceivePacket error: {message in arbitrary language} (1617)",
4550 * which is ERROR_DEVICE_REMOVED.
4552 * Current libpcap/Npcap treat ERROR_GEN_FAILURE as
4553 * "the device is no longer attached"; users are also
4554 * getting ERROR_DEVICE_REMOVED.
4556 * For now, some users appear to be getg ERROR_DEVICE_REMOVED
4557 * in cases where the device *wasn't* removed, so tell
4558 * them to report this as an Npcap issue; I seem to
4559 * remember some discussion between Daniel and somebody
4560 * at Microsoft about the Windows 10 network stack setup/
4561 * teardown code being modified to try to prevent those
4562 * sort of problems popping up, but I can't find that
4563 * discussion.
4565 primary_msg = ws_strdup_printf("The network adapter \"%s\" "
4566 "is no longer attached; the "
4567 "capture has stopped.",
4568 interface_opts->display_name);
4569 secondary_msg = handle_npcap_bug(interface_opts->display_name,
4570 "The interface disappeared (error code ERROR_DEVICE_REMOVED/STATUS_DEVICE_REMOVED)");
4571 } else if (strcmp(cap_err_str, "The other host terminated the connection.") == 0 ||
4572 g_str_has_prefix(cap_err_str, "Is the server properly installed?")) {
4574 * Networking error for a remote capture.
4576 primary_msg = g_strdup(cap_err_str);
4577 secondary_msg = g_strdup("This may be a problem with the "
4578 "remote host on which you are "
4579 "capturing packets.");
4580 } else {
4581 primary_msg = ws_strdup_printf("Error while capturing packets: %s",
4582 cap_err_str);
4583 secondary_msg = g_strdup(please_report_bug());
4585 report_capture_error(primary_msg, secondary_msg);
4586 g_free(primary_msg);
4587 g_free(secondary_msg);
4588 break;
4589 } else if (pcap_src->from_cap_pipe && pcap_src->cap_pipe_err == PIPERR) {
4590 report_capture_error(errmsg, "");
4591 break;
4594 /* did we have an output error while capturing? */
4595 if (global_ld.err == 0) {
4596 write_ok = true;
4597 } else {
4598 capture_loop_get_errmsg(errmsg, sizeof(errmsg), secondary_errmsg,
4599 sizeof(secondary_errmsg),
4600 capture_opts->save_file, global_ld.err, false);
4601 report_capture_error(errmsg, secondary_errmsg);
4602 write_ok = false;
4605 if (capture_opts->saving_to_file) {
4606 /* close the output file */
4607 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
4608 } else
4609 close_ok = true;
4611 /* there might be packets not yet notified to the parent */
4612 /* (do this after closing the file, so all packets are already flushed) */
4613 if (global_ld.inpkts_to_sync_pipe) {
4614 if (!quiet)
4615 report_packet_count(global_ld.inpkts_to_sync_pipe);
4616 global_ld.inpkts_to_sync_pipe = 0;
4619 /* If we've displayed a message about a write error, there's no point
4620 in displaying another message about an error on close. */
4621 if (!close_ok && write_ok) {
4622 capture_loop_get_errmsg(errmsg, sizeof(errmsg), secondary_errmsg,
4623 sizeof(secondary_errmsg),
4624 capture_opts->save_file, err_close, true);
4625 report_capture_error(errmsg, secondary_errmsg);
4629 * XXX We exhibit different behaviour between normal mode and sync mode
4630 * when the pipe is stdin and not already at EOF. If we're a child, the
4631 * parent's stdin isn't closed, so if the user starts another capture,
4632 * cap_pipe_open_live() will very likely not see the expected magic bytes and
4633 * will say "Unrecognized libpcap format". On the other hand, in normal
4634 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
4637 report_capture_count(!really_quiet);
4639 /* get packet drop statistics from pcap */
4640 for (i = 0; i < capture_opts->ifaces->len; i++) {
4641 uint32_t received;
4642 uint32_t pcap_dropped = 0;
4644 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4645 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
4646 received = pcap_src->received;
4647 if (pcap_src->pcap_h != NULL) {
4648 ws_assert(!pcap_src->from_cap_pipe);
4649 /* Get the capture statistics, so we know how many packets were dropped. */
4650 if (pcap_stats(pcap_src->pcap_h, stats) >= 0) {
4651 *stats_known = true;
4652 /* Let the parent process know. */
4653 pcap_dropped += stats->ps_drop;
4654 } else {
4655 snprintf(errmsg, sizeof(errmsg),
4656 "Can't get packet-drop statistics: %s",
4657 pcap_geterr(pcap_src->pcap_h));
4658 report_capture_error(errmsg, please_report_bug());
4661 report_packet_drops(received, pcap_dropped, pcap_src->dropped, pcap_src->flushed, stats->ps_ifdrop, interface_opts->display_name);
4664 /* close the input file (pcap or capture pipe) */
4665 capture_loop_close_input(&global_ld);
4667 ws_info("Capture loop stopped.");
4669 /* ok, if the write and the close were successful. */
4670 return write_ok && close_ok;
4672 error:
4673 if (capture_opts->multi_files_on) {
4674 /* cleanup ringbuffer */
4675 ringbuf_error_cleanup();
4676 } else {
4677 /* We can't use the save file, and we have no FILE * for the stream
4678 to close in order to close it, so close the FD directly. */
4679 if (global_ld.save_file_fd != -1) {
4680 ws_close(global_ld.save_file_fd);
4683 /* We couldn't even start the capture, so get rid of the capture
4684 file. */
4685 if (capture_opts->save_file != NULL) {
4686 ws_unlink(capture_opts->save_file);
4689 if (cfilter_error)
4690 report_cfilter_error(capture_opts, error_index, errmsg);
4691 else
4692 report_capture_error(errmsg, secondary_errmsg);
4694 /* close the input file (pcap or cap_pipe) */
4695 capture_loop_close_input(&global_ld);
4697 ws_info("Capture loop stopped with error");
4699 return false;
4703 static void
4704 capture_loop_stop(void)
4706 unsigned i;
4707 capture_src *pcap_src;
4709 for (i = 0; i < global_ld.pcaps->len; i++) {
4710 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4711 if (pcap_src->pcap_h != NULL)
4712 pcap_breakloop(pcap_src->pcap_h);
4714 global_ld.go = false;
4718 static void
4719 capture_loop_get_errmsg(char *errmsg, size_t errmsglen, char *secondary_errmsg,
4720 size_t secondary_errmsglen, const char *fname,
4721 int err, bool is_close)
4723 static const char find_space[] =
4724 "You will need to free up space on that file system"
4725 " or put the capture file on a different file system.";
4727 switch (err) {
4729 case ENOSPC:
4730 snprintf(errmsg, errmsglen,
4731 "Not all the packets could be written to the file"
4732 " to which the capture was being saved\n"
4733 "(\"%s\") because there is no space left on the file system\n"
4734 "on which that file resides.",
4735 fname);
4736 snprintf(secondary_errmsg, secondary_errmsglen, "%s", find_space);
4737 break;
4739 #ifdef EDQUOT
4740 case EDQUOT:
4741 snprintf(errmsg, errmsglen,
4742 "Not all the packets could be written to the file"
4743 " to which the capture was being saved\n"
4744 "(\"%s\") because you are too close to, or over,"
4745 " your disk quota\n"
4746 "on the file system on which that file resides.",
4747 fname);
4748 snprintf(secondary_errmsg, secondary_errmsglen, "%s", find_space);
4749 break;
4750 #endif
4752 default:
4753 if (is_close) {
4754 snprintf(errmsg, errmsglen,
4755 "The file to which the capture was being saved\n"
4756 "(\"%s\") could not be closed: %s.",
4757 fname, g_strerror(err));
4758 } else {
4759 snprintf(errmsg, errmsglen,
4760 "An error occurred while writing to the file"
4761 " to which the capture was being saved\n"
4762 "(\"%s\"): %s.",
4763 fname, g_strerror(err));
4765 snprintf(secondary_errmsg, secondary_errmsglen,
4766 "%s", please_report_bug());
4767 break;
4772 * We wrote one packet. Update some statistics and check if we've met any
4773 * autostop or ring buffer conditions.
4775 static void
4776 capture_loop_wrote_one_packet(capture_src *pcap_src) {
4777 global_ld.packets_captured++;
4778 global_ld.packets_written++;
4779 global_ld.inpkts_to_sync_pipe++;
4781 if (!use_threads) {
4782 pcap_src->received++;
4785 /* check -c NUM */
4786 if (global_capture_opts.has_autostop_packets && global_ld.packets_captured >= global_capture_opts.autostop_packets) {
4787 writecap_flush(global_ld.pdh, NULL);
4788 global_ld.go = false;
4789 return;
4791 /* check -a packets:NUM (treat like -c NUM) */
4792 if (global_capture_opts.has_autostop_written_packets && global_ld.packets_captured >= global_capture_opts.autostop_written_packets) {
4793 writecap_flush(global_ld.pdh, NULL);
4794 global_ld.go = false;
4795 return;
4797 /* check -b packets:NUM */
4798 if (global_capture_opts.has_file_packets && global_ld.packets_written >= global_capture_opts.file_packets) {
4799 do_file_switch_or_stop(&global_capture_opts);
4800 return;
4802 /* check -a filesize:NUM */
4803 if (global_capture_opts.has_autostop_filesize &&
4804 global_capture_opts.autostop_filesize > 0 &&
4805 global_ld.bytes_written / 1000 >= global_capture_opts.autostop_filesize) {
4806 /* Capture size limit reached, do we have another file? */
4807 do_file_switch_or_stop(&global_capture_opts);
4808 return;
4812 /* one pcapng block was captured, process it */
4813 static void
4814 capture_loop_write_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, uint8_t *pd)
4816 int err;
4819 * This should never be called if we're not writing pcapng.
4821 ws_assert(global_capture_opts.use_pcapng);
4823 /* We may be called multiple times from pcap_dispatch(); if we've set
4824 the "stop capturing" flag, ignore this packet, as we're not
4825 supposed to be saving any more packets. */
4826 if (!global_ld.go) {
4827 pcap_src->flushed++;
4828 return;
4831 if (!pcapng_adjust_block(pcap_src, bh, pd)) {
4832 ws_info("%s failed to adjust pcapng block.", G_STRFUNC);
4833 ws_assert_not_reached();
4834 return;
4837 if (bh->block_type == BLOCK_TYPE_SHB && !global_ld.pcapng_passthrough) {
4839 * capture_loop_init_pcapng_output should've handled this. We need
4840 * to write ISBs when they're initially read so we shouldn't skip
4841 * them here.
4843 return;
4846 if (global_ld.pdh) {
4847 bool successful;
4849 /* We're supposed to write the packet to a file; do so.
4850 If this fails, set "ld->go" to false, to stop the capture, and set
4851 "ld->err" to the error. */
4852 successful = pcapng_write_block(global_ld.pdh,
4854 bh->block_total_length,
4855 &global_ld.bytes_written, &err);
4857 writecap_flush(global_ld.pdh, NULL);
4858 if (!successful) {
4859 global_ld.go = false;
4860 global_ld.err = err;
4861 pcap_src->dropped++;
4862 } else if (is_data_block(bh->block_type)) {
4863 /* Count packets for block types that should be dissected, i.e. ones that show up in the packet list. */
4864 ws_debug("Wrote a pcapng block type 0x%04x of length %d captured on interface %u.",
4865 bh->block_type, bh->block_total_length, pcap_src->interface_id);
4866 capture_loop_wrote_one_packet(pcap_src);
4867 } else if (bh->block_type == BLOCK_TYPE_SHB && report_capture_filename) {
4868 ws_debug("Sending SP_FILE on first SHB");
4869 /* SHB is now ready for capture parent to read on SP_FILE message */
4870 sync_pipe_write_string_msg(sync_pipe_fd, SP_FILE, report_capture_filename);
4871 report_capture_filename = NULL;
4876 /* one pcap packet was captured, process it */
4877 static void
4878 capture_loop_write_packet_cb(uint8_t *pcap_src_p, const struct pcap_pkthdr *phdr,
4879 const uint8_t *pd)
4881 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4882 int err;
4883 unsigned ts_mul = pcap_src->ts_nsec ? 1000000000 : 1000000;
4885 ws_debug("capture_loop_write_packet_cb");
4887 /* We may be called multiple times from pcap_dispatch(); if we've set
4888 the "stop capturing" flag, ignore this packet, as we're not
4889 supposed to be saving any more packets. */
4890 if (!global_ld.go) {
4891 pcap_src->flushed++;
4892 return;
4895 if (global_ld.pdh) {
4896 bool successful;
4898 /* We're supposed to write the packet to a file; do so.
4899 If this fails, set "ld->go" to false, to stop the capture, and set
4900 "ld->err" to the error. */
4901 if (global_capture_opts.use_pcapng) {
4902 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
4903 NULL,
4904 phdr->ts.tv_sec, (int32_t)phdr->ts.tv_usec,
4905 phdr->caplen, phdr->len,
4906 pcap_src->idb_id,
4907 ts_mul,
4908 pd, 0,
4909 &global_ld.bytes_written, &err);
4910 } else {
4911 successful = libpcap_write_packet(global_ld.pdh,
4912 phdr->ts.tv_sec, (int32_t)phdr->ts.tv_usec,
4913 phdr->caplen, phdr->len,
4915 &global_ld.bytes_written, &err);
4917 if (!successful) {
4918 global_ld.go = false;
4919 global_ld.err = err;
4920 pcap_src->dropped++;
4921 } else {
4922 ws_debug("Wrote a pcap packet of length %d captured on interface %u.",
4923 phdr->caplen, pcap_src->interface_id);
4924 capture_loop_wrote_one_packet(pcap_src);
4929 /* one packet was captured, queue it */
4930 static void
4931 capture_loop_queue_packet_cb(uint8_t *pcap_src_p, const struct pcap_pkthdr *phdr,
4932 const uint8_t *pd)
4934 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4935 pcap_queue_element *queue_element;
4936 bool limit_reached;
4938 /* We may be called multiple times from pcap_dispatch(); if we've set
4939 the "stop capturing" flag, ignore this packet, as we're not
4940 supposed to be saving any more packets. */
4941 if (!global_ld.go) {
4942 pcap_src->flushed++;
4943 return;
4946 queue_element = g_new(pcap_queue_element, 1);
4947 if (queue_element == NULL) {
4948 pcap_src->dropped++;
4949 return;
4951 queue_element->pcap_src = pcap_src;
4952 queue_element->u.phdr = *phdr;
4953 queue_element->pd = (uint8_t *)g_malloc(phdr->caplen);
4954 if (queue_element->pd == NULL) {
4955 pcap_src->dropped++;
4956 g_free(queue_element);
4957 return;
4959 memcpy(queue_element->pd, pd, phdr->caplen);
4960 g_async_queue_lock(pcap_queue);
4961 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4962 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4963 limit_reached = false;
4964 g_async_queue_push_unlocked(pcap_queue, queue_element);
4965 pcap_queue_bytes += phdr->caplen;
4966 pcap_queue_packets += 1;
4967 } else {
4968 limit_reached = true;
4970 g_async_queue_unlock(pcap_queue);
4971 if (limit_reached) {
4972 pcap_src->dropped++;
4973 g_free(queue_element->pd);
4974 g_free(queue_element);
4975 ws_info("Dropped a packet of length %d captured on interface %u.",
4976 phdr->caplen, pcap_src->interface_id);
4977 } else {
4978 pcap_src->received++;
4979 ws_info("Queued a packet of length %d captured on interface %u.",
4980 phdr->caplen, pcap_src->interface_id);
4982 /* I don't want to hold the mutex over the debug output. So the
4983 output may be wrong */
4984 ws_info("Queue size is now %" PRId64 " bytes (%" PRId64 " packets)",
4985 pcap_queue_bytes, pcap_queue_packets);
4988 /* one pcapng block was captured, queue it */
4989 static void
4990 capture_loop_queue_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, uint8_t *pd)
4992 pcap_queue_element *queue_element;
4993 bool limit_reached;
4995 /* We may be called multiple times from pcap_dispatch(); if we've set
4996 the "stop capturing" flag, ignore this packet, as we're not
4997 supposed to be saving any more packets. */
4998 if (!global_ld.go) {
4999 pcap_src->flushed++;
5000 return;
5003 queue_element = g_new(pcap_queue_element, 1);
5004 if (queue_element == NULL) {
5005 pcap_src->dropped++;
5006 return;
5008 queue_element->pcap_src = pcap_src;
5009 queue_element->u.bh = *bh;
5010 queue_element->pd = (uint8_t *)g_malloc(bh->block_total_length);
5011 if (queue_element->pd == NULL) {
5012 pcap_src->dropped++;
5013 g_free(queue_element);
5014 return;
5016 memcpy(queue_element->pd, pd, bh->block_total_length);
5017 g_async_queue_lock(pcap_queue);
5018 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
5019 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
5020 limit_reached = false;
5021 g_async_queue_push_unlocked(pcap_queue, queue_element);
5022 pcap_queue_bytes += bh->block_total_length;
5023 pcap_queue_packets += 1;
5024 } else {
5025 limit_reached = true;
5027 g_async_queue_unlock(pcap_queue);
5028 if (limit_reached) {
5029 pcap_src->dropped++;
5030 g_free(queue_element->pd);
5031 g_free(queue_element);
5032 ws_info("Dropped a packet of length %d captured on interface %u.",
5033 bh->block_total_length, pcap_src->interface_id);
5034 } else {
5035 pcap_src->received++;
5036 ws_info("Queued a block of type 0x%08x of length %d captured on interface %u.",
5037 bh->block_type, bh->block_total_length, pcap_src->interface_id);
5039 /* I don't want to hold the mutex over the debug output. So the
5040 output may be wrong */
5041 ws_info("Queue size is now %" PRId64 " bytes (%" PRId64 " packets)",
5042 pcap_queue_bytes, pcap_queue_packets);
5045 static int
5046 set_80211_channel(const char *iface, const char *opt)
5048 uint32_t freq = 0;
5049 int type = -1;
5050 uint32_t center_freq1 = 0;
5051 uint32_t center_freq2 = 0;
5052 int args;
5053 int ret = 0;
5054 char **options = NULL;
5056 options = g_strsplit_set(opt, ",", 4);
5057 for (args = 0; options[args]; args++)
5060 ret = ws80211_init();
5061 if (ret != WS80211_INIT_OK) {
5062 if (ret == WS80211_INIT_NOT_SUPPORTED)
5063 cmdarg_err("Setting 802.11 channels is not supported on this platform");
5064 else
5065 cmdarg_err("Failed to init ws80211: %s", g_strerror(abs(ret)));
5066 ret = 2;
5067 goto out;
5070 if (options[0])
5071 freq = get_nonzero_uint32(options[0], "802.11 channel frequency");
5073 if (args >= 1 && options[1]) {
5074 type = ws80211_str_to_chan_type(options[1]);
5075 if (type == -1) {
5076 cmdarg_err("\"%s\" is not a valid 802.11 channel type", options[1]);
5077 ret = EINVAL;
5078 goto out;
5082 if (args >= 2 && options[2])
5083 center_freq1 = get_nonzero_uint32(options[2], "VHT center frequency");
5085 if (args >= 3 && options[3])
5086 center_freq2 = get_nonzero_uint32(options[3], "VHT center frequency 2");
5088 ret = ws80211_set_freq(iface, freq, type, center_freq1, center_freq2);
5090 if (ret) {
5091 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
5092 ret = 2;
5093 goto out;
5096 if (capture_child)
5097 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
5099 out:
5100 g_strfreev(options);
5101 return ret;
5104 static void
5105 gather_dumpcap_compiled_info(feature_list l)
5107 /* Capture libraries */
5108 gather_caplibs_compile_info(l);
5111 static void
5112 gather_dumpcap_runtime_info(feature_list l)
5114 /* Capture libraries */
5115 gather_caplibs_runtime_info(l);
5118 #define LONGOPT_IFNAME LONGOPT_BASE_APPLICATION+1
5119 #define LONGOPT_IFDESCR LONGOPT_BASE_APPLICATION+2
5120 #define LONGOPT_CAPTURE_COMMENT LONGOPT_BASE_APPLICATION+3
5121 #define LONGOPT_APPLICATION_FLAVOR LONGOPT_BASE_APPLICATION+4
5122 #ifdef _WIN32
5123 #define LONGOPT_SIGNAL_PIPE LONGOPT_BASE_APPLICATION+5
5124 #endif
5126 /* And now our feature presentation... [ fade to music ] */
5128 main(int argc, char *argv[])
5130 char *err_msg;
5131 int opt;
5132 static const struct ws_option long_options[] = {
5133 {"help", ws_no_argument, NULL, 'h'},
5134 {"version", ws_no_argument, NULL, 'v'},
5135 LONGOPT_CAPTURE_COMMON
5136 {"ifname", ws_required_argument, NULL, LONGOPT_IFNAME},
5137 {"ifdescr", ws_required_argument, NULL, LONGOPT_IFDESCR},
5138 {"capture-comment", ws_required_argument, NULL, LONGOPT_CAPTURE_COMMENT},
5139 {"application-flavor", ws_required_argument, NULL, LONGOPT_APPLICATION_FLAVOR},
5140 #ifdef _WIN32
5141 {"signal-pipe", ws_required_argument, NULL, LONGOPT_SIGNAL_PIPE},
5142 #endif
5143 {0, 0, 0, 0 }
5146 bool arg_error = false;
5148 #ifndef _WIN32
5149 struct sigaction action, oldaction;
5150 #endif
5152 bool stats_known;
5153 struct pcap_stat stats = {0};
5154 bool list_interfaces = false;
5155 int caps_queries = 0;
5156 bool print_bpf_code = false;
5157 bool set_chan = false;
5158 char *set_chan_arg = NULL;
5159 bool machine_readable = false;
5160 bool print_statistics = false;
5161 int status, run_once_args = 0;
5162 int i;
5163 unsigned j;
5164 #if defined(__APPLE__) && defined(__LP64__)
5165 struct utsname osinfo;
5166 #endif
5167 GString *str;
5169 /* Set the program name. */
5170 g_set_prgname("dumpcap");
5173 * Determine if dumpcap is being requested to run in a special
5174 * capture_child mode by going thru the command line args to see if
5175 * a -Z is present. (-Z is a hidden option).
5177 * The primary result of running in capture_child mode is that
5178 * all messages sent out on stderr are in a special type/len/string
5179 * format to allow message processing by type. These messages include
5180 * error messages if dumpcap fails to start the operation it was
5181 * requested to do, as well as various "status" messages which are sent
5182 * when an actual capture is in progress, and a "success" message sent
5183 * if dumpcap was requested to perform an operation other than a
5184 * capture.
5186 * Capture_child mode would normally be requested by a parent process
5187 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
5188 * to which dumpcap stderr has been redirected. It might also have
5189 * another pipe to obtain dumpcap stdout output; for operations other
5190 * than a capture, that information is formatted specially for easier
5191 * parsing by the parent process.
5193 * Capture_child mode needs to be determined immediately upon
5194 * startup so that any messages generated by dumpcap in this mode
5195 * (eg: during initialization) will be formatted properly.
5198 for (i=1; i<argc; i++) {
5199 if (strcmp("-Z", argv[i]) == 0) {
5200 capture_child = true;
5201 machine_readable = true; /* request machine-readable output */
5202 i++;
5203 if (i >= argc) {
5204 exit_main(1);
5207 if (strcmp(argv[i], SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
5208 // get_positive_int calls cmdarg_err
5209 if (!ws_strtoi(argv[i], NULL, &sync_pipe_fd) || sync_pipe_fd <= 0) {
5210 exit_main(1);
5212 #ifdef _WIN32
5213 /* On UN*X the fd is the same when we fork + exec.
5214 * On Windows the HANDLE value is the same for inherited
5215 * handles in the child process and the parent, although
5216 * not necessarily the fd value from _open_osfhandle.
5217 * https://learn.microsoft.com/en-us/windows/win32/procthread/inheritance
5218 * Also, "64-bit versions of Windows use 32-bit handles for
5219 * interoperability... only the lower 32 bits are significant,
5220 * so it is safe to truncate... or sign-extend the handle."
5221 * https://learn.microsoft.com/en-us/windows/win32/winprog64/interprocess-communication
5223 /* set output pipe to binary mode, avoid ugly text conversions */
5224 sync_pipe_fd = _open_osfhandle( (intptr_t) sync_pipe_fd, _O_BINARY);
5225 #endif
5230 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
5232 /* Initialize log handler early so we can have proper logging during startup. */
5233 ws_log_init_with_writer(dumpcap_log_writer, vcmdarg_err);
5235 /* Early logging command-line initialization. */
5236 ws_log_parse_args(&argc, argv, vcmdarg_err, 1);
5238 #if DEBUG_CHILD_DUMPCAP
5239 /* Assume that if we're specially compiled with dumpcap debugging
5240 * then we want maximum debugging.
5242 if (capture_child) {
5243 ws_log_set_level(LOG_LEVEL_NOISY);
5246 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
5247 fprintf (stderr, "Unable to open debug log file .\n");
5248 exit (1);
5250 #endif
5252 ws_noisy("Finished log init and parsing command line log arguments");
5254 #ifdef _WIN32
5255 create_app_running_mutex();
5258 * Initialize our DLL search path. MUST be called before LoadLibrary
5259 * or g_module_open.
5261 ws_init_dll_search_path();
5263 /* Load wpcap if possible. Do this before collecting the run-time version information */
5264 load_wpcap();
5265 #endif
5267 /* Initialize the version information. */
5268 ws_init_version_info("Dumpcap", gather_dumpcap_compiled_info,
5269 gather_dumpcap_runtime_info);
5271 #ifdef HAVE_PCAP_REMOTE
5272 #define OPTSTRING_r "r"
5273 #define OPTSTRING_u "u"
5274 #else
5275 #define OPTSTRING_r
5276 #define OPTSTRING_u
5277 #endif
5279 #ifdef HAVE_PCAP_SETSAMPLING
5280 #define OPTSTRING_m "m:"
5281 #else
5282 #define OPTSTRING_m
5283 #endif
5285 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:dghk:" OPTSTRING_m "MN:nPqQ" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
5287 #if defined(__APPLE__) && defined(__LP64__)
5289 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
5290 * a bug workaround - timeouts less than 1 second don't work with libpcap
5291 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
5292 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
5293 * The problem is extremely unlikely to be reintroduced in a future
5294 * release.)
5296 if (uname(&osinfo) == 0) {
5298 * {Mac} OS X/macOS 10.x uses Darwin {x+4}.0.0; 10.x.y uses Darwin
5299 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
5300 * number of 10.0.0, not 10.1.0 - go figure).
5302 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
5303 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
5304 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
5305 need_timeout_workaround = true;
5307 #endif
5309 /* Initialize the pcaps list and IDBs */
5310 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(capture_src *));
5311 global_ld.pcapng_passthrough = false;
5312 global_ld.saved_shb = NULL;
5313 global_ld.saved_idbs = g_array_new(FALSE, TRUE, sizeof(saved_idb_t));
5315 err_msg = ws_init_sockets();
5316 if (err_msg != NULL)
5318 ws_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_ERROR,
5319 "ERROR: %s", err_msg);
5320 g_free(err_msg);
5321 ws_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_ERROR,
5322 "%s", please_report_bug());
5323 exit_main(1);
5326 #ifdef _WIN32
5327 /* Set handler for Ctrl+C key */
5328 SetConsoleCtrlHandler(capture_cleanup_handler, true);
5329 #else
5330 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
5331 and exit. Do the same with SIGPIPE, in case, for example,
5332 we're writing to our standard output and it's a pipe.
5333 Do the same with SIGHUP if it's not being ignored (if we're
5334 being run under nohup, it might be ignored, in which case we
5335 should leave it ignored).
5337 XXX - apparently, Coverity complained that part of action
5338 wasn't initialized. Perhaps it's running on Linux, where
5339 struct sigaction has an ignored "sa_restorer" element and
5340 where "sa_handler" and "sa_sigaction" might not be two
5341 members of a union. */
5342 memset(&action, 0, sizeof(action));
5343 action.sa_handler = capture_cleanup_handler;
5345 * Arrange that system calls not get restarted, because when
5346 * our signal handler returns we don't want to restart
5347 * a call that was waiting for packets to arrive.
5349 action.sa_flags = 0;
5350 sigemptyset(&action.sa_mask);
5351 sigaction(SIGTERM, &action, NULL);
5352 sigaction(SIGINT, &action, NULL);
5353 sigaction(SIGPIPE, &action, NULL);
5354 sigaction(SIGHUP, NULL, &oldaction);
5355 if (oldaction.sa_handler == SIG_DFL)
5356 sigaction(SIGHUP, &action, NULL);
5358 #ifdef SIGINFO
5359 /* Catch SIGINFO and, if we get it and we're capturing in
5360 quiet mode, report the number of packets we've captured. */
5361 action.sa_handler = report_counts_siginfo;
5362 action.sa_flags = SA_RESTART;
5363 sigemptyset(&action.sa_mask);
5364 sigaction(SIGINFO, &action, NULL);
5365 #endif /* SIGINFO */
5366 #endif /* _WIN32 */
5368 /* ----------------------------------------------------------------- */
5369 /* Privilege and capability handling */
5370 /* Cases: */
5371 /* 1. Running not as root or suid root; no special capabilities. */
5372 /* Action: none */
5373 /* */
5374 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
5375 /* Action: none */
5376 /* */
5377 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
5378 /* Action: */
5379 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
5380 /* capabilities; Drop all other capabilities; */
5381 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5382 /* else: after pcap_open_live() in capture_loop_open_input() */
5383 /* drop all capabilities (NET_RAW and NET_ADMIN); */
5384 /* (Note: this means that the process, although logged in */
5385 /* as root, does not have various permissions such as the */
5386 /* ability to bypass file access permissions). */
5387 /* XXX: Should we just leave capabilities alone in this case */
5388 /* so that user gets expected effect that root can do */
5389 /* anything ?? */
5390 /* */
5391 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
5392 /* Action: */
5393 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5394 /* else: after pcap_open_live() in capture_loop_open_input() */
5395 /* drop suid root (set euid=ruid).(ie: keep suid until after */
5396 /* pcap_open_live). */
5397 /* */
5398 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
5399 /* Action: */
5400 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
5401 /* capabilities; Drop all other capabilities; */
5402 /* Drop suid privileges (euid=ruid); */
5403 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5404 /* else: after pcap_open_live() in capture_loop_open_input() */
5405 /* drop all capabilities (NET_RAW and NET_ADMIN). */
5406 /* */
5407 /* XXX: For some Linux versions/distros with capabilities */
5408 /* a 'normal' process with any capabilities cannot be */
5409 /* 'killed' (signaled) from another (same uid) non-privileged */
5410 /* process. */
5411 /* For example: If (non-suid) Wireshark forks a */
5412 /* child suid dumpcap which acts as described here (case 5), */
5413 /* Wireshark will be unable to kill (signal) the child */
5414 /* dumpcap process until the capabilities have been dropped */
5415 /* (after pcap_open_live()). */
5416 /* This behaviour will apparently be changed in the kernel */
5417 /* to allow the kill (signal) in this case. */
5418 /* See the following for details: */
5419 /* https://www.mail-archive.com/ [wrapped] */
5420 /* linux-security-module@vger.kernel.org/msg02913.html */
5421 /* */
5422 /* It is therefore conceivable that if dumpcap somehow hangs */
5423 /* in pcap_open_live or before that wireshark will not */
5424 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
5425 /* In this case, exiting wireshark will kill the child */
5426 /* dumpcap process. */
5427 /* */
5428 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
5429 /* capabilities; Using libcap. Note: capset cmd (which see) */
5430 /* used to assign capabilities to file. */
5431 /* Action: */
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 /* ToDo: -S (stats) should drop privileges/capabilities when no */
5437 /* longer required (similar to capture). */
5438 /* */
5439 /* ----------------------------------------------------------------- */
5441 init_process_policies();
5443 #ifdef HAVE_LIBCAP
5444 /* If 'started with special privileges' (and using libcap) */
5445 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
5446 /* Set euid/egid = ruid/rgid to remove suid privileges */
5447 relinquish_privs_except_capture();
5448 #endif
5450 init_report_failure_message_simple("dumpcap");
5452 /* Set the initial values in the capture options. This might be overwritten
5453 by the command line parameters. */
5454 capture_opts_init(&global_capture_opts, get_interface_list);
5455 /* We always save to a file - if no file was specified, we save to a
5456 temporary file. */
5457 global_capture_opts.saving_to_file = true;
5458 global_capture_opts.has_ring_num_files = true;
5460 /* Pass on capture_child mode for capture_opts */
5461 global_capture_opts.capture_child = capture_child;
5463 /* Now get our args */
5464 while ((opt = ws_getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
5465 switch (opt) {
5466 case 'h': /* Print help and exit */
5467 show_help_header("Capture network packets and dump them into a pcapng or pcap file.");
5468 print_usage(stdout);
5469 exit_main(0);
5470 break;
5471 case 'v': /* Show version and exit */
5472 show_version();
5473 exit_main(0);
5474 break;
5475 case LONGOPT_APPLICATION_FLAVOR:
5476 set_application_flavor(application_name_to_flavor(ws_optarg));
5477 break;
5478 /*** capture option specific ***/
5479 case 'a': /* autostop criteria */
5480 case 'b': /* Ringbuffer option */
5481 case 'c': /* Capture x packets */
5482 case 'f': /* capture filter */
5483 case 'F': /* capture file type */
5484 case 'g': /* enable group read access on file(s) */
5485 case 'i': /* Use interface x */
5486 case LONGOPT_SET_TSTAMP_TYPE: /* Set capture timestamp type */
5487 case 'n': /* Use pcapng format */
5488 case 'p': /* Don't capture in promiscuous mode */
5489 case 'P': /* Use pcap format */
5490 case 's': /* Set the snapshot (capture) length */
5491 case 'w': /* Write to capture file x */
5492 case 'y': /* Set the pcap data link type */
5493 #ifdef HAVE_PCAP_REMOTE
5494 case 'u': /* Use UDP for data transfer */
5495 case 'r': /* Capture own RPCAP traffic too */
5496 case 'A': /* Authentication */
5497 #endif
5498 #ifdef HAVE_PCAP_SETSAMPLING
5499 case 'm': /* Sampling */
5500 #endif
5501 case 'B': /* Buffer size */
5502 case 'I': /* Monitor mode */
5503 case LONGOPT_COMPRESS_TYPE: /* compress type */
5504 case LONGOPT_CAPTURE_TMPDIR: /* capture temp directory */
5505 case LONGOPT_UPDATE_INTERVAL: /* sync pipe update interval */
5506 status = capture_opts_add_opt(&global_capture_opts, opt, ws_optarg);
5507 if (status != 0) {
5508 exit_main(status);
5510 break;
5511 /*** hidden option: Wireshark child mode (using binary output messages) ***/
5512 case LONGOPT_IFNAME:
5513 if (global_capture_opts.ifaces->len > 0) {
5514 interface_options *interface_opts;
5516 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, global_capture_opts.ifaces->len - 1);
5517 interface_opts->ifname = g_strdup(ws_optarg);
5518 } else {
5519 cmdarg_err("--ifname must be specified after a -i option");
5520 exit_main(1);
5522 break;
5523 case LONGOPT_IFDESCR:
5524 if (global_capture_opts.ifaces->len > 0) {
5525 interface_options *interface_opts;
5527 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, global_capture_opts.ifaces->len - 1);
5528 interface_opts->descr = g_strdup(ws_optarg);
5529 } else {
5530 cmdarg_err("--ifdescr must be specified after a -i option");
5531 exit_main(1);
5533 break;
5534 case LONGOPT_CAPTURE_COMMENT: /* capture comment */
5535 if (capture_comments == NULL) {
5536 capture_comments = g_ptr_array_new_with_free_func(g_free);
5538 g_ptr_array_add(capture_comments, g_strdup(ws_optarg));
5539 break;
5540 case 'Z':
5541 capture_child = true;
5543 * Handled above
5545 break;
5546 #ifdef _WIN32
5547 case LONGOPT_SIGNAL_PIPE:
5548 if (!capture_child) {
5549 /* We have already checked for -Z at the very beginning. */
5550 cmdarg_err("--signal-pipe may only be specified with -Z");
5551 exit_main(1);
5554 * ws_optarg = the control ID, aka the PPID, currently used for the
5555 * signal pipe name.
5557 if (strcmp(ws_optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
5558 sig_pipe_name = ws_strdup_printf(SIGNAL_PIPE_FORMAT, ws_optarg);
5559 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
5560 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
5562 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
5563 ws_info("Signal pipe: Unable to open %s. Dead parent?",
5564 sig_pipe_name);
5565 exit_main(1);
5568 break;
5569 #endif
5570 case 'q': /* Quiet */
5571 quiet = true;
5572 break;
5573 case 'Q': /* Really quiet */
5574 quiet = true;
5575 really_quiet = true;
5576 break;
5577 case 't':
5578 use_threads = true;
5579 break;
5580 /*** all non capture option specific ***/
5581 case 'D': /* Print a list of capture devices and exit */
5582 if (!list_interfaces && !caps_queries & !print_statistics) {
5583 run_once_args++;
5585 list_interfaces = true;
5586 break;
5587 case 'L': /* Print list of link-layer types and exit */
5588 if (!list_interfaces && !caps_queries & !print_statistics) {
5589 run_once_args++;
5591 caps_queries |= CAPS_QUERY_LINK_TYPES;
5592 break;
5593 case LONGOPT_LIST_TSTAMP_TYPES:
5594 if (!list_interfaces && !caps_queries & !print_statistics) {
5595 run_once_args++;
5597 caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
5598 break;
5599 case 'd': /* Print BPF code for capture filter and exit */
5600 if (!print_bpf_code) {
5601 print_bpf_code = true;
5602 run_once_args++;
5604 break;
5605 case 'S': /* Print interface statistics once a second */
5606 if (!list_interfaces && !caps_queries & !print_statistics) {
5607 run_once_args++;
5609 print_statistics = true;
5610 break;
5611 case 'k': /* Set wireless channel */
5612 if (!set_chan) {
5613 set_chan = true;
5614 set_chan_arg = ws_optarg;
5615 run_once_args++;
5616 } else {
5617 cmdarg_err("Only one -k flag may be specified");
5618 arg_error = true;
5620 break;
5621 case 'M': /* For -D, -L, and -S, print machine-readable output */
5622 machine_readable = true;
5623 break;
5624 case 'C':
5625 pcap_queue_byte_limit = get_positive_int(ws_optarg, "byte_limit");
5626 break;
5627 case 'N':
5628 pcap_queue_packet_limit = get_positive_int(ws_optarg, "packet_limit");
5629 break;
5630 default:
5631 cmdarg_err("Invalid Option: %s", argv[ws_optind-1]);
5632 /* FALLTHROUGH */
5633 case '?': /* Bad flag - print usage message */
5634 arg_error = true;
5635 break;
5638 if (!arg_error) {
5639 argc -= ws_optind;
5640 argv += ws_optind;
5641 if (argc >= 1) {
5642 /* user specified file name as regular command-line argument */
5643 /* XXX - use it as the capture file name (or something else)? */
5644 argc--;
5645 argv++;
5647 if (argc != 0) {
5649 * Extra command line arguments were specified; complain.
5650 * XXX - interpret as capture filter, as tcpdump and tshark do?
5652 cmdarg_err("Invalid argument: %s", argv[0]);
5653 arg_error = true;
5657 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
5658 use_threads = true;
5660 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
5661 /* Use some default if the user hasn't specified some */
5662 /* XXX: Are these defaults good enough? */
5663 pcap_queue_byte_limit = 1000 * 1000;
5664 pcap_queue_packet_limit = 1000;
5666 if (arg_error) {
5667 if (ws_optopt == 'F') {
5668 capture_opts_list_file_types();
5669 exit_main(1);
5671 print_usage(stderr);
5672 exit_main(1);
5675 if (run_once_args > 1) {
5676 cmdarg_err("Only one of -D, -L, -d, -k or -S may be supplied.");
5677 exit_main(1);
5678 } else if (run_once_args == 1) {
5679 /* We're supposed to print some information, rather than
5680 to capture traffic; did they specify a ring buffer option? */
5681 if (global_capture_opts.multi_files_on) {
5682 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
5683 exit_main(1);
5685 } else {
5686 /* We're supposed to capture traffic; */
5688 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
5689 if (global_capture_opts.ifaces->len > 1) {
5690 use_threads = true;
5691 global_capture_opts.use_pcapng = true;
5694 if (capture_comments &&
5695 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
5696 /* XXX - for ringbuffer, should we apply the comments to each file? */
5697 cmdarg_err("Capture comments can only be set if we capture into a single pcapng file.");
5698 exit_main(1);
5701 /* Was the ring buffer option specified and, if so, does it make sense? */
5702 if (global_capture_opts.multi_files_on) {
5703 /* Ring buffer works only under certain conditions:
5704 a) ring buffer does not work with temporary files;
5705 b) it makes no sense to enable the ring buffer if the maximum
5706 file size is set to "infinite". */
5707 if (global_capture_opts.save_file == NULL) {
5708 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
5709 global_capture_opts.multi_files_on = false;
5711 if (!global_capture_opts.has_autostop_filesize &&
5712 !global_capture_opts.has_file_duration &&
5713 !global_capture_opts.has_file_interval &&
5714 !global_capture_opts.has_file_packets) {
5715 cmdarg_err("Ring buffer requested, but no maximum capture file size, duration "
5716 "interval, or packets were specified.");
5717 #if 0
5718 /* XXX - this must be redesigned as the conditions changed */
5719 global_capture_opts.multi_files_on = false;
5720 #endif
5722 if (global_capture_opts.has_file_duration && global_capture_opts.has_file_interval) {
5723 cmdarg_err("Ring buffer file duration and interval can't be used at the same time.");
5724 exit_main(1);
5730 * "-D" requires no interface to be selected; it's supposed to list
5731 * all interfaces.
5733 if (list_interfaces) {
5734 /* Get the list of interfaces */
5735 GList *if_list;
5736 int err;
5737 char *err_str;
5739 if_list = get_interface_list(&err, &err_str);
5740 if (if_list == NULL) {
5741 if (err == 0) {
5743 * If we're being run by another program, just give them
5744 * an empty list of interfaces, don't report this as
5745 * an error; that lets them decide whether to report
5746 * this as an error or not.
5748 if (!machine_readable) {
5749 cmdarg_err("There are no interfaces on which a capture can be done");
5750 exit_main(2);
5752 } else {
5753 cmdarg_err("%s", err_str);
5754 g_free(err_str);
5755 exit_main(2);
5759 if (!machine_readable) {
5760 status = 0;
5761 capture_opts_print_interfaces(if_list);
5764 if (caps_queries) {
5765 if_info_t *if_info;
5766 interface_options *interface_opts;
5767 cap_device_open_status open_status;
5768 char *open_status_str;
5769 for (GList *if_entry = if_list; if_entry != NULL; if_entry = g_list_next(if_entry)) {
5770 if_info = (if_info_t *)if_entry->data;
5773 * XXX - If on the command line we had the options -i <interface> -I,
5774 * we should retrieve the link-types for the interface in monitor mode.
5775 * We've already copied that information to global_capture_opts, but
5776 * the below statement wipes it away.
5778 interface_opts = interface_opts_from_if_info(&global_capture_opts, if_info);
5780 if_info->caps = get_if_capabilities(interface_opts, &open_status, &open_status_str);
5782 if (!machine_readable) {
5783 if (if_info->caps == NULL) {
5784 cmdarg_err("The capabilities of the capture device "
5785 "\"%s\" could not be obtained (%s).\n%s",
5786 interface_opts->name, open_status_str,
5787 get_pcap_failure_secondary_error_message(open_status, open_status_str));
5788 g_free(open_status_str);
5789 /* Break after one error, as when printing selected
5790 * interface capabilities. (XXX: We could print all
5791 * the primary status strings, and only the unique
5792 * set of secondary messages / suggestions; printing
5793 * the same long secondary error is a lot.)
5795 interface_opts_free(interface_opts);
5796 g_free(interface_opts);
5797 break;
5798 } else {
5799 status = capture_opts_print_if_capabilities(if_info->caps, interface_opts, caps_queries);
5800 if (status != 0) {
5801 interface_opts_free(interface_opts);
5802 g_free(interface_opts);
5803 break;
5806 } else {
5807 if (if_info->caps == NULL) {
5808 if_info->caps = g_new0(if_capabilities_t, 1);
5809 if_info->caps->primary_msg = open_status_str;
5810 if_info->caps->secondary_msg = get_pcap_failure_secondary_error_message(open_status, open_status_str);
5812 if_info->caps->status = open_status;
5815 interface_opts_free(interface_opts);
5816 g_free(interface_opts);
5820 if (machine_readable) {
5821 status = print_machine_readable_interfaces(if_list, caps_queries, print_statistics);
5823 free_interface_list(if_list);
5824 if (!print_statistics) {
5825 exit_main(status);
5830 * "-S" requires no interface to be selected; it gives statistics
5831 * for all interfaces.
5833 if (print_statistics) {
5834 status = print_statistics_loop(machine_readable);
5835 exit_main(status);
5838 if (set_chan) {
5839 interface_options *interface_opts;
5841 if (global_capture_opts.ifaces->len != 1) {
5842 cmdarg_err("Need one interface");
5843 exit_main(2);
5846 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
5847 status = set_80211_channel(interface_opts->name, set_chan_arg);
5848 exit_main(status);
5852 * "-L", "-d", and capturing act on a particular interface, so we have to
5853 * have an interface; if none was specified, pick a default.
5855 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
5856 if (status != 0) {
5857 /* cmdarg_err() already called .... */
5858 exit_main(status);
5861 if (caps_queries) {
5862 /* Get the list of link-layer and/or timestamp types for the capture device. */
5863 if_capabilities_t *caps;
5864 cap_device_open_status open_status;
5865 char *open_status_str;
5866 unsigned ii;
5868 if (machine_readable) {
5869 json_dumper dumper = {
5870 .output_file = stdout,
5871 .flags = JSON_DUMPER_FLAGS_NO_DEBUG,
5872 // Don't abort on failure
5874 json_dumper_begin_array(&dumper);
5875 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
5876 interface_options *interface_opts;
5878 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, ii);
5880 json_dumper_begin_object(&dumper);
5881 json_dumper_set_member_name(&dumper, interface_opts->name);
5883 json_dumper_begin_object(&dumper);
5885 open_status = CAP_DEVICE_OPEN_NO_ERR;
5886 caps = get_if_capabilities(interface_opts, &open_status, &open_status_str);
5887 if (caps == NULL) {
5888 json_dumper_set_member_name(&dumper, "status");
5889 json_dumper_value_anyf(&dumper, "%i", open_status);
5890 json_dumper_set_member_name(&dumper, "primary_msg");
5891 json_dumper_value_string(&dumper, open_status_str);
5892 g_free(open_status_str);
5893 } else {
5894 caps->status = open_status;
5895 print_machine_readable_if_capabilities(&dumper, caps, caps_queries);
5896 free_if_capabilities(caps);
5898 json_dumper_end_object(&dumper);
5899 json_dumper_end_object(&dumper);
5901 json_dumper_end_array(&dumper);
5902 if (json_dumper_finish(&dumper)) {
5903 status = 0;
5904 if (capture_child) {
5905 /* Let our parent know we succeeded. */
5906 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
5908 } else {
5909 status = 2;
5910 if (capture_child) {
5911 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, "Unexpected JSON error", "");
5914 } else {
5915 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
5916 interface_options *interface_opts;
5918 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, ii);
5920 caps = get_if_capabilities(interface_opts, &open_status, &open_status_str);
5921 if (caps == NULL) {
5922 if (capture_child) {
5923 char *error_msg = ws_strdup_printf("The capabilities of the capture device "
5924 "\"%s\" could not be obtained (%s)",
5925 interface_opts->name, open_status_str);
5926 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, error_msg,
5927 get_pcap_failure_secondary_error_message(open_status, open_status_str));
5928 g_free(error_msg);
5930 else {
5931 cmdarg_err("The capabilities of the capture device "
5932 "\"%s\" could not be obtained (%s).\n%s",
5933 interface_opts->name, open_status_str,
5934 get_pcap_failure_secondary_error_message(open_status, open_status_str));
5936 g_free(open_status_str);
5937 exit_main(2);
5940 /* XXX: We might want to print also the interface name */
5941 status = capture_opts_print_if_capabilities(caps,
5942 interface_opts,
5943 caps_queries);
5944 free_if_capabilities(caps);
5945 if (status != 0)
5946 break;
5949 exit_main(status);
5952 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
5953 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5954 interface_options *interface_opts;
5956 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5957 if (interface_opts->timestamp_type) {
5958 interface_opts->timestamp_type_id = pcap_tstamp_type_name_to_val(interface_opts->timestamp_type);
5959 if (interface_opts->timestamp_type_id < 0) {
5960 cmdarg_err("Invalid argument to option: --time-stamp-type=%s", interface_opts->timestamp_type);
5961 exit_main(1);
5965 #endif
5967 /* We're supposed to do a capture, or print the BPF code for a filter. */
5969 /* Let the user know what interfaces were chosen. */
5970 if (capture_child) {
5971 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5972 interface_options *interface_opts;
5974 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5975 ws_debug("Interface: %s\n", interface_opts->name);
5977 } else {
5978 str = g_string_new("");
5979 #ifdef _WIN32
5980 if (global_capture_opts.ifaces->len < 2)
5981 #else
5982 if (global_capture_opts.ifaces->len < 4)
5983 #endif
5985 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5986 interface_options *interface_opts;
5988 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5989 if (j > 0) {
5990 if (global_capture_opts.ifaces->len > 2) {
5991 g_string_append_printf(str, ",");
5993 g_string_append_printf(str, " ");
5994 if (j == global_capture_opts.ifaces->len - 1) {
5995 g_string_append_printf(str, "and ");
5998 if (interface_opts->ifname != NULL) {
6000 * Re-generate the display name based on the strins
6001 * we were handed.
6003 g_free(interface_opts->display_name);
6004 if (interface_opts->descr != NULL) {
6005 #ifdef _WIN32
6006 interface_opts->display_name = ws_strdup_printf("%s",
6007 interface_opts->descr);
6008 #else
6009 interface_opts->display_name = ws_strdup_printf("%s: %s",
6010 interface_opts->descr, interface_opts->ifname);
6011 #endif
6012 } else {
6013 interface_opts->display_name = ws_strdup_printf("%s",
6014 interface_opts->ifname);
6017 g_string_append_printf(str, "'%s'", interface_opts->display_name);
6019 } else {
6020 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
6022 if (!really_quiet)
6023 fprintf(stderr, "Capturing on %s\n", str->str);
6024 g_string_free(str, TRUE);
6027 /* Process the snapshot length, as that affects the generated BPF code. */
6028 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
6030 if (print_bpf_code) {
6031 show_filter_code(&global_capture_opts);
6032 exit_main(0);
6035 /* We're supposed to do a capture. Process the ring buffer arguments. */
6036 capture_opts_trim_ring_num_files(&global_capture_opts);
6038 /* flush stderr prior to starting the main capture loop */
6039 fflush(stderr);
6041 /* Now start the capture. */
6042 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == true) {
6043 /* capture ok */
6044 exit_main(0);
6045 } else {
6046 /* capture failed */
6047 exit_main(1);
6049 return 0; /* never here, make compiler happy */
6052 static void
6053 dumpcap_log_writer(const char *domain, enum ws_log_level level,
6054 const char *file, long line, const char *func,
6055 const char *fatal_msg _U_,
6056 ws_log_manifest_t *mft,
6057 const char *user_format, va_list user_ap,
6058 void *user_data _U_)
6060 if (ws_log_msg_is_active(domain, level)) {
6061 /* log messages go to stderr or */
6062 /* to parent especially formatted if dumpcap running as child. */
6063 #ifdef DEBUG_CHILD_DUMPCAP
6064 va_list user_ap_copy;
6065 va_copy(user_ap_copy, user_ap);
6066 #endif
6067 if (capture_child) {
6068 /* Format the log mesage as the numeric level, followed
6069 * by a colon and then a string matching the standard log
6070 * string. In the future perhaps we serialize file, line,
6071 * and func (which can be NULL) instead.
6073 GString *msg = g_string_new(NULL);
6074 g_string_append_printf(msg, "%u:", level);
6075 if (file != NULL) {
6076 g_string_append_printf(msg, "%s", file);
6077 if (line >= 0) {
6078 g_string_append_printf(msg, ":%ld", line);
6081 g_string_append(msg, " --");
6082 if (func != NULL) {
6083 g_string_append_printf(msg, " %s():", func);
6085 g_string_append_c(msg, ' ');
6086 g_string_append_vprintf(msg, user_format, user_ap);
6088 sync_pipe_write_string_msg(sync_pipe_fd, SP_LOG_MSG, msg->str);
6089 g_string_free(msg, TRUE);
6090 } else {
6091 ws_log_console_writer(domain, level, file, line, func, mft, user_format, user_ap);
6093 #ifdef DEBUG_CHILD_DUMPCAP
6094 ws_log_file_writer(debug_log, domain, level, file, line, func, mft, user_format, user_ap_copy);
6095 va_end(user_ap_copy);
6096 #endif
6101 /****************************************************************************************************************/
6102 /* indication report routines */
6105 static void
6106 report_packet_count(unsigned int packet_count)
6108 static unsigned int count = 0;
6110 if (capture_child) {
6111 ws_debug("Packets: %u", packet_count);
6112 sync_pipe_write_uint_msg(sync_pipe_fd, SP_PACKET_COUNT, packet_count);
6113 } else {
6114 count += packet_count;
6115 fprintf(stderr, "\rPackets: %u ", count);
6116 /* stderr could be line buffered */
6117 fflush(stderr);
6121 static void
6122 report_new_capture_file(const char *filename)
6124 if (capture_child) {
6125 ws_debug("File: %s", filename);
6126 if (global_ld.pcapng_passthrough) {
6127 /* Save filename for sending SP_FILE to capture parent after SHB is passed-through */
6128 ws_debug("Delaying SP_FILE until first SHB");
6129 report_capture_filename = filename;
6130 } else {
6131 sync_pipe_write_string_msg(sync_pipe_fd, SP_FILE, filename);
6133 } else {
6134 #ifdef SIGINFO
6136 * Prevent a SIGINFO handler from writing to the standard error
6137 * while we're doing so; instead, have it just set a flag telling
6138 * us to print that information when we're done.
6140 infodelay = true;
6141 #endif /* SIGINFO */
6142 if (!really_quiet) {
6143 fprintf(stderr, "File: %s\n", filename);
6144 /* stderr could be line buffered */
6145 fflush(stderr);
6148 #ifdef SIGINFO
6150 * Allow SIGINFO handlers to write.
6152 infodelay = false;
6155 * If a SIGINFO handler asked us to write out capture counts, do so.
6157 if (infoprint)
6158 report_counts_for_siginfo();
6159 #endif /* SIGINFO */
6163 static void
6164 report_cfilter_error(capture_options *capture_opts, unsigned i, const char *errmsg)
6166 interface_options *interface_opts;
6167 char tmp[MSG_MAX_LENGTH+1+6];
6169 if (i < capture_opts->ifaces->len) {
6170 if (capture_child) {
6171 snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
6172 ws_debug("Capture filter error: %s", errmsg);
6173 sync_pipe_write_string_msg(sync_pipe_fd, SP_BAD_FILTER, tmp);
6174 } else {
6176 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
6177 * the error message below.
6179 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
6180 cmdarg_err(
6181 "Invalid capture filter \"%s\" for interface '%s'.\n"
6182 "\n"
6183 "That string isn't a valid capture filter (%s).\n"
6184 "See the User's Guide for a description of the capture filter syntax.",
6185 interface_opts->cfilter, interface_opts->name, errmsg);
6190 static void
6191 report_capture_error(const char *error_msg, const char *secondary_error_msg)
6193 if (capture_child) {
6194 ws_debug("Primary Error: %s", error_msg);
6195 ws_debug("Secondary Error: %s", secondary_error_msg);
6196 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, error_msg, secondary_error_msg);
6197 } else {
6198 cmdarg_err("%s", error_msg);
6199 if (secondary_error_msg[0] != '\0')
6200 cmdarg_err_cont("%s", secondary_error_msg);
6204 static void
6205 report_packet_drops(uint32_t received, uint32_t pcap_drops, uint32_t drops, uint32_t flushed, uint32_t ps_ifdrop, char *name)
6207 uint32_t total_drops = pcap_drops + drops + flushed;
6209 if (capture_child) {
6210 char* tmp = ws_strdup_printf("%u:%s", total_drops, name);
6212 ws_debug("Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
6213 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
6214 sync_pipe_write_string_msg(sync_pipe_fd, SP_DROPS, tmp);
6215 g_free(tmp);
6216 } else {
6217 if (!really_quiet) {
6218 fprintf(stderr,
6219 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
6220 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
6221 received ? 100.0 * received / (received + total_drops) : 0.0);
6222 /* stderr could be line buffered */
6223 fflush(stderr);
6229 /************************************************************************************************/
6230 /* signal_pipe handling */
6233 #ifdef _WIN32
6234 static bool
6235 signal_pipe_check_running(void)
6237 /* any news from our parent? -> just stop the capture */
6238 DWORD avail = 0;
6239 bool result;
6241 /* if we are running standalone, no check required */
6242 if (!capture_child) {
6243 return true;
6246 if (!sig_pipe_name || !sig_pipe_handle) {
6247 /* This shouldn't happen */
6248 ws_info("Signal pipe: No name or handle");
6249 return false;
6253 * XXX - We should have the process ID of the parent (from the "-Z" flag)
6254 * at this point. Should we check to see if the parent is still alive,
6255 * e.g. by using OpenProcess?
6258 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
6260 if (!result || avail > 0) {
6261 /* peek failed or some bytes really available */
6262 /* (if not piping from stdin this would fail) */
6263 ws_info("Signal pipe: Stop capture: %s", sig_pipe_name);
6264 ws_debug("Signal pipe: %s (%p) result: %u avail: %lu", sig_pipe_name,
6265 sig_pipe_handle, result, avail);
6266 return false;
6267 } else {
6268 /* pipe ok and no bytes available */
6269 return true;
6272 #endif
6275 * Editor modelines - https://www.wireshark.org/tools/modelines.html
6277 * Local variables:
6278 * c-basic-offset: 4
6279 * tab-width: 8
6280 * indent-tabs-mode: nil
6281 * End:
6283 * vi: set shiftwidth=4 tabstop=8 expandtab:
6284 * :indentSize=4:tabSize=8:noTabs=true: