TODO epan/dissectors/asn1/kerberos/packet-kerberos-template.c new GSS flags
[wireshark-sm.git] / dumpcap.c
blob9cabf06f4243d32b05128ab98afb4582cf00521e
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 FILE *pdh;
362 int save_file_fd;
363 char *io_buffer; /**< Our IO buffer if we increase the size from the standard size */
364 uint64_t bytes_written; /**< Bytes written for the current file. */
365 /* autostop conditions */
366 int packets_written; /**< Packets written for the current file. */
367 int file_count;
368 /* ring buffer conditions */
369 GTimer *file_duration_timer;
370 time_t next_interval_time;
371 int interval_s;
372 } loop_data;
374 typedef struct _pcap_queue_element {
375 capture_src *pcap_src;
376 union {
377 struct pcap_pkthdr phdr;
378 pcapng_block_header_t bh;
379 } u;
380 uint8_t *pd;
381 } pcap_queue_element;
384 * This needs to be static, so that the SIGINT handler can clear the "go"
385 * flag and for saved_shb_idb_lock.
387 static loop_data global_ld;
390 * Timeout, in milliseconds, for reads from the stream of captured packets
391 * from a capture device.
393 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
394 * 64-bit applications, with sub-second timeouts not to work. The bug is
395 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
397 #if defined(__APPLE__) && defined(__LP64__)
398 static bool need_timeout_workaround;
400 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
401 #else
402 #define CAP_READ_TIMEOUT 250
403 #endif
406 * Timeout, in microseconds, for reads from the stream of captured packets
407 * from a pipe. Pipes don't have the same problem that BPF devices do
408 * in Mac OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
409 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
410 * of the offending versions of Snow Leopard.
412 * On Windows this value is converted to milliseconds and passed to
413 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
414 * will return immediately.
416 #if defined(_WIN32)
417 #define PIPE_READ_TIMEOUT 100000
418 #else
419 #define PIPE_READ_TIMEOUT 250000
420 #endif
422 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
424 static void
425 dumpcap_log_writer(const char *domain, enum ws_log_level level,
426 const char *file, long line, const char *func,
427 const char *fatal_msg, ws_log_manifest_t *mft,
428 const char *user_format, va_list user_ap,
429 void *user_data);
431 /* capture related options */
432 static capture_options global_capture_opts;
433 static GPtrArray *capture_comments;
434 static bool quiet;
435 static bool really_quiet;
436 static bool use_threads;
437 static uint64_t start_time;
439 static void capture_loop_write_packet_cb(uint8_t *pcap_src_p, const struct pcap_pkthdr *phdr,
440 const uint8_t *pd);
441 static void capture_loop_queue_packet_cb(uint8_t *pcap_src_p, const struct pcap_pkthdr *phdr,
442 const uint8_t *pd);
443 static void capture_loop_write_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, uint8_t *pd);
444 static void capture_loop_queue_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, uint8_t *pd);
445 static void capture_loop_get_errmsg(char *errmsg, size_t errmsglen,
446 char *secondary_errmsg,
447 size_t secondary_errmsglen,
448 const char *fname, int err,
449 bool is_close);
451 WS_NORETURN static void exit_main(int err);
453 static void report_new_capture_file(const char *filename);
454 static void report_packet_count(unsigned int packet_count);
455 static void report_packet_drops(uint32_t received, uint32_t pcap_drops, uint32_t drops, uint32_t flushed, uint32_t ps_ifdrop, char *name);
456 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
457 static void report_cfilter_error(capture_options *capture_opts, unsigned i, const char *errmsg);
459 #define MSG_MAX_LENGTH 4096
461 static void
462 print_usage(FILE *output)
464 fprintf(output, "\nUsage: dumpcap [options] ...\n");
465 fprintf(output, "\n");
466 fprintf(output, "Capture interface:\n");
467 fprintf(output, " -i <interface>, --interface <interface>\n");
468 fprintf(output, " name or idx of interface (def: first non-loopback)\n"
469 #ifdef HAVE_PCAP_REMOTE
470 " or for remote capturing, use one of these formats:\n"
471 " rpcap://<host>/<interface>\n"
472 #else
473 " or for remote capturing, use this format:\n"
474 #endif
475 " TCP@<host>:<port>\n");
476 fprintf(output, " --ifname <name> name to use in the capture file for a pipe from which\n");
477 fprintf(output, " we're capturing\n");
478 fprintf(output, " --ifdescr <description>\n");
479 fprintf(output, " description to use in the capture file for a pipe\n");
480 fprintf(output, " from which we're capturing\n");
481 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
482 fprintf(output, " -s <snaplen>, --snapshot-length <snaplen>\n");
483 #ifdef HAVE_PCAP_CREATE
484 fprintf(output, " packet snapshot length (def: appropriate maximum)\n");
485 #else
486 fprintf(output, " packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
487 #endif
488 fprintf(output, " -p, --no-promiscuous-mode\n");
489 fprintf(output, " don't capture in promiscuous mode\n");
490 #ifdef HAVE_PCAP_CREATE
491 fprintf(output, " -I, --monitor-mode capture in monitor mode, if available\n");
492 #endif
493 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
494 fprintf(output, " -B <buffer size>, --buffer-size <buffer size>\n");
495 fprintf(output, " size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
496 #endif
497 fprintf(output, " -y <link type>, --linktype <link type>\n");
498 fprintf(output, " link layer type (def: first appropriate)\n");
499 fprintf(output, " --time-stamp-type <type> timestamp method for interface\n");
500 fprintf(output, " -D, --list-interfaces print list of interfaces and exit\n");
501 fprintf(output, " -L, --list-data-link-types\n");
502 fprintf(output, " print list of link-layer types of iface and exit\n");
503 fprintf(output, " --list-time-stamp-types print list of timestamp types for iface and exit\n");
504 fprintf(output, " --update-interval interval between updates with new packets, in milliseconds (def: %dms)\n", DEFAULT_UPDATE_INTERVAL);
505 fprintf(output, " -d print generated BPF code for capture filter\n");
506 fprintf(output, " -k <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
507 fprintf(output, " set channel on wifi interface\n");
508 fprintf(output, " -S print statistics for each interface once per second\n");
509 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
510 fprintf(output, "\n");
511 #ifdef HAVE_PCAP_REMOTE
512 fprintf(output, "RPCAP options:\n");
513 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
514 fprintf(output, " -u use UDP for RPCAP data transfer\n");
515 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
516 #ifdef HAVE_PCAP_SETSAMPLING
517 fprintf(output, " -m <sampling type> use packet sampling\n");
518 fprintf(output, " count:NUM - capture one packet of every NUM\n");
519 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
520 #endif
521 #endif
522 fprintf(output, "Stop conditions:\n");
523 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
524 fprintf(output, " -a <autostop cond.> ..., --autostop <autostop cond.> ...\n");
525 fprintf(output, " duration:NUM - stop after NUM seconds\n");
526 fprintf(output, " filesize:NUM - stop this file after NUM kB\n");
527 fprintf(output, " files:NUM - stop after NUM files\n");
528 fprintf(output, " packets:NUM - stop after NUM packets\n");
529 /*fprintf(output, "\n");*/
530 fprintf(output, "Output (files):\n");
531 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
532 fprintf(output, " -g enable group read access on the output file(s)\n");
533 fprintf(output, " -b <ringbuffer opt.> ..., --ring-buffer <ringbuffer opt.>\n");
534 fprintf(output, " duration:NUM - switch to next file after NUM secs\n");
535 fprintf(output, " filesize:NUM - switch to next file after NUM kB\n");
536 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
537 fprintf(output, " packets:NUM - ringbuffer: replace after NUM packets\n");
538 fprintf(output, " interval:NUM - switch to next file when the time is\n");
539 fprintf(output, " an exact multiple of NUM secs\n");
540 fprintf(output, " printname:FILE - print filename to FILE when written\n");
541 fprintf(output, " (can use 'stdout' or 'stderr')\n");
542 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
543 fprintf(output, " -P use libpcap format instead of pcapng\n");
544 fprintf(output, " --capture-comment <comment>\n");
545 fprintf(output, " add a capture comment to the output file\n");
546 fprintf(output, " (only for pcapng)\n");
547 fprintf(output, " --temp-dir <directory> write temporary files to this directory\n");
548 fprintf(output, " (default: %s)\n", g_get_tmp_dir());
549 fprintf(output, "\n");
551 ws_log_print_usage(output);
552 fprintf(output, "\n");
554 fprintf(output, "Miscellaneous:\n");
555 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
556 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
557 fprintf(output, " within dumpcap\n");
558 fprintf(output, " -t use a separate thread per interface\n");
559 fprintf(output, " -q don't report packet capture counts\n");
560 fprintf(output, " --application-flavor <flavor>\n");
561 fprintf(output, " set the application flavor\n");
562 fprintf(output, " -v, --version print version information and exit\n");
563 fprintf(output, " -h, --help display this help and exit\n");
564 fprintf(output, "\n");
565 #ifdef __linux__
566 fprintf(output, "Dumpcap can benefit from an enabled BPF JIT compiler if available.\n");
567 fprintf(output, "You might want to enable it by executing:\n");
568 fprintf(output, " \"echo 1 > /proc/sys/net/core/bpf_jit_enable\"\n");
569 fprintf(output, "Note that this can make your system less secure!\n");
570 fprintf(output, "\n");
571 #endif
572 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
573 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
574 fprintf(output, "\n");
575 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
579 * Report an error in command-line arguments.
580 * If we're a capture child, send a message back to the parent, otherwise
581 * just print it.
583 static void
584 dumpcap_cmdarg_err(const char *fmt, va_list ap)
586 if (capture_child) {
587 char *msg;
588 /* Generate a 'special format' message back to parent */
589 msg = ws_strdup_vprintf(fmt, ap);
590 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, msg, "");
591 g_free(msg);
592 } else {
593 fprintf(stderr, "dumpcap: ");
594 vfprintf(stderr, fmt, ap);
595 fprintf(stderr, "\n");
600 * Report additional information for an error in command-line arguments.
601 * If we're a capture child, send a message back to the parent, otherwise
602 * just print it.
604 static void
605 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
607 if (capture_child) {
608 char *msg;
609 msg = ws_strdup_vprintf(fmt, ap);
610 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, msg, "");
611 g_free(msg);
612 } else {
613 vfprintf(stderr, fmt, ap);
614 fprintf(stderr, "\n");
618 #ifdef HAVE_LIBCAP
619 static void
620 /* see 'man cap_to_text()' for explanation of output */
621 /* '=' means 'all= ' ie: no capabilities */
622 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
623 /* .... */
624 print_caps(const char *pfx) {
625 if (ws_log_msg_is_active(WS_LOG_DOMAIN, LOG_LEVEL_NOISY)) {
626 cap_t caps = cap_get_proc();
627 char *caps_text = cap_to_text(caps, NULL);
628 ws_noisy("%s: EUID: %d Capabilities: %s", pfx, geteuid(), caps_text);
629 cap_free(caps_text);
630 cap_free(caps);
634 static void
635 relinquish_all_capabilities(void)
637 /* Drop any and all capabilities this process may have. */
638 /* Allowed whether or not process has any privileges. */
639 cap_t caps = cap_init(); /* all capabilities initialized to off */
640 print_caps("Pre-clear");
641 if (cap_set_proc(caps)) {
642 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
644 print_caps("Post-clear");
645 cap_free(caps);
647 #endif
649 static void
650 get_capture_device_open_failure_messages(cap_device_open_status open_status,
651 const char *open_status_str,
652 const char *iface,
653 char *errmsg, size_t errmsg_len,
654 char *secondary_errmsg,
655 size_t secondary_errmsg_len)
657 switch (open_status) {
659 case CAP_DEVICE_OPEN_ERROR_NO_SUCH_DEVICE:
660 snprintf(errmsg, errmsg_len,
661 "There is no device named \"%s\".\n(%s)",
662 iface, open_status_str);
663 break;
665 case CAP_DEVICE_OPEN_ERROR_RFMON_NOTSUP:
666 snprintf(errmsg, errmsg_len,
667 "Capturing in monitor mode is not supported on device \"%s\".\n(%s)",
668 iface, open_status_str);
669 break;
671 case CAP_DEVICE_OPEN_ERROR_PERM_DENIED:
672 snprintf(errmsg, errmsg_len,
673 "You do not have permission to capture on device \"%s\".\n(%s)",
674 iface, open_status_str);
675 break;
677 case CAP_DEVICE_OPEN_ERROR_IFACE_NOT_UP:
678 snprintf(errmsg, errmsg_len,
679 "Device \"%s\" is not up.\n(%s)",
680 iface, open_status_str);
681 break;
683 case CAP_DEVICE_OPEN_ERROR_PROMISC_PERM_DENIED:
684 snprintf(errmsg, errmsg_len,
685 "You do not have permission to capture in promiscuous mode on device \"%s\".\n(%s)",
686 iface, open_status_str);
687 break;
689 case CAP_DEVICE_OPEN_ERROR_OTHER:
690 default:
691 snprintf(errmsg, errmsg_len,
692 "The capture session could not be initiated on capture device \"%s\".\n(%s)",
693 iface, open_status_str);
694 break;
696 snprintf(secondary_errmsg, secondary_errmsg_len, "%s",
697 get_pcap_failure_secondary_error_message(open_status, open_status_str));
700 static bool
701 compile_capture_filter(const char *iface, pcap_t *pcap_h,
702 struct bpf_program *fcode, const char *cfilter)
704 bpf_u_int32 netnum, netmask;
705 char lookup_net_err_str[PCAP_ERRBUF_SIZE];
707 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
709 * Well, we can't get the netmask for this interface; it's used
710 * only for filters that check for broadcast IP addresses, so
711 * we just punt and use 0. It might be nice to warn the user,
712 * but that's a pain in a GUI application, as it'd involve popping
713 * up a message box, and it's not clear how often this would make
714 * a difference (only filters that check for IP broadcast addresses
715 * use the netmask).
717 /*cmdarg_err(
718 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
719 netmask = 0;
723 * Sigh. Older versions of libpcap don't properly declare the
724 * third argument to pcap_compile() as a const pointer. Cast
725 * away the warning.
727 DIAG_OFF(cast-qual)
728 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
729 return false;
730 DIAG_ON(cast-qual)
731 return true;
734 static bool
735 show_filter_code(capture_options *capture_opts)
737 interface_options *interface_opts;
738 pcap_t *pcap_h;
739 cap_device_open_status open_status;
740 char open_status_str[PCAP_ERRBUF_SIZE];
741 char errmsg[MSG_MAX_LENGTH+1];
742 char secondary_errmsg[MSG_MAX_LENGTH+1];
743 struct bpf_program fcode;
744 struct bpf_insn *insn;
745 u_int i;
746 unsigned j;
748 for (j = 0; j < capture_opts->ifaces->len; j++) {
749 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, j);
750 pcap_h = open_capture_device(capture_opts, interface_opts,
751 CAP_READ_TIMEOUT, &open_status, &open_status_str);
752 if (pcap_h == NULL) {
753 /* Open failed; get messages */
754 get_capture_device_open_failure_messages(open_status, open_status_str,
755 interface_opts->name,
756 errmsg, sizeof errmsg,
757 secondary_errmsg,
758 sizeof secondary_errmsg);
759 /* And report them */
760 report_capture_error(errmsg, secondary_errmsg);
761 return false;
764 /* Set the link-layer type. */
765 if (!set_pcap_datalink(pcap_h, interface_opts->linktype, interface_opts->name,
766 errmsg, sizeof errmsg,
767 secondary_errmsg, sizeof secondary_errmsg)) {
768 pcap_close(pcap_h);
769 report_capture_error(errmsg, secondary_errmsg);
770 return false;
773 /* OK, try to compile the capture filter. */
774 if (!compile_capture_filter(interface_opts->name, pcap_h, &fcode,
775 interface_opts->cfilter)) {
776 snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_h));
777 pcap_close(pcap_h);
778 report_cfilter_error(capture_opts, j, errmsg);
779 return false;
781 pcap_close(pcap_h);
783 /* Now print the filter code. */
784 insn = fcode.bf_insns;
786 for (i = 0; i < fcode.bf_len; insn++, i++)
787 printf("%s\n", bpf_image(insn, i));
789 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
790 /* to remove any suid privileges. */
791 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
792 /* (euid/egid have already previously been set to ruid/rgid. */
793 /* (See comment in main() for details) */
794 /* XXX - On Linux, if we're capturing on a mac80211 device and enabling */
795 /* rfmon via libpcap with libnl support, that creates a new monitor mode */
796 /* device that libpcap will attempt to delete when capture is done. That */
797 /* will fail with EPERM because we dropped privileges. */
798 #ifndef HAVE_LIBCAP
799 relinquish_special_privs_perm();
800 #else
801 relinquish_all_capabilities();
802 #endif
803 if (capture_child) {
804 /* Let our parent know we succeeded. */
805 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
807 return true;
810 static void
811 print_machine_readable_if_capabilities(json_dumper *dumper, if_capabilities_t *caps, int queries);
814 * Output a machine readable list of the interfaces
815 * This list is retrieved by the sync_interface_list_open() function
816 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
818 static int
819 print_machine_readable_interfaces(GList *if_list, int caps_queries, bool print_statistics)
821 GList *if_entry;
822 if_info_t *if_info;
823 GSList *addr;
824 if_addr_t *if_addr;
825 char addr_str[WS_INET6_ADDRSTRLEN];
826 int status;
828 json_dumper dumper = {
829 .output_string = g_string_new(NULL),
830 .flags = JSON_DUMPER_FLAGS_NO_DEBUG,
831 // Don't abort on failure
833 json_dumper_begin_array(&dumper);
836 * Print the contents of the if_entry struct in a parseable format (JSON)
838 for (if_entry = g_list_first(if_list); if_entry != NULL;
839 if_entry = g_list_next(if_entry)) {
840 if_info = (if_info_t *)if_entry->data;
842 json_dumper_begin_object(&dumper);
843 json_dumper_set_member_name(&dumper, if_info->name);
845 json_dumper_begin_object(&dumper);
847 json_dumper_set_member_name(&dumper, "friendly_name");
848 json_dumper_value_string(&dumper, if_info->friendly_name);
850 json_dumper_set_member_name(&dumper, "vendor_description");
851 json_dumper_value_string(&dumper, if_info->vendor_description);
853 json_dumper_set_member_name(&dumper, "type");
854 json_dumper_value_anyf(&dumper, "%i", if_info->type);
856 json_dumper_set_member_name(&dumper, "addrs");
858 json_dumper_begin_array(&dumper);
859 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
860 addr = g_slist_next(addr)) {
862 if_addr = (if_addr_t *)addr->data;
863 switch(if_addr->ifat_type) {
864 case IF_AT_IPv4:
865 json_dumper_value_string(&dumper, ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str, sizeof(addr_str)));
866 break;
867 case IF_AT_IPv6:
868 json_dumper_value_string(&dumper, ws_inet_ntop6(&if_addr->addr.ip6_addr, addr_str, sizeof(addr_str)));
869 break;
870 default:
871 json_dumper_value_anyf(&dumper, "<type unknown %i>", if_addr->ifat_type);
874 json_dumper_end_array(&dumper);
876 json_dumper_set_member_name(&dumper, "loopback");
877 json_dumper_value_anyf(&dumper, "%s", if_info->loopback ? "true" : "false");
879 json_dumper_set_member_name(&dumper, "extcap");
880 json_dumper_value_string(&dumper, if_info->extcap);
882 if (if_info->caps && caps_queries) {
883 json_dumper_set_member_name(&dumper, "caps");
884 json_dumper_begin_object(&dumper);
885 print_machine_readable_if_capabilities(&dumper, if_info->caps, caps_queries);
886 json_dumper_end_object(&dumper);
888 json_dumper_end_object(&dumper);
889 json_dumper_end_object(&dumper);
891 json_dumper_end_array(&dumper);
892 if (json_dumper_finish(&dumper)) {
893 status = 0;
894 if (capture_child) {
895 if (print_statistics) {
896 sync_pipe_write_string_msg(sync_pipe_fd, SP_IFACE_LIST, dumper.output_string->str);
897 } else {
898 /* Let our parent know we succeeded. */
899 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
900 printf("%s", dumper.output_string->str);
902 } else {
903 printf("%s", dumper.output_string->str);
905 } else {
906 status = 2;
907 if (capture_child) {
908 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, "Unexpected JSON error", "");
909 } else {
910 cmdarg_err("Unexpected JSON error");
913 g_string_free(dumper.output_string, TRUE);
914 return status;
918 * If you change the machine-readable output format of this function,
919 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
921 static void
922 print_machine_readable_if_capabilities(json_dumper *dumper, if_capabilities_t *caps, int queries)
924 GList *lt_entry, *ts_entry;
925 const char *desc_str;
927 json_dumper_set_member_name(dumper, "status");
928 json_dumper_value_anyf(dumper, "%i", caps->status);
929 if (caps->primary_msg) {
930 json_dumper_set_member_name(dumper, "primary_msg");
931 json_dumper_value_string(dumper, caps->primary_msg);
934 if (queries & CAPS_QUERY_LINK_TYPES) {
935 json_dumper_set_member_name(dumper, "rfmon");
936 json_dumper_value_anyf(dumper, "%s", caps->can_set_rfmon ? "true" : "false");
937 json_dumper_set_member_name(dumper, "data_link_types");
938 json_dumper_begin_array(dumper);
939 for (lt_entry = caps->data_link_types; lt_entry != NULL;
940 lt_entry = g_list_next(lt_entry)) {
941 data_link_info_t *data_link_info = (data_link_info_t *)lt_entry->data;
942 if (data_link_info->description != NULL)
943 desc_str = data_link_info->description;
944 else
945 desc_str = "(not supported)";
946 json_dumper_begin_object(dumper);
947 json_dumper_set_member_name(dumper, "dlt");
948 json_dumper_value_anyf(dumper, "%d", data_link_info->dlt);
949 json_dumper_set_member_name(dumper, "name");
950 json_dumper_value_string(dumper, data_link_info->name);
951 json_dumper_set_member_name(dumper, "description");
952 json_dumper_value_string(dumper, desc_str);
953 json_dumper_end_object(dumper);
955 json_dumper_end_array(dumper);
957 json_dumper_set_member_name(dumper, "data_link_types_rfmon");
958 json_dumper_begin_array(dumper);
959 for (lt_entry = caps->data_link_types_rfmon; lt_entry != NULL;
960 lt_entry = g_list_next(lt_entry)) {
961 data_link_info_t *data_link_info = (data_link_info_t *)lt_entry->data;
962 if (data_link_info->description != NULL)
963 desc_str = data_link_info->description;
964 else
965 desc_str = "(not supported)";
966 json_dumper_begin_object(dumper);
967 json_dumper_set_member_name(dumper, "dlt");
968 json_dumper_value_anyf(dumper, "%d", data_link_info->dlt);
969 json_dumper_set_member_name(dumper, "name");
970 json_dumper_value_string(dumper, data_link_info->name);
971 json_dumper_set_member_name(dumper, "description");
972 json_dumper_value_string(dumper, desc_str);
973 json_dumper_end_object(dumper);
975 json_dumper_end_array(dumper);
977 if (queries & CAPS_QUERY_TIMESTAMP_TYPES) {
978 json_dumper_set_member_name(dumper, "timestamp_types");
979 json_dumper_begin_array(dumper);
980 for (ts_entry = caps->timestamp_types; ts_entry != NULL;
981 ts_entry = g_list_next(ts_entry)) {
982 timestamp_info_t *timestamp = (timestamp_info_t *)ts_entry->data;
983 if (timestamp->description != NULL)
984 desc_str = timestamp->description;
985 else
986 desc_str = "(none)";
987 json_dumper_begin_object(dumper);
988 json_dumper_set_member_name(dumper, "name");
989 json_dumper_value_string(dumper, timestamp->name);
990 json_dumper_set_member_name(dumper, "description");
991 json_dumper_value_string(dumper, desc_str);
992 json_dumper_end_object(dumper);
994 json_dumper_end_array(dumper);
998 typedef struct {
999 char *name;
1000 pcap_t *pch;
1001 } if_stat_t;
1003 /* Print the number of packets captured for each interface until we're killed. */
1004 static int
1005 print_statistics_loop(bool machine_readable)
1007 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1008 if_info_t *if_info;
1009 if_stat_t *if_stat;
1010 int err;
1011 char *err_str;
1012 pcap_t *pch;
1013 char errbuf[PCAP_ERRBUF_SIZE];
1014 struct pcap_stat ps;
1016 if_list = get_interface_list(&err, &err_str);
1017 if (if_list == NULL) {
1018 if (err == 0) {
1019 cmdarg_err("There are no interfaces on which a capture can be done");
1020 err = WS_EXIT_NO_INTERFACES;
1022 else {
1023 cmdarg_err("%s", err_str);
1024 g_free(err_str);
1026 return err;
1029 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1030 if_info = (if_info_t *)if_entry->data;
1032 #ifdef __linux__
1033 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
1034 * connections. We avoid collecting stats on them.
1036 if (!strncmp(if_info->name, "nf", 2)) {
1037 ws_debug("Skipping interface %s for stats", if_info->name);
1038 continue;
1040 #endif
1042 #ifdef HAVE_PCAP_OPEN
1044 * If we're opening a remote device, use pcap_open(); that's currently
1045 * the only open routine that supports remote devices.
1047 if (strncmp(if_info->name, "rpcap://", 8) == 0)
1048 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1049 else
1050 #endif
1051 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1053 if (pch) {
1054 if_stat = g_new(if_stat_t, 1);
1055 if_stat->name = g_strdup(if_info->name);
1056 if_stat->pch = pch;
1057 stat_list = g_list_append(stat_list, if_stat);
1061 if (!stat_list) {
1062 cmdarg_err("There are no interfaces on which a capture can be done");
1063 return 2;
1066 if (capture_child) {
1067 /* Let our parent know we succeeded. */
1068 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
1071 if (!machine_readable) {
1072 printf("%-15s %10s %10s\n", "Interface", "Received",
1073 "Dropped");
1076 global_ld.go = true;
1077 while (global_ld.go) {
1078 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1079 if_stat = (if_stat_t *)stat_entry->data;
1080 /* XXX - what if this fails? */
1081 if (pcap_stats(if_stat->pch, &ps) == 0) {
1082 if (!machine_readable) {
1083 printf("%-15s %10u %10u\n", if_stat->name,
1084 ps.ps_recv, ps.ps_drop);
1085 } else {
1086 printf("%s\t%u\t%u\n", if_stat->name,
1087 ps.ps_recv, ps.ps_drop);
1088 fflush(stdout);
1092 #ifdef _WIN32
1093 /* If we have a dummy signal pipe check it */
1094 if (!signal_pipe_check_running()) {
1095 global_ld.go = false;
1097 Sleep(1 * 1000);
1098 #else
1099 sleep(1);
1100 #endif
1103 /* XXX - Not reached. Should we look for 'q' in stdin? */
1104 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1105 if_stat = (if_stat_t *)stat_entry->data;
1106 pcap_close(if_stat->pch);
1107 g_free(if_stat->name);
1108 g_free(if_stat);
1110 g_list_free(stat_list);
1111 free_interface_list(if_list);
1113 return 0;
1117 #ifdef _WIN32
1118 static BOOL WINAPI
1119 capture_cleanup_handler(DWORD dwCtrlType)
1121 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1122 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1123 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1124 like SIGTERM at least when the machine's shutting down.
1126 For now, if we're running as a command rather than a capture child,
1127 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1128 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1129 in that way on UN*X.
1131 If we're not running as a capture child, we might be running as
1132 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1133 user logs out. (XXX - can we explicitly check whether we're
1134 running as a service?) */
1136 ws_info("Console: Control signal");
1137 ws_debug("Console: Control signal, CtrlType: %lu", dwCtrlType);
1139 /* Keep capture running if we're a service and a user logs off */
1140 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1141 capture_loop_stop();
1142 return true;
1143 } else {
1144 return false;
1147 #else
1148 static void
1149 capture_cleanup_handler(int signum _U_)
1151 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1152 SIGTERM. We assume that if the user wanted it to keep running
1153 after they logged out, they'd have nohupped it. */
1155 capture_loop_stop();
1157 #endif
1160 static void
1161 report_capture_count(bool reportit)
1163 /* Don't print this if we're a capture child. */
1164 if (!capture_child && reportit) {
1165 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packets_captured);
1166 /* stderr could be line buffered */
1167 fflush(stderr);
1172 #ifdef SIGINFO
1173 static void
1174 report_counts_for_siginfo(void)
1176 report_capture_count(quiet);
1177 infoprint = false; /* we just reported it */
1180 static void
1181 report_counts_siginfo(int signum _U_)
1183 int sav_errno = errno;
1185 /* If we've been told to delay printing, just set a flag asking
1186 that we print counts (if we're supposed to), otherwise print
1187 the count of packets captured (if we're supposed to). */
1188 if (infodelay)
1189 infoprint = true;
1190 else
1191 report_counts_for_siginfo();
1192 errno = sav_errno;
1194 #endif /* SIGINFO */
1196 static void
1197 exit_main(int status)
1199 ws_cleanup_sockets();
1201 #ifdef _WIN32
1202 /* can be helpful for debugging */
1203 #ifdef DEBUG_DUMPCAP
1204 printf("Press any key\n");
1205 _getch();
1206 #endif
1208 #endif /* _WIN32 */
1210 if (ringbuf_is_initialized()) {
1211 /* save_file is managed by ringbuffer, be sure to release the memory and
1212 * avoid capture_opts_cleanup from double-freeing 'save_file'. */
1213 ringbuf_free();
1214 global_capture_opts.save_file = NULL;
1217 capture_opts_cleanup(&global_capture_opts);
1218 exit(status);
1221 #ifdef HAVE_LIBCAP
1223 * If we were linked with libcap (not related to libpcap), make sure we have
1224 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1225 * (See comment in main() for details)
1227 static void
1228 relinquish_privs_except_capture(void)
1231 * Drop any capabilities other than NET_ADMIN and NET_RAW:
1233 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1234 * stuff we don't need (and shouldn't have).
1235 * CAP_NET_RAW: Packet capture (raw sockets).
1237 * If 'started_with_special_privs' (ie: suid) then drop our
1238 * suid privileges.
1241 cap_t current_caps = cap_get_proc();
1242 print_caps("Pre set");
1244 cap_t caps = cap_init(); /* all capabilities initialized to off */
1247 * We can only set capabilities that are in the permitted set.
1248 * If the real or effective user ID is 0 (root), then the file
1249 * inherited and permitted sets are ignored, and our permitted
1250 * set should be all ones - unless the effective ID is 0, the
1251 * real ID is not zero, and the binary has file capabilities,
1252 * in which case the permitted set is only that of the file.
1253 * (E.g., set-user-ID-root + file capabilities.)
1255 * If one or more of the euid, ruid, and saved set user ID are
1256 * all zero and all change to nonzero, then all capabilities are
1257 * cleared from the permitted, effective, and ambient sets.
1258 * PR_SET_KEEPCAPS causes the permitted set to be retained, so
1259 * we can relinquish our changed user ID.
1261 * All capabilities are always cleared from the effective set
1262 * when the euid is changed from 0 to nonzero.
1264 * See capabilities(7).
1266 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1267 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1270 if (started_with_special_privs()) {
1271 relinquish_special_privs_perm();
1275 * If cap_set_proc() fails, it leaves the capabilities unchanged.
1276 * So the only way to guarantee that we've dropped all other
1277 * capabilities is to ensure that cap_set_proc() succeeds.
1278 * One option might be to exit if cap_set_proc() fails - but some
1279 * captures will work with CAP_NET_RAW but not CAP_NET_ADMIN.
1282 cap_value_t cap_list[1] = { CAP_NET_ADMIN };
1283 int cl_len = array_length(cap_list);
1284 cap_flag_value_t value;
1286 cap_get_flag(current_caps, cap_list[0], CAP_PERMITTED, &value);
1288 if (value != CAP_SET) {
1289 // XXX - Should we warn here? Some captures will still work.
1291 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, value);
1292 // XXX - Do we really need CAP_INHERITABLE?
1293 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, value);
1294 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, value);
1296 cap_list[0] = CAP_NET_RAW;
1297 cap_get_flag(current_caps, cap_list[0], CAP_PERMITTED, &value);
1299 if (value != CAP_SET) {
1300 // XXX - Should we warn here?
1302 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, value);
1303 // XXX - Do we really need CAP_INHERITABLE?
1304 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, value);
1305 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, value);
1307 if (cap_set_proc(caps)) {
1309 * This shouldn't happen, we're only trying to set capabilities
1310 * already in the permitted set.
1312 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1315 print_caps("Post set");
1317 cap_free(current_caps);
1318 cap_free(caps);
1321 #endif /* HAVE_LIBCAP */
1323 /* Map DLT_ values, as returned by pcap_datalink(), to LINKTYPE_ values,
1324 as are written to capture files.
1326 Most of the time, a DLT_ value and the corresponding LINKYPE_ value
1327 are the same, but there are some cases, where a numeric value as
1328 a DLT_ doesn't uniquely identify a particular link-layer header type,
1329 where they differ, so that the values in files *do* identify
1330 particular link-layer header types. */
1332 /* LINKTYPE_ values that don't match corresponding DLT_ values on
1333 all platforms. */
1334 #define LINKTYPE_ATM_RFC1483 100
1335 #define LINKTYPE_RAW 101
1336 #define LINKTYPE_SLIP_BSDOS 102
1337 #define LINKTYPE_PPP_BSDOS 103
1338 #define LINKTYPE_C_HDLC 104
1339 #define LINKTYPE_IEEE802_11 105
1340 #define LINKTYPE_ATM_CLIP 106
1341 #define LINKTYPE_FRELAY 107
1342 #define LINKTYPE_LOOP 108
1343 #define LINKTYPE_ENC 109
1344 #define LINKTYPE_NETBSD_HDLC 112
1345 #define LINKTYPE_PFSYNC 246
1346 #define LINKTYPE_PKTAP 258
1348 static int
1349 dlt_to_linktype(int dlt)
1351 /* DLT_NULL through DLT_FDDI have the same numeric value on
1352 all platforms, so the corresponding LINKTYPE_s have the
1353 same numeric values. */
1354 if (dlt >= DLT_NULL && dlt <= DLT_FDDI)
1355 return (dlt);
1357 #if defined(DLT_PFSYNC) && DLT_PFSYNC != LINKTYPE_PFSYNC
1358 /* DLT_PFSYNC has a value on several platforms that's in the
1359 non-matching range, a value on FreeBSD that's in the high
1360 matching range and that's *not* equal to LINKTYPE_PFSYNC,
1361 and has a value on the rmaining platforms that's equal
1362 to LINKTYPE_PFSYNC, which is in the high matching range.
1364 Map it to LINKTYPE_PFSYNC if it's not equal to LINKTYPE_PFSYNC. */
1365 if (dlt == DLT_PFSYNC)
1366 return (LINKTYPE_PFSYNC);
1367 #endif
1369 /* DLT_PKTAP is defined as DLT_USER2 - which is in the high
1370 matching range - on Darwin because Apple used DLT_USER2
1371 on systems that users ran, not just as an internal thing.
1373 We map it to LINKTYPE_PKTAP if it's not equal to LINKTYPE_PKTAP
1374 so that DLT_PKTAP captures from Apple machines can be read by
1375 software that either doesn't handle DLT_USER2 or that handles it
1376 as something other than Apple PKTAP. */
1377 #if defined(DLT_PKTAP) && DLT_PKTAP != LINKTYPE_PKTAP
1378 if (dlt == DLT_PKTAP)
1379 return (LINKTYPE_PKTAP);
1380 #endif
1382 /* For all other DLT_s with values beyond 104, the value
1383 of the corresponding LINKTYPE_ is the same. */
1384 if (dlt >= 104)
1385 return (dlt);
1387 /* These DLT_ values have different values on different
1388 platforms, so we assigned them LINKTYPE_ values just
1389 below the lower bound of the high matchig range;
1390 those values should never be equal to any DLT_
1391 values, so that should avoid collisions.
1393 That way, for example, "raw IP" packets will have
1394 LINKTYPE_RAW as the code in all savefiles for
1395 which the code that writes them maps to that
1396 value, regardless of the platform on which they
1397 were written, so they should be readable on all
1398 platforms without having to determine on which
1399 platform they were written.
1401 We map the DLT_ values on this platform, whatever
1402 it might be, to the corresponding LINKTYPE_ values. */
1403 #ifdef DLT_ATM_RFC1483
1404 if (dlt == DLT_ATM_RFC1483)
1405 return (LINKTYPE_ATM_RFC1483);
1406 #endif
1407 #ifdef DLT_RAW
1408 if (dlt == DLT_RAW)
1409 return (LINKTYPE_RAW);
1410 #endif
1411 #ifdef DLT_SLIP_BSDOS
1412 if (dlt == DLT_SLIP_BSDOS)
1413 return (LINKTYPE_SLIP_BSDOS);
1414 #endif
1415 #ifdef DLT_PPP_BSDOS
1416 if (dlt == DLT_PPP_BSDOS)
1417 return (LINKTYPE_PPP_BSDOS);
1418 #endif
1420 /* These DLT_ values were originally defined on some platform,
1421 and weren't defined on other platforms.
1423 At least some of those values, on at least one platform,
1424 collide with the values of other DLT_s on other platforms,
1425 e.g. DLT_LOOP, so we don't just define them, on all
1426 platforms, as having the same value as on the original
1427 platform.
1429 Therefore, we assigned new LINKTYPE_ values to them, and,
1430 on the platforms where they weren't originally defined,
1431 define the DLT_s to have the same value as the corresponding
1432 LINKTYPE_.
1434 This means that, for capture files with the original
1435 platform's DLT_ value rather than the LINKTYPE_ value
1436 as a link-layer type, we will recognize those types
1437 on that platform, but not on other platforms. */
1438 #ifdef DLT_FR
1439 /* BSD/OS Frame Relay */
1440 if (dlt == DLT_FR)
1441 return (LINKTYPE_FRELAY);
1442 #endif
1443 #if defined(DLT_HDLC) && DLT_HDLC != LINKTYPE_NETBSD_HDLC
1444 /* NetBSD HDLC */
1445 if (dlt == DLT_HDLC)
1446 return (LINKTYPE_NETBSD_HDLC);
1447 #endif
1448 #if defined(DLT_C_HDLC) && DLT_C_HDLC != LINKTYPE_C_HDLC
1449 /* BSD/OS Cisco HDLC */
1450 if (dlt == DLT_C_HDLC)
1451 return (LINKTYPE_C_HDLC);
1452 #endif
1453 #if defined(DLT_LOOP) && DLT_LOOP != LINKTYPE_LOOP
1454 /* OpenBSD DLT_LOOP */
1455 if (dlt == DLT_LOOP)
1456 return (LINKTYPE_LOOP);
1457 #endif
1458 #if defined(DLT_ENC) && DLT_ENC != LINKTYPE_ENC
1459 /* OpenBSD DLT_ENC */
1460 if (dlt == DLT_ENC)
1461 return (LINKTYPE_ENC);
1462 #endif
1464 /* These DLT_ values are not on all platforms, but, so far,
1465 there don't appear to be any platforms that define
1466 other DLT_s with those values; we map them to
1467 different LINKTYPE_ values anyway, just in case. */
1468 #ifdef DLT_ATM_CLIP
1469 /* Linux ATM Classical IP */
1470 if (dlt == DLT_ATM_CLIP)
1471 return (LINKTYPE_ATM_CLIP);
1472 #endif
1474 /* Treat all other DLT_s as having the same value as the
1475 corresponding LINKTYPE_. */
1476 return (dlt);
1479 /* Take care of byte order in the libpcap headers read from pipes.
1480 * (function taken from wiretap/libpcap.c) */
1481 static void
1482 cap_pipe_adjust_pcap_header(bool byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1484 if (byte_swapped) {
1485 /* Byte-swap the record header fields. */
1486 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1487 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1488 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1489 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1492 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1493 swapped, in order to match the BPF header layout.
1495 Unfortunately, some files were, according to a comment in the "libpcap"
1496 source, written with version 2.3 in their headers but without the
1497 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1498 would make no sense - we assume that we need to swap them. */
1499 if (hdr->version_major == 2 &&
1500 (hdr->version_minor < 3 ||
1501 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1502 uint32_t temp;
1504 temp = rechdr->orig_len;
1505 rechdr->orig_len = rechdr->incl_len;
1506 rechdr->incl_len = temp;
1510 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1511 * or just read().
1513 static ssize_t
1514 cap_pipe_read(int pipe_fd, char *buf, size_t sz, bool from_socket _U_)
1516 #ifdef _WIN32
1517 if (from_socket) {
1518 return recv(pipe_fd, buf, (int)sz, 0);
1519 } else {
1520 return -1;
1522 #else
1523 return ws_read(pipe_fd, buf, sz);
1524 #endif
1527 #if defined(_WIN32)
1529 * Thread function that reads from a pipe and pushes the data
1530 * to the main application thread.
1533 * XXX Right now we use async queues for basic signaling. The main thread
1534 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1535 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1536 * Iff the read is successful cap_pipe_read pushes an item onto
1537 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1538 * the queues themselves (yet).
1540 * We might want to move some of the cap_pipe_dispatch logic here so that
1541 * we can let cap_thread_read run independently, queuing up multiple reads
1542 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1544 static void *cap_thread_read(void *arg)
1546 capture_src *pcap_src;
1547 #ifdef _WIN32
1548 BOOL res;
1549 DWORD last_err, bytes_read;
1550 #else /* _WIN32 */
1551 size_t bytes_read;
1552 #endif /* _WIN32 */
1554 pcap_src = (capture_src *)arg;
1555 while (pcap_src->cap_pipe_err == PIPOK) {
1556 g_async_queue_pop(pcap_src->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1557 g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1558 bytes_read = 0;
1559 while (bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1560 if ((pcap_src->from_cap_socket)
1561 #ifndef _WIN32
1562 || 1
1563 #endif
1566 ssize_t b;
1567 b = cap_pipe_read(pcap_src->cap_pipe_fd, pcap_src->cap_pipe_buf+bytes_read,
1568 pcap_src->cap_pipe_bytes_to_read - bytes_read, pcap_src->from_cap_socket);
1569 if (b <= 0) {
1570 if (b == 0) {
1571 pcap_src->cap_pipe_err = PIPEOF;
1572 bytes_read = 0;
1573 break;
1574 } else {
1575 pcap_src->cap_pipe_err = PIPERR;
1576 bytes_read = -1;
1577 break;
1579 } else {
1580 bytes_read += (DWORD)b;
1583 #ifdef _WIN32
1584 else
1586 /* If we try to use read() on a named pipe on Windows with partial
1587 * data it appears to return EOF.
1589 DWORD b;
1590 res = ReadFile(pcap_src->cap_pipe_h, pcap_src->cap_pipe_buf+bytes_read,
1591 pcap_src->cap_pipe_bytes_to_read - bytes_read,
1592 &b, NULL);
1594 bytes_read += b;
1595 if (!res) {
1596 last_err = GetLastError();
1597 if (last_err == ERROR_MORE_DATA) {
1598 continue;
1599 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1600 pcap_src->cap_pipe_err = PIPEOF;
1601 bytes_read = 0;
1602 break;
1604 pcap_src->cap_pipe_err = PIPERR;
1605 bytes_read = -1;
1606 break;
1607 } else if (b == 0 && pcap_src->cap_pipe_bytes_to_read > 0) {
1608 pcap_src->cap_pipe_err = PIPEOF;
1609 bytes_read = 0;
1610 break;
1613 #endif /*_WIN32 */
1615 pcap_src->cap_pipe_bytes_read = bytes_read;
1616 if (pcap_src->cap_pipe_bytes_read >= pcap_src->cap_pipe_bytes_to_read) {
1617 g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1619 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1621 /* Post to queue if we didn't read enough data as the main thread waits for the message */
1622 g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1623 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1624 /* There's still more of the record to read. */
1625 g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1627 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1628 return NULL;
1632 * Do a blocking read from a pipe within the main thread, by pushing
1633 * the read onto the pipe queue and then popping it off that queue;
1634 * the pipe will block until the pushed read completes.
1636 * We do it with another thread because we can't use select() on
1637 * pipes on Windows, as we can on UN*Xes, we can only use it on
1638 * sockets.
1640 void
1641 pipe_read_sync(capture_src *pcap_src, void *buf, DWORD nbytes)
1643 pcap_src->cap_pipe_buf = (char *) buf;
1644 pcap_src->cap_pipe_bytes_read = 0;
1645 pcap_src->cap_pipe_bytes_to_read = nbytes;
1646 /* We don't have to worry about cap_pipe_read_mtx here */
1647 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1648 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1650 #endif
1652 /* Provide select() functionality for a single file descriptor
1653 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1655 * Returns the same values as select.
1657 static int
1658 cap_pipe_select(int pipe_fd)
1660 fd_set rfds;
1661 struct timeval timeout;
1663 FD_ZERO(&rfds);
1664 FD_SET(pipe_fd, &rfds);
1666 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1667 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1669 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1672 #define DEF_TCP_PORT 19000
1674 static int
1675 cap_open_socket(char *pipename, capture_src *pcap_src, char *errmsg, size_t errmsgl)
1677 struct sockaddr_storage sa;
1678 socklen_t sa_len;
1679 int fd;
1681 /* Skip the initial "TCP@" in the pipename. */
1682 if (ws_socket_ptoa(&sa, pipename + 4, DEF_TCP_PORT) < 0) {
1683 snprintf(errmsg, errmsgl,
1684 "The capture session could not be initiated because"
1685 "\"%s\" is not a valid socket specification", pipename);
1686 pcap_src->cap_pipe_err = PIPERR;
1687 return -1;
1690 if ((fd = (int)socket(sa.ss_family, SOCK_STREAM, 0)) < 0) {
1691 snprintf(errmsg, errmsgl,
1692 "The capture session could not be initiated because"
1693 " the socket couldn't be created due to the socket error: \n"
1694 #ifdef _WIN32
1695 " %s", win32strerror(WSAGetLastError()));
1696 #else
1697 " %d: %s", errno, g_strerror(errno));
1698 #endif
1699 pcap_src->cap_pipe_err = PIPERR;
1700 return -1;
1703 if (sa.ss_family == AF_INET6)
1704 sa_len = sizeof(struct sockaddr_in6);
1705 else
1706 sa_len = sizeof(struct sockaddr_in);
1707 if (connect(fd, (struct sockaddr *)&sa, sa_len) < 0) {
1708 snprintf(errmsg, errmsgl,
1709 "The capture session could not be initiated because"
1710 " the socket couldn't be connected due to the socket error: \n"
1711 #ifdef _WIN32
1712 " %s", win32strerror(WSAGetLastError()));
1713 #else
1714 " %d: %s", errno, g_strerror(errno));
1715 #endif
1716 pcap_src->cap_pipe_err = PIPERR;
1718 cap_pipe_close(fd, true);
1719 return -1;
1722 pcap_src->from_cap_socket = true;
1723 return fd;
1726 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1727 * otherwise.
1729 static void
1730 cap_pipe_close(int pipe_fd, bool from_socket)
1732 #ifdef _WIN32
1733 if (from_socket) {
1734 closesocket(pipe_fd);
1736 #else
1737 (void) from_socket; /* Mark unused, similar to Q_UNUSED */
1738 ws_close(pipe_fd);
1739 #endif
1742 /** Read bytes from a capture source, which is assumed to be a pipe or
1743 * socket.
1745 * Returns -1, or the number of bytes read similar to read(2).
1746 * Sets pcap_src->cap_pipe_err on error or EOF.
1748 static ssize_t
1749 cap_pipe_read_data_bytes(capture_src *pcap_src, char *errmsg, size_t errmsgl)
1751 int sel_ret;
1752 int fd = pcap_src->cap_pipe_fd;
1753 #ifdef _WIN32
1754 DWORD sz, bytes_read = 0;
1755 #else /* _WIN32 */
1756 ssize_t sz, bytes_read = 0;
1757 #endif /* _WIN32 */
1758 ssize_t b;
1760 #ifdef LOG_CAPTURE_VERBOSE
1761 ws_debug("cap_pipe_read_data_bytes read %lu of %lu",
1762 pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1763 #endif
1764 sz = pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read;
1765 while (bytes_read < sz) {
1766 if (fd == -1) {
1767 snprintf(errmsg, errmsgl, "Invalid file descriptor.");
1768 pcap_src->cap_pipe_err = PIPNEXIST;
1769 return -1;
1772 sel_ret = cap_pipe_select(fd);
1773 if (sel_ret < 0) {
1774 snprintf(errmsg, errmsgl,
1775 "Unexpected error from select: %s.", g_strerror(errno));
1776 pcap_src->cap_pipe_err = PIPERR;
1777 return -1;
1778 } else if (sel_ret > 0) {
1779 b = cap_pipe_read(fd, pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read+bytes_read,
1780 sz-bytes_read, pcap_src->from_cap_socket);
1781 if (b <= 0) {
1782 if (b == 0) {
1783 snprintf(errmsg, errmsgl,
1784 "End of file reading from pipe or socket.");
1785 pcap_src->cap_pipe_err = PIPEOF;
1786 } else {
1787 #ifdef _WIN32
1789 * On Windows, we only do this for sockets.
1791 DWORD lastError = WSAGetLastError();
1792 errno = lastError;
1793 snprintf(errmsg, errmsgl,
1794 "Error reading from pipe or socket: %s.",
1795 win32strerror(lastError));
1796 #else
1797 snprintf(errmsg, errmsgl,
1798 "Error reading from pipe or socket: %s.",
1799 g_strerror(errno));
1800 #endif
1801 pcap_src->cap_pipe_err = PIPERR;
1803 return -1;
1805 #ifdef _WIN32
1806 bytes_read += (DWORD)b;
1807 #else
1808 bytes_read += b;
1809 #endif
1812 pcap_src->cap_pipe_bytes_read += bytes_read;
1813 #ifdef LOG_CAPTURE_VERBOSE
1814 ws_debug("cap_pipe_read_data_bytes read %lu of %lu",
1815 pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1816 #endif
1817 return bytes_read;
1820 /* Some forward declarations for breaking up cap_pipe_open_live for pcap and pcapng formats */
1821 static void pcap_pipe_open_live(int fd, capture_src *pcap_src,
1822 struct pcap_hdr *hdr,
1823 char *errmsg, size_t errmsgl,
1824 char *secondary_errmsg, size_t secondary_errmsgl);
1825 static void pcapng_pipe_open_live(int fd, capture_src *pcap_src,
1826 char *errmsg, size_t errmsgl);
1827 static int pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src,
1828 char *errmsg, size_t errmsgl);
1830 /* For problems that are probably Not Our Fault. */
1831 static char not_our_bug[] =
1832 "Please report this to the developers of the program writing to the pipe.";
1834 /* Mimic pcap_open_live() for pipe captures
1836 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1837 * open it, and read the header.
1839 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1840 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1841 static void
1842 cap_pipe_open_live(char *pipename,
1843 capture_src *pcap_src,
1844 void *hdr,
1845 char *errmsg, size_t errmsgl,
1846 char *secondary_errmsg, size_t secondary_errmsgl)
1848 #ifndef _WIN32
1849 ws_statb64 pipe_stat;
1850 struct sockaddr_un sa;
1851 #else /* _WIN32 */
1852 uintptr_t extcap_pipe_handle;
1853 #endif
1854 bool extcap_pipe = false;
1855 ssize_t b;
1856 int fd = -1, sel_ret;
1857 size_t bytes_read;
1858 uint32_t magic = 0;
1859 pcap_src->cap_pipe_fd = -1;
1860 #ifdef _WIN32
1861 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1862 #endif
1864 ws_debug("cap_pipe_open_live: %s", pipename);
1867 * XXX - this blocks until a pcap per-file header has been written to
1868 * the pipe, so it could block indefinitely.
1870 if (strcmp(pipename, "-") == 0) {
1871 #ifndef _WIN32
1872 fd = 0; /* read from stdin */
1873 #else /* _WIN32 */
1874 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1875 #endif /* _WIN32 */
1876 } else if (!strncmp(pipename, "TCP@", 4)) {
1877 if ((fd = cap_open_socket(pipename, pcap_src, errmsg, errmsgl)) < 0) {
1878 return;
1880 } else {
1881 #ifndef _WIN32
1882 if ( g_strrstr(pipename, EXTCAP_PIPE_PREFIX) != NULL )
1883 extcap_pipe = true;
1885 if (ws_stat64(pipename, &pipe_stat) < 0) {
1886 if (errno == ENOENT || errno == ENOTDIR)
1887 pcap_src->cap_pipe_err = PIPNEXIST;
1888 else {
1889 snprintf(errmsg, errmsgl,
1890 "The capture session could not be initiated "
1891 "due to error getting information on pipe or socket: %s.", g_strerror(errno));
1892 pcap_src->cap_pipe_err = PIPERR;
1894 return;
1896 if (S_ISFIFO(pipe_stat.st_mode)) {
1897 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1898 if (fd == -1) {
1899 snprintf(errmsg, errmsgl,
1900 "The capture session could not be initiated "
1901 "due to error on pipe open: %s.", g_strerror(errno));
1902 pcap_src->cap_pipe_err = PIPERR;
1903 return;
1905 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1906 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1907 if (fd == -1) {
1908 snprintf(errmsg, errmsgl,
1909 "The capture session could not be initiated "
1910 "due to error on socket create: %s.", g_strerror(errno));
1911 pcap_src->cap_pipe_err = PIPERR;
1912 return;
1914 sa.sun_family = AF_UNIX;
1916 * The Single UNIX Specification says:
1918 * The size of sun_path has intentionally been left undefined.
1919 * This is because different implementations use different sizes.
1920 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1921 * of 104. Since most implementations originate from BSD versions,
1922 * the size is typically in the range 92 to 108.
1924 * Applications should not assume a particular length for sun_path
1925 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1927 * It also says
1929 * The <sys/un.h> header shall define the sockaddr_un structure,
1930 * which shall include at least the following members:
1932 * sa_family_t sun_family Address family.
1933 * char sun_path[] Socket pathname.
1935 * so we assume that it's an array, with a specified size,
1936 * and that the size reflects the maximum path length.
1938 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1939 /* Path name too long */
1940 snprintf(errmsg, errmsgl,
1941 "The capture session could not be initiated "
1942 "due to error on socket connect: Path name too long.");
1943 pcap_src->cap_pipe_err = PIPERR;
1944 ws_close(fd);
1945 return;
1947 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1948 if (b == -1) {
1949 snprintf(errmsg, errmsgl,
1950 "The capture session could not be initiated "
1951 "due to error on socket connect: %s.", g_strerror(errno));
1952 pcap_src->cap_pipe_err = PIPERR;
1953 ws_close(fd);
1954 return;
1956 } else {
1957 if (S_ISCHR(pipe_stat.st_mode)) {
1959 * Assume the user specified an interface on a system where
1960 * interfaces are in /dev. Pretend we haven't seen it.
1962 pcap_src->cap_pipe_err = PIPNEXIST;
1963 } else {
1964 snprintf(errmsg, errmsgl,
1965 "The capture session could not be initiated because\n"
1966 "\"%s\" is neither an interface nor a socket nor a pipe.", pipename);
1967 pcap_src->cap_pipe_err = PIPERR;
1969 return;
1972 #else /* _WIN32 */
1973 if (sscanf(pipename, EXTCAP_PIPE_PREFIX "%" SCNuPTR, &extcap_pipe_handle) == 1)
1975 /* The client is already connected to extcap pipe.
1976 * We have inherited the handle from parent process.
1978 extcap_pipe = true;
1979 pcap_src->cap_pipe_h = (HANDLE)extcap_pipe_handle;
1981 else
1983 if (!win32_is_pipe_name(pipename)) {
1984 snprintf(errmsg, errmsgl,
1985 "The capture session could not be initiated because\n"
1986 "\"%s\" is neither an interface nor a pipe.", pipename);
1987 pcap_src->cap_pipe_err = PIPNEXIST;
1988 return;
1991 /* Wait for the pipe to appear */
1992 while (1) {
1993 pcap_src->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1994 OPEN_EXISTING, 0, NULL);
1996 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE)
1997 break;
1999 if (GetLastError() != ERROR_PIPE_BUSY) {
2000 snprintf(errmsg, errmsgl,
2001 "The capture session on \"%s\" could not be started "
2002 "due to error on pipe open: %s.",
2003 pipename, win32strerror(GetLastError()));
2004 pcap_src->cap_pipe_err = PIPERR;
2005 return;
2008 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
2009 snprintf(errmsg, errmsgl,
2010 "The capture session on \"%s\" timed out during "
2011 "pipe open: %s.",
2012 pipename, win32strerror(GetLastError()));
2013 pcap_src->cap_pipe_err = PIPERR;
2014 return;
2018 #endif /* _WIN32 */
2021 pcap_src->from_cap_pipe = true;
2024 * We start with a 2KB buffer for packet data, which should be
2025 * large enough for most regular network packets. We increase it,
2026 * up to the maximum size we allow, as necessary.
2028 pcap_src->cap_pipe_databuf = (char*)g_malloc(2048);
2029 pcap_src->cap_pipe_databuf_size = 2048;
2032 * Read the first 4 bytes of data from the pipe.
2034 * If a pcap file is being written to it, that will be
2035 * the pcap magic number.
2037 * If a pcapng file is being written to it, that will be
2038 * the block type of the initial SHB.
2040 #ifdef _WIN32
2042 * On UN*X, we can use select() on pipes or sockets.
2044 * On Windows, we can only use it on sockets; to do non-blocking
2045 * reads from pipes, we currently do reads in a separate thread
2046 * and use GLib asynchronous queues from the main thread to start
2047 * read operations and to wait for them to complete.
2049 if (pcap_src->from_cap_socket)
2050 #endif
2052 bytes_read = 0;
2053 while (bytes_read < sizeof magic) {
2054 sel_ret = cap_pipe_select(fd);
2055 if (sel_ret < 0) {
2056 snprintf(errmsg, errmsgl,
2057 "Unexpected error from select: %s.",
2058 g_strerror(errno));
2059 goto error;
2060 } else if (sel_ret > 0) {
2061 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
2062 sizeof magic-bytes_read,
2063 pcap_src->from_cap_socket);
2064 /* jump messaging, if extcap had an error, stderr will provide the correct message */
2065 if (extcap_pipe && b <= 0)
2066 goto error;
2068 if (b <= 0) {
2069 if (b == 0)
2070 snprintf(errmsg, errmsgl,
2071 "End of file on pipe magic during open.");
2072 else
2073 snprintf(errmsg, errmsgl,
2074 "Error on pipe magic during open: %s.",
2075 g_strerror(errno));
2076 goto error;
2078 bytes_read += b;
2082 #ifdef _WIN32
2083 else {
2084 /* Create a thread to read from this pipe */
2085 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
2087 pipe_read_sync(pcap_src, &magic, sizeof(magic));
2088 /* jump messaging, if extcap had an error, stderr will provide the correct message */
2089 if (pcap_src->cap_pipe_bytes_read <= 0 && extcap_pipe)
2090 goto error;
2092 if (pcap_src->cap_pipe_bytes_read <= 0) {
2093 if (pcap_src->cap_pipe_bytes_read == 0)
2094 snprintf(errmsg, errmsgl,
2095 "End of file on pipe magic during open.");
2096 else
2097 snprintf(errmsg, errmsgl,
2098 "Error on pipe magic during open: %s.",
2099 g_strerror(errno));
2100 goto error;
2103 #endif
2105 switch (magic) {
2106 case PCAP_MAGIC:
2107 case PCAP_NSEC_MAGIC:
2108 /* This is a pcap file.
2109 The host that wrote it has our byte order, and was running
2110 a program using either standard or ss990417 libpcap. */
2111 pcap_src->cap_pipe_info.pcap.byte_swapped = false;
2112 pcap_src->cap_pipe_modified = false;
2113 pcap_src->ts_nsec = magic == PCAP_NSEC_MAGIC;
2114 break;
2115 case PCAP_MODIFIED_MAGIC:
2116 /* This is a pcap file.
2117 The host that wrote it has our byte order, but was running
2118 a program using either ss990915 or ss991029 libpcap. */
2119 pcap_src->cap_pipe_info.pcap.byte_swapped = false;
2120 pcap_src->cap_pipe_modified = true;
2121 break;
2122 case PCAP_SWAPPED_MAGIC:
2123 case PCAP_SWAPPED_NSEC_MAGIC:
2124 /* This is a pcap file.
2125 The host that wrote it has a byte order opposite to ours,
2126 and was running a program using either standard or
2127 ss990417 libpcap. */
2128 pcap_src->cap_pipe_info.pcap.byte_swapped = true;
2129 pcap_src->cap_pipe_modified = false;
2130 pcap_src->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
2131 break;
2132 case PCAP_SWAPPED_MODIFIED_MAGIC:
2133 /* This is a pcap file.
2134 The host that wrote it out has a byte order opposite to
2135 ours, and was running a program using either ss990915
2136 or ss991029 libpcap. */
2137 pcap_src->cap_pipe_info.pcap.byte_swapped = true;
2138 pcap_src->cap_pipe_modified = true;
2139 break;
2140 case BLOCK_TYPE_SHB:
2141 /* This is a pcapng file. */
2142 pcap_src->from_pcapng = true;
2143 pcap_src->cap_pipe_dispatch = pcapng_pipe_dispatch;
2144 pcap_src->cap_pipe_info.pcapng.src_iface_to_global = g_array_new(FALSE, FALSE, sizeof(uint32_t));
2145 global_capture_opts.use_pcapng = true; /* we can only output in pcapng format */
2146 break;
2147 default:
2148 /* Not a pcapng file, and either not a pcap type we know about
2149 or not a pcap file, either. */
2150 snprintf(errmsg, errmsgl,
2151 "File type is neither a supported pcap nor pcapng format. (magic = 0x%08x)", magic);
2152 snprintf(secondary_errmsg, secondary_errmsgl, "%s",
2153 not_our_bug);
2154 goto error;
2157 if (pcap_src->from_pcapng)
2158 pcapng_pipe_open_live(fd, pcap_src, errmsg, errmsgl);
2159 else
2160 pcap_pipe_open_live(fd, pcap_src, (struct pcap_hdr *) hdr, errmsg, errmsgl,
2161 secondary_errmsg, secondary_errmsgl);
2163 return;
2165 error:
2166 ws_debug("cap_pipe_open_live: error %s", errmsg);
2167 pcap_src->cap_pipe_err = PIPERR;
2168 cap_pipe_close(fd, pcap_src->from_cap_socket);
2169 pcap_src->cap_pipe_fd = -1;
2170 #ifdef _WIN32
2171 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2172 #endif
2176 * Read the part of the pcap file header that follows the magic
2177 * number (we've already read the magic number).
2179 static void
2180 pcap_pipe_open_live(int fd,
2181 capture_src *pcap_src,
2182 struct pcap_hdr *hdr,
2183 char *errmsg, size_t errmsgl,
2184 char *secondary_errmsg, size_t secondary_errmsgl)
2186 size_t bytes_read;
2187 ssize_t b;
2188 int sel_ret;
2191 * We're reading from a pcap file. We've already read the magic
2192 * number; read the rest of the header.
2194 * (Note that struct pcap_hdr is a structure for the part of a
2195 * pcap file header *following the magic number*; it does not
2196 * include the magic number itself.)
2198 #ifdef _WIN32
2199 if (pcap_src->from_cap_socket)
2200 #endif
2202 /* Keep reading until we get the rest of the header. */
2203 bytes_read = 0;
2204 while (bytes_read < sizeof(struct pcap_hdr)) {
2205 sel_ret = cap_pipe_select(fd);
2206 if (sel_ret < 0) {
2207 snprintf(errmsg, errmsgl,
2208 "Unexpected error from select: %s.",
2209 g_strerror(errno));
2210 goto error;
2211 } else if (sel_ret > 0) {
2212 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
2213 sizeof(struct pcap_hdr) - bytes_read,
2214 pcap_src->from_cap_socket);
2215 if (b <= 0) {
2216 if (b == 0)
2217 snprintf(errmsg, errmsgl,
2218 "End of file on pipe header during open.");
2219 else
2220 snprintf(errmsg, errmsgl,
2221 "Error on pipe header during open: %s.",
2222 g_strerror(errno));
2223 snprintf(secondary_errmsg, secondary_errmsgl,
2224 "%s", not_our_bug);
2225 goto error;
2227 bytes_read += b;
2231 #ifdef _WIN32
2232 else {
2233 pipe_read_sync(pcap_src, hdr, sizeof(struct pcap_hdr));
2234 if (pcap_src->cap_pipe_bytes_read <= 0) {
2235 if (pcap_src->cap_pipe_bytes_read == 0)
2236 snprintf(errmsg, errmsgl,
2237 "End of file on pipe header during open.");
2238 else
2239 snprintf(errmsg, errmsgl,
2240 "Error on pipe header header during open: %s.",
2241 g_strerror(errno));
2242 snprintf(secondary_errmsg, secondary_errmsgl, "%s",
2243 not_our_bug);
2244 goto error;
2247 #endif
2249 if (pcap_src->cap_pipe_info.pcap.byte_swapped) {
2250 /* Byte-swap the header fields about which we care. */
2251 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
2252 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
2253 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
2254 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
2257 * The link-layer header type field of the pcap header is
2258 * probably a LINKTYPE_ value, as the vast majority of
2259 * LINKTYPE_ values and their corresponding DLT_ values
2260 * are the same.
2262 * However, in case the file was written by a program
2263 * that used a DLT_ value, rather than a LINKTYPE_ value,
2264 * in one of the cases where the two differ, use dlt_to_linktype()
2265 * to map to a LINKTYPE_ value, just as we use it to map
2266 * the result of pcap_datalink() to a LINKTYPE_ value.
2268 pcap_src->linktype = dlt_to_linktype(hdr->network);
2269 /* Pick the appropriate maximum packet size for the link type */
2270 switch (pcap_src->linktype) {
2272 case 231: /* DLT_DBUS */
2273 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_DBUS;
2274 break;
2276 case 279: /* DLT_EBHSCR */
2277 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_EBHSCR;
2278 break;
2280 case 249: /* DLT_USBPCAP */
2281 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_USBPCAP;
2282 break;
2284 default:
2285 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
2286 break;
2289 if (hdr->version_major < 2) {
2290 snprintf(errmsg, errmsgl,
2291 "The old pcap format version %d.%d is not supported.",
2292 hdr->version_major, hdr->version_minor);
2293 snprintf(secondary_errmsg, secondary_errmsgl, "%s",
2294 not_our_bug);
2295 goto error;
2298 pcap_src->cap_pipe_fd = fd;
2299 return;
2301 error:
2302 ws_debug("pcap_pipe_open_live: error %s", errmsg);
2303 pcap_src->cap_pipe_err = PIPERR;
2304 cap_pipe_close(fd, pcap_src->from_cap_socket);
2305 pcap_src->cap_pipe_fd = -1;
2306 #ifdef _WIN32
2307 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2308 #endif
2312 * Synchronously read the fixed portion of the pcapng section header block
2313 * (we've already read the pcapng block header).
2315 static int
2316 pcapng_read_shb(capture_src *pcap_src,
2317 char *errmsg,
2318 size_t errmsgl)
2320 pcapng_section_header_block_t shb;
2322 #ifdef _WIN32
2323 if (pcap_src->from_cap_socket)
2324 #endif
2326 pcap_src->cap_pipe_bytes_to_read = sizeof(pcapng_block_header_t) + sizeof(pcapng_section_header_block_t);
2327 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2328 return -1;
2331 #ifdef _WIN32
2332 else {
2333 pipe_read_sync(pcap_src, pcap_src->cap_pipe_databuf + sizeof(pcapng_block_header_t),
2334 sizeof(pcapng_section_header_block_t));
2335 if (pcap_src->cap_pipe_bytes_read <= 0) {
2336 if (pcap_src->cap_pipe_bytes_read == 0)
2337 snprintf(errmsg, errmsgl,
2338 "End of file reading from pipe or socket.");
2339 else
2340 snprintf(errmsg, errmsgl,
2341 "Error reading from pipe or socket: %s.",
2342 g_strerror(errno));
2343 return -1;
2345 /* Continuing with STATE_EXPECT_DATA requires reading into cap_pipe_databuf at offset cap_pipe_bytes_read */
2346 pcap_src->cap_pipe_bytes_read = sizeof(pcapng_block_header_t) + sizeof(pcapng_section_header_block_t);
2348 #endif
2349 memcpy(&shb, pcap_src->cap_pipe_databuf + sizeof(pcapng_block_header_t), sizeof(pcapng_section_header_block_t));
2350 switch (shb.magic)
2352 case PCAPNG_MAGIC:
2353 ws_debug("pcapng SHB MAGIC");
2354 break;
2355 case PCAPNG_SWAPPED_MAGIC:
2356 ws_debug("pcapng SHB SWAPPED MAGIC");
2358 * pcapng sources can contain all sorts of block types.
2359 * Rather than add a bunch of complexity to this code (which is
2360 * often privileged), punt and tell the user to swap bytes
2361 * elsewhere.
2363 * XXX - punting means that the Wireshark test suite must be
2364 * modified to:
2366 * 1) have both little-endian and big-endian versions of
2367 * all pcapng files piped to dumpcap;
2369 * 2) pipe the appropriate file to dumpcap, depending on
2370 * the byte order of the host on which the tests are
2371 * being run;
2373 * as per comments in bug 15772 and 15754.
2375 * Are we *really* certain that the complexity added would be
2376 * significant enough to make adding it a security risk? And
2377 * why would this code even be running with any elevated
2378 * privileges if you're capturing from a pipe? We should not
2379 * only have given up all additional privileges if we're reading
2380 * from a pipe, we should give them up in such a fashion that
2381 * we can't reclaim them.
2383 #if G_BYTE_ORDER == G_BIG_ENDIAN
2384 #define OUR_ENDIAN "big"
2385 #define IFACE_ENDIAN "little"
2386 #else
2387 #define OUR_ENDIAN "little"
2388 #define IFACE_ENDIAN "big"
2389 #endif
2390 snprintf(errmsg, errmsgl,
2391 "Interface %u is " IFACE_ENDIAN " endian but we're " OUR_ENDIAN " endian.",
2392 pcap_src->interface_id);
2393 return -1;
2394 default:
2395 /* Not a pcapng type we know about, or not pcapng at all. */
2396 snprintf(errmsg, errmsgl,
2397 "Unrecognized pcapng format or not pcapng data.");
2398 return -1;
2401 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
2403 /* Setup state to capture any options following the section header block */
2404 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2406 return 0;
2410 * Save IDB blocks for playback whenever we change output files, and
2411 * fix LINKTYPE_ values that are really platform-dependent DLT_ values.
2412 * Rewrite EPB and ISB interface IDs.
2414 static bool
2415 pcapng_adjust_block(capture_src *pcap_src, const pcapng_block_header_t *bh, uint8_t *pd)
2417 switch(bh->block_type) {
2418 case BLOCK_TYPE_SHB:
2420 if (global_ld.pcapng_passthrough) {
2422 * We have a single pcapng input. We pass the SHB through when
2423 * writing a single output file and for the first ring buffer
2424 * file. We need to save it for the second and subsequent ring
2425 * buffer files.
2427 g_free(global_ld.saved_shb);
2428 global_ld.saved_shb = (uint8_t *) g_memdup2(pd, bh->block_total_length);
2431 * We're dealing with one section at a time, so we can (and must)
2432 * get rid of our old IDBs.
2434 for (unsigned i = 0; i < global_ld.saved_idbs->len; i++) {
2435 saved_idb_t *idb_source = &g_array_index(global_ld.saved_idbs, saved_idb_t, i);
2436 g_free(idb_source->idb);
2438 g_array_set_size(global_ld.saved_idbs, 0);
2439 } else {
2441 * We have a new SHB from this capture source. We need to keep
2442 * global_ld.saved_idbs intact, so we mark IDBs we previously
2443 * collected from this source as deleted.
2445 for (unsigned i = 0; i < pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len; i++) {
2446 uint32_t iface_id = g_array_index(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, uint32_t, i);
2447 saved_idb_t *idb_source = &g_array_index(global_ld.saved_idbs, saved_idb_t, iface_id);
2448 ws_assert(idb_source->interface_id == pcap_src->interface_id);
2449 g_free(idb_source->idb);
2450 memset(idb_source, 0, sizeof(saved_idb_t));
2451 idb_source->deleted = true;
2452 ws_debug("%s: deleted pcapng IDB %u", G_STRFUNC, iface_id);
2455 g_array_set_size(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, 0);
2457 break;
2458 case BLOCK_TYPE_IDB:
2461 * Always gather IDBs. We can remove them or mark them as deleted
2462 * when we get a new SHB.
2464 saved_idb_t idb_source = { 0 };
2465 idb_source.interface_id = pcap_src->interface_id;
2466 idb_source.idb_len = bh->block_total_length;
2467 idb_source.idb = (uint8_t *) g_memdup2(pd, idb_source.idb_len);
2468 g_array_append_val(global_ld.saved_idbs, idb_source);
2469 uint32_t iface_id = global_ld.saved_idbs->len - 1;
2470 g_array_append_val(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, iface_id);
2471 ws_debug("%s: mapped pcapng IDB %u -> %u from source %u",
2472 G_STRFUNC, pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len - 1, iface_id, pcap_src->interface_id);
2474 break;
2475 case BLOCK_TYPE_EPB:
2476 case BLOCK_TYPE_ISB:
2478 if (global_ld.pcapng_passthrough) {
2479 /* Our input and output interface IDs are the same. */
2480 break;
2482 /* The interface ID is the first 32-bit field after the BH for both EPBs and ISBs. */
2483 uint32_t iface_id;
2484 memcpy(&iface_id, pd + sizeof(pcapng_block_header_t), 4);
2485 if (iface_id < pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len) {
2486 memcpy(pd + sizeof(pcapng_block_header_t),
2487 &g_array_index(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, uint32_t, iface_id), 4);
2488 } else {
2489 ws_debug("%s: pcapng EPB or ISB interface id %u > max %u", G_STRFUNC, iface_id, pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len);
2490 return false;
2493 break;
2494 default:
2495 break;
2498 return true;
2502 * Return true if the block contains packet, event, or log data. Return false otherwise.
2504 static bool is_data_block(uint32_t block_type)
2506 // Any block types that lead to calling wtap_read_packet_bytes in
2507 // wiretap/pcapng.c should be listed here.
2508 switch (block_type) {
2509 case BLOCK_TYPE_PB:
2510 case BLOCK_TYPE_EPB:
2511 case BLOCK_TYPE_SPB:
2512 case BLOCK_TYPE_SYSTEMD_JOURNAL_EXPORT:
2513 case BLOCK_TYPE_SYSDIG_EVENT:
2514 case BLOCK_TYPE_SYSDIG_EVENT_V2:
2515 case BLOCK_TYPE_SYSDIG_EVENT_V2_LARGE:
2516 return true;
2517 default:
2518 break;
2520 return false;
2524 * Read the part of the initial pcapng SHB following the block type
2525 * (we've already read the block type).
2527 static void
2528 pcapng_pipe_open_live(int fd,
2529 capture_src *pcap_src,
2530 char *errmsg,
2531 size_t errmsgl)
2533 uint32_t type = BLOCK_TYPE_SHB;
2534 pcapng_block_header_t *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2536 ws_debug("pcapng_pipe_open_live: fd %d", fd);
2539 * A pcapng block begins with the block type followed by the block
2540 * total length; we've already read the block type, now read the
2541 * block length.
2543 #ifdef _WIN32
2545 * On UN*X, we can use select() on pipes or sockets.
2547 * On Windows, we can only use it on sockets; to do non-blocking
2548 * reads from pipes, we currently do reads in a separate thread
2549 * and use GLib asynchronous queues from the main thread to start
2550 * read operations and to wait for them to complete.
2552 if (pcap_src->from_cap_socket)
2553 #endif
2555 memcpy(pcap_src->cap_pipe_databuf, &type, sizeof(uint32_t));
2556 pcap_src->cap_pipe_bytes_read = sizeof(uint32_t);
2557 pcap_src->cap_pipe_bytes_to_read = sizeof(pcapng_block_header_t);
2558 pcap_src->cap_pipe_fd = fd;
2559 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2560 goto error;
2562 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(pcapng_block_header_t));
2564 #ifdef _WIN32
2565 else {
2566 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
2568 bh->block_type = type;
2569 pipe_read_sync(pcap_src, &bh->block_total_length,
2570 sizeof(bh->block_total_length));
2571 if (pcap_src->cap_pipe_bytes_read <= 0) {
2572 if (pcap_src->cap_pipe_bytes_read == 0)
2573 snprintf(errmsg, errmsgl,
2574 "End of file reading from pipe or socket.");
2575 else
2576 snprintf(errmsg, errmsgl,
2577 "Error reading from pipe or socket: %s.",
2578 g_strerror(errno));
2579 goto error;
2581 pcap_src->cap_pipe_bytes_read = sizeof(pcapng_block_header_t);
2582 memcpy(pcap_src->cap_pipe_databuf, bh, sizeof(pcapng_block_header_t));
2583 pcap_src->cap_pipe_fd = fd;
2585 #endif
2586 if ((bh->block_total_length & 0x03) != 0) {
2587 snprintf(errmsg, errmsgl,
2588 "block_total_length read from pipe is %u, which is not a multiple of 4.",
2589 bh->block_total_length);
2590 goto error;
2592 if (pcapng_read_shb(pcap_src, errmsg, errmsgl)) {
2593 goto error;
2596 return;
2598 error:
2599 ws_debug("pcapng_pipe_open_live: error %s", errmsg);
2600 pcap_src->cap_pipe_err = PIPERR;
2601 cap_pipe_close(fd, pcap_src->from_cap_socket);
2602 pcap_src->cap_pipe_fd = -1;
2603 #ifdef _WIN32
2604 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2605 #endif
2608 /* We read one record from the pipe, take care of byte order in the record
2609 * header, write the record to the capture file, and update capture statistics. */
2610 static int
2611 pcap_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, size_t errmsgl)
2613 struct pcap_pkthdr phdr;
2614 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2615 PD_ERR } result;
2616 #ifdef _WIN32
2617 void * q_status;
2618 #endif
2619 ssize_t b;
2620 unsigned new_bufsize;
2621 pcap_pipe_info_t *pcap_info = &pcap_src->cap_pipe_info.pcap;
2623 #ifdef LOG_CAPTURE_VERBOSE
2624 ws_debug("pcap_pipe_dispatch");
2625 #endif
2627 switch (pcap_src->cap_pipe_state) {
2629 case STATE_EXPECT_REC_HDR:
2630 #ifdef _WIN32
2631 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2632 #endif
2634 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2635 pcap_src->cap_pipe_bytes_to_read = pcap_src->cap_pipe_modified ?
2636 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2637 pcap_src->cap_pipe_bytes_read = 0;
2639 #ifdef _WIN32
2640 pcap_src->cap_pipe_buf = (char *) &pcap_info->rechdr;
2641 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2642 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2644 #endif
2645 /* Fall through */
2647 case STATE_READ_REC_HDR:
2648 #ifdef _WIN32
2649 if (pcap_src->from_cap_socket)
2650 #endif
2652 b = cap_pipe_read(pcap_src->cap_pipe_fd, ((char *)&pcap_info->rechdr)+pcap_src->cap_pipe_bytes_read,
2653 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read, pcap_src->from_cap_socket);
2654 if (b <= 0) {
2655 if (b == 0)
2656 result = PD_PIPE_EOF;
2657 else
2658 result = PD_PIPE_ERR;
2659 break;
2661 #ifdef _WIN32
2662 pcap_src->cap_pipe_bytes_read += (DWORD)b;
2663 #else
2664 pcap_src->cap_pipe_bytes_read += b;
2665 #endif
2667 #ifdef _WIN32
2668 else {
2669 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2670 if (pcap_src->cap_pipe_err == PIPEOF) {
2671 result = PD_PIPE_EOF;
2672 break;
2673 } else if (pcap_src->cap_pipe_err == PIPERR) {
2674 result = PD_PIPE_ERR;
2675 break;
2677 if (!q_status) {
2678 return 0;
2681 #endif
2682 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2683 /* There's still more of the pcap packet header to read. */
2684 return 0;
2686 result = PD_REC_HDR_READ;
2687 break;
2689 case STATE_EXPECT_DATA:
2690 #ifdef _WIN32
2691 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2692 #endif
2694 pcap_src->cap_pipe_state = STATE_READ_DATA;
2695 pcap_src->cap_pipe_bytes_to_read = pcap_info->rechdr.hdr.incl_len;
2696 pcap_src->cap_pipe_bytes_read = 0;
2698 #ifdef _WIN32
2699 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2700 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2701 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2703 #endif
2704 /* Fall through */
2706 case STATE_READ_DATA:
2707 #ifdef _WIN32
2708 if (pcap_src->from_cap_socket)
2709 #endif
2711 b = cap_pipe_read(pcap_src->cap_pipe_fd,
2712 pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read,
2713 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read,
2714 pcap_src->from_cap_socket);
2715 if (b <= 0) {
2716 if (b == 0)
2717 result = PD_PIPE_EOF;
2718 else
2719 result = PD_PIPE_ERR;
2720 break;
2722 #ifdef _WIN32
2723 pcap_src->cap_pipe_bytes_read += (DWORD)b;
2724 #else
2725 pcap_src->cap_pipe_bytes_read += b;
2726 #endif
2728 #ifdef _WIN32
2729 else {
2731 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2732 if (pcap_src->cap_pipe_err == PIPEOF) {
2733 result = PD_PIPE_EOF;
2734 break;
2735 } else if (pcap_src->cap_pipe_err == PIPERR) {
2736 result = PD_PIPE_ERR;
2737 break;
2739 if (!q_status) {
2740 return 0;
2743 #endif /* _WIN32 */
2744 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2745 /* There's still more of the pcap packet data to read. */
2746 return 0;
2748 result = PD_DATA_READ;
2749 break;
2751 default:
2752 snprintf(errmsg, errmsgl,
2753 "pcap_pipe_dispatch: invalid state");
2754 result = PD_ERR;
2756 } /* switch (pcap_src->cap_pipe_state) */
2759 * We've now read as much data as we were expecting, so process it.
2761 switch (result) {
2763 case PD_REC_HDR_READ:
2765 * We've read the packet header, so we know the captured length,
2766 * and thus the number of packet data bytes. Take care of byte order.
2768 cap_pipe_adjust_pcap_header(pcap_src->cap_pipe_info.pcap.byte_swapped, &pcap_info->hdr,
2769 &pcap_info->rechdr.hdr);
2770 if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_max_pkt_size) {
2772 * The record contains more data than the advertised/allowed in the
2773 * pcap header, do not try to read more data (do not change to
2774 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2775 * instead stop with an error.
2777 snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2778 ld->packets_captured+1, pcap_info->rechdr.hdr.incl_len);
2779 break;
2782 if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_databuf_size) {
2784 * Grow the buffer to the packet size, rounded up to a power of
2785 * 2.
2787 new_bufsize = pcap_info->rechdr.hdr.incl_len;
2789 * https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2791 new_bufsize--;
2792 new_bufsize |= new_bufsize >> 1;
2793 new_bufsize |= new_bufsize >> 2;
2794 new_bufsize |= new_bufsize >> 4;
2795 new_bufsize |= new_bufsize >> 8;
2796 new_bufsize |= new_bufsize >> 16;
2797 new_bufsize++;
2798 pcap_src->cap_pipe_databuf = (char*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2799 pcap_src->cap_pipe_databuf_size = new_bufsize;
2802 if (pcap_info->rechdr.hdr.incl_len) {
2804 * The record has some data following the header, try
2805 * to read it next time.
2807 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2808 return 0;
2812 * No data following the record header? Then no more data needs to be
2813 * read and we will fallthrough and emit an empty packet.
2815 /* FALLTHROUGH */
2817 case PD_DATA_READ:
2819 * We've read the full contents of the packet record.
2820 * Fill in a "struct pcap_pkthdr", and process the packet.
2822 phdr.ts.tv_sec = pcap_info->rechdr.hdr.ts_sec;
2823 phdr.ts.tv_usec = pcap_info->rechdr.hdr.ts_usec;
2824 phdr.caplen = pcap_info->rechdr.hdr.incl_len;
2825 phdr.len = pcap_info->rechdr.hdr.orig_len;
2827 if (use_threads) {
2828 capture_loop_queue_packet_cb((uint8_t *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2829 } else {
2830 capture_loop_write_packet_cb((uint8_t *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2834 * Now we want to read the next packet's header.
2836 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2837 return 1;
2839 case PD_PIPE_EOF:
2840 pcap_src->cap_pipe_err = PIPEOF;
2841 return -1;
2843 case PD_PIPE_ERR:
2844 snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2845 #ifdef _WIN32
2846 win32strerror(GetLastError()));
2847 #else
2848 g_strerror(errno));
2849 #endif
2850 /* Fall through */
2851 case PD_ERR:
2852 break;
2855 pcap_src->cap_pipe_err = PIPERR;
2856 /* Return here rather than inside the switch to prevent GCC warning */
2857 return -1;
2860 static int
2861 pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, size_t errmsgl)
2863 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2864 PD_ERR } result;
2865 #ifdef _WIN32
2866 void * q_status;
2867 #endif
2868 unsigned new_bufsize;
2869 pcapng_block_header_t *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2871 #ifdef LOG_CAPTURE_VERBOSE
2872 ws_debug("pcapng_pipe_dispatch");
2873 #endif
2875 switch (pcap_src->cap_pipe_state) {
2877 case STATE_EXPECT_REC_HDR:
2878 #ifdef LOG_CAPTURE_VERBOSE
2879 ws_debug("pcapng_pipe_dispatch STATE_EXPECT_REC_HDR");
2880 #endif
2881 #ifdef _WIN32
2882 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2883 #endif
2885 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2886 pcap_src->cap_pipe_bytes_to_read = sizeof(pcapng_block_header_t);
2887 pcap_src->cap_pipe_bytes_read = 0;
2889 #ifdef _WIN32
2890 if (!pcap_src->from_cap_socket) {
2891 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2892 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2894 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2896 #endif
2897 /* Fall through */
2899 case STATE_READ_REC_HDR:
2900 #ifdef LOG_CAPTURE_VERBOSE
2901 ws_debug("pcapng_pipe_dispatch STATE_READ_REC_HDR");
2902 #endif
2903 #ifdef _WIN32
2904 if (pcap_src->from_cap_socket) {
2905 #endif
2906 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2907 return -1;
2909 #ifdef _WIN32
2910 } else {
2911 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2912 if (pcap_src->cap_pipe_err == PIPEOF) {
2913 result = PD_PIPE_EOF;
2914 break;
2915 } else if (pcap_src->cap_pipe_err == PIPERR) {
2916 result = PD_PIPE_ERR;
2917 break;
2919 if (!q_status) {
2920 return 0;
2923 #endif
2924 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2925 /* There's still more of the pcapng block header to read. */
2926 return 0;
2928 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(pcapng_block_header_t));
2929 result = PD_REC_HDR_READ;
2930 break;
2932 case STATE_EXPECT_DATA:
2933 #ifdef LOG_CAPTURE_VERBOSE
2934 ws_debug("pcapng_pipe_dispatch STATE_EXPECT_DATA");
2935 #endif
2936 #ifdef _WIN32
2937 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2938 #endif
2939 pcap_src->cap_pipe_state = STATE_READ_DATA;
2940 pcap_src->cap_pipe_bytes_to_read = bh->block_total_length;
2942 #ifdef _WIN32
2943 if (!pcap_src->from_cap_socket) {
2944 pcap_src->cap_pipe_bytes_to_read -= pcap_src->cap_pipe_bytes_read;
2945 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf + pcap_src->cap_pipe_bytes_read;
2946 pcap_src->cap_pipe_bytes_read = 0;
2947 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2949 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2951 #endif
2952 /* Fall through */
2954 case STATE_READ_DATA:
2955 #ifdef LOG_CAPTURE_VERBOSE
2956 ws_debug("pcapng_pipe_dispatch STATE_READ_DATA");
2957 #endif
2958 #ifdef _WIN32
2959 if (pcap_src->from_cap_socket) {
2960 #endif
2961 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2962 return -1;
2964 #ifdef _WIN32
2965 } else {
2967 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2968 if (pcap_src->cap_pipe_err == PIPEOF) {
2969 result = PD_PIPE_EOF;
2970 break;
2971 } else if (pcap_src->cap_pipe_err == PIPERR) {
2972 result = PD_PIPE_ERR;
2973 break;
2975 if (!q_status) {
2976 return 0;
2979 #endif /* _WIN32 */
2980 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2981 /* There's still more of the pcap block contents to read. */
2982 return 0;
2984 result = PD_DATA_READ;
2985 break;
2987 default:
2988 snprintf(errmsg, errmsgl,
2989 "pcapng_pipe_dispatch: invalid state");
2990 result = PD_ERR;
2992 } /* switch (pcap_src->cap_pipe_state) */
2995 * We've now read as much data as we were expecting, so process it.
2997 switch (result) {
2999 case PD_REC_HDR_READ:
3001 * We've read the pcapng block header, so we know the block type
3002 * and length.
3004 if (bh->block_type == BLOCK_TYPE_SHB) {
3006 * We need to read the fixed portion of the SHB before to
3007 * get the endianness before we can interpret the block length.
3008 * (The block type of the SHB is byte-order-independent, so that
3009 * an SHB can be recognized before we know the endianness of
3010 * the section.)
3012 * Continue the read process.
3014 pcapng_read_shb(pcap_src, errmsg, errmsgl);
3015 return 1;
3018 if ((bh->block_total_length & 0x03) != 0) {
3019 snprintf(errmsg, errmsgl,
3020 "Total length of pcapng block read from pipe is %u, which is not a multiple of 4.",
3021 bh->block_total_length);
3022 break;
3024 if (is_data_block(bh->block_type) && bh->block_total_length > pcap_src->cap_pipe_max_pkt_size) {
3026 * The record contains more data than the advertised/allowed in the
3027 * pcapng header, do not try to read more data (do not change to
3028 * STATE_EXPECT_DATA) as that would not fit in the buffer and
3029 * instead stop with an error.
3031 snprintf(errmsg, errmsgl, "Block %u type 0x%08x too long (%d bytes)",
3032 ld->packets_captured+1, bh->block_type, bh->block_total_length);
3033 break;
3036 if (bh->block_total_length > pcap_src->cap_pipe_databuf_size) {
3038 * Grow the buffer to the packet size, rounded up to a power of
3039 * 2.
3041 new_bufsize = bh->block_total_length;
3043 * https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
3045 new_bufsize--;
3046 new_bufsize |= new_bufsize >> 1;
3047 new_bufsize |= new_bufsize >> 2;
3048 new_bufsize |= new_bufsize >> 4;
3049 new_bufsize |= new_bufsize >> 8;
3050 new_bufsize |= new_bufsize >> 16;
3051 new_bufsize++;
3052 pcap_src->cap_pipe_databuf = (unsigned char*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
3053 pcap_src->cap_pipe_databuf_size = new_bufsize;
3056 /* The record always has at least the block total length following the header */
3057 if (bh->block_total_length < sizeof(pcapng_block_header_t)+sizeof(uint32_t)) {
3058 snprintf(errmsg, errmsgl,
3059 "malformed pcapng block_total_length < minimum");
3060 pcap_src->cap_pipe_err = PIPEOF;
3061 return -1;
3065 * Now we want to read the block contents.
3067 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
3068 return 0;
3070 case PD_DATA_READ:
3072 * We've read the full contents of the block.
3073 * Process the block.
3075 if (use_threads) {
3076 capture_loop_queue_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
3077 } else {
3078 capture_loop_write_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
3082 * Now we want to read the next block's header.
3084 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
3085 return 1;
3087 case PD_PIPE_EOF:
3088 pcap_src->cap_pipe_err = PIPEOF;
3089 return -1;
3091 case PD_PIPE_ERR:
3092 snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
3093 #ifdef _WIN32
3094 win32strerror(GetLastError()));
3095 #else
3096 g_strerror(errno));
3097 #endif
3098 /* Fall through */
3099 case PD_ERR:
3100 break;
3103 pcap_src->cap_pipe_err = PIPERR;
3104 /* Return here rather than inside the switch to prevent GCC warning */
3105 return -1;
3108 /** Open the capture input sources; each one is either a pcap device,
3109 * a capture pipe, or a capture socket.
3110 * Returns true if it succeeds, false otherwise. */
3111 static bool
3112 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
3113 char *errmsg, size_t errmsg_len,
3114 char *secondary_errmsg, size_t secondary_errmsg_len)
3116 cap_device_open_status open_status;
3117 char open_status_str[PCAP_ERRBUF_SIZE];
3118 char *sync_msg_str;
3119 interface_options *interface_opts;
3120 capture_src *pcap_src;
3121 unsigned i;
3123 if ((use_threads == false) &&
3124 (capture_opts->ifaces->len > 1)) {
3125 snprintf(errmsg, errmsg_len,
3126 "Using threads is required for capturing on multiple interfaces.");
3127 return false;
3130 int pcapng_src_count = 0;
3131 for (i = 0; i < capture_opts->ifaces->len; i++) {
3132 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
3133 pcap_src = g_new0(capture_src, 1);
3134 if (pcap_src == NULL) {
3135 snprintf(errmsg, errmsg_len,
3136 "Could not allocate memory.");
3137 return false;
3140 #ifdef MUST_DO_SELECT
3141 pcap_src->pcap_fd = -1;
3142 #endif
3143 pcap_src->interface_id = i;
3144 pcap_src->linktype = -1;
3145 #ifdef _WIN32
3146 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
3147 #endif
3148 pcap_src->cap_pipe_fd = -1;
3149 pcap_src->cap_pipe_dispatch = pcap_pipe_dispatch;
3150 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
3151 pcap_src->cap_pipe_err = PIPOK;
3152 #ifdef _WIN32
3153 pcap_src->cap_pipe_read_mtx = g_new(GMutex, 1);
3154 g_mutex_init(pcap_src->cap_pipe_read_mtx);
3155 pcap_src->cap_pipe_pending_q = g_async_queue_new();
3156 pcap_src->cap_pipe_done_q = g_async_queue_new();
3157 #endif
3158 g_array_append_val(ld->pcaps, pcap_src);
3160 ws_debug("capture_loop_open_input : %s", interface_opts->name);
3161 pcap_src->pcap_h = open_capture_device(capture_opts, interface_opts,
3162 CAP_READ_TIMEOUT, &open_status, &open_status_str);
3164 if (pcap_src->pcap_h != NULL) {
3165 /* we've opened "iface" as a network device */
3167 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
3168 /* Find out if we're getting nanosecond-precision time stamps */
3169 pcap_src->ts_nsec = have_high_resolution_timestamp(pcap_src->pcap_h);
3170 #endif
3172 #if defined(HAVE_PCAP_SETSAMPLING)
3173 if (interface_opts->sampling_method != CAPTURE_SAMP_NONE) {
3174 struct pcap_samp *samp;
3176 if ((samp = pcap_setsampling(pcap_src->pcap_h)) != NULL) {
3177 switch (interface_opts->sampling_method) {
3178 case CAPTURE_SAMP_BY_COUNT:
3179 samp->method = PCAP_SAMP_1_EVERY_N;
3180 break;
3182 case CAPTURE_SAMP_BY_TIMER:
3183 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
3184 break;
3186 default:
3187 sync_msg_str = ws_strdup_printf(
3188 "Unknown sampling method %d specified,\n"
3189 "continue without packet sampling",
3190 interface_opts->sampling_method);
3191 report_capture_error("Couldn't set the capture "
3192 "sampling", sync_msg_str);
3193 g_free(sync_msg_str);
3195 samp->value = interface_opts->sampling_param;
3196 } else {
3197 report_capture_error("Couldn't set the capture sampling",
3198 "Cannot get packet sampling data structure");
3201 #endif
3203 /* setting the data link type only works on real interfaces */
3204 if (!set_pcap_datalink(pcap_src->pcap_h, interface_opts->linktype,
3205 interface_opts->name,
3206 errmsg, errmsg_len,
3207 secondary_errmsg, secondary_errmsg_len)) {
3208 return false;
3210 pcap_src->linktype = dlt_to_linktype(get_pcap_datalink(pcap_src->pcap_h, interface_opts->name));
3211 } else {
3212 /* We couldn't open "iface" as a network device. */
3213 /* Try to open it as a pipe */
3214 bool pipe_err = false;
3215 cap_pipe_open_live(interface_opts->name, pcap_src,
3216 &pcap_src->cap_pipe_info.pcap.hdr,
3217 errmsg, errmsg_len,
3218 secondary_errmsg, secondary_errmsg_len);
3220 #ifdef _WIN32
3221 if (pcap_src->from_cap_socket) {
3222 #endif
3223 if (pcap_src->cap_pipe_fd == -1) {
3224 pipe_err = true;
3226 #ifdef _WIN32
3227 } else {
3228 if (pcap_src->cap_pipe_h == INVALID_HANDLE_VALUE) {
3229 pipe_err = true;
3232 #endif
3234 if (pipe_err) {
3235 if (pcap_src->cap_pipe_err == PIPNEXIST) {
3237 * We tried opening as an interface, and that failed,
3238 * so we tried to open it as a pipe, but the pipe
3239 * doesn't exist. Report the error message for
3240 * the interface.
3242 get_capture_device_open_failure_messages(open_status,
3243 open_status_str,
3244 interface_opts->name,
3245 errmsg,
3246 errmsg_len,
3247 secondary_errmsg,
3248 secondary_errmsg_len);
3251 * Else pipe (or file) does exist and cap_pipe_open_live() has
3252 * filled in errmsg
3254 return false;
3255 } else {
3257 * We tried opening as an interface, and that failed,
3258 * so we tried to open it as a pipe, and that succeeded.
3260 open_status = CAP_DEVICE_OPEN_NO_ERR;
3264 /* XXX - will this work for tshark? */
3265 #ifdef MUST_DO_SELECT
3266 if (!pcap_src->from_cap_pipe) {
3267 pcap_src->pcap_fd = pcap_get_selectable_fd(pcap_src->pcap_h);
3269 #endif
3271 /* Is "open_status" something other than CAP_DEVICE_OPEN_NO_ERR?
3272 If so, "open_capture_device()" returned a warning; print it,
3273 but keep capturing. */
3274 if (open_status != CAP_DEVICE_OPEN_NO_ERR) {
3275 sync_msg_str = ws_strdup_printf("%s.", open_status_str);
3276 report_capture_error(sync_msg_str, "");
3277 g_free(sync_msg_str);
3279 if (pcap_src->from_pcapng) {
3281 * We will use the IDBs from the source (but rewrite the
3282 * interface IDs if there's more than one source.)
3284 pcapng_src_count++;
3285 } else {
3287 * Add our pcapng interface entry.
3289 saved_idb_t idb_source = { 0 };
3290 idb_source.interface_id = i;
3291 g_rw_lock_writer_lock (&ld->saved_shb_idb_lock);
3292 pcap_src->idb_id = global_ld.saved_idbs->len;
3293 g_array_append_val(global_ld.saved_idbs, idb_source);
3294 g_rw_lock_writer_unlock (&ld->saved_shb_idb_lock);
3295 ws_debug("%s: saved capture_opts %u to IDB %u",
3296 G_STRFUNC, i, pcap_src->idb_id);
3301 * Are we capturing from one source that is providing pcapng
3302 * information?
3304 if (capture_opts->ifaces->len == 1 && pcapng_src_count == 1) {
3306 * Yes; pass through SHBs and IDBs from the source, rather
3307 * than generating our own.
3309 ld->pcapng_passthrough = true;
3310 g_rw_lock_writer_lock (&ld->saved_shb_idb_lock);
3311 ws_assert(global_ld.saved_idbs->len == 0);
3312 ws_debug("%s: Pass through SHBs and IDBs directly", G_STRFUNC);
3313 g_rw_lock_writer_unlock (&ld->saved_shb_idb_lock);
3316 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
3317 /* to remove any suid privileges. */
3318 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
3319 /* (euid/egid have already previously been set to ruid/rgid. */
3320 /* (See comment in main() for details) */
3321 #ifndef HAVE_LIBCAP
3322 relinquish_special_privs_perm();
3323 #else
3324 relinquish_all_capabilities();
3325 #endif
3326 return true;
3329 /* close the capture input file (pcap or capture pipe) */
3330 static void capture_loop_close_input(loop_data *ld)
3332 unsigned i;
3333 capture_src *pcap_src;
3335 ws_debug("capture_loop_close_input");
3337 for (i = 0; i < ld->pcaps->len; i++) {
3338 pcap_src = g_array_index(ld->pcaps, capture_src *, i);
3339 /* Pipe, or capture device? */
3340 if (pcap_src->from_cap_pipe) {
3341 /* Pipe. If open, close the capture pipe "input file". */
3342 if (pcap_src->cap_pipe_fd >= 0) {
3343 cap_pipe_close(pcap_src->cap_pipe_fd, pcap_src->from_cap_socket);
3344 pcap_src->cap_pipe_fd = -1;
3346 #ifdef _WIN32
3347 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE) {
3348 CloseHandle(pcap_src->cap_pipe_h);
3349 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
3351 #endif
3352 if (pcap_src->cap_pipe_databuf != NULL) {
3353 /* Free the buffer. */
3354 g_free(pcap_src->cap_pipe_databuf);
3355 pcap_src->cap_pipe_databuf = NULL;
3357 if (pcap_src->from_pcapng) {
3358 g_array_free(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, TRUE);
3359 pcap_src->cap_pipe_info.pcapng.src_iface_to_global = NULL;
3361 } else {
3362 /* Capture device. If open, close the pcap_t. */
3363 if (pcap_src->pcap_h != NULL) {
3364 ws_debug("capture_loop_close_input: closing %p", (void *)pcap_src->pcap_h);
3365 pcap_close(pcap_src->pcap_h);
3366 pcap_src->pcap_h = NULL;
3371 ld->go = false;
3375 /* init the capture filter */
3376 static initfilter_status_t
3377 capture_loop_init_filter(pcap_t *pcap_h, bool from_cap_pipe,
3378 const char * name, const char * cfilter)
3380 struct bpf_program fcode;
3382 ws_debug("capture_loop_init_filter: %s", cfilter);
3384 /* capture filters only work on real interfaces */
3385 if (cfilter && !from_cap_pipe) {
3386 /* A capture filter was specified; set it up. */
3387 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
3388 /* Treat this specially - our caller might try to compile this
3389 as a display filter and, if that succeeds, warn the user that
3390 the display and capture filter syntaxes are different. */
3391 return INITFILTER_BAD_FILTER;
3393 if (pcap_setfilter(pcap_h, &fcode) < 0) {
3394 #ifdef HAVE_PCAP_FREECODE
3395 pcap_freecode(&fcode);
3396 #endif
3397 return INITFILTER_OTHER_ERROR;
3399 #ifdef HAVE_PCAP_FREECODE
3400 pcap_freecode(&fcode);
3401 #endif
3404 return INITFILTER_NO_ERROR;
3408 * Write the dumpcap pcapng SHB and IDBs if needed.
3409 * Called from capture_loop_init_output and do_file_switch_or_stop.
3411 static bool
3412 capture_loop_init_pcapng_output(capture_options *capture_opts, loop_data *ld,
3413 int *err)
3415 g_rw_lock_reader_lock (&ld->saved_shb_idb_lock);
3417 if (ld->pcapng_passthrough && !ld->saved_shb) {
3418 /* We have a single pcapng capture interface and this is the first or only output file. */
3419 ws_debug("%s: skipping dumpcap SHB and IDBs in favor of source", G_STRFUNC);
3420 g_rw_lock_reader_unlock (&ld->saved_shb_idb_lock);
3421 return true;
3424 bool successful = true;
3425 GString *os_info_str = g_string_new("");
3427 *err = 0;
3428 get_os_version_info(os_info_str);
3430 if (ld->saved_shb) {
3431 /* We have a single pcapng capture interface and multiple output files. */
3433 pcapng_block_header_t bh;
3435 memcpy(&bh, ld->saved_shb, sizeof(pcapng_block_header_t));
3437 successful = pcapng_write_block(ld->pdh, ld->saved_shb, bh.block_total_length, &ld->bytes_written, err);
3439 ws_debug("%s: wrote saved passthrough SHB %d", G_STRFUNC, successful);
3440 } else {
3441 GString *cpu_info_str = g_string_new("");
3442 get_cpu_info(cpu_info_str);
3444 successful = pcapng_write_section_header_block(ld->pdh,
3445 capture_comments, /* Comments */
3446 cpu_info_str->str, /* HW */
3447 os_info_str->str, /* OS */
3448 get_appname_and_version(),
3449 -1, /* section_length */
3450 &ld->bytes_written,
3451 err);
3452 ws_debug("%s: wrote dumpcap SHB %d", G_STRFUNC, successful);
3453 g_string_free(cpu_info_str, TRUE);
3456 for (unsigned i = 0; successful && (i < ld->saved_idbs->len); i++) {
3457 saved_idb_t idb_source = g_array_index(ld->saved_idbs, saved_idb_t, i);
3458 if (idb_source.deleted) {
3460 * Our interface is out of scope. Suppose we're writing multiple
3461 * files and a source switches sections. We currently write dummy
3462 * IDBs like so:
3464 * File 1: IDB0, IDB1, IDB2
3465 * [ The source of IDBs 1 and 2 writes an SHB with two new IDBs ]
3466 * [ We switch output files ]
3467 * File 2: IDB0, dummy IDB, dummy IDB, IDB3, IDB4
3469 * It might make more sense to write the original data so that
3470 * so that our IDB lists are more consistent across files.
3472 successful = pcapng_write_interface_description_block(global_ld.pdh,
3473 "Interface went out of scope", /* OPT_COMMENT 1 */
3474 "dummy", /* IDB_NAME 2 */
3475 "Dumpcap dummy interface", /* IDB_DESCRIPTION 3 */
3476 NULL, /* IDB_FILTER 11 */
3477 os_info_str->str, /* IDB_OS 12 */
3478 NULL, /* IDB_HARDWARE 15 */
3481 &(global_ld.bytes_written),
3482 0, /* IDB_IF_SPEED 8 */
3483 6, /* IDB_TSRESOL 9 */
3484 &global_ld.err);
3485 ws_debug("%s: skipping deleted pcapng IDB %u", G_STRFUNC, i);
3486 } else if (idb_source.idb && idb_source.idb_len) {
3487 successful = pcapng_write_block(global_ld.pdh, idb_source.idb, idb_source.idb_len, &ld->bytes_written, err);
3488 ws_debug("%s: wrote pcapng IDB %d", G_STRFUNC, successful);
3489 } else if (idb_source.interface_id < capture_opts->ifaces->len) {
3490 unsigned if_id = idb_source.interface_id;
3491 interface_options *interface_opts = &g_array_index(capture_opts->ifaces, interface_options, if_id);
3492 capture_src *pcap_src = g_array_index(ld->pcaps, capture_src *, if_id);
3493 if (pcap_src->from_cap_pipe) {
3494 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
3495 } else {
3496 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
3498 successful = pcapng_write_interface_description_block(global_ld.pdh,
3499 NULL, /* OPT_COMMENT 1 */
3500 (interface_opts->ifname != NULL) ? interface_opts->ifname : interface_opts->name, /* IDB_NAME 2 */
3501 interface_opts->descr, /* IDB_DESCRIPTION 3 */
3502 interface_opts->cfilter, /* IDB_FILTER 11 */
3503 os_info_str->str, /* IDB_OS 12 */
3504 interface_opts->hardware, /* IDB_HARDWARE 15 */
3505 pcap_src->linktype,
3506 pcap_src->snaplen,
3507 &(global_ld.bytes_written),
3508 0, /* IDB_IF_SPEED 8 */
3509 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3510 &global_ld.err);
3511 ws_debug("%s: wrote capture_opts IDB %d: %d", G_STRFUNC, if_id, successful);
3514 g_rw_lock_reader_unlock (&ld->saved_shb_idb_lock);
3516 g_string_free(os_info_str, TRUE);
3518 return successful;
3521 /* set up to write to the already-opened capture output file/files */
3522 static bool
3523 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
3525 int err = 0;
3527 ws_debug("capture_loop_init_output");
3529 if ((capture_opts->use_pcapng == false) &&
3530 (capture_opts->ifaces->len > 1)) {
3531 snprintf(errmsg, errmsg_len,
3532 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
3533 return false;
3536 /* Set up to write to the capture file. */
3537 if (capture_opts->multi_files_on) {
3538 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
3539 } else {
3540 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
3541 if (ld->pdh == NULL) {
3542 err = errno;
3543 } else {
3544 size_t buffsize = IO_BUF_SIZE;
3545 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
3546 ws_statb64 statb;
3548 if (ws_fstat64(ld->save_file_fd, &statb) == 0) {
3549 if (statb.st_blksize > IO_BUF_SIZE) {
3550 buffsize = statb.st_blksize;
3553 #endif
3554 /* Increase the size of the IO buffer */
3555 ld->io_buffer = (char *)g_malloc(buffsize);
3556 setvbuf(ld->pdh, ld->io_buffer, _IOFBF, buffsize);
3557 ws_debug("capture_loop_init_output: buffsize %zu", buffsize);
3560 if (ld->pdh) {
3561 bool successful;
3562 if (capture_opts->use_pcapng) {
3563 successful = capture_loop_init_pcapng_output(capture_opts, ld, &err);
3564 } else {
3565 capture_src *pcap_src;
3566 pcap_src = g_array_index(ld->pcaps, capture_src *, 0);
3567 if (pcap_src->from_cap_pipe) {
3568 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
3569 } else {
3570 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
3572 successful = libpcap_write_file_header(ld->pdh, pcap_src->linktype, pcap_src->snaplen,
3573 pcap_src->ts_nsec, &ld->bytes_written, &err);
3575 if (!successful) {
3576 fclose(ld->pdh);
3577 ld->pdh = NULL;
3578 g_free(ld->io_buffer);
3579 ld->io_buffer = NULL;
3583 if (ld->pdh == NULL) {
3584 /* We couldn't set up to write to the capture file. */
3585 /* XXX - use cf_open_error_message from tshark instead? */
3586 if (err < 0) {
3587 snprintf(errmsg, errmsg_len,
3588 "The file to which the capture would be"
3589 " saved (\"%s\") could not be opened: Error %d.",
3590 capture_opts->save_file, err);
3591 } else {
3592 snprintf(errmsg, errmsg_len,
3593 "The file to which the capture would be"
3594 " saved (\"%s\") could not be opened: %s.",
3595 capture_opts->save_file, g_strerror(err));
3597 return false;
3600 return true;
3603 static bool
3604 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
3607 unsigned int i;
3608 capture_src *pcap_src;
3609 uint64_t end_time = create_timestamp();
3610 bool success;
3612 ws_debug("capture_loop_close_output");
3614 if (capture_opts->multi_files_on) {
3615 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
3616 } else {
3617 if (capture_opts->use_pcapng) {
3618 for (i = 0; i < global_ld.pcaps->len; i++) {
3619 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3620 if (!pcap_src->from_cap_pipe) {
3621 uint64_t isb_ifrecv, isb_ifdrop;
3622 struct pcap_stat stats;
3624 if (pcap_stats(pcap_src->pcap_h, &stats) >= 0) {
3625 isb_ifrecv = pcap_src->received;
3626 isb_ifdrop = stats.ps_drop + pcap_src->dropped + pcap_src->flushed;
3627 } else {
3628 isb_ifrecv = UINT64_MAX;
3629 isb_ifdrop = UINT64_MAX;
3631 pcapng_write_interface_statistics_block(ld->pdh,
3633 &ld->bytes_written,
3634 "Counters provided by dumpcap",
3635 start_time,
3636 end_time,
3637 isb_ifrecv,
3638 isb_ifdrop,
3639 err_close);
3643 if (fclose(ld->pdh) == EOF) {
3644 if (err_close != NULL) {
3645 *err_close = errno;
3647 success = false;
3648 } else {
3649 success = true;
3651 g_free(ld->io_buffer);
3652 ld->io_buffer = NULL;
3653 return success;
3657 /* dispatch incoming packets (pcap or capture pipe)
3659 * Waits for incoming packets to be available, and calls pcap_dispatch()
3660 * to cause them to be processed.
3662 * Returns the number of packets which were processed.
3664 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3665 * packet-batching behaviour does not cause packets to get held back
3666 * indefinitely.
3668 static int
3669 capture_loop_dispatch(loop_data *ld,
3670 char *errmsg, int errmsg_len, capture_src *pcap_src)
3672 int inpkts = 0;
3673 int packet_count_before;
3674 int sel_ret;
3676 packet_count_before = ld->packets_captured;
3677 if (pcap_src->from_cap_pipe) {
3678 /* dispatch from capture pipe */
3679 #ifdef LOG_CAPTURE_VERBOSE
3680 ws_debug("capture_loop_dispatch: from capture pipe");
3681 #endif
3682 #ifdef _WIN32
3683 if (pcap_src->from_cap_socket) {
3684 #endif
3685 sel_ret = cap_pipe_select(pcap_src->cap_pipe_fd);
3686 if (sel_ret <= 0) {
3687 if (sel_ret < 0 && errno != EINTR) {
3688 snprintf(errmsg, errmsg_len,
3689 "Unexpected error from select: %s", g_strerror(errno));
3690 report_capture_error(errmsg, please_report_bug());
3691 ld->go = false;
3694 #ifdef _WIN32
3695 } else {
3696 /* Windows does not have select() for pipes. */
3697 /* Proceed with _dispatch() which waits for cap_pipe_done_q
3698 * notification from cap_thread_read() when ReadFile() on
3699 * the pipe has read enough bytes. */
3700 sel_ret = 1;
3702 #endif
3703 if (sel_ret > 0) {
3705 * "select()" says we can read from the pipe without blocking
3707 inpkts = pcap_src->cap_pipe_dispatch(ld, pcap_src, errmsg, errmsg_len);
3708 if (inpkts < 0) {
3709 ws_debug("%s: src %u pipe reached EOF or err, rcv: %u drop: %u flush: %u",
3710 G_STRFUNC, pcap_src->interface_id, pcap_src->received, pcap_src->dropped, pcap_src->flushed);
3711 ws_assert(pcap_src->cap_pipe_err != PIPOK);
3715 else
3717 /* dispatch from pcap */
3718 #ifdef MUST_DO_SELECT
3720 * If we have "pcap_get_selectable_fd()", we use it to get the
3721 * descriptor on which to select; if that's -1, it means there
3722 * is no descriptor on which you can do a "select()" (perhaps
3723 * because you're capturing on a special device, and that device's
3724 * driver unfortunately doesn't support "select()", in which case
3725 * we don't do the select - which means it might not be possible
3726 * to stop a capture until a packet arrives. If that's unacceptable,
3727 * plead with whoever supplies the software for that device to add
3728 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3729 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3730 * later, so it can use pcap_breakloop().
3732 #ifdef LOG_CAPTURE_VERBOSE
3733 ws_debug("capture_loop_dispatch: from pcap_dispatch with select");
3734 #endif
3735 if (pcap_src->pcap_fd != -1) {
3736 sel_ret = cap_pipe_select(pcap_src->pcap_fd);
3737 if (sel_ret > 0) {
3739 * "select()" says we can read from it without blocking; go for
3740 * it.
3742 * We don't have pcap_breakloop(), so we only process one packet
3743 * per pcap_dispatch() call, to allow a signal to stop the
3744 * processing immediately, rather than processing all packets
3745 * in a batch before quitting.
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 if (inpkts < 0) {
3753 if (inpkts == -1) {
3754 /* Error, rather than pcap_breakloop(). */
3755 pcap_src->pcap_err = true;
3757 ld->go = false; /* error or pcap_breakloop() - stop capturing */
3759 } else {
3760 if (sel_ret < 0 && errno != EINTR) {
3761 snprintf(errmsg, errmsg_len,
3762 "Unexpected error from select: %s", g_strerror(errno));
3763 report_capture_error(errmsg, please_report_bug());
3764 ld->go = false;
3768 else
3769 #endif /* MUST_DO_SELECT */
3771 /* dispatch from pcap without select */
3772 #if 1
3773 #ifdef LOG_CAPTURE_VERBOSE
3774 ws_debug("capture_loop_dispatch: from pcap_dispatch");
3775 #endif
3776 #ifdef _WIN32
3778 * On Windows, we don't support asynchronously telling a process to
3779 * stop capturing; instead, we check for an indication on a pipe
3780 * after processing packets. We therefore process only one packet
3781 * at a time, so that we can check the pipe after every packet.
3783 if (use_threads) {
3784 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (uint8_t *)pcap_src);
3785 } else {
3786 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (uint8_t *)pcap_src);
3788 #else
3789 if (use_threads) {
3790 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_queue_packet_cb, (uint8_t *)pcap_src);
3791 } else {
3792 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_write_packet_cb, (uint8_t *)pcap_src);
3794 #endif
3795 if (inpkts < 0) {
3796 if (inpkts == -1) {
3797 /* Error, rather than pcap_breakloop(). */
3798 pcap_src->pcap_err = true;
3800 ld->go = false; /* error or pcap_breakloop() - stop capturing */
3802 #else /* pcap_next_ex */
3803 #ifdef LOG_CAPTURE_VERBOSE
3804 ws_debug("capture_loop_dispatch: from pcap_next_ex");
3805 #endif
3806 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3809 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3810 * see https://gitlab.com/wireshark/wireshark/-/wikis/CaptureSetup/WinPcapRemote
3811 * This should be fixed in the WinPcap 4.0 alpha release.
3813 * For reference, an example remote interface:
3814 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3817 /* emulate dispatch from pcap */
3819 int in;
3820 struct pcap_pkthdr *pkt_header;
3821 uint8_t *pkt_data;
3823 in = 0;
3824 while(ld->go &&
3825 (in = pcap_next_ex(pcap_src->pcap_h, &pkt_header, &pkt_data)) == 1) {
3826 if (use_threads) {
3827 capture_loop_queue_packet_cb((uint8_t *)pcap_src, pkt_header, pkt_data);
3828 } else {
3829 capture_loop_write_packet_cb((uint8_t *)pcap_src, pkt_header, pkt_data);
3833 if (in < 0) {
3834 pcap_src->pcap_err = true;
3835 ld->go = false;
3838 #endif /* pcap_next_ex */
3842 #ifdef LOG_CAPTURE_VERBOSE
3843 ws_debug("capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3844 #endif
3846 return ld->packets_captured - packet_count_before;
3849 #ifdef _WIN32
3850 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3851 * want to grab only the characters between the '{' and '}' delimiters.
3853 * Returns a GString that must be freed with g_string_free(). */
3854 static GString *
3855 isolate_uuid(const char *iface)
3857 char *ptr;
3858 GString *gstr;
3860 ptr = strchr(iface, '{');
3861 if (ptr == NULL)
3862 return g_string_new(iface);
3863 gstr = g_string_new(ptr + 1);
3865 ptr = strchr(gstr->str, '}');
3866 if (ptr == NULL)
3867 return gstr;
3869 gstr = g_string_truncate(gstr, ptr - gstr->str);
3870 return gstr;
3872 #endif
3874 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3875 /* Returns true if the file opened successfully, false otherwise. */
3876 static bool
3877 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3878 char *errmsg, int errmsg_len)
3880 char *capfile_name = NULL;
3881 char *prefix, *suffix;
3882 bool is_tempfile;
3883 GError *err_tempfile = NULL;
3885 ws_debug("capture_loop_open_output: %s",
3886 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3888 if (capture_opts->save_file != NULL) {
3889 /* We return to the caller while the capture is in progress.
3890 * Therefore we need to take a copy of save_file in
3891 * case the caller destroys it after we return.
3893 capfile_name = g_strdup(capture_opts->save_file);
3895 if (capture_opts->output_to_pipe == true) { /* either "-" or named pipe */
3896 if (capture_opts->multi_files_on) {
3897 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3898 snprintf(errmsg, errmsg_len,
3899 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3900 g_free(capfile_name);
3901 return false;
3903 if (strcmp(capfile_name, "-") == 0) {
3904 /* write to stdout */
3905 *save_file_fd = 1;
3906 #ifdef _WIN32
3907 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3908 _setmode(1, O_BINARY);
3909 #endif
3910 } else {
3911 /* Try to open the specified FIFO for use as a capture buffer.
3912 Do *not* create it if it doesn't exist. There's nothing
3913 to truncate. If we need to read it, We Have A Problem. */
3914 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY, 0);
3916 } /* if (...output_to_pipe ... */
3918 else {
3919 if (capture_opts->multi_files_on) {
3920 /* ringbuffer is enabled */
3921 *save_file_fd = ringbuf_init(capfile_name,
3922 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3923 capture_opts->group_read_access,
3924 capture_opts->compress_type,
3925 capture_opts->has_nametimenum);
3927 /* capfile_name is unused as the ringbuffer provides its own filename. */
3928 if (*save_file_fd != -1) {
3929 g_free(capfile_name);
3930 capfile_name = NULL;
3932 if (capture_opts->print_file_names) {
3933 if (!ringbuf_set_print_name(capture_opts->print_name_to, NULL)) {
3934 snprintf(errmsg, errmsg_len, "Could not write filenames to %s: %s.\n",
3935 capture_opts->print_name_to,
3936 g_strerror(errno));
3937 g_free(capfile_name);
3938 ringbuf_error_cleanup();
3939 return false;
3942 } else {
3943 /* Try to open/create the specified file for use as a capture buffer. */
3944 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY|O_TRUNC|O_CREAT,
3945 (capture_opts->group_read_access) ? 0640 : 0600);
3948 is_tempfile = false;
3949 } else {
3950 /* Choose a random name for the temporary capture buffer */
3951 if (global_capture_opts.ifaces->len > 1) {
3953 * More than one interface; just use the number of interfaces
3954 * to generate the temporary file name prefix.
3956 prefix = ws_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3957 } else {
3959 * One interface; use its description, if it has one, to generate
3960 * the temporary file name, otherwise use its name.
3962 char *basename;
3963 const interface_options *interface_opts;
3965 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
3968 * Do we have a description?
3970 if (interface_opts->descr) {
3972 * Yes - use it.
3974 * Strip off any stuff we shouldn't use in the file name,
3975 * by getting the last component of what would be a file
3976 * name.
3978 basename = g_path_get_basename(interface_opts->descr);
3979 } else {
3981 * No - use the name.
3983 * Strip off any stuff we shouldn't use in the file name,
3984 * by getting the last component of what would be a file
3985 * name.
3987 basename = g_path_get_basename(interface_opts->name);
3988 #ifdef _WIN32
3990 * This is Windows, where we might have an ugly GUID-based
3991 * interface name.
3993 * If it's an ugly GUID-based name, use the generic portion
3994 * of the interface GUID to form the basis of the filename.
3996 if (strncmp("NPF_{", basename, 5) == 0) {
3998 * We have a GUID-based name; extract the GUID digits
3999 * as the basis of the filename.
4001 GString *iface;
4002 iface = isolate_uuid(basename);
4003 g_free(basename);
4004 basename = g_strdup(iface->str);
4005 g_string_free(iface, TRUE);
4007 #endif
4009 /* generate the temp file name prefix */
4010 prefix = g_strconcat("wireshark_", basename, NULL);
4011 g_free(basename);
4014 /* Generate the appropriate suffix. */
4015 if (capture_opts->use_pcapng) {
4016 suffix = ".pcapng";
4017 } else {
4018 suffix = ".pcap";
4020 *save_file_fd = create_tempfile(capture_opts->temp_dir, &capfile_name, prefix, suffix, &err_tempfile);
4021 g_free(prefix);
4022 is_tempfile = true;
4025 /* did we fail to open the output file? */
4026 if (*save_file_fd == -1) {
4027 if (is_tempfile) {
4028 snprintf(errmsg, errmsg_len,
4029 "The temporary file to which the capture would be saved "
4030 "could not be opened: %s.", err_tempfile->message);
4031 g_error_free(err_tempfile);
4032 } else {
4033 if (capture_opts->multi_files_on) {
4034 /* Ensures that the ringbuffer is not used. This ensures that
4035 * !ringbuf_is_initialized() is equivalent to
4036 * capture_opts->save_file not being part of ringbuffer. */
4037 ringbuf_error_cleanup();
4040 snprintf(errmsg, errmsg_len,
4041 "The file to which the capture would be saved (\"%s\") "
4042 "could not be opened: %s.", capfile_name,
4043 g_strerror(errno));
4045 g_free(capfile_name);
4046 return false;
4049 g_free(capture_opts->save_file);
4050 if (!is_tempfile && capture_opts->multi_files_on) {
4051 /* In ringbuffer mode, save_file points to a filename from ringbuffer.c.
4052 * capfile_name was already freed before. */
4053 capture_opts->save_file = (char *)ringbuf_current_filename();
4054 } else {
4055 /* capture_opts_cleanup will g_free(capture_opts->save_file). */
4056 capture_opts->save_file = capfile_name;
4059 return true;
4062 static time_t get_next_time_interval(int interval_s) {
4063 time_t next_time = time(NULL);
4064 next_time -= next_time % interval_s;
4065 next_time += interval_s;
4066 return next_time;
4069 /* Do the work of handling either the file size or file duration capture
4070 conditions being reached, and switching files or stopping. */
4071 static bool
4072 do_file_switch_or_stop(capture_options *capture_opts)
4074 bool successful;
4076 if (capture_opts->multi_files_on) {
4077 if (capture_opts->has_autostop_files &&
4078 ++global_ld.file_count >= capture_opts->autostop_files) {
4079 /* no files left: stop here */
4080 global_ld.go = false;
4081 return false;
4084 /* Switch to the next ringbuffer file */
4085 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
4086 &global_ld.save_file_fd, &global_ld.err)) {
4088 /* File switch succeeded: reset the conditions */
4089 global_ld.bytes_written = 0;
4090 global_ld.packets_written = 0;
4091 if (capture_opts->use_pcapng) {
4092 successful = capture_loop_init_pcapng_output(capture_opts, &global_ld, &global_ld.err);
4093 } else {
4094 capture_src *pcap_src;
4095 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
4096 successful = libpcap_write_file_header(global_ld.pdh, pcap_src->linktype, pcap_src->snaplen,
4097 pcap_src->ts_nsec, &global_ld.bytes_written, &global_ld.err);
4100 if (!successful) {
4101 fclose(global_ld.pdh);
4102 global_ld.pdh = NULL;
4103 global_ld.go = false;
4104 g_free(global_ld.io_buffer);
4105 global_ld.io_buffer = NULL;
4106 return false;
4108 if (global_ld.file_duration_timer) {
4109 g_timer_reset(global_ld.file_duration_timer);
4111 if (global_ld.next_interval_time) {
4112 global_ld.next_interval_time = get_next_time_interval(global_ld.interval_s);
4114 fflush(global_ld.pdh);
4115 if (global_ld.inpkts_to_sync_pipe) {
4116 if (!quiet)
4117 report_packet_count(global_ld.inpkts_to_sync_pipe);
4118 global_ld.inpkts_to_sync_pipe = 0;
4120 report_new_capture_file(capture_opts->save_file);
4121 } else {
4122 /* File switch failed: stop here */
4123 global_ld.go = false;
4124 return false;
4126 } else {
4127 /* single file, stop now */
4128 global_ld.go = false;
4129 return false;
4131 return true;
4134 static void *
4135 pcap_read_handler(void* arg)
4137 capture_src *pcap_src = (capture_src *)arg;
4138 char errmsg[MSG_MAX_LENGTH+1];
4140 ws_info("Started thread for interface %d.", pcap_src->interface_id);
4142 /* If this is a pipe input it might finish early. */
4143 while (global_ld.go && pcap_src->cap_pipe_err == PIPOK) {
4144 /* dispatch incoming packets */
4145 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_src);
4148 ws_info("Stopped thread for interface %d.", pcap_src->interface_id);
4149 g_thread_exit(NULL);
4150 return (NULL);
4153 /* Try to pop an item off the packet queue and if it exists, write it */
4154 static bool
4155 capture_loop_dequeue_packet(void) {
4156 pcap_queue_element *queue_element;
4158 g_async_queue_lock(pcap_queue);
4159 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
4160 if (queue_element) {
4161 if (queue_element->pcap_src->from_pcapng) {
4162 pcap_queue_bytes -= queue_element->u.bh.block_total_length;
4163 } else {
4164 pcap_queue_bytes -= queue_element->u.phdr.caplen;
4166 pcap_queue_packets -= 1;
4168 g_async_queue_unlock(pcap_queue);
4169 if (queue_element) {
4170 if (queue_element->pcap_src->from_pcapng) {
4171 ws_info("Dequeued a block of type 0x%08x of length %d captured on interface %d.",
4172 queue_element->u.bh.block_type, queue_element->u.bh.block_total_length,
4173 queue_element->pcap_src->interface_id);
4175 capture_loop_write_pcapng_cb(queue_element->pcap_src,
4176 &queue_element->u.bh,
4177 queue_element->pd);
4178 } else {
4179 ws_info("Dequeued a packet of length %d captured on interface %d.",
4180 queue_element->u.phdr.caplen, queue_element->pcap_src->interface_id);
4182 capture_loop_write_packet_cb((uint8_t *) queue_element->pcap_src,
4183 &queue_element->u.phdr,
4184 queue_element->pd);
4186 g_free(queue_element->pd);
4187 g_free(queue_element);
4188 return true;
4190 return false;
4194 * Note: this code will never be run on any OS other than Windows.
4196 * We keep the arguments in case there's something in the future
4197 * that needs to be reported as an NPCAP bug.
4199 static char *
4200 handle_npcap_bug(char *adapter_name _U_, char *cap_err_str _U_)
4202 bool have_npcap = false;
4204 #ifdef _WIN32
4205 have_npcap = caplibs_have_npcap();
4206 #endif
4208 if (!have_npcap) {
4210 * We're not using Npcap, so don't recommend a user
4211 * file a bug against Npcap.
4213 return g_strdup("");
4216 return ws_strdup_printf("If you have not removed that adapter, this "
4217 "is probably a known issue in Npcap resulting from "
4218 "the behavior of the Windows networking stack. "
4219 "Work is being done in Npcap to improve the "
4220 "handling of this issue; it does not need to "
4221 "be reported as a Wireshark or Npcap bug.");
4224 /* Do the low-level work of a capture.
4225 Returns true if it succeeds, false otherwise. */
4226 static bool
4227 capture_loop_start(capture_options *capture_opts, bool *stats_known, struct pcap_stat *stats)
4229 #ifdef _WIN32
4230 ULONGLONG upd_time, cur_time; /* GetTickCount64() returns a "ULONGLONG" */
4231 #else
4232 struct timeval upd_time, cur_time;
4233 #endif
4234 int err_close;
4235 int inpkts;
4236 GTimer *autostop_duration_timer = NULL;
4237 bool write_ok;
4238 bool close_ok;
4239 bool cfilter_error = false;
4240 char errmsg[MSG_MAX_LENGTH+1];
4241 char secondary_errmsg[MSG_MAX_LENGTH+1];
4242 capture_src *pcap_src;
4243 interface_options *interface_opts;
4244 unsigned i, error_index = 0;
4246 *errmsg = '\0';
4247 *secondary_errmsg = '\0';
4249 /* init the loop data */
4250 global_ld.go = true;
4251 global_ld.packets_captured = 0;
4252 #ifdef SIGINFO
4253 global_ld.report_packet_count = false;
4254 #endif
4255 global_ld.inpkts_to_sync_pipe = 0;
4256 global_ld.err = 0; /* no error seen yet */
4257 global_ld.pdh = NULL;
4258 global_ld.save_file_fd = -1;
4259 global_ld.io_buffer = NULL;
4260 global_ld.file_count = 0;
4261 global_ld.file_duration_timer = NULL;
4262 global_ld.next_interval_time = 0;
4263 global_ld.interval_s = 0;
4265 /* We haven't yet gotten the capture statistics. */
4266 *stats_known = false;
4268 ws_info("Capture loop starting ...");
4269 capture_opts_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_DEBUG, capture_opts);
4271 /* open the "input file" from network interface or capture pipe */
4272 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
4273 secondary_errmsg, sizeof(secondary_errmsg))) {
4274 goto error;
4276 for (i = 0; i < capture_opts->ifaces->len; i++) {
4277 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4278 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
4279 /* init the input filter from the network interface (capture pipe will do nothing) */
4281 * When remote capturing WinPCap crashes when the capture filter
4282 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
4283 * string.
4285 switch (capture_loop_init_filter(pcap_src->pcap_h, pcap_src->from_cap_pipe,
4286 interface_opts->name,
4287 interface_opts->cfilter?interface_opts->cfilter:"")) {
4289 case INITFILTER_NO_ERROR:
4290 break;
4292 case INITFILTER_BAD_FILTER:
4293 cfilter_error = true;
4294 error_index = i;
4295 snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_src->pcap_h));
4296 goto error;
4298 case INITFILTER_OTHER_ERROR:
4299 snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
4300 pcap_geterr(pcap_src->pcap_h));
4301 snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report_bug());
4302 goto error;
4306 /* If we're supposed to write to a capture file, open it for output
4307 (temporary/specified name/ringbuffer) */
4308 if (capture_opts->saving_to_file) {
4309 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
4310 errmsg, sizeof(errmsg))) {
4311 goto error;
4314 /* set up to write to the already-opened capture output file/files */
4315 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
4316 sizeof(errmsg))) {
4317 goto error;
4320 /* XXX - capture SIGTERM and close the capture, in case we're on a
4321 Linux 2.0[.x] system and you have to explicitly close the capture
4322 stream in order to turn promiscuous mode off? We need to do that
4323 in other places as well - and I don't think that works all the
4324 time in any case, due to libpcap bugs. */
4326 /* Well, we should be able to start capturing.
4328 Sync out the capture file, so the header makes it to the file system,
4329 and send a "capture started successfully and capture file created"
4330 message to our parent so that they'll open the capture file and
4331 update its windows to indicate that we have a live capture in
4332 progress. */
4333 fflush(global_ld.pdh);
4334 report_new_capture_file(capture_opts->save_file);
4337 if (capture_opts->has_file_interval) {
4338 global_ld.interval_s = capture_opts->file_interval;
4339 global_ld.next_interval_time = get_next_time_interval(global_ld.interval_s);
4341 /* create stop conditions */
4342 if (capture_opts->has_autostop_filesize) {
4343 if (capture_opts->autostop_filesize > UINT32_C(2000000000)) {
4344 capture_opts->autostop_filesize = UINT32_C(2000000000);
4347 if (capture_opts->has_autostop_duration) {
4348 autostop_duration_timer = g_timer_new();
4351 if (capture_opts->multi_files_on) {
4352 if (capture_opts->has_file_duration) {
4353 global_ld.file_duration_timer = g_timer_new();
4357 /* init the time values */
4358 #ifdef _WIN32
4359 upd_time = GetTickCount64();
4360 #else
4361 gettimeofday(&upd_time, NULL);
4362 #endif
4363 start_time = create_timestamp();
4364 ws_info("Capture loop running.");
4365 capture_opts_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_DEBUG, capture_opts);
4367 /* WOW, everything is prepared! */
4368 /* please fasten your seat belts, we will enter now the actual capture loop */
4369 if (use_threads) {
4370 pcap_queue = g_async_queue_new();
4371 pcap_queue_bytes = 0;
4372 pcap_queue_packets = 0;
4373 for (i = 0; i < global_ld.pcaps->len; i++) {
4374 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4375 /* XXX - Add an interface name here? */
4376 pcap_src->tid = g_thread_new("Capture read", pcap_read_handler, pcap_src);
4379 while (global_ld.go) {
4380 /* dispatch incoming packets */
4381 if (use_threads) {
4382 bool dequeued = capture_loop_dequeue_packet();
4384 if (dequeued) {
4385 inpkts = 1;
4386 } else {
4387 inpkts = 0;
4389 } else {
4390 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
4391 inpkts = capture_loop_dispatch(&global_ld, errmsg,
4392 sizeof(errmsg), pcap_src);
4394 if (inpkts == 0) {
4395 /* Stop capturing if all of our sources are pipes and none of them are open. */
4396 bool open_interfaces = false;
4397 for (i = 0; i < global_ld.pcaps->len; i++) {
4398 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4399 if (pcap_src->cap_pipe_err == PIPOK) {
4400 /* True for both non-pipes and open pipes. */
4401 open_interfaces = true;
4404 if (!open_interfaces) {
4405 global_ld.go = false;
4408 #ifdef SIGINFO
4409 /* Were we asked to print packet counts by the SIGINFO handler? */
4410 if (global_ld.report_packet_count) {
4411 fprintf(stderr, "%u packet%s captured\n", global_ld.packets_captured,
4412 plurality(global_ld.packets_captured, "", "s"));
4413 global_ld.report_packet_count = false;
4415 #endif
4417 #ifdef _WIN32
4418 /* any news from our parent (signal pipe)? -> just stop the capture */
4419 if (!signal_pipe_check_running()) {
4420 global_ld.go = false;
4422 #endif
4424 if (inpkts > 0) {
4425 if (capture_opts->output_to_pipe) {
4426 fflush(global_ld.pdh);
4428 } /* inpkts */
4430 /* Only update after an interval so as not to overload slow displays.
4431 * This also prevents too much context-switching between the dumpcap
4432 * and wireshark processes.
4433 * XXX: Should we send updates sooner if there have been lots of
4434 * packets we haven't notified the parent about, such as on fast links?
4436 #ifdef _WIN32
4437 cur_time = GetTickCount64();
4438 if ((cur_time - upd_time) > capture_opts->update_interval)
4439 #else
4440 gettimeofday(&cur_time, NULL);
4441 if (((uint64_t)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
4442 ((uint64_t)upd_time.tv_sec * 1000000 + upd_time.tv_usec + capture_opts->update_interval*1000))
4443 #endif
4446 upd_time = cur_time;
4448 #if 0
4449 if (pcap_stats(pch, stats) >= 0) {
4450 *stats_known = true;
4452 #endif
4453 /* Let the parent process know. */
4454 if (global_ld.inpkts_to_sync_pipe) {
4455 /* do sync here */
4456 fflush(global_ld.pdh);
4458 /* Send our parent a message saying we've written out
4459 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
4460 if (!quiet)
4461 report_packet_count(global_ld.inpkts_to_sync_pipe);
4463 global_ld.inpkts_to_sync_pipe = 0;
4466 /* check capture duration condition */
4467 if (autostop_duration_timer != NULL && g_timer_elapsed(autostop_duration_timer, NULL) >= capture_opts->autostop_duration) {
4468 /* The maximum capture time has elapsed; stop the capture. */
4469 global_ld.go = false;
4470 continue;
4473 /* check capture file duration condition */
4474 if (global_ld.file_duration_timer != NULL && g_timer_elapsed(global_ld.file_duration_timer, NULL) >= capture_opts->file_duration) {
4475 /* duration limit reached, do we have another file? */
4476 if (!do_file_switch_or_stop(capture_opts))
4477 continue;
4478 } /* cnd_file_duration */
4480 /* check capture file interval condition */
4481 if (global_ld.interval_s && time(NULL) >= global_ld.next_interval_time) {
4482 /* end of interval reached, do we have another file? */
4483 if (!do_file_switch_or_stop(capture_opts))
4484 continue;
4485 } /* cnd_file_interval */
4489 ws_info("Capture loop stopping ...");
4490 if (use_threads) {
4492 for (i = 0; i < global_ld.pcaps->len; i++) {
4493 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4494 ws_info("Waiting for thread of interface %u...", pcap_src->interface_id);
4495 g_thread_join(pcap_src->tid);
4496 ws_info("Thread of interface %u terminated.", pcap_src->interface_id);
4498 while (1) {
4499 bool dequeued = capture_loop_dequeue_packet();
4500 if (!dequeued) {
4501 break;
4503 if (capture_opts->output_to_pipe) {
4504 fflush(global_ld.pdh);
4510 /* delete stop conditions */
4511 if (global_ld.file_duration_timer != NULL)
4512 g_timer_destroy(global_ld.file_duration_timer);
4513 if (autostop_duration_timer != NULL)
4514 g_timer_destroy(autostop_duration_timer);
4516 /* did we have a pcap (input) error? */
4517 for (i = 0; i < capture_opts->ifaces->len; i++) {
4518 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4519 if (pcap_src->pcap_err) {
4520 /* On Linux, if an interface goes down while you're capturing on it,
4521 you'll get "recvfrom: Network is down".
4522 (At least you will if g_strerror() doesn't show a local translation
4523 of the error.)
4525 Newer versions of libpcap maps that to just
4526 "The interface went down".
4528 On FreeBSD, DragonFly BSD, and macOS, if a network adapter
4529 disappears while you're capturing on it, you'll get
4530 "read: Device not configured" error (ENXIO). (See previous
4531 parenthetical note.)
4533 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
4535 With WinPcap and Npcap, you'll get
4536 "read error: PacketReceivePacket failed" or
4537 "PacketReceivePacket error: The device has been removed. (1617)".
4539 Newer versions of libpcap map some or all of those to just
4540 "The interface disappeared" or something beginning with
4541 "The interface disappeared".
4543 These should *not* be reported to the Wireshark developers,
4544 although, with Npcap, "The interface disappeared" messages
4545 should perhaps be reported to the Npcap developers, at least
4546 until errors of that sort that shouldn't happen are fixed,
4547 if that's possible. */
4548 char *cap_err_str;
4549 char *primary_msg;
4550 char *secondary_msg;
4552 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
4553 cap_err_str = pcap_geterr(pcap_src->pcap_h);
4554 if (strcmp(cap_err_str, "The interface went down") == 0 ||
4555 strcmp(cap_err_str, "recvfrom: Network is down") == 0) {
4556 primary_msg = ws_strdup_printf("The network adapter \"%s\" "
4557 "is no longer running; the "
4558 "capture has stopped.",
4559 interface_opts->display_name);
4560 secondary_msg = g_strdup("");
4561 } else if (strcmp(cap_err_str, "The interface disappeared") == 0 ||
4562 strcmp(cap_err_str, "read: Device not configured") == 0 ||
4563 strcmp(cap_err_str, "read: I/O error") == 0 ||
4564 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
4565 primary_msg = ws_strdup_printf("The network adapter \"%s\" "
4566 "is no longer attached; the "
4567 "capture has stopped.",
4568 interface_opts->display_name);
4569 secondary_msg = g_strdup("");
4570 } else if (g_str_has_prefix(cap_err_str, "The interface disappeared ")) {
4572 * Npcap, if it picks up a recent commit to libpcap, will
4573 * report an error *beginning* with "The interface
4574 * disappeared", with the name of the Windows status code,
4575 * and the corresponding NT status code, after it.
4577 * Those should be reported as Npcap issues.
4579 primary_msg = ws_strdup_printf("The network adapter \"%s\" "
4580 "is no longer attached; the "
4581 "capture has stopped.",
4582 interface_opts->display_name);
4583 secondary_msg = handle_npcap_bug(interface_opts->display_name,
4584 cap_err_str);
4585 } else if (g_str_has_prefix(cap_err_str, "PacketReceivePacket error:") &&
4586 g_str_has_suffix(cap_err_str, "(1617)")) {
4588 * "PacketReceivePacket error: {message in arbitrary language} (1617)",
4589 * which is ERROR_DEVICE_REMOVED.
4591 * Current libpcap/Npcap treat ERROR_GEN_FAILURE as
4592 * "the device is no longer attached"; users are also
4593 * getting ERROR_DEVICE_REMOVED.
4595 * For now, some users appear to be getg ERROR_DEVICE_REMOVED
4596 * in cases where the device *wasn't* removed, so tell
4597 * them to report this as an Npcap issue; I seem to
4598 * remember some discussion between Daniel and somebody
4599 * at Microsoft about the Windows 10 network stack setup/
4600 * teardown code being modified to try to prevent those
4601 * sort of problems popping up, but I can't find that
4602 * discussion.
4604 primary_msg = ws_strdup_printf("The network adapter \"%s\" "
4605 "is no longer attached; the "
4606 "capture has stopped.",
4607 interface_opts->display_name);
4608 secondary_msg = handle_npcap_bug(interface_opts->display_name,
4609 "The interface disappeared (error code ERROR_DEVICE_REMOVED/STATUS_DEVICE_REMOVED)");
4610 } else if (strcmp(cap_err_str, "The other host terminated the connection.") == 0 ||
4611 g_str_has_prefix(cap_err_str, "Is the server properly installed?")) {
4613 * Networking error for a remote capture.
4615 primary_msg = g_strdup(cap_err_str);
4616 secondary_msg = g_strdup("This may be a problem with the "
4617 "remote host on which you are "
4618 "capturing packets.");
4619 } else {
4620 primary_msg = ws_strdup_printf("Error while capturing packets: %s",
4621 cap_err_str);
4622 secondary_msg = g_strdup(please_report_bug());
4624 report_capture_error(primary_msg, secondary_msg);
4625 g_free(primary_msg);
4626 g_free(secondary_msg);
4627 break;
4628 } else if (pcap_src->from_cap_pipe && pcap_src->cap_pipe_err == PIPERR) {
4629 report_capture_error(errmsg, "");
4630 break;
4633 /* did we have an output error while capturing? */
4634 if (global_ld.err == 0) {
4635 write_ok = true;
4636 } else {
4637 capture_loop_get_errmsg(errmsg, sizeof(errmsg), secondary_errmsg,
4638 sizeof(secondary_errmsg),
4639 capture_opts->save_file, global_ld.err, false);
4640 report_capture_error(errmsg, secondary_errmsg);
4641 write_ok = false;
4644 if (capture_opts->saving_to_file) {
4645 /* close the output file */
4646 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
4647 } else
4648 close_ok = true;
4650 /* there might be packets not yet notified to the parent */
4651 /* (do this after closing the file, so all packets are already flushed) */
4652 if (global_ld.inpkts_to_sync_pipe) {
4653 if (!quiet)
4654 report_packet_count(global_ld.inpkts_to_sync_pipe);
4655 global_ld.inpkts_to_sync_pipe = 0;
4658 /* If we've displayed a message about a write error, there's no point
4659 in displaying another message about an error on close. */
4660 if (!close_ok && write_ok) {
4661 capture_loop_get_errmsg(errmsg, sizeof(errmsg), secondary_errmsg,
4662 sizeof(secondary_errmsg),
4663 capture_opts->save_file, err_close, true);
4664 report_capture_error(errmsg, secondary_errmsg);
4668 * XXX We exhibit different behaviour between normal mode and sync mode
4669 * when the pipe is stdin and not already at EOF. If we're a child, the
4670 * parent's stdin isn't closed, so if the user starts another capture,
4671 * cap_pipe_open_live() will very likely not see the expected magic bytes and
4672 * will say "Unrecognized libpcap format". On the other hand, in normal
4673 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
4676 report_capture_count(!really_quiet);
4678 /* get packet drop statistics from pcap */
4679 for (i = 0; i < capture_opts->ifaces->len; i++) {
4680 uint32_t received;
4681 uint32_t pcap_dropped = 0;
4683 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4684 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
4685 received = pcap_src->received;
4686 if (pcap_src->pcap_h != NULL) {
4687 ws_assert(!pcap_src->from_cap_pipe);
4688 /* Get the capture statistics, so we know how many packets were dropped. */
4689 if (pcap_stats(pcap_src->pcap_h, stats) >= 0) {
4690 *stats_known = true;
4691 /* Let the parent process know. */
4692 pcap_dropped += stats->ps_drop;
4693 } else {
4694 snprintf(errmsg, sizeof(errmsg),
4695 "Can't get packet-drop statistics: %s",
4696 pcap_geterr(pcap_src->pcap_h));
4697 report_capture_error(errmsg, please_report_bug());
4700 report_packet_drops(received, pcap_dropped, pcap_src->dropped, pcap_src->flushed, stats->ps_ifdrop, interface_opts->display_name);
4703 /* close the input file (pcap or capture pipe) */
4704 capture_loop_close_input(&global_ld);
4706 ws_info("Capture loop stopped.");
4708 /* ok, if the write and the close were successful. */
4709 return write_ok && close_ok;
4711 error:
4712 if (capture_opts->multi_files_on) {
4713 /* cleanup ringbuffer */
4714 ringbuf_error_cleanup();
4715 } else {
4716 /* We can't use the save file, and we have no FILE * for the stream
4717 to close in order to close it, so close the FD directly. */
4718 if (global_ld.save_file_fd != -1) {
4719 ws_close(global_ld.save_file_fd);
4722 /* We couldn't even start the capture, so get rid of the capture
4723 file. */
4724 if (capture_opts->save_file != NULL) {
4725 ws_unlink(capture_opts->save_file);
4728 if (cfilter_error)
4729 report_cfilter_error(capture_opts, error_index, errmsg);
4730 else
4731 report_capture_error(errmsg, secondary_errmsg);
4733 /* close the input file (pcap or cap_pipe) */
4734 capture_loop_close_input(&global_ld);
4736 ws_info("Capture loop stopped with error");
4738 return false;
4742 static void
4743 capture_loop_stop(void)
4745 unsigned i;
4746 capture_src *pcap_src;
4748 for (i = 0; i < global_ld.pcaps->len; i++) {
4749 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4750 if (pcap_src->pcap_h != NULL)
4751 pcap_breakloop(pcap_src->pcap_h);
4753 global_ld.go = false;
4757 static void
4758 capture_loop_get_errmsg(char *errmsg, size_t errmsglen, char *secondary_errmsg,
4759 size_t secondary_errmsglen, const char *fname,
4760 int err, bool is_close)
4762 static const char find_space[] =
4763 "You will need to free up space on that file system"
4764 " or put the capture file on a different file system.";
4766 switch (err) {
4768 case ENOSPC:
4769 snprintf(errmsg, errmsglen,
4770 "Not all the packets could be written to the file"
4771 " to which the capture was being saved\n"
4772 "(\"%s\") because there is no space left on the file system\n"
4773 "on which that file resides.",
4774 fname);
4775 snprintf(secondary_errmsg, secondary_errmsglen, "%s", find_space);
4776 break;
4778 #ifdef EDQUOT
4779 case EDQUOT:
4780 snprintf(errmsg, errmsglen,
4781 "Not all the packets could be written to the file"
4782 " to which the capture was being saved\n"
4783 "(\"%s\") because you are too close to, or over,"
4784 " your disk quota\n"
4785 "on the file system on which that file resides.",
4786 fname);
4787 snprintf(secondary_errmsg, secondary_errmsglen, "%s", find_space);
4788 break;
4789 #endif
4791 default:
4792 if (is_close) {
4793 snprintf(errmsg, errmsglen,
4794 "The file to which the capture was being saved\n"
4795 "(\"%s\") could not be closed: %s.",
4796 fname, g_strerror(err));
4797 } else {
4798 snprintf(errmsg, errmsglen,
4799 "An error occurred while writing to the file"
4800 " to which the capture was being saved\n"
4801 "(\"%s\"): %s.",
4802 fname, g_strerror(err));
4804 snprintf(secondary_errmsg, secondary_errmsglen,
4805 "%s", please_report_bug());
4806 break;
4811 * We wrote one packet. Update some statistics and check if we've met any
4812 * autostop or ring buffer conditions.
4814 static void
4815 capture_loop_wrote_one_packet(capture_src *pcap_src) {
4816 global_ld.packets_captured++;
4817 global_ld.packets_written++;
4818 global_ld.inpkts_to_sync_pipe++;
4820 if (!use_threads) {
4821 pcap_src->received++;
4824 /* check -c NUM */
4825 if (global_capture_opts.has_autostop_packets && global_ld.packets_captured >= global_capture_opts.autostop_packets) {
4826 fflush(global_ld.pdh);
4827 global_ld.go = false;
4828 return;
4830 /* check -a packets:NUM (treat like -c NUM) */
4831 if (global_capture_opts.has_autostop_written_packets && global_ld.packets_captured >= global_capture_opts.autostop_written_packets) {
4832 fflush(global_ld.pdh);
4833 global_ld.go = false;
4834 return;
4836 /* check -b packets:NUM */
4837 if (global_capture_opts.has_file_packets && global_ld.packets_written >= global_capture_opts.file_packets) {
4838 do_file_switch_or_stop(&global_capture_opts);
4839 return;
4841 /* check -a filesize:NUM */
4842 if (global_capture_opts.has_autostop_filesize &&
4843 global_capture_opts.autostop_filesize > 0 &&
4844 global_ld.bytes_written / 1000 >= global_capture_opts.autostop_filesize) {
4845 /* Capture size limit reached, do we have another file? */
4846 do_file_switch_or_stop(&global_capture_opts);
4847 return;
4851 /* one pcapng block was captured, process it */
4852 static void
4853 capture_loop_write_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, uint8_t *pd)
4855 int err;
4858 * This should never be called if we're not writing pcapng.
4860 ws_assert(global_capture_opts.use_pcapng);
4862 /* We may be called multiple times from pcap_dispatch(); if we've set
4863 the "stop capturing" flag, ignore this packet, as we're not
4864 supposed to be saving any more packets. */
4865 if (!global_ld.go) {
4866 pcap_src->flushed++;
4867 return;
4870 if (!pcapng_adjust_block(pcap_src, bh, pd)) {
4871 ws_info("%s failed to adjust pcapng block.", G_STRFUNC);
4872 ws_assert_not_reached();
4873 return;
4876 if (bh->block_type == BLOCK_TYPE_SHB && !global_ld.pcapng_passthrough) {
4878 * capture_loop_init_pcapng_output should've handled this. We need
4879 * to write ISBs when they're initially read so we shouldn't skip
4880 * them here.
4882 return;
4885 if (global_ld.pdh) {
4886 bool successful;
4888 /* We're supposed to write the packet to a file; do so.
4889 If this fails, set "ld->go" to false, to stop the capture, and set
4890 "ld->err" to the error. */
4891 successful = pcapng_write_block(global_ld.pdh,
4893 bh->block_total_length,
4894 &global_ld.bytes_written, &err);
4896 fflush(global_ld.pdh);
4897 if (!successful) {
4898 global_ld.go = false;
4899 global_ld.err = err;
4900 pcap_src->dropped++;
4901 } else if (is_data_block(bh->block_type)) {
4902 /* Count packets for block types that should be dissected, i.e. ones that show up in the packet list. */
4903 ws_debug("Wrote a pcapng block type 0x%04x of length %d captured on interface %u.",
4904 bh->block_type, bh->block_total_length, pcap_src->interface_id);
4905 capture_loop_wrote_one_packet(pcap_src);
4906 } else if (bh->block_type == BLOCK_TYPE_SHB && report_capture_filename) {
4907 ws_debug("Sending SP_FILE on first SHB");
4908 /* SHB is now ready for capture parent to read on SP_FILE message */
4909 sync_pipe_write_string_msg(sync_pipe_fd, SP_FILE, report_capture_filename);
4910 report_capture_filename = NULL;
4915 /* one pcap packet was captured, process it */
4916 static void
4917 capture_loop_write_packet_cb(uint8_t *pcap_src_p, const struct pcap_pkthdr *phdr,
4918 const uint8_t *pd)
4920 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4921 int err;
4922 unsigned ts_mul = pcap_src->ts_nsec ? 1000000000 : 1000000;
4924 ws_debug("capture_loop_write_packet_cb");
4926 /* We may be called multiple times from pcap_dispatch(); if we've set
4927 the "stop capturing" flag, ignore this packet, as we're not
4928 supposed to be saving any more packets. */
4929 if (!global_ld.go) {
4930 pcap_src->flushed++;
4931 return;
4934 if (global_ld.pdh) {
4935 bool successful;
4937 /* We're supposed to write the packet to a file; do so.
4938 If this fails, set "ld->go" to false, to stop the capture, and set
4939 "ld->err" to the error. */
4940 if (global_capture_opts.use_pcapng) {
4941 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
4942 NULL,
4943 phdr->ts.tv_sec, (int32_t)phdr->ts.tv_usec,
4944 phdr->caplen, phdr->len,
4945 pcap_src->idb_id,
4946 ts_mul,
4947 pd, 0,
4948 &global_ld.bytes_written, &err);
4949 } else {
4950 successful = libpcap_write_packet(global_ld.pdh,
4951 phdr->ts.tv_sec, (int32_t)phdr->ts.tv_usec,
4952 phdr->caplen, phdr->len,
4954 &global_ld.bytes_written, &err);
4956 if (!successful) {
4957 global_ld.go = false;
4958 global_ld.err = err;
4959 pcap_src->dropped++;
4960 } else {
4961 ws_debug("Wrote a pcap packet of length %d captured on interface %u.",
4962 phdr->caplen, pcap_src->interface_id);
4963 capture_loop_wrote_one_packet(pcap_src);
4968 /* one packet was captured, queue it */
4969 static void
4970 capture_loop_queue_packet_cb(uint8_t *pcap_src_p, const struct pcap_pkthdr *phdr,
4971 const uint8_t *pd)
4973 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4974 pcap_queue_element *queue_element;
4975 bool limit_reached;
4977 /* We may be called multiple times from pcap_dispatch(); if we've set
4978 the "stop capturing" flag, ignore this packet, as we're not
4979 supposed to be saving any more packets. */
4980 if (!global_ld.go) {
4981 pcap_src->flushed++;
4982 return;
4985 queue_element = g_new(pcap_queue_element, 1);
4986 if (queue_element == NULL) {
4987 pcap_src->dropped++;
4988 return;
4990 queue_element->pcap_src = pcap_src;
4991 queue_element->u.phdr = *phdr;
4992 queue_element->pd = (uint8_t *)g_malloc(phdr->caplen);
4993 if (queue_element->pd == NULL) {
4994 pcap_src->dropped++;
4995 g_free(queue_element);
4996 return;
4998 memcpy(queue_element->pd, pd, phdr->caplen);
4999 g_async_queue_lock(pcap_queue);
5000 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
5001 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
5002 limit_reached = false;
5003 g_async_queue_push_unlocked(pcap_queue, queue_element);
5004 pcap_queue_bytes += phdr->caplen;
5005 pcap_queue_packets += 1;
5006 } else {
5007 limit_reached = true;
5009 g_async_queue_unlock(pcap_queue);
5010 if (limit_reached) {
5011 pcap_src->dropped++;
5012 g_free(queue_element->pd);
5013 g_free(queue_element);
5014 ws_info("Dropped a packet of length %d captured on interface %u.",
5015 phdr->caplen, pcap_src->interface_id);
5016 } else {
5017 pcap_src->received++;
5018 ws_info("Queued a packet of length %d captured on interface %u.",
5019 phdr->caplen, pcap_src->interface_id);
5021 /* I don't want to hold the mutex over the debug output. So the
5022 output may be wrong */
5023 ws_info("Queue size is now %" PRId64 " bytes (%" PRId64 " packets)",
5024 pcap_queue_bytes, pcap_queue_packets);
5027 /* one pcapng block was captured, queue it */
5028 static void
5029 capture_loop_queue_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, uint8_t *pd)
5031 pcap_queue_element *queue_element;
5032 bool limit_reached;
5034 /* We may be called multiple times from pcap_dispatch(); if we've set
5035 the "stop capturing" flag, ignore this packet, as we're not
5036 supposed to be saving any more packets. */
5037 if (!global_ld.go) {
5038 pcap_src->flushed++;
5039 return;
5042 queue_element = g_new(pcap_queue_element, 1);
5043 if (queue_element == NULL) {
5044 pcap_src->dropped++;
5045 return;
5047 queue_element->pcap_src = pcap_src;
5048 queue_element->u.bh = *bh;
5049 queue_element->pd = (uint8_t *)g_malloc(bh->block_total_length);
5050 if (queue_element->pd == NULL) {
5051 pcap_src->dropped++;
5052 g_free(queue_element);
5053 return;
5055 memcpy(queue_element->pd, pd, bh->block_total_length);
5056 g_async_queue_lock(pcap_queue);
5057 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
5058 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
5059 limit_reached = false;
5060 g_async_queue_push_unlocked(pcap_queue, queue_element);
5061 pcap_queue_bytes += bh->block_total_length;
5062 pcap_queue_packets += 1;
5063 } else {
5064 limit_reached = true;
5066 g_async_queue_unlock(pcap_queue);
5067 if (limit_reached) {
5068 pcap_src->dropped++;
5069 g_free(queue_element->pd);
5070 g_free(queue_element);
5071 ws_info("Dropped a packet of length %d captured on interface %u.",
5072 bh->block_total_length, pcap_src->interface_id);
5073 } else {
5074 pcap_src->received++;
5075 ws_info("Queued a block of type 0x%08x of length %d captured on interface %u.",
5076 bh->block_type, bh->block_total_length, pcap_src->interface_id);
5078 /* I don't want to hold the mutex over the debug output. So the
5079 output may be wrong */
5080 ws_info("Queue size is now %" PRId64 " bytes (%" PRId64 " packets)",
5081 pcap_queue_bytes, pcap_queue_packets);
5084 static int
5085 set_80211_channel(const char *iface, const char *opt)
5087 uint32_t freq = 0;
5088 int type = -1;
5089 uint32_t center_freq1 = 0;
5090 uint32_t center_freq2 = 0;
5091 int args;
5092 int ret = 0;
5093 char **options = NULL;
5095 options = g_strsplit_set(opt, ",", 4);
5096 for (args = 0; options[args]; args++)
5099 ret = ws80211_init();
5100 if (ret != WS80211_INIT_OK) {
5101 if (ret == WS80211_INIT_NOT_SUPPORTED)
5102 cmdarg_err("Setting 802.11 channels is not supported on this platform");
5103 else
5104 cmdarg_err("Failed to init ws80211: %s", g_strerror(abs(ret)));
5105 ret = 2;
5106 goto out;
5109 if (options[0])
5110 freq = get_nonzero_uint32(options[0], "802.11 channel frequency");
5112 if (args >= 1 && options[1]) {
5113 type = ws80211_str_to_chan_type(options[1]);
5114 if (type == -1) {
5115 cmdarg_err("\"%s\" is not a valid 802.11 channel type", options[1]);
5116 ret = EINVAL;
5117 goto out;
5121 if (args >= 2 && options[2])
5122 center_freq1 = get_nonzero_uint32(options[2], "VHT center frequency");
5124 if (args >= 3 && options[3])
5125 center_freq2 = get_nonzero_uint32(options[3], "VHT center frequency 2");
5127 ret = ws80211_set_freq(iface, freq, type, center_freq1, center_freq2);
5129 if (ret) {
5130 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
5131 ret = 2;
5132 goto out;
5135 if (capture_child)
5136 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
5138 out:
5139 g_strfreev(options);
5140 return ret;
5143 static void
5144 gather_dumpcap_compiled_info(feature_list l)
5146 /* Capture libraries */
5147 gather_caplibs_compile_info(l);
5150 static void
5151 gather_dumpcap_runtime_info(feature_list l)
5153 /* Capture libraries */
5154 gather_caplibs_runtime_info(l);
5157 #define LONGOPT_IFNAME LONGOPT_BASE_APPLICATION+1
5158 #define LONGOPT_IFDESCR LONGOPT_BASE_APPLICATION+2
5159 #define LONGOPT_CAPTURE_COMMENT LONGOPT_BASE_APPLICATION+3
5160 #define LONGOPT_APPLICATION_FLAVOR LONGOPT_BASE_APPLICATION+4
5161 #ifdef _WIN32
5162 #define LONGOPT_SIGNAL_PIPE LONGOPT_BASE_APPLICATION+5
5163 #endif
5165 /* And now our feature presentation... [ fade to music ] */
5167 main(int argc, char *argv[])
5169 char *err_msg;
5170 int opt;
5171 static const struct ws_option long_options[] = {
5172 {"help", ws_no_argument, NULL, 'h'},
5173 {"version", ws_no_argument, NULL, 'v'},
5174 LONGOPT_CAPTURE_COMMON
5175 {"ifname", ws_required_argument, NULL, LONGOPT_IFNAME},
5176 {"ifdescr", ws_required_argument, NULL, LONGOPT_IFDESCR},
5177 {"capture-comment", ws_required_argument, NULL, LONGOPT_CAPTURE_COMMENT},
5178 {"application-flavor", ws_required_argument, NULL, LONGOPT_APPLICATION_FLAVOR},
5179 #ifdef _WIN32
5180 {"signal-pipe", ws_required_argument, NULL, LONGOPT_SIGNAL_PIPE},
5181 #endif
5182 {0, 0, 0, 0 }
5185 bool arg_error = false;
5187 #ifndef _WIN32
5188 struct sigaction action, oldaction;
5189 #endif
5191 bool stats_known;
5192 struct pcap_stat stats = {0};
5193 bool list_interfaces = false;
5194 int caps_queries = 0;
5195 bool print_bpf_code = false;
5196 bool set_chan = false;
5197 char *set_chan_arg = NULL;
5198 bool machine_readable = false;
5199 bool print_statistics = false;
5200 int status, run_once_args = 0;
5201 int i;
5202 unsigned j;
5203 #if defined(__APPLE__) && defined(__LP64__)
5204 struct utsname osinfo;
5205 #endif
5206 GString *str;
5208 /* Set the program name. */
5209 g_set_prgname("dumpcap");
5212 * Determine if dumpcap is being requested to run in a special
5213 * capture_child mode by going thru the command line args to see if
5214 * a -Z is present. (-Z is a hidden option).
5216 * The primary result of running in capture_child mode is that
5217 * all messages sent out on stderr are in a special type/len/string
5218 * format to allow message processing by type. These messages include
5219 * error messages if dumpcap fails to start the operation it was
5220 * requested to do, as well as various "status" messages which are sent
5221 * when an actual capture is in progress, and a "success" message sent
5222 * if dumpcap was requested to perform an operation other than a
5223 * capture.
5225 * Capture_child mode would normally be requested by a parent process
5226 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
5227 * to which dumpcap stderr has been redirected. It might also have
5228 * another pipe to obtain dumpcap stdout output; for operations other
5229 * than a capture, that information is formatted specially for easier
5230 * parsing by the parent process.
5232 * Capture_child mode needs to be determined immediately upon
5233 * startup so that any messages generated by dumpcap in this mode
5234 * (eg: during initialization) will be formatted properly.
5237 for (i=1; i<argc; i++) {
5238 if (strcmp("-Z", argv[i]) == 0) {
5239 capture_child = true;
5240 machine_readable = true; /* request machine-readable output */
5241 i++;
5242 if (i >= argc) {
5243 exit_main(1);
5246 if (strcmp(argv[i], SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
5247 // get_positive_int calls cmdarg_err
5248 if (!ws_strtoi(argv[i], NULL, &sync_pipe_fd) || sync_pipe_fd <= 0) {
5249 exit_main(1);
5251 #ifdef _WIN32
5252 /* On UN*X the fd is the same when we fork + exec.
5253 * On Windows the HANDLE value is the same for inherited
5254 * handles in the child process and the parent, although
5255 * not necessarily the fd value from _open_osfhandle.
5256 * https://learn.microsoft.com/en-us/windows/win32/procthread/inheritance
5257 * Also, "64-bit versions of Windows use 32-bit handles for
5258 * interoperability... only the lower 32 bits are significant,
5259 * so it is safe to truncate... or sign-extend the handle."
5260 * https://learn.microsoft.com/en-us/windows/win32/winprog64/interprocess-communication
5262 /* set output pipe to binary mode, avoid ugly text conversions */
5263 sync_pipe_fd = _open_osfhandle( (intptr_t) sync_pipe_fd, _O_BINARY);
5264 #endif
5269 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
5271 /* Initialize log handler early so we can have proper logging during startup. */
5272 ws_log_init_with_writer(dumpcap_log_writer, vcmdarg_err);
5274 /* Early logging command-line initialization. */
5275 ws_log_parse_args(&argc, argv, vcmdarg_err, 1);
5277 #if DEBUG_CHILD_DUMPCAP
5278 /* Assume that if we're specially compiled with dumpcap debugging
5279 * then we want maximum debugging.
5281 if (capture_child) {
5282 ws_log_set_level(LOG_LEVEL_NOISY);
5285 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
5286 fprintf (stderr, "Unable to open debug log file .\n");
5287 exit (1);
5289 #endif
5291 ws_noisy("Finished log init and parsing command line log arguments");
5293 #ifdef _WIN32
5294 create_app_running_mutex();
5297 * Initialize our DLL search path. MUST be called before LoadLibrary
5298 * or g_module_open.
5300 ws_init_dll_search_path();
5302 /* Load wpcap if possible. Do this before collecting the run-time version information */
5303 load_wpcap();
5304 #endif
5306 /* Initialize the version information. */
5307 ws_init_version_info("Dumpcap", gather_dumpcap_compiled_info,
5308 gather_dumpcap_runtime_info);
5310 #ifdef HAVE_PCAP_REMOTE
5311 #define OPTSTRING_r "r"
5312 #define OPTSTRING_u "u"
5313 #else
5314 #define OPTSTRING_r
5315 #define OPTSTRING_u
5316 #endif
5318 #ifdef HAVE_PCAP_SETSAMPLING
5319 #define OPTSTRING_m "m:"
5320 #else
5321 #define OPTSTRING_m
5322 #endif
5324 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:dghk:" OPTSTRING_m "MN:nPqQ" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
5326 #if defined(__APPLE__) && defined(__LP64__)
5328 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
5329 * a bug workaround - timeouts less than 1 second don't work with libpcap
5330 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
5331 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
5332 * The problem is extremely unlikely to be reintroduced in a future
5333 * release.)
5335 if (uname(&osinfo) == 0) {
5337 * {Mac} OS X/macOS 10.x uses Darwin {x+4}.0.0; 10.x.y uses Darwin
5338 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
5339 * number of 10.0.0, not 10.1.0 - go figure).
5341 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
5342 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
5343 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
5344 need_timeout_workaround = true;
5346 #endif
5348 /* Initialize the pcaps list and IDBs */
5349 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(capture_src *));
5350 global_ld.pcapng_passthrough = false;
5351 global_ld.saved_shb = NULL;
5352 global_ld.saved_idbs = g_array_new(FALSE, TRUE, sizeof(saved_idb_t));
5354 err_msg = ws_init_sockets();
5355 if (err_msg != NULL)
5357 ws_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_ERROR,
5358 "ERROR: %s", err_msg);
5359 g_free(err_msg);
5360 ws_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_ERROR,
5361 "%s", please_report_bug());
5362 exit_main(1);
5365 #ifdef _WIN32
5366 /* Set handler for Ctrl+C key */
5367 SetConsoleCtrlHandler(capture_cleanup_handler, true);
5368 #else
5369 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
5370 and exit. Do the same with SIGPIPE, in case, for example,
5371 we're writing to our standard output and it's a pipe.
5372 Do the same with SIGHUP if it's not being ignored (if we're
5373 being run under nohup, it might be ignored, in which case we
5374 should leave it ignored).
5376 XXX - apparently, Coverity complained that part of action
5377 wasn't initialized. Perhaps it's running on Linux, where
5378 struct sigaction has an ignored "sa_restorer" element and
5379 where "sa_handler" and "sa_sigaction" might not be two
5380 members of a union. */
5381 memset(&action, 0, sizeof(action));
5382 action.sa_handler = capture_cleanup_handler;
5384 * Arrange that system calls not get restarted, because when
5385 * our signal handler returns we don't want to restart
5386 * a call that was waiting for packets to arrive.
5388 action.sa_flags = 0;
5389 sigemptyset(&action.sa_mask);
5390 sigaction(SIGTERM, &action, NULL);
5391 sigaction(SIGINT, &action, NULL);
5392 sigaction(SIGPIPE, &action, NULL);
5393 sigaction(SIGHUP, NULL, &oldaction);
5394 if (oldaction.sa_handler == SIG_DFL)
5395 sigaction(SIGHUP, &action, NULL);
5397 #ifdef SIGINFO
5398 /* Catch SIGINFO and, if we get it and we're capturing in
5399 quiet mode, report the number of packets we've captured. */
5400 action.sa_handler = report_counts_siginfo;
5401 action.sa_flags = SA_RESTART;
5402 sigemptyset(&action.sa_mask);
5403 sigaction(SIGINFO, &action, NULL);
5404 #endif /* SIGINFO */
5405 #endif /* _WIN32 */
5407 /* ----------------------------------------------------------------- */
5408 /* Privilege and capability handling */
5409 /* Cases: */
5410 /* 1. Running not as root or suid root; no special capabilities. */
5411 /* Action: none */
5412 /* */
5413 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
5414 /* Action: none */
5415 /* */
5416 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
5417 /* Action: */
5418 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
5419 /* capabilities; Drop all other capabilities; */
5420 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5421 /* else: after pcap_open_live() in capture_loop_open_input() */
5422 /* drop all capabilities (NET_RAW and NET_ADMIN); */
5423 /* (Note: this means that the process, although logged in */
5424 /* as root, does not have various permissions such as the */
5425 /* ability to bypass file access permissions). */
5426 /* XXX: Should we just leave capabilities alone in this case */
5427 /* so that user gets expected effect that root can do */
5428 /* anything ?? */
5429 /* */
5430 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
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 suid root (set euid=ruid).(ie: keep suid until after */
5435 /* pcap_open_live). */
5436 /* */
5437 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
5438 /* Action: */
5439 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
5440 /* capabilities; Drop all other capabilities; */
5441 /* Drop suid privileges (euid=ruid); */
5442 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5443 /* else: after pcap_open_live() in capture_loop_open_input() */
5444 /* drop all capabilities (NET_RAW and NET_ADMIN). */
5445 /* */
5446 /* XXX: For some Linux versions/distros with capabilities */
5447 /* a 'normal' process with any capabilities cannot be */
5448 /* 'killed' (signaled) from another (same uid) non-privileged */
5449 /* process. */
5450 /* For example: If (non-suid) Wireshark forks a */
5451 /* child suid dumpcap which acts as described here (case 5), */
5452 /* Wireshark will be unable to kill (signal) the child */
5453 /* dumpcap process until the capabilities have been dropped */
5454 /* (after pcap_open_live()). */
5455 /* This behaviour will apparently be changed in the kernel */
5456 /* to allow the kill (signal) in this case. */
5457 /* See the following for details: */
5458 /* https://www.mail-archive.com/ [wrapped] */
5459 /* linux-security-module@vger.kernel.org/msg02913.html */
5460 /* */
5461 /* It is therefore conceivable that if dumpcap somehow hangs */
5462 /* in pcap_open_live or before that wireshark will not */
5463 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
5464 /* In this case, exiting wireshark will kill the child */
5465 /* dumpcap process. */
5466 /* */
5467 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
5468 /* capabilities; Using libcap. Note: capset cmd (which see) */
5469 /* used to assign capabilities to file. */
5470 /* Action: */
5471 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5472 /* else: after pcap_open_live() in capture_loop_open_input() */
5473 /* drop all capabilities (NET_RAW and NET_ADMIN) */
5474 /* */
5475 /* ToDo: -S (stats) should drop privileges/capabilities when no */
5476 /* longer required (similar to capture). */
5477 /* */
5478 /* ----------------------------------------------------------------- */
5480 init_process_policies();
5482 #ifdef HAVE_LIBCAP
5483 /* If 'started with special privileges' (and using libcap) */
5484 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
5485 /* Set euid/egid = ruid/rgid to remove suid privileges */
5486 relinquish_privs_except_capture();
5487 #endif
5489 init_report_failure_message_simple("dumpcap");
5491 /* Set the initial values in the capture options. This might be overwritten
5492 by the command line parameters. */
5493 capture_opts_init(&global_capture_opts, get_interface_list);
5494 /* We always save to a file - if no file was specified, we save to a
5495 temporary file. */
5496 global_capture_opts.saving_to_file = true;
5497 global_capture_opts.has_ring_num_files = true;
5499 /* Pass on capture_child mode for capture_opts */
5500 global_capture_opts.capture_child = capture_child;
5502 /* Now get our args */
5503 while ((opt = ws_getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
5504 switch (opt) {
5505 case 'h': /* Print help and exit */
5506 show_help_header("Capture network packets and dump them into a pcapng or pcap file.");
5507 print_usage(stdout);
5508 exit_main(0);
5509 break;
5510 case 'v': /* Show version and exit */
5511 show_version();
5512 exit_main(0);
5513 break;
5514 case LONGOPT_APPLICATION_FLAVOR:
5515 set_application_flavor(application_name_to_flavor(ws_optarg));
5516 break;
5517 /*** capture option specific ***/
5518 case 'a': /* autostop criteria */
5519 case 'b': /* Ringbuffer option */
5520 case 'c': /* Capture x packets */
5521 case 'f': /* capture filter */
5522 case 'F': /* capture file type */
5523 case 'g': /* enable group read access on file(s) */
5524 case 'i': /* Use interface x */
5525 case LONGOPT_SET_TSTAMP_TYPE: /* Set capture timestamp type */
5526 case 'n': /* Use pcapng format */
5527 case 'p': /* Don't capture in promiscuous mode */
5528 case 'P': /* Use pcap format */
5529 case 's': /* Set the snapshot (capture) length */
5530 case 'w': /* Write to capture file x */
5531 case 'y': /* Set the pcap data link type */
5532 #ifdef HAVE_PCAP_REMOTE
5533 case 'u': /* Use UDP for data transfer */
5534 case 'r': /* Capture own RPCAP traffic too */
5535 case 'A': /* Authentication */
5536 #endif
5537 #ifdef HAVE_PCAP_SETSAMPLING
5538 case 'm': /* Sampling */
5539 #endif
5540 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
5541 case 'B': /* Buffer size */
5542 #endif
5543 #ifdef HAVE_PCAP_CREATE
5544 case 'I': /* Monitor mode */
5545 #endif
5546 case LONGOPT_COMPRESS_TYPE: /* compress type */
5547 case LONGOPT_CAPTURE_TMPDIR: /* capture temp directory */
5548 case LONGOPT_UPDATE_INTERVAL: /* sync pipe update interval */
5549 status = capture_opts_add_opt(&global_capture_opts, opt, ws_optarg);
5550 if (status != 0) {
5551 exit_main(status);
5553 break;
5554 /*** hidden option: Wireshark child mode (using binary output messages) ***/
5555 case LONGOPT_IFNAME:
5556 if (global_capture_opts.ifaces->len > 0) {
5557 interface_options *interface_opts;
5559 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, global_capture_opts.ifaces->len - 1);
5560 interface_opts->ifname = g_strdup(ws_optarg);
5561 } else {
5562 cmdarg_err("--ifname must be specified after a -i option");
5563 exit_main(1);
5565 break;
5566 case LONGOPT_IFDESCR:
5567 if (global_capture_opts.ifaces->len > 0) {
5568 interface_options *interface_opts;
5570 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, global_capture_opts.ifaces->len - 1);
5571 interface_opts->descr = g_strdup(ws_optarg);
5572 } else {
5573 cmdarg_err("--ifdescr must be specified after a -i option");
5574 exit_main(1);
5576 break;
5577 case LONGOPT_CAPTURE_COMMENT: /* capture comment */
5578 if (capture_comments == NULL) {
5579 capture_comments = g_ptr_array_new_with_free_func(g_free);
5581 g_ptr_array_add(capture_comments, g_strdup(ws_optarg));
5582 break;
5583 case 'Z':
5584 capture_child = true;
5586 * Handled above
5588 break;
5589 #ifdef _WIN32
5590 case LONGOPT_SIGNAL_PIPE:
5591 if (!capture_child) {
5592 /* We have already checked for -Z at the very beginning. */
5593 cmdarg_err("--signal-pipe may only be specified with -Z");
5594 exit_main(1);
5597 * ws_optarg = the control ID, aka the PPID, currently used for the
5598 * signal pipe name.
5600 if (strcmp(ws_optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
5601 sig_pipe_name = ws_strdup_printf(SIGNAL_PIPE_FORMAT, ws_optarg);
5602 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
5603 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
5605 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
5606 ws_info("Signal pipe: Unable to open %s. Dead parent?",
5607 sig_pipe_name);
5608 exit_main(1);
5611 break;
5612 #endif
5613 case 'q': /* Quiet */
5614 quiet = true;
5615 break;
5616 case 'Q': /* Really quiet */
5617 quiet = true;
5618 really_quiet = true;
5619 break;
5620 case 't':
5621 use_threads = true;
5622 break;
5623 /*** all non capture option specific ***/
5624 case 'D': /* Print a list of capture devices and exit */
5625 if (!list_interfaces && !caps_queries & !print_statistics) {
5626 run_once_args++;
5628 list_interfaces = true;
5629 break;
5630 case 'L': /* Print list of link-layer types and exit */
5631 if (!list_interfaces && !caps_queries & !print_statistics) {
5632 run_once_args++;
5634 caps_queries |= CAPS_QUERY_LINK_TYPES;
5635 break;
5636 case LONGOPT_LIST_TSTAMP_TYPES:
5637 if (!list_interfaces && !caps_queries & !print_statistics) {
5638 run_once_args++;
5640 caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
5641 break;
5642 case 'd': /* Print BPF code for capture filter and exit */
5643 if (!print_bpf_code) {
5644 print_bpf_code = true;
5645 run_once_args++;
5647 break;
5648 case 'S': /* Print interface statistics once a second */
5649 if (!list_interfaces && !caps_queries & !print_statistics) {
5650 run_once_args++;
5652 print_statistics = true;
5653 break;
5654 case 'k': /* Set wireless channel */
5655 if (!set_chan) {
5656 set_chan = true;
5657 set_chan_arg = ws_optarg;
5658 run_once_args++;
5659 } else {
5660 cmdarg_err("Only one -k flag may be specified");
5661 arg_error = true;
5663 break;
5664 case 'M': /* For -D, -L, and -S, print machine-readable output */
5665 machine_readable = true;
5666 break;
5667 case 'C':
5668 pcap_queue_byte_limit = get_positive_int(ws_optarg, "byte_limit");
5669 break;
5670 case 'N':
5671 pcap_queue_packet_limit = get_positive_int(ws_optarg, "packet_limit");
5672 break;
5673 default:
5674 cmdarg_err("Invalid Option: %s", argv[ws_optind-1]);
5675 /* FALLTHROUGH */
5676 case '?': /* Bad flag - print usage message */
5677 arg_error = true;
5678 break;
5681 if (!arg_error) {
5682 argc -= ws_optind;
5683 argv += ws_optind;
5684 if (argc >= 1) {
5685 /* user specified file name as regular command-line argument */
5686 /* XXX - use it as the capture file name (or something else)? */
5687 argc--;
5688 argv++;
5690 if (argc != 0) {
5692 * Extra command line arguments were specified; complain.
5693 * XXX - interpret as capture filter, as tcpdump and tshark do?
5695 cmdarg_err("Invalid argument: %s", argv[0]);
5696 arg_error = true;
5700 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
5701 use_threads = true;
5703 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
5704 /* Use some default if the user hasn't specified some */
5705 /* XXX: Are these defaults good enough? */
5706 pcap_queue_byte_limit = 1000 * 1000;
5707 pcap_queue_packet_limit = 1000;
5709 if (arg_error) {
5710 if (ws_optopt == 'F') {
5711 capture_opts_list_file_types();
5712 exit_main(1);
5714 print_usage(stderr);
5715 exit_main(1);
5718 if (run_once_args > 1) {
5719 cmdarg_err("Only one of -D, -L, -d, -k or -S may be supplied.");
5720 exit_main(1);
5721 } else if (run_once_args == 1) {
5722 /* We're supposed to print some information, rather than
5723 to capture traffic; did they specify a ring buffer option? */
5724 if (global_capture_opts.multi_files_on) {
5725 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
5726 exit_main(1);
5728 } else {
5729 /* We're supposed to capture traffic; */
5731 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
5732 if (global_capture_opts.ifaces->len > 1) {
5733 use_threads = true;
5734 global_capture_opts.use_pcapng = true;
5737 if (capture_comments &&
5738 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
5739 /* XXX - for ringbuffer, should we apply the comments to each file? */
5740 cmdarg_err("Capture comments can only be set if we capture into a single pcapng file.");
5741 exit_main(1);
5744 /* Was the ring buffer option specified and, if so, does it make sense? */
5745 if (global_capture_opts.multi_files_on) {
5746 /* Ring buffer works only under certain conditions:
5747 a) ring buffer does not work with temporary files;
5748 b) it makes no sense to enable the ring buffer if the maximum
5749 file size is set to "infinite". */
5750 if (global_capture_opts.save_file == NULL) {
5751 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
5752 global_capture_opts.multi_files_on = false;
5754 if (!global_capture_opts.has_autostop_filesize &&
5755 !global_capture_opts.has_file_duration &&
5756 !global_capture_opts.has_file_interval &&
5757 !global_capture_opts.has_file_packets) {
5758 cmdarg_err("Ring buffer requested, but no maximum capture file size, duration "
5759 "interval, or packets were specified.");
5760 #if 0
5761 /* XXX - this must be redesigned as the conditions changed */
5762 global_capture_opts.multi_files_on = false;
5763 #endif
5765 if (global_capture_opts.has_file_duration && global_capture_opts.has_file_interval) {
5766 cmdarg_err("Ring buffer file duration and interval can't be used at the same time.");
5767 exit_main(1);
5773 * "-D" requires no interface to be selected; it's supposed to list
5774 * all interfaces.
5776 if (list_interfaces) {
5777 /* Get the list of interfaces */
5778 GList *if_list;
5779 int err;
5780 char *err_str;
5782 if_list = get_interface_list(&err, &err_str);
5783 if (if_list == NULL) {
5784 if (err == 0) {
5786 * If we're being run by another program, just give them
5787 * an empty list of interfaces, don't report this as
5788 * an error; that lets them decide whether to report
5789 * this as an error or not.
5791 if (!machine_readable) {
5792 cmdarg_err("There are no interfaces on which a capture can be done");
5793 exit_main(2);
5795 } else {
5796 cmdarg_err("%s", err_str);
5797 g_free(err_str);
5798 exit_main(2);
5802 if (!machine_readable) {
5803 status = 0;
5804 capture_opts_print_interfaces(if_list);
5807 if (caps_queries) {
5808 if_info_t *if_info;
5809 interface_options *interface_opts;
5810 cap_device_open_status open_status;
5811 char *open_status_str;
5812 for (GList *if_entry = if_list; if_entry != NULL; if_entry = g_list_next(if_entry)) {
5813 if_info = (if_info_t *)if_entry->data;
5816 * XXX - If on the command line we had the options -i <interface> -I,
5817 * we should retrieve the link-types for the interface in monitor mode.
5818 * We've already copied that information to global_capture_opts, but
5819 * the below statement wipes it away.
5821 interface_opts = interface_opts_from_if_info(&global_capture_opts, if_info);
5823 if_info->caps = get_if_capabilities(interface_opts, &open_status, &open_status_str);
5825 if (!machine_readable) {
5826 if (if_info->caps == NULL) {
5827 cmdarg_err("The capabilities of the capture device "
5828 "\"%s\" could not be obtained (%s).\n%s",
5829 interface_opts->name, open_status_str,
5830 get_pcap_failure_secondary_error_message(open_status, open_status_str));
5831 g_free(open_status_str);
5832 /* Break after one error, as when printing selected
5833 * interface capabilities. (XXX: We could print all
5834 * the primary status strings, and only the unique
5835 * set of secondary messages / suggestions; printing
5836 * the same long secondary error is a lot.)
5838 interface_opts_free(interface_opts);
5839 g_free(interface_opts);
5840 break;
5841 } else {
5842 status = capture_opts_print_if_capabilities(if_info->caps, interface_opts, caps_queries);
5843 if (status != 0) {
5844 interface_opts_free(interface_opts);
5845 g_free(interface_opts);
5846 break;
5849 } else {
5850 if (if_info->caps == NULL) {
5851 if_info->caps = g_new0(if_capabilities_t, 1);
5852 if_info->caps->primary_msg = open_status_str;
5853 if_info->caps->secondary_msg = get_pcap_failure_secondary_error_message(open_status, open_status_str);
5855 if_info->caps->status = open_status;
5858 interface_opts_free(interface_opts);
5859 g_free(interface_opts);
5863 if (machine_readable) {
5864 status = print_machine_readable_interfaces(if_list, caps_queries, print_statistics);
5866 free_interface_list(if_list);
5867 if (!print_statistics) {
5868 exit_main(status);
5873 * "-S" requires no interface to be selected; it gives statistics
5874 * for all interfaces.
5876 if (print_statistics) {
5877 status = print_statistics_loop(machine_readable);
5878 exit_main(status);
5881 if (set_chan) {
5882 interface_options *interface_opts;
5884 if (global_capture_opts.ifaces->len != 1) {
5885 cmdarg_err("Need one interface");
5886 exit_main(2);
5889 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
5890 status = set_80211_channel(interface_opts->name, set_chan_arg);
5891 exit_main(status);
5895 * "-L", "-d", and capturing act on a particular interface, so we have to
5896 * have an interface; if none was specified, pick a default.
5898 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
5899 if (status != 0) {
5900 /* cmdarg_err() already called .... */
5901 exit_main(status);
5904 if (caps_queries) {
5905 /* Get the list of link-layer and/or timestamp types for the capture device. */
5906 if_capabilities_t *caps;
5907 cap_device_open_status open_status;
5908 char *open_status_str;
5909 unsigned ii;
5911 if (machine_readable) {
5912 json_dumper dumper = {
5913 .output_file = stdout,
5914 .flags = JSON_DUMPER_FLAGS_NO_DEBUG,
5915 // Don't abort on failure
5917 json_dumper_begin_array(&dumper);
5918 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
5919 interface_options *interface_opts;
5921 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, ii);
5923 json_dumper_begin_object(&dumper);
5924 json_dumper_set_member_name(&dumper, interface_opts->name);
5926 json_dumper_begin_object(&dumper);
5928 open_status = CAP_DEVICE_OPEN_NO_ERR;
5929 caps = get_if_capabilities(interface_opts, &open_status, &open_status_str);
5930 if (caps == NULL) {
5931 json_dumper_set_member_name(&dumper, "status");
5932 json_dumper_value_anyf(&dumper, "%i", open_status);
5933 json_dumper_set_member_name(&dumper, "primary_msg");
5934 json_dumper_value_string(&dumper, open_status_str);
5935 g_free(open_status_str);
5936 } else {
5937 caps->status = open_status;
5938 print_machine_readable_if_capabilities(&dumper, caps, caps_queries);
5939 free_if_capabilities(caps);
5941 json_dumper_end_object(&dumper);
5942 json_dumper_end_object(&dumper);
5944 json_dumper_end_array(&dumper);
5945 if (json_dumper_finish(&dumper)) {
5946 status = 0;
5947 if (capture_child) {
5948 /* Let our parent know we succeeded. */
5949 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
5951 } else {
5952 status = 2;
5953 if (capture_child) {
5954 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, "Unexpected JSON error", "");
5957 } else {
5958 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
5959 interface_options *interface_opts;
5961 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, ii);
5963 caps = get_if_capabilities(interface_opts, &open_status, &open_status_str);
5964 if (caps == NULL) {
5965 if (capture_child) {
5966 char *error_msg = ws_strdup_printf("The capabilities of the capture device "
5967 "\"%s\" could not be obtained (%s)",
5968 interface_opts->name, open_status_str);
5969 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, error_msg,
5970 get_pcap_failure_secondary_error_message(open_status, open_status_str));
5971 g_free(error_msg);
5973 else {
5974 cmdarg_err("The capabilities of the capture device "
5975 "\"%s\" could not be obtained (%s).\n%s",
5976 interface_opts->name, open_status_str,
5977 get_pcap_failure_secondary_error_message(open_status, open_status_str));
5979 g_free(open_status_str);
5980 exit_main(2);
5983 /* XXX: We might want to print also the interface name */
5984 status = capture_opts_print_if_capabilities(caps,
5985 interface_opts,
5986 caps_queries);
5987 free_if_capabilities(caps);
5988 if (status != 0)
5989 break;
5992 exit_main(status);
5995 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
5996 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5997 interface_options *interface_opts;
5999 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
6000 if (interface_opts->timestamp_type) {
6001 interface_opts->timestamp_type_id = pcap_tstamp_type_name_to_val(interface_opts->timestamp_type);
6002 if (interface_opts->timestamp_type_id < 0) {
6003 cmdarg_err("Invalid argument to option: --time-stamp-type=%s", interface_opts->timestamp_type);
6004 exit_main(1);
6008 #endif
6010 /* We're supposed to do a capture, or print the BPF code for a filter. */
6012 /* Let the user know what interfaces were chosen. */
6013 if (capture_child) {
6014 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
6015 interface_options *interface_opts;
6017 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
6018 ws_debug("Interface: %s\n", interface_opts->name);
6020 } else {
6021 str = g_string_new("");
6022 #ifdef _WIN32
6023 if (global_capture_opts.ifaces->len < 2)
6024 #else
6025 if (global_capture_opts.ifaces->len < 4)
6026 #endif
6028 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
6029 interface_options *interface_opts;
6031 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
6032 if (j > 0) {
6033 if (global_capture_opts.ifaces->len > 2) {
6034 g_string_append_printf(str, ",");
6036 g_string_append_printf(str, " ");
6037 if (j == global_capture_opts.ifaces->len - 1) {
6038 g_string_append_printf(str, "and ");
6041 if (interface_opts->ifname != NULL) {
6043 * Re-generate the display name based on the strins
6044 * we were handed.
6046 g_free(interface_opts->display_name);
6047 if (interface_opts->descr != NULL) {
6048 #ifdef _WIN32
6049 interface_opts->display_name = ws_strdup_printf("%s",
6050 interface_opts->descr);
6051 #else
6052 interface_opts->display_name = ws_strdup_printf("%s: %s",
6053 interface_opts->descr, interface_opts->ifname);
6054 #endif
6055 } else {
6056 interface_opts->display_name = ws_strdup_printf("%s",
6057 interface_opts->ifname);
6060 g_string_append_printf(str, "'%s'", interface_opts->display_name);
6062 } else {
6063 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
6065 if (!really_quiet)
6066 fprintf(stderr, "Capturing on %s\n", str->str);
6067 g_string_free(str, TRUE);
6070 /* Process the snapshot length, as that affects the generated BPF code. */
6071 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
6073 if (print_bpf_code) {
6074 show_filter_code(&global_capture_opts);
6075 exit_main(0);
6078 /* We're supposed to do a capture. Process the ring buffer arguments. */
6079 capture_opts_trim_ring_num_files(&global_capture_opts);
6081 /* flush stderr prior to starting the main capture loop */
6082 fflush(stderr);
6084 /* Now start the capture. */
6085 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == true) {
6086 /* capture ok */
6087 exit_main(0);
6088 } else {
6089 /* capture failed */
6090 exit_main(1);
6092 return 0; /* never here, make compiler happy */
6095 static void
6096 dumpcap_log_writer(const char *domain, enum ws_log_level level,
6097 const char *file, long line, const char *func,
6098 const char *fatal_msg _U_,
6099 ws_log_manifest_t *mft,
6100 const char *user_format, va_list user_ap,
6101 void *user_data _U_)
6103 if (ws_log_msg_is_active(domain, level)) {
6104 /* log messages go to stderr or */
6105 /* to parent especially formatted if dumpcap running as child. */
6106 #ifdef DEBUG_CHILD_DUMPCAP
6107 va_list user_ap_copy;
6108 va_copy(user_ap_copy, user_ap);
6109 #endif
6110 if (capture_child) {
6111 /* Format the log mesage as the numeric level, followed
6112 * by a colon and then a string matching the standard log
6113 * string. In the future perhaps we serialize file, line,
6114 * and func (which can be NULL) instead.
6116 GString *msg = g_string_new(NULL);
6117 g_string_append_printf(msg, "%u:", level);
6118 if (file != NULL) {
6119 g_string_append_printf(msg, "%s", file);
6120 if (line >= 0) {
6121 g_string_append_printf(msg, ":%ld", line);
6124 g_string_append(msg, " --");
6125 if (func != NULL) {
6126 g_string_append_printf(msg, " %s():", func);
6128 g_string_append_c(msg, ' ');
6129 g_string_append_vprintf(msg, user_format, user_ap);
6131 sync_pipe_write_string_msg(sync_pipe_fd, SP_LOG_MSG, msg->str);
6132 g_string_free(msg, TRUE);
6133 } else {
6134 ws_log_console_writer(domain, level, file, line, func, mft, user_format, user_ap);
6136 #ifdef DEBUG_CHILD_DUMPCAP
6137 ws_log_file_writer(debug_log, domain, level, file, line, func, mft, user_format, user_ap_copy);
6138 va_end(user_ap_copy);
6139 #endif
6144 /****************************************************************************************************************/
6145 /* indication report routines */
6148 static void
6149 report_packet_count(unsigned int packet_count)
6151 static unsigned int count = 0;
6153 if (capture_child) {
6154 ws_debug("Packets: %u", packet_count);
6155 sync_pipe_write_uint_msg(sync_pipe_fd, SP_PACKET_COUNT, packet_count);
6156 } else {
6157 count += packet_count;
6158 fprintf(stderr, "\rPackets: %u ", count);
6159 /* stderr could be line buffered */
6160 fflush(stderr);
6164 static void
6165 report_new_capture_file(const char *filename)
6167 if (capture_child) {
6168 ws_debug("File: %s", filename);
6169 if (global_ld.pcapng_passthrough) {
6170 /* Save filename for sending SP_FILE to capture parent after SHB is passed-through */
6171 ws_debug("Delaying SP_FILE until first SHB");
6172 report_capture_filename = filename;
6173 } else {
6174 sync_pipe_write_string_msg(sync_pipe_fd, SP_FILE, filename);
6176 } else {
6177 #ifdef SIGINFO
6179 * Prevent a SIGINFO handler from writing to the standard error
6180 * while we're doing so; instead, have it just set a flag telling
6181 * us to print that information when we're done.
6183 infodelay = true;
6184 #endif /* SIGINFO */
6185 if (!really_quiet) {
6186 fprintf(stderr, "File: %s\n", filename);
6187 /* stderr could be line buffered */
6188 fflush(stderr);
6191 #ifdef SIGINFO
6193 * Allow SIGINFO handlers to write.
6195 infodelay = false;
6198 * If a SIGINFO handler asked us to write out capture counts, do so.
6200 if (infoprint)
6201 report_counts_for_siginfo();
6202 #endif /* SIGINFO */
6206 static void
6207 report_cfilter_error(capture_options *capture_opts, unsigned i, const char *errmsg)
6209 interface_options *interface_opts;
6210 char tmp[MSG_MAX_LENGTH+1+6];
6212 if (i < capture_opts->ifaces->len) {
6213 if (capture_child) {
6214 snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
6215 ws_debug("Capture filter error: %s", errmsg);
6216 sync_pipe_write_string_msg(sync_pipe_fd, SP_BAD_FILTER, tmp);
6217 } else {
6219 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
6220 * the error message below.
6222 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
6223 cmdarg_err(
6224 "Invalid capture filter \"%s\" for interface '%s'.\n"
6225 "\n"
6226 "That string isn't a valid capture filter (%s).\n"
6227 "See the User's Guide for a description of the capture filter syntax.",
6228 interface_opts->cfilter, interface_opts->name, errmsg);
6233 static void
6234 report_capture_error(const char *error_msg, const char *secondary_error_msg)
6236 if (capture_child) {
6237 ws_debug("Primary Error: %s", error_msg);
6238 ws_debug("Secondary Error: %s", secondary_error_msg);
6239 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, error_msg, secondary_error_msg);
6240 } else {
6241 cmdarg_err("%s", error_msg);
6242 if (secondary_error_msg[0] != '\0')
6243 cmdarg_err_cont("%s", secondary_error_msg);
6247 static void
6248 report_packet_drops(uint32_t received, uint32_t pcap_drops, uint32_t drops, uint32_t flushed, uint32_t ps_ifdrop, char *name)
6250 uint32_t total_drops = pcap_drops + drops + flushed;
6252 if (capture_child) {
6253 char* tmp = ws_strdup_printf("%u:%s", total_drops, name);
6255 ws_debug("Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
6256 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
6257 sync_pipe_write_string_msg(sync_pipe_fd, SP_DROPS, tmp);
6258 g_free(tmp);
6259 } else {
6260 if (!really_quiet) {
6261 fprintf(stderr,
6262 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
6263 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
6264 received ? 100.0 * received / (received + total_drops) : 0.0);
6265 /* stderr could be line buffered */
6266 fflush(stderr);
6272 /************************************************************************************************/
6273 /* signal_pipe handling */
6276 #ifdef _WIN32
6277 static bool
6278 signal_pipe_check_running(void)
6280 /* any news from our parent? -> just stop the capture */
6281 DWORD avail = 0;
6282 bool result;
6284 /* if we are running standalone, no check required */
6285 if (!capture_child) {
6286 return true;
6289 if (!sig_pipe_name || !sig_pipe_handle) {
6290 /* This shouldn't happen */
6291 ws_info("Signal pipe: No name or handle");
6292 return false;
6296 * XXX - We should have the process ID of the parent (from the "-Z" flag)
6297 * at this point. Should we check to see if the parent is still alive,
6298 * e.g. by using OpenProcess?
6301 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
6303 if (!result || avail > 0) {
6304 /* peek failed or some bytes really available */
6305 /* (if not piping from stdin this would fail) */
6306 ws_info("Signal pipe: Stop capture: %s", sig_pipe_name);
6307 ws_debug("Signal pipe: %s (%p) result: %u avail: %lu", sig_pipe_name,
6308 sig_pipe_handle, result, avail);
6309 return false;
6310 } else {
6311 /* pipe ok and no bytes available */
6312 return true;
6315 #endif
6318 * Editor modelines - https://www.wireshark.org/tools/modelines.html
6320 * Local variables:
6321 * c-basic-offset: 4
6322 * tab-width: 8
6323 * indent-tabs-mode: nil
6324 * End:
6326 * vi: set shiftwidth=4 tabstop=8 expandtab:
6327 * :indentSize=4:tabSize=8:noTabs=true: