Qt: Fix leak on CaptureFileDialog preview of file with errors
[wireshark.git] / dumpcap.c
blobb528f028a69e0dd8c943aa3b3026df1b8ecc747d
1 /* dumpcap.c
3 * Wireshark - Network traffic analyzer
4 * By Gerald Combs <gerald@wireshark.org>
5 * Copyright 1998 Gerald Combs
7 * SPDX-License-Identifier: GPL-2.0-or-later
8 */
10 #include <config.h>
11 #define WS_LOG_DOMAIN LOG_DOMAIN_CAPCHILD
13 #include <stdio.h>
14 #include <stdlib.h> /* for exit() */
15 #include <glib.h>
17 #include <string.h>
19 #include <ws_exit_codes.h>
21 #include <sys/types.h>
23 #ifdef HAVE_NETINET_IN_H
24 #include <netinet/in.h>
25 #endif
27 #include <wsutil/ws_getopt.h>
29 #if defined(__APPLE__) && defined(__LP64__)
30 #include <sys/utsname.h>
31 #endif
33 #include <signal.h>
34 #include <errno.h>
36 #include <wsutil/array.h>
37 #include <wsutil/cmdarg_err.h>
38 #include <wsutil/strtoi.h>
39 #include <cli_main.h>
40 #include <wsutil/version_info.h>
42 #include <wsutil/socket.h>
43 #include <wsutil/wslog.h>
44 #include <wsutil/file_util.h>
46 #ifdef HAVE_LIBCAP
47 # include <sys/prctl.h>
48 # include <sys/capability.h>
49 #endif
51 #include "ringbuffer.h"
53 #include "capture/capture_ifinfo.h"
54 #include "capture/capture-pcap-util.h"
55 #include "capture/capture-pcap-util-int.h"
56 #ifdef _WIN32
57 #include "capture/capture-wpcap.h"
58 #endif /* _WIN32 */
60 #include "writecap/pcapio.h"
62 #ifndef _WIN32
63 #include <sys/un.h>
64 #endif
66 #include <wsutil/clopts_common.h>
67 #include <wsutil/privileges.h>
69 #include "sync_pipe.h"
71 #include "capture_opts.h"
72 #include <capture/capture_session.h>
73 #include <capture/capture_sync.h>
75 #include "wsutil/tempfile.h"
76 #include "wsutil/file_util.h"
77 #include "wsutil/cpu_info.h"
78 #include "wsutil/os_version_info.h"
79 #include "wsutil/str_util.h"
80 #include "wsutil/inet_addr.h"
81 #include "wsutil/time_util.h"
82 #include "wsutil/please_report_bug.h"
83 #include "wsutil/glib-compat.h"
84 #include <wsutil/json_dumper.h>
85 #include <wsutil/ws_assert.h>
87 #include "capture/ws80211_utils.h"
89 #include "extcap.h"
92 * Get information about libpcap format from "wiretap/libpcap.h".
93 * Get information about pcapng format from "wiretap/pcapng_module.h".
94 * XXX - can we just use pcap_open_offline() to read the pipe?
96 #include "wiretap/libpcap.h"
97 #include "wiretap/pcapng_module.h"
98 #include "wiretap/pcapng.h"
101 * Define these for extra logging. Note that when dumpcap is spawned as
102 * a child process, logs are sent to the parent via the sync pipe.
103 * The parent will pass along the Capchild domain log level settings,
104 * so "--log-debug Capchild" or "--log-level debug" can be used to get
105 * debugging from dumpcap sent to the parent.
107 //#define DEBUG_DUMPCAP /* Waits for keypress on quitting on Windows */
108 //#define DEBUG_CHILD_DUMPCAP /* Writes logs to file */
110 #ifdef _WIN32
111 #include "wsutil/win32-utils.h"
112 #ifdef DEBUG_DUMPCAP
113 #include <conio.h> /* _getch() */
114 #endif
115 #endif
117 #ifdef DEBUG_CHILD_DUMPCAP
118 FILE *debug_log; /* for logging debug messages to */
119 /* a file if DEBUG_CHILD_DUMPCAP */
120 /* is defined */
121 #include <stdarg.h> /* va_copy */
122 #endif
124 static GAsyncQueue *pcap_queue;
125 static gint64 pcap_queue_bytes;
126 static gint64 pcap_queue_packets;
127 static gint64 pcap_queue_byte_limit;
128 static gint64 pcap_queue_packet_limit;
130 static gboolean capture_child; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
131 static const char *report_capture_filename; /* capture child file name */
132 #ifdef _WIN32
133 static gchar *sig_pipe_name;
134 static HANDLE sig_pipe_handle;
135 static gboolean signal_pipe_check_running(void);
136 #endif
137 static int sync_pipe_fd = 2;
139 #ifdef ENABLE_ASAN
140 /* This has public visibility so that if compiled with shared libasan (the
141 * gcc default) function interposition occurs.
143 WS_DLL_PUBLIC int
144 __lsan_is_turned_off(void)
146 /* If we're in capture child mode, don't run a LSan report and
147 * send it to stderr, because it isn't properly formatted for
148 * the sync pipe.
149 * We could, if debugging variables are set, send the reports
150 * elsewhere instead, by calling __sanitizer_set_report_path()
151 * or __sanitizer_set_report_fd()
153 if (capture_child) {
154 return 1;
156 #ifdef HAVE_LIBCAP
157 /* LSan dies with a fatal error without explanation if it can't ptrace.
158 * Normally, the "dumpable" attribute (which also controls ptracing)
159 * is set to 1 (SUID_DUMP_USER, process is dumpable.) However, it is
160 * reset to the current value in /proc/sys/fs/suid_dumpable in the
161 * following circumstances: euid/egid changes, fsuid/fsgid changes,
162 * execve of a setuid or setgid program that changes the euid or egid,
163 * execve of a program with capabilities exceeding those already
164 * permitted for the process.
166 * Unless we're running as root, one of those applies to dumpcap.
168 * The default value of /proc/sys/fs/suid_dumpable is 0, SUID_DUMP_DISABLE.
169 * In such a case, LeakSanitizer temporarily sets the value to 1 to
170 * allow ptracing, and then sets it back to 0.
172 * Another possible value, used by Ubuntu, Fedora, etc., is 2,
173 * which creates dumps readable by root only. For security reasons,
174 * unprivileged programs are not allowed to change the value to 2.
175 * (See https://nvd.nist.gov/vuln/detail/CVE-2006-2451 )
177 * LSan does not check for the value 2 and change dumpable to 1 in that
178 * case, possibly because if it did it could not change it back to 2
179 * and would have to either leave the process dumpable or change it to 0.
181 * The usual way to control the family of sanitizers is through environment
182 * variables. However, complicating things, changing the dumpable attribute
183 * to 0 or 2 changes the ownership of files in /proc/[pid] (including
184 * /proc/self ) to root:root, in particular /proc/[pid]/environ, and so
185 * ASAN_OPTIONS=detect_leaks=0 has no effect. (Unless the process has
186 * CAP_SYS_PTRACE, which allows tracing of any process, but that's also
187 * a security risk and we'll have dropped that with other privileges.)
189 * So if prctl(PR_GET_DUMPABLE) returns 2, we know that the process will
190 * die with a fatal error if it attempts to run LSan, so don't.
192 * See proc(5), prctl(2), ptrace(2), and
193 * https://github.com/google/sanitizers/issues/1306
194 * https://github.com/llvm/llvm-project/issues/55944
196 if (prctl(PR_GET_DUMPABLE) == 2) {
197 ws_debug("Not running LeakSanitizer because /proc/sys/fs/suid_dumpable is 2");
198 return 1;
200 #endif
201 return 0;
204 WS_DLL_PUBLIC const char*
205 __asan_default_options(void)
207 /* By default don't override our exit code if there's a leak or error.
208 * We particularly don't want to do this if running as a capture child,
209 * because capture/capture_sync doesn't expect the ASan exit codes.
211 return "exitcode=0";
213 #endif
215 #ifdef SIGINFO
216 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
217 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
218 #endif /* SIGINFO */
220 /** Stop a low-level capture (stops the capture child). */
221 static void capture_loop_stop(void);
222 /** Close a pipe, or socket if \a from_socket is TRUE */
223 static void cap_pipe_close(int pipe_fd, gboolean from_socket);
225 #if defined (__linux__)
226 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
227 * in pcap_dispatch(); on the other hand, select() works just fine there.
228 * Hence we use a select for that come what may.
230 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
231 * internally, and, with TPACKET_V3, once that's supported, it'll
232 * support timeouts, at least as I understand the way the code works.
234 #define MUST_DO_SELECT
235 #endif
237 /** init the capture filter */
238 typedef enum {
239 INITFILTER_NO_ERROR,
240 INITFILTER_BAD_FILTER,
241 INITFILTER_OTHER_ERROR
242 } initfilter_status_t;
244 typedef enum {
245 STATE_EXPECT_REC_HDR,
246 STATE_READ_REC_HDR,
247 STATE_EXPECT_DATA,
248 STATE_READ_DATA
249 } cap_pipe_state_t;
251 typedef enum {
252 PIPOK,
253 PIPEOF,
254 PIPERR,
255 PIPNEXIST
256 } cap_pipe_err_t;
258 typedef struct _pcap_pipe_info {
259 gboolean byte_swapped; /**< TRUE if data in the pipe is byte swapped. */
260 struct pcap_hdr hdr; /**< Pcap header when capturing from a pipe */
261 struct pcaprec_modified_hdr rechdr; /**< Pcap record header when capturing from a pipe */
262 } pcap_pipe_info_t;
264 typedef struct _pcapng_pipe_info {
265 pcapng_block_header_t bh; /**< Pcapng general block header when capturing from a pipe */
266 GArray *src_iface_to_global; /**< Int array mapping local IDB numbers to global_ld.interface_data */
267 } pcapng_pipe_info_t;
269 struct _loop_data; /* forward declaration so we can use it in the cap_pipe_dispatch function pointer */
272 * A source of packets from which we're capturing.
274 typedef struct _capture_src {
275 guint32 received;
276 guint32 dropped;
277 guint32 flushed;
278 pcap_t *pcap_h;
279 #ifdef MUST_DO_SELECT
280 int pcap_fd; /**< pcap file descriptor */
281 #endif
282 gboolean pcap_err;
283 guint interface_id;
284 guint idb_id; /**< If from_pcapng is false, the output IDB interface ID. Otherwise the mapping in src_iface_to_global is used. */
285 GThread *tid;
286 int snaplen;
287 int linktype;
288 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
289 /**< capture pipe (unix only "input file") */
290 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
291 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
292 gboolean from_pcapng; /**< TRUE if we're capturing from pcapng format */
293 union {
294 pcap_pipe_info_t pcap; /**< Pcap info when capturing from a pipe */
295 pcapng_pipe_info_t pcapng; /**< Pcapng info when capturing from a pipe */
296 } cap_pipe_info;
297 #ifdef _WIN32
298 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
299 #endif
300 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
301 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
302 char * cap_pipe_databuf; /**< Pointer to the data buffer we've allocated */
303 size_t cap_pipe_databuf_size; /**< Current size of the data buffer */
304 guint cap_pipe_max_pkt_size; /**< Maximum packet size allowed */
305 #if defined(_WIN32)
306 char * cap_pipe_buf; /**< Pointer to the buffer we read into */
307 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
308 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
309 #else
310 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
311 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
312 #endif
313 int (*cap_pipe_dispatch)(struct _loop_data *, struct _capture_src *, char *, size_t);
314 cap_pipe_state_t cap_pipe_state;
315 cap_pipe_err_t cap_pipe_err;
317 #if defined(_WIN32)
318 GMutex *cap_pipe_read_mtx;
319 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
320 #endif
321 } capture_src;
323 typedef struct _saved_idb {
324 gboolean deleted;
325 guint interface_id; /* capture_src->interface_id for the associated SHB */
326 guint8 *idb; /* If non-NULL, IDB read from capture_src. This is an interface specified on the command line otherwise. */
327 guint idb_len;
328 } saved_idb_t;
331 * Global capture loop state.
333 typedef struct _loop_data {
334 /* common */
335 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
336 int err; /**< if non-zero, error seen while capturing */
337 gint packets_captured; /**< Number of packets we have already captured */
338 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
339 #ifdef SIGINFO
340 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
341 #endif
342 GArray *pcaps; /**< Array of capture_src's on which we're capturing */
343 gboolean pcapng_passthrough; /**< We have one source and it's pcapng. Pass its SHB and IDBs through. */
344 guint8 *saved_shb; /**< SHB to write when we have one pcapng input */
345 GArray *saved_idbs; /**< Array of saved_idb_t, written when we have a new section or output file. */
346 GRWLock saved_shb_idb_lock; /**< Saved IDB RW mutex */
347 /* output file(s) */
348 FILE *pdh;
349 int save_file_fd;
350 char *io_buffer; /**< Our IO buffer if we increase the size from the standard size */
351 guint64 bytes_written; /**< Bytes written for the current file. */
352 /* autostop conditions */
353 int packets_written; /**< Packets written for the current file. */
354 int file_count;
355 /* ring buffer conditions */
356 GTimer *file_duration_timer;
357 time_t next_interval_time;
358 int interval_s;
359 } loop_data;
361 typedef struct _pcap_queue_element {
362 capture_src *pcap_src;
363 union {
364 struct pcap_pkthdr phdr;
365 pcapng_block_header_t bh;
366 } u;
367 u_char *pd;
368 } pcap_queue_element;
371 * This needs to be static, so that the SIGINT handler can clear the "go"
372 * flag and for saved_shb_idb_lock.
374 static loop_data global_ld;
377 * Timeout, in milliseconds, for reads from the stream of captured packets
378 * from a capture device.
380 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
381 * 64-bit applications, with sub-second timeouts not to work. The bug is
382 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
384 #if defined(__APPLE__) && defined(__LP64__)
385 static gboolean need_timeout_workaround;
387 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
388 #else
389 #define CAP_READ_TIMEOUT 250
390 #endif
393 * Timeout, in microseconds, for reads from the stream of captured packets
394 * from a pipe. Pipes don't have the same problem that BPF devices do
395 * in Mac OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
396 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
397 * of the offending versions of Snow Leopard.
399 * On Windows this value is converted to milliseconds and passed to
400 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
401 * will return immediately.
403 #if defined(_WIN32)
404 #define PIPE_READ_TIMEOUT 100000
405 #else
406 #define PIPE_READ_TIMEOUT 250000
407 #endif
409 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
411 static void
412 dumpcap_log_writer(const char *domain, enum ws_log_level level,
413 const char *file, long line, const char *func,
414 const char *fatal_msg, ws_log_manifest_t *mft,
415 const char *user_format, va_list user_ap,
416 void *user_data);
418 /* capture related options */
419 static capture_options global_capture_opts;
420 static GPtrArray *capture_comments;
421 static gboolean quiet;
422 static gboolean use_threads;
423 static guint64 start_time;
425 static void capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
426 const u_char *pd);
427 static void capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
428 const u_char *pd);
429 static void capture_loop_write_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd);
430 static void capture_loop_queue_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd);
431 static void capture_loop_get_errmsg(char *errmsg, size_t errmsglen,
432 char *secondary_errmsg,
433 size_t secondary_errmsglen,
434 const char *fname, int err,
435 gboolean is_close);
437 WS_NORETURN static void exit_main(int err);
439 static void report_new_capture_file(const char *filename);
440 static void report_packet_count(unsigned int packet_count);
441 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
442 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
443 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
445 #define MSG_MAX_LENGTH 4096
447 static void
448 print_usage(FILE *output)
450 fprintf(output, "\nUsage: dumpcap [options] ...\n");
451 fprintf(output, "\n");
452 fprintf(output, "Capture interface:\n");
453 fprintf(output, " -i <interface>, --interface <interface>\n");
454 fprintf(output, " name or idx of interface (def: first non-loopback),\n"
455 " or for remote capturing, use one of these formats:\n"
456 " rpcap://<host>/<interface>\n"
457 " TCP@<host>:<port>\n");
458 fprintf(output, " --ifname <name> name to use in the capture file for a pipe from which\n");
459 fprintf(output, " we're capturing\n");
460 fprintf(output, " --ifdescr <description>\n");
461 fprintf(output, " description to use in the capture file for a pipe\n");
462 fprintf(output, " from which we're capturing\n");
463 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
464 fprintf(output, " -s <snaplen>, --snapshot-length <snaplen>\n");
465 #ifdef HAVE_PCAP_CREATE
466 fprintf(output, " packet snapshot length (def: appropriate maximum)\n");
467 #else
468 fprintf(output, " packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
469 #endif
470 fprintf(output, " -p, --no-promiscuous-mode\n");
471 fprintf(output, " don't capture in promiscuous mode\n");
472 #ifdef HAVE_PCAP_CREATE
473 fprintf(output, " -I, --monitor-mode capture in monitor mode, if available\n");
474 #endif
475 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
476 fprintf(output, " -B <buffer size>, --buffer-size <buffer size>\n");
477 fprintf(output, " size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
478 #endif
479 fprintf(output, " -y <link type>, --linktype <link type>\n");
480 fprintf(output, " link layer type (def: first appropriate)\n");
481 fprintf(output, " --time-stamp-type <type> timestamp method for interface\n");
482 fprintf(output, " -D, --list-interfaces print list of interfaces and exit\n");
483 fprintf(output, " -L, --list-data-link-types\n");
484 fprintf(output, " print list of link-layer types of iface and exit\n");
485 fprintf(output, " --list-time-stamp-types print list of timestamp types for iface and exit\n");
486 fprintf(output, " --update-interval interval between updates with new packets (def: %dms)\n", DEFAULT_UPDATE_INTERVAL);
487 fprintf(output, " -d print generated BPF code for capture filter\n");
488 fprintf(output, " -k <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
489 fprintf(output, " set channel on wifi interface\n");
490 fprintf(output, " -S print statistics for each interface once per second\n");
491 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
492 fprintf(output, "\n");
493 #ifdef HAVE_PCAP_REMOTE
494 fprintf(output, "RPCAP options:\n");
495 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
496 fprintf(output, " -u use UDP for RPCAP data transfer\n");
497 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
498 #ifdef HAVE_PCAP_SETSAMPLING
499 fprintf(output, " -m <sampling type> use packet sampling\n");
500 fprintf(output, " count:NUM - capture one packet of every NUM\n");
501 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
502 #endif
503 #endif
504 fprintf(output, "Stop conditions:\n");
505 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
506 fprintf(output, " -a <autostop cond.> ..., --autostop <autostop cond.> ...\n");
507 fprintf(output, " duration:NUM - stop after NUM seconds\n");
508 fprintf(output, " filesize:NUM - stop this file after NUM kB\n");
509 fprintf(output, " files:NUM - stop after NUM files\n");
510 fprintf(output, " packets:NUM - stop after NUM packets\n");
511 /*fprintf(output, "\n");*/
512 fprintf(output, "Output (files):\n");
513 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
514 fprintf(output, " -g enable group read access on the output file(s)\n");
515 fprintf(output, " -b <ringbuffer opt.> ..., --ring-buffer <ringbuffer opt.>\n");
516 fprintf(output, " duration:NUM - switch to next file after NUM secs\n");
517 fprintf(output, " filesize:NUM - switch to next file after NUM kB\n");
518 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
519 fprintf(output, " packets:NUM - ringbuffer: replace after NUM packets\n");
520 fprintf(output, " interval:NUM - switch to next file when the time is\n");
521 fprintf(output, " an exact multiple of NUM secs\n");
522 fprintf(output, " printname:FILE - print filename to FILE when written\n");
523 fprintf(output, " (can use 'stdout' or 'stderr')\n");
524 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
525 fprintf(output, " -P use libpcap format instead of pcapng\n");
526 fprintf(output, " --capture-comment <comment>\n");
527 fprintf(output, " add a capture comment to the output file\n");
528 fprintf(output, " (only for pcapng)\n");
529 fprintf(output, " --temp-dir <directory> write temporary files to this directory\n");
530 fprintf(output, " (default: %s)\n", g_get_tmp_dir());
531 fprintf(output, "\n");
533 ws_log_print_usage(output);
534 fprintf(output, "\n");
536 fprintf(output, "Miscellaneous:\n");
537 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
538 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
539 fprintf(output, " within dumpcap\n");
540 fprintf(output, " -t use a separate thread per interface\n");
541 fprintf(output, " -q don't report packet capture counts\n");
542 fprintf(output, " -v, --version print version information and exit\n");
543 fprintf(output, " -h, --help display this help and exit\n");
544 fprintf(output, "\n");
545 #ifdef __linux__
546 fprintf(output, "Dumpcap can benefit from an enabled BPF JIT compiler if available.\n");
547 fprintf(output, "You might want to enable it by executing:\n");
548 fprintf(output, " \"echo 1 > /proc/sys/net/core/bpf_jit_enable\"\n");
549 fprintf(output, "Note that this can make your system less secure!\n");
550 fprintf(output, "\n");
551 #endif
552 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
553 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
554 fprintf(output, "\n");
555 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
559 * Report an error in command-line arguments.
560 * If we're a capture child, send a message back to the parent, otherwise
561 * just print it.
563 static void
564 dumpcap_cmdarg_err(const char *fmt, va_list ap)
566 if (capture_child) {
567 gchar *msg;
568 /* Generate a 'special format' message back to parent */
569 msg = ws_strdup_vprintf(fmt, ap);
570 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, msg, "");
571 g_free(msg);
572 } else {
573 fprintf(stderr, "dumpcap: ");
574 vfprintf(stderr, fmt, ap);
575 fprintf(stderr, "\n");
580 * Report additional information for an error in command-line arguments.
581 * If we're a capture child, send a message back to the parent, otherwise
582 * just print it.
584 static void
585 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
587 if (capture_child) {
588 gchar *msg;
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 vfprintf(stderr, fmt, ap);
594 fprintf(stderr, "\n");
598 #ifdef HAVE_LIBCAP
599 static void
600 #if 0 /* Set to enable capability debugging */
601 /* see 'man cap_to_text()' for explanation of output */
602 /* '=' means 'all= ' ie: no capabilities */
603 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
604 /* .... */
605 print_caps(const char *pfx) {
606 cap_t caps = cap_get_proc();
607 ws_debug("%s: EUID: %d Capabilities: %s", pfx, geteuid(), cap_to_text(caps, NULL));
608 cap_free(caps);
610 #else
611 print_caps(const char *pfx _U_) {
613 #endif
615 static void
616 relinquish_all_capabilities(void)
618 /* Drop any and all capabilities this process may have. */
619 /* Allowed whether or not process has any privileges. */
620 cap_t caps = cap_init(); /* all capabilities initialized to off */
621 print_caps("Pre-clear");
622 if (cap_set_proc(caps)) {
623 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
625 print_caps("Post-clear");
626 cap_free(caps);
628 #endif
630 static void
631 get_capture_device_open_failure_messages(cap_device_open_status open_status,
632 const char *open_status_str,
633 const char *iface,
634 char *errmsg, size_t errmsg_len,
635 char *secondary_errmsg,
636 size_t secondary_errmsg_len)
638 switch (open_status) {
640 case CAP_DEVICE_OPEN_ERROR_NO_SUCH_DEVICE:
641 snprintf(errmsg, errmsg_len,
642 "There is no device named \"%s\".\n(%s)",
643 iface, open_status_str);
644 break;
646 case CAP_DEVICE_OPEN_ERROR_RFMON_NOTSUP:
647 snprintf(errmsg, errmsg_len,
648 "Capturing in monitor mode is not supported on device \"%s\".\n(%s)",
649 iface, open_status_str);
650 break;
652 case CAP_DEVICE_OPEN_ERROR_PERM_DENIED:
653 snprintf(errmsg, errmsg_len,
654 "You do not have permission to capture on device \"%s\".\n(%s)",
655 iface, open_status_str);
656 break;
658 case CAP_DEVICE_OPEN_ERROR_IFACE_NOT_UP:
659 snprintf(errmsg, errmsg_len,
660 "Device \"%s\" is not up.\n(%s)",
661 iface, open_status_str);
662 break;
664 case CAP_DEVICE_OPEN_ERROR_PROMISC_PERM_DENIED:
665 snprintf(errmsg, errmsg_len,
666 "You do not have permission to capture in promiscuous mode on device \"%s\".\n(%s)",
667 iface, open_status_str);
668 break;
670 case CAP_DEVICE_OPEN_ERROR_OTHER:
671 default:
672 snprintf(errmsg, errmsg_len,
673 "The capture session could not be initiated on capture device \"%s\".\n(%s)",
674 iface, open_status_str);
675 break;
677 snprintf(secondary_errmsg, secondary_errmsg_len, "%s",
678 get_pcap_failure_secondary_error_message(open_status, open_status_str));
681 static gboolean
682 compile_capture_filter(const char *iface, pcap_t *pcap_h,
683 struct bpf_program *fcode, const char *cfilter)
685 bpf_u_int32 netnum, netmask;
686 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
688 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
690 * Well, we can't get the netmask for this interface; it's used
691 * only for filters that check for broadcast IP addresses, so
692 * we just punt and use 0. It might be nice to warn the user,
693 * but that's a pain in a GUI application, as it'd involve popping
694 * up a message box, and it's not clear how often this would make
695 * a difference (only filters that check for IP broadcast addresses
696 * use the netmask).
698 /*cmdarg_err(
699 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
700 netmask = 0;
704 * Sigh. Older versions of libpcap don't properly declare the
705 * third argument to pcap_compile() as a const pointer. Cast
706 * away the warning.
708 DIAG_OFF(cast-qual)
709 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
710 return FALSE;
711 DIAG_ON(cast-qual)
712 return TRUE;
715 static gboolean
716 show_filter_code(capture_options *capture_opts)
718 interface_options *interface_opts;
719 pcap_t *pcap_h;
720 cap_device_open_status open_status;
721 gchar open_status_str[PCAP_ERRBUF_SIZE];
722 char errmsg[MSG_MAX_LENGTH+1];
723 char secondary_errmsg[MSG_MAX_LENGTH+1];
724 struct bpf_program fcode;
725 struct bpf_insn *insn;
726 u_int i;
727 guint j;
729 for (j = 0; j < capture_opts->ifaces->len; j++) {
730 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, j);
731 pcap_h = open_capture_device(capture_opts, interface_opts,
732 CAP_READ_TIMEOUT, &open_status, &open_status_str);
733 if (pcap_h == NULL) {
734 /* Open failed; get messages */
735 get_capture_device_open_failure_messages(open_status, open_status_str,
736 interface_opts->name,
737 errmsg, sizeof errmsg,
738 secondary_errmsg,
739 sizeof secondary_errmsg);
740 /* And report them */
741 report_capture_error(errmsg, secondary_errmsg);
742 return FALSE;
745 /* Set the link-layer type. */
746 if (!set_pcap_datalink(pcap_h, interface_opts->linktype, interface_opts->name,
747 errmsg, sizeof errmsg,
748 secondary_errmsg, sizeof secondary_errmsg)) {
749 pcap_close(pcap_h);
750 report_capture_error(errmsg, secondary_errmsg);
751 return FALSE;
754 /* OK, try to compile the capture filter. */
755 if (!compile_capture_filter(interface_opts->name, pcap_h, &fcode,
756 interface_opts->cfilter)) {
757 snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_h));
758 pcap_close(pcap_h);
759 report_cfilter_error(capture_opts, j, errmsg);
760 return FALSE;
762 pcap_close(pcap_h);
764 /* Now print the filter code. */
765 insn = fcode.bf_insns;
767 for (i = 0; i < fcode.bf_len; insn++, i++)
768 printf("%s\n", bpf_image(insn, i));
770 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
771 /* to remove any suid privileges. */
772 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
773 /* (euid/egid have already previously been set to ruid/rgid. */
774 /* (See comment in main() for details) */
775 #ifndef HAVE_LIBCAP
776 relinquish_special_privs_perm();
777 #else
778 relinquish_all_capabilities();
779 #endif
780 if (capture_child) {
781 /* Let our parent know we succeeded. */
782 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
784 return TRUE;
787 static void
788 print_machine_readable_if_capabilities(json_dumper *dumper, if_capabilities_t *caps, int queries);
791 * Output a machine readable list of the interfaces
792 * This list is retrieved by the sync_interface_list_open() function
793 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
795 static int
796 print_machine_readable_interfaces(GList *if_list, int caps_queries, bool print_statistics)
798 GList *if_entry;
799 if_info_t *if_info;
800 GSList *addr;
801 if_addr_t *if_addr;
802 char addr_str[WS_INET6_ADDRSTRLEN];
803 int status;
805 json_dumper dumper = {
806 .output_string = g_string_new(NULL),
807 .flags = JSON_DUMPER_FLAGS_NO_DEBUG,
808 // Don't abort on failure
810 json_dumper_begin_array(&dumper);
813 * Print the contents of the if_entry struct in a parseable format (JSON)
815 for (if_entry = g_list_first(if_list); if_entry != NULL;
816 if_entry = g_list_next(if_entry)) {
817 if_info = (if_info_t *)if_entry->data;
819 json_dumper_begin_object(&dumper);
820 json_dumper_set_member_name(&dumper, if_info->name);
822 json_dumper_begin_object(&dumper);
824 json_dumper_set_member_name(&dumper, "friendly_name");
825 json_dumper_value_string(&dumper, if_info->friendly_name);
827 json_dumper_set_member_name(&dumper, "vendor_description");
828 json_dumper_value_string(&dumper, if_info->vendor_description);
830 json_dumper_set_member_name(&dumper, "type");
831 json_dumper_value_anyf(&dumper, "%i", if_info->type);
833 json_dumper_set_member_name(&dumper, "addrs");
835 json_dumper_begin_array(&dumper);
836 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
837 addr = g_slist_next(addr)) {
839 if_addr = (if_addr_t *)addr->data;
840 switch(if_addr->ifat_type) {
841 case IF_AT_IPv4:
842 json_dumper_value_string(&dumper, ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str, sizeof(addr_str)));
843 break;
844 case IF_AT_IPv6:
845 json_dumper_value_string(&dumper, ws_inet_ntop6(&if_addr->addr.ip6_addr, addr_str, sizeof(addr_str)));
846 break;
847 default:
848 json_dumper_value_anyf(&dumper, "<type unknown %i>", if_addr->ifat_type);
851 json_dumper_end_array(&dumper);
853 json_dumper_set_member_name(&dumper, "loopback");
854 json_dumper_value_anyf(&dumper, "%s", if_info->loopback ? "true" : "false");
856 json_dumper_set_member_name(&dumper, "extcap");
857 json_dumper_value_string(&dumper, if_info->extcap);
859 if (if_info->caps && caps_queries) {
860 json_dumper_set_member_name(&dumper, "caps");
861 json_dumper_begin_object(&dumper);
862 print_machine_readable_if_capabilities(&dumper, if_info->caps, caps_queries);
863 json_dumper_end_object(&dumper);
865 json_dumper_end_object(&dumper);
866 json_dumper_end_object(&dumper);
868 json_dumper_end_array(&dumper);
869 if (json_dumper_finish(&dumper)) {
870 status = 0;
871 if (capture_child) {
872 if (print_statistics) {
873 sync_pipe_write_string_msg(sync_pipe_fd, SP_IFACE_LIST, dumper.output_string->str);
874 } else {
875 /* Let our parent know we succeeded. */
876 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
877 printf("%s", dumper.output_string->str);
880 } else {
881 status = 2;
882 if (capture_child) {
883 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, "Unexpected JSON error", "");
886 g_string_free(dumper.output_string, TRUE);
887 return status;
891 * If you change the machine-readable output format of this function,
892 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
894 static void
895 print_machine_readable_if_capabilities(json_dumper *dumper, if_capabilities_t *caps, int queries)
897 GList *lt_entry, *ts_entry;
898 const gchar *desc_str;
900 json_dumper_set_member_name(dumper, "status");
901 json_dumper_value_anyf(dumper, "%i", caps->status);
902 if (caps->primary_msg) {
903 json_dumper_set_member_name(dumper, "primary_msg");
904 json_dumper_value_string(dumper, caps->primary_msg);
907 if (queries & CAPS_QUERY_LINK_TYPES) {
908 json_dumper_set_member_name(dumper, "rfmon");
909 json_dumper_value_anyf(dumper, "%s", caps->can_set_rfmon ? "true" : "false");
910 json_dumper_set_member_name(dumper, "data_link_types");
911 json_dumper_begin_array(dumper);
912 for (lt_entry = caps->data_link_types; lt_entry != NULL;
913 lt_entry = g_list_next(lt_entry)) {
914 data_link_info_t *data_link_info = (data_link_info_t *)lt_entry->data;
915 if (data_link_info->description != NULL)
916 desc_str = data_link_info->description;
917 else
918 desc_str = "(not supported)";
919 json_dumper_begin_object(dumper);
920 json_dumper_set_member_name(dumper, "dlt");
921 json_dumper_value_anyf(dumper, "%d", data_link_info->dlt);
922 json_dumper_set_member_name(dumper, "name");
923 json_dumper_value_string(dumper, data_link_info->name);
924 json_dumper_set_member_name(dumper, "description");
925 json_dumper_value_string(dumper, desc_str);
926 json_dumper_end_object(dumper);
928 json_dumper_end_array(dumper);
930 json_dumper_set_member_name(dumper, "data_link_types_rfmon");
931 json_dumper_begin_array(dumper);
932 for (lt_entry = caps->data_link_types_rfmon; lt_entry != NULL;
933 lt_entry = g_list_next(lt_entry)) {
934 data_link_info_t *data_link_info = (data_link_info_t *)lt_entry->data;
935 if (data_link_info->description != NULL)
936 desc_str = data_link_info->description;
937 else
938 desc_str = "(not supported)";
939 json_dumper_begin_object(dumper);
940 json_dumper_set_member_name(dumper, "dlt");
941 json_dumper_value_anyf(dumper, "%d", data_link_info->dlt);
942 json_dumper_set_member_name(dumper, "name");
943 json_dumper_value_string(dumper, data_link_info->name);
944 json_dumper_set_member_name(dumper, "description");
945 json_dumper_value_string(dumper, desc_str);
946 json_dumper_end_object(dumper);
948 json_dumper_end_array(dumper);
950 if (queries & CAPS_QUERY_TIMESTAMP_TYPES) {
951 json_dumper_set_member_name(dumper, "timestamp_types");
952 json_dumper_begin_array(dumper);
953 for (ts_entry = caps->timestamp_types; ts_entry != NULL;
954 ts_entry = g_list_next(ts_entry)) {
955 timestamp_info_t *timestamp = (timestamp_info_t *)ts_entry->data;
956 if (timestamp->description != NULL)
957 desc_str = timestamp->description;
958 else
959 desc_str = "(none)";
960 json_dumper_begin_object(dumper);
961 json_dumper_set_member_name(dumper, "name");
962 json_dumper_value_string(dumper, timestamp->name);
963 json_dumper_set_member_name(dumper, "description");
964 json_dumper_value_string(dumper, desc_str);
965 json_dumper_end_object(dumper);
967 json_dumper_end_array(dumper);
971 typedef struct {
972 char *name;
973 pcap_t *pch;
974 } if_stat_t;
976 /* Print the number of packets captured for each interface until we're killed. */
977 static int
978 print_statistics_loop(gboolean machine_readable)
980 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
981 if_info_t *if_info;
982 if_stat_t *if_stat;
983 int err;
984 gchar *err_str;
985 pcap_t *pch;
986 char errbuf[PCAP_ERRBUF_SIZE];
987 struct pcap_stat ps;
989 if_list = get_interface_list(&err, &err_str);
990 if (if_list == NULL) {
991 if (err == 0) {
992 cmdarg_err("There are no interfaces on which a capture can be done");
993 err = WS_EXIT_NO_INTERFACES;
995 else {
996 cmdarg_err("%s", err_str);
997 g_free(err_str);
999 return err;
1002 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1003 if_info = (if_info_t *)if_entry->data;
1005 #ifdef __linux__
1006 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
1007 * connections. We avoid collecting stats on them.
1009 if (!strncmp(if_info->name, "nf", 2)) {
1010 ws_debug("Skipping interface %s for stats", if_info->name);
1011 continue;
1013 #endif
1015 #ifdef HAVE_PCAP_OPEN
1017 * If we're opening a remote device, use pcap_open(); that's currently
1018 * the only open routine that supports remote devices.
1020 if (strncmp(if_info->name, "rpcap://", 8) == 0)
1021 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1022 else
1023 #endif
1024 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1026 if (pch) {
1027 if_stat = g_new(if_stat_t, 1);
1028 if_stat->name = g_strdup(if_info->name);
1029 if_stat->pch = pch;
1030 stat_list = g_list_append(stat_list, if_stat);
1034 if (!stat_list) {
1035 cmdarg_err("There are no interfaces on which a capture can be done");
1036 return 2;
1039 if (capture_child) {
1040 /* Let our parent know we succeeded. */
1041 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
1044 if (!machine_readable) {
1045 printf("%-15s %10s %10s\n", "Interface", "Received",
1046 "Dropped");
1049 global_ld.go = TRUE;
1050 while (global_ld.go) {
1051 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1052 if_stat = (if_stat_t *)stat_entry->data;
1053 /* XXX - what if this fails? */
1054 if (pcap_stats(if_stat->pch, &ps) == 0) {
1055 if (!machine_readable) {
1056 printf("%-15s %10u %10u\n", if_stat->name,
1057 ps.ps_recv, ps.ps_drop);
1058 } else {
1059 printf("%s\t%u\t%u\n", if_stat->name,
1060 ps.ps_recv, ps.ps_drop);
1061 fflush(stdout);
1065 #ifdef _WIN32
1066 /* If we have a dummy signal pipe check it */
1067 if (!signal_pipe_check_running()) {
1068 global_ld.go = FALSE;
1070 Sleep(1 * 1000);
1071 #else
1072 sleep(1);
1073 #endif
1076 /* XXX - Not reached. Should we look for 'q' in stdin? */
1077 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1078 if_stat = (if_stat_t *)stat_entry->data;
1079 pcap_close(if_stat->pch);
1080 g_free(if_stat->name);
1081 g_free(if_stat);
1083 g_list_free(stat_list);
1084 free_interface_list(if_list);
1086 return 0;
1090 #ifdef _WIN32
1091 static BOOL WINAPI
1092 capture_cleanup_handler(DWORD dwCtrlType)
1094 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1095 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1096 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1097 like SIGTERM at least when the machine's shutting down.
1099 For now, if we're running as a command rather than a capture child,
1100 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1101 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1102 in that way on UN*X.
1104 If we're not running as a capture child, we might be running as
1105 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1106 user logs out. (XXX - can we explicitly check whether we're
1107 running as a service?) */
1109 ws_info("Console: Control signal");
1110 ws_debug("Console: Control signal, CtrlType: %lu", dwCtrlType);
1112 /* Keep capture running if we're a service and a user logs off */
1113 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1114 capture_loop_stop();
1115 return TRUE;
1116 } else {
1117 return FALSE;
1120 #else
1121 static void
1122 capture_cleanup_handler(int signum _U_)
1124 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1125 SIGTERM. We assume that if the user wanted it to keep running
1126 after they logged out, they'd have nohupped it. */
1128 capture_loop_stop();
1130 #endif
1133 static void
1134 report_capture_count(gboolean reportit)
1136 /* Don't print this if we're a capture child. */
1137 if (!capture_child && reportit) {
1138 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packets_captured);
1139 /* stderr could be line buffered */
1140 fflush(stderr);
1145 #ifdef SIGINFO
1146 static void
1147 report_counts_for_siginfo(void)
1149 report_capture_count(quiet);
1150 infoprint = FALSE; /* we just reported it */
1153 static void
1154 report_counts_siginfo(int signum _U_)
1156 int sav_errno = errno;
1158 /* If we've been told to delay printing, just set a flag asking
1159 that we print counts (if we're supposed to), otherwise print
1160 the count of packets captured (if we're supposed to). */
1161 if (infodelay)
1162 infoprint = TRUE;
1163 else
1164 report_counts_for_siginfo();
1165 errno = sav_errno;
1167 #endif /* SIGINFO */
1169 static void
1170 exit_main(int status)
1172 ws_cleanup_sockets();
1174 #ifdef _WIN32
1175 /* can be helpful for debugging */
1176 #ifdef DEBUG_DUMPCAP
1177 printf("Press any key\n");
1178 _getch();
1179 #endif
1181 #endif /* _WIN32 */
1183 if (ringbuf_is_initialized()) {
1184 /* save_file is managed by ringbuffer, be sure to release the memory and
1185 * avoid capture_opts_cleanup from double-freeing 'save_file'. */
1186 ringbuf_free();
1187 global_capture_opts.save_file = NULL;
1190 capture_opts_cleanup(&global_capture_opts);
1191 exit(status);
1194 #ifdef HAVE_LIBCAP
1196 * If we were linked with libcap (not related to libpcap), make sure we have
1197 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1198 * (See comment in main() for details)
1200 static void
1201 relinquish_privs_except_capture(void)
1203 /* If 'started_with_special_privs' (ie: suid) then enable for
1204 * ourself the NET_ADMIN and NET_RAW capabilities and then
1205 * drop our suid privileges.
1207 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1208 * stuff we don't need (and shouldn't have).
1209 * CAP_NET_RAW: Packet capture (raw sockets).
1212 if (started_with_special_privs()) {
1213 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1214 int cl_len = array_length(cap_list);
1216 cap_t caps = cap_init(); /* all capabilities initialized to off */
1218 print_caps("Pre drop, pre set");
1220 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1221 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1224 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1225 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1227 if (cap_set_proc(caps)) {
1228 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1230 print_caps("Pre drop, post set");
1232 relinquish_special_privs_perm();
1234 print_caps("Post drop, pre set");
1235 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1236 if (cap_set_proc(caps)) {
1237 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1239 print_caps("Post drop, post set");
1241 cap_free(caps);
1245 #endif /* HAVE_LIBCAP */
1247 /* Map DLT_ values, as returned by pcap_datalink(), to LINKTYPE_ values,
1248 as are written to capture files.
1250 Most of the time, a DLT_ value and the corresponding LINKYPE_ value
1251 are the same, but there are some cases, where a numeric value as
1252 a DLT_ doesn't uniquely identify a particular link-layer header type,
1253 where they differ, so that the values in files *do* identify
1254 particular link-layer header types. */
1256 /* LINKTYPE_ values that don't match corresponding DLT_ values on
1257 all platforms. */
1258 #define LINKTYPE_ATM_RFC1483 100
1259 #define LINKTYPE_RAW 101
1260 #define LINKTYPE_SLIP_BSDOS 102
1261 #define LINKTYPE_PPP_BSDOS 103
1262 #define LINKTYPE_C_HDLC 104
1263 #define LINKTYPE_IEEE802_11 105
1264 #define LINKTYPE_ATM_CLIP 106
1265 #define LINKTYPE_FRELAY 107
1266 #define LINKTYPE_LOOP 108
1267 #define LINKTYPE_ENC 109
1268 #define LINKTYPE_NETBSD_HDLC 112
1269 #define LINKTYPE_PFSYNC 246
1270 #define LINKTYPE_PKTAP 258
1272 static int
1273 dlt_to_linktype(int dlt)
1275 /* DLT_NULL through DLT_FDDI have the same numeric value on
1276 all platforms, so the corresponding LINKTYPE_s have the
1277 same numeric values. */
1278 if (dlt >= DLT_NULL && dlt <= DLT_FDDI)
1279 return (dlt);
1281 #if defined(DLT_PFSYNC) && DLT_PFSYNC != LINKTYPE_PFSYNC
1282 /* DLT_PFSYNC has a value on several platforms that's in the
1283 non-matching range, a value on FreeBSD that's in the high
1284 matching range and that's *not* equal to LINKTYPE_PFSYNC,
1285 and has a value on the rmaining platforms that's equal
1286 to LINKTYPE_PFSYNC, which is in the high matching range.
1288 Map it to LINKTYPE_PFSYNC if it's not equal to LINKTYPE_PFSYNC. */
1289 if (dlt == DLT_PFSYNC)
1290 return (LINKTYPE_PFSYNC);
1291 #endif
1293 /* DLT_PKTAP is defined as DLT_USER2 - which is in the high
1294 matching range - on Darwin because Apple used DLT_USER2
1295 on systems that users ran, not just as an internal thing.
1297 We map it to LINKTYPE_PKTAP if it's not equal to LINKTYPE_PKTAP
1298 so that DLT_PKTAP captures from Apple machines can be read by
1299 software that either doesn't handle DLT_USER2 or that handles it
1300 as something other than Apple PKTAP. */
1301 #if defined(DLT_PKTAP) && DLT_PKTAP != LINKTYPE_PKTAP
1302 if (dlt == DLT_PKTAP)
1303 return (LINKTYPE_PKTAP);
1304 #endif
1306 /* For all other DLT_s with values beyond 104, the value
1307 of the corresponding LINKTYPE_ is the same. */
1308 if (dlt >= 104)
1309 return (dlt);
1311 /* These DLT_ values have different values on different
1312 platforms, so we assigned them LINKTYPE_ values just
1313 below the lower bound of the high matchig range;
1314 those values should never be equal to any DLT_
1315 values, so that should avoid collisions.
1317 That way, for example, "raw IP" packets will have
1318 LINKTYPE_RAW as the code in all savefiles for
1319 which the code that writes them maps to that
1320 value, regardless of the platform on which they
1321 were written, so they should be readable on all
1322 platforms without having to determine on which
1323 platform they were written.
1325 We map the DLT_ values on this platform, whatever
1326 it might be, to the corresponding LINKTYPE_ values. */
1327 #ifdef DLT_ATM_RFC1483
1328 if (dlt == DLT_ATM_RFC1483)
1329 return (LINKTYPE_ATM_RFC1483);
1330 #endif
1331 #ifdef DLT_RAW
1332 if (dlt == DLT_RAW)
1333 return (LINKTYPE_RAW);
1334 #endif
1335 #ifdef DLT_SLIP_BSDOS
1336 if (dlt == DLT_SLIP_BSDOS)
1337 return (LINKTYPE_SLIP_BSDOS);
1338 #endif
1339 #ifdef DLT_PPP_BSDOS
1340 if (dlt == DLT_PPP_BSDOS)
1341 return (LINKTYPE_PPP_BSDOS);
1342 #endif
1344 /* These DLT_ values were originally defined on some platform,
1345 and weren't defined on other platforms.
1347 At least some of those values, on at least one platform,
1348 collide with the values of other DLT_s on other platforms,
1349 e.g. DLT_LOOP, so we don't just define them, on all
1350 platforms, as having the same value as on the original
1351 platform.
1353 Therefore, we assigned new LINKTYPE_ values to them, and,
1354 on the platforms where they weren't originally defined,
1355 define the DLT_s to have the same value as the corresponding
1356 LINKTYPE_.
1358 This means that, for capture files with the original
1359 platform's DLT_ value rather than the LINKTYPE_ value
1360 as a link-layer type, we will recognize those types
1361 on that platform, but not on other platforms. */
1362 #ifdef DLT_FR
1363 /* BSD/OS Frame Relay */
1364 if (dlt == DLT_FR)
1365 return (LINKTYPE_FRELAY);
1366 #endif
1367 #if defined(DLT_HDLC) && DLT_HDLC != LINKTYPE_NETBSD_HDLC
1368 /* NetBSD HDLC */
1369 if (dlt == DLT_HDLC)
1370 return (LINKTYPE_NETBSD_HDLC);
1371 #endif
1372 #if defined(DLT_C_HDLC) && DLT_C_HDLC != LINKTYPE_C_HDLC
1373 /* BSD/OS Cisco HDLC */
1374 if (dlt == DLT_C_HDLC)
1375 return (LINKTYPE_C_HDLC);
1376 #endif
1377 #if defined(DLT_LOOP) && DLT_LOOP != LINKTYPE_LOOP
1378 /* OpenBSD DLT_LOOP */
1379 if (dlt == DLT_LOOP)
1380 return (LINKTYPE_LOOP);
1381 #endif
1382 #if defined(DLT_ENC) && DLT_ENC != LINKTYPE_ENC
1383 /* OpenBSD DLT_ENC */
1384 if (dlt == DLT_ENC)
1385 return (LINKTYPE_ENC);
1386 #endif
1388 /* These DLT_ values are not on all platforms, but, so far,
1389 there don't appear to be any platforms that define
1390 other DLT_s with those values; we map them to
1391 different LINKTYPE_ values anyway, just in case. */
1392 #ifdef DLT_ATM_CLIP
1393 /* Linux ATM Classical IP */
1394 if (dlt == DLT_ATM_CLIP)
1395 return (LINKTYPE_ATM_CLIP);
1396 #endif
1398 /* Treat all other DLT_s as having the same value as the
1399 corresponding LINKTYPE_. */
1400 return (dlt);
1403 /* Take care of byte order in the libpcap headers read from pipes.
1404 * (function taken from wiretap/libpcap.c) */
1405 static void
1406 cap_pipe_adjust_pcap_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1408 if (byte_swapped) {
1409 /* Byte-swap the record header fields. */
1410 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1411 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1412 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1413 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1416 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1417 swapped, in order to match the BPF header layout.
1419 Unfortunately, some files were, according to a comment in the "libpcap"
1420 source, written with version 2.3 in their headers but without the
1421 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1422 would make no sense - we assume that we need to swap them. */
1423 if (hdr->version_major == 2 &&
1424 (hdr->version_minor < 3 ||
1425 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1426 guint32 temp;
1428 temp = rechdr->orig_len;
1429 rechdr->orig_len = rechdr->incl_len;
1430 rechdr->incl_len = temp;
1434 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1435 * or just read().
1437 static ssize_t
1438 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1440 #ifdef _WIN32
1441 if (from_socket) {
1442 return recv(pipe_fd, buf, (int)sz, 0);
1443 } else {
1444 return -1;
1446 #else
1447 return ws_read(pipe_fd, buf, sz);
1448 #endif
1451 #if defined(_WIN32)
1453 * Thread function that reads from a pipe and pushes the data
1454 * to the main application thread.
1457 * XXX Right now we use async queues for basic signaling. The main thread
1458 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1459 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1460 * Iff the read is successful cap_pipe_read pushes an item onto
1461 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1462 * the queues themselves (yet).
1464 * We might want to move some of the cap_pipe_dispatch logic here so that
1465 * we can let cap_thread_read run independently, queuing up multiple reads
1466 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1468 static void *cap_thread_read(void *arg)
1470 capture_src *pcap_src;
1471 #ifdef _WIN32
1472 BOOL res;
1473 DWORD last_err, bytes_read;
1474 #else /* _WIN32 */
1475 size_t bytes_read;
1476 #endif /* _WIN32 */
1478 pcap_src = (capture_src *)arg;
1479 while (pcap_src->cap_pipe_err == PIPOK) {
1480 g_async_queue_pop(pcap_src->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1481 g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1482 bytes_read = 0;
1483 while (bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1484 if ((pcap_src->from_cap_socket)
1485 #ifndef _WIN32
1486 || 1
1487 #endif
1490 ssize_t b;
1491 b = cap_pipe_read(pcap_src->cap_pipe_fd, pcap_src->cap_pipe_buf+bytes_read,
1492 pcap_src->cap_pipe_bytes_to_read - bytes_read, pcap_src->from_cap_socket);
1493 if (b <= 0) {
1494 if (b == 0) {
1495 pcap_src->cap_pipe_err = PIPEOF;
1496 bytes_read = 0;
1497 break;
1498 } else {
1499 pcap_src->cap_pipe_err = PIPERR;
1500 bytes_read = -1;
1501 break;
1503 } else {
1504 bytes_read += (DWORD)b;
1507 #ifdef _WIN32
1508 else
1510 /* If we try to use read() on a named pipe on Windows with partial
1511 * data it appears to return EOF.
1513 DWORD b;
1514 res = ReadFile(pcap_src->cap_pipe_h, pcap_src->cap_pipe_buf+bytes_read,
1515 pcap_src->cap_pipe_bytes_to_read - bytes_read,
1516 &b, NULL);
1518 bytes_read += b;
1519 if (!res) {
1520 last_err = GetLastError();
1521 if (last_err == ERROR_MORE_DATA) {
1522 continue;
1523 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1524 pcap_src->cap_pipe_err = PIPEOF;
1525 bytes_read = 0;
1526 break;
1528 pcap_src->cap_pipe_err = PIPERR;
1529 bytes_read = -1;
1530 break;
1531 } else if (b == 0 && pcap_src->cap_pipe_bytes_to_read > 0) {
1532 pcap_src->cap_pipe_err = PIPEOF;
1533 bytes_read = 0;
1534 break;
1537 #endif /*_WIN32 */
1539 pcap_src->cap_pipe_bytes_read = bytes_read;
1540 if (pcap_src->cap_pipe_bytes_read >= pcap_src->cap_pipe_bytes_to_read) {
1541 g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1543 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1545 /* Post to queue if we didn't read enough data as the main thread waits for the message */
1546 g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1547 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1548 /* There's still more of the record to read. */
1549 g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1551 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1552 return NULL;
1556 * Do a blocking read from a pipe within the main thread, by pushing
1557 * the read onto the pipe queue and then popping it off that queue;
1558 * the pipe will block until the pushed read completes.
1560 * We do it with another thread because we can't use select() on
1561 * pipes on Windows, as we can on UN*Xes, we can only use it on
1562 * sockets.
1564 void
1565 pipe_read_sync(capture_src *pcap_src, void *buf, DWORD nbytes)
1567 pcap_src->cap_pipe_buf = (char *) buf;
1568 pcap_src->cap_pipe_bytes_read = 0;
1569 pcap_src->cap_pipe_bytes_to_read = nbytes;
1570 /* We don't have to worry about cap_pipe_read_mtx here */
1571 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1572 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1574 #endif
1576 /* Provide select() functionality for a single file descriptor
1577 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1579 * Returns the same values as select.
1581 static int
1582 cap_pipe_select(int pipe_fd)
1584 fd_set rfds;
1585 struct timeval timeout;
1587 FD_ZERO(&rfds);
1588 FD_SET(pipe_fd, &rfds);
1590 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1591 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1593 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1596 #define DEF_TCP_PORT 19000
1598 static int
1599 cap_open_socket(char *pipename, capture_src *pcap_src, char *errmsg, size_t errmsgl)
1601 struct sockaddr_storage sa;
1602 socklen_t sa_len;
1603 int fd;
1605 /* Skip the initial "TCP@" in the pipename. */
1606 if (ws_socket_ptoa(&sa, pipename + 4, DEF_TCP_PORT) < 0) {
1607 snprintf(errmsg, errmsgl,
1608 "The capture session could not be initiated because"
1609 "\"%s\" is not a valid socket specification", pipename);
1610 pcap_src->cap_pipe_err = PIPERR;
1611 return -1;
1614 if ((fd = (int)socket(sa.ss_family, SOCK_STREAM, 0)) < 0) {
1615 snprintf(errmsg, errmsgl,
1616 "The capture session could not be initiated because"
1617 " the socket couldn't be created due to the socket error: \n"
1618 #ifdef _WIN32
1619 " %s", win32strerror(WSAGetLastError()));
1620 #else
1621 " %d: %s", errno, g_strerror(errno));
1622 #endif
1623 pcap_src->cap_pipe_err = PIPERR;
1624 return -1;
1627 if (sa.ss_family == AF_INET6)
1628 sa_len = sizeof(struct sockaddr_in6);
1629 else
1630 sa_len = sizeof(struct sockaddr_in);
1631 if (connect(fd, (struct sockaddr *)&sa, sa_len) < 0) {
1632 snprintf(errmsg, errmsgl,
1633 "The capture session could not be initiated because"
1634 " the socket couldn't be connected due to the socket error: \n"
1635 #ifdef _WIN32
1636 " %s", win32strerror(WSAGetLastError()));
1637 #else
1638 " %d: %s", errno, g_strerror(errno));
1639 #endif
1640 pcap_src->cap_pipe_err = PIPERR;
1642 cap_pipe_close(fd, TRUE);
1643 return -1;
1646 pcap_src->from_cap_socket = TRUE;
1647 return fd;
1650 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1651 * otherwise.
1653 static void
1654 cap_pipe_close(int pipe_fd, gboolean from_socket)
1656 #ifdef _WIN32
1657 if (from_socket) {
1658 closesocket(pipe_fd);
1660 #else
1661 (void) from_socket; /* Mark unused, similar to Q_UNUSED */
1662 ws_close(pipe_fd);
1663 #endif
1666 /** Read bytes from a capture source, which is assumed to be a pipe or
1667 * socket.
1669 * Returns -1, or the number of bytes read similar to read(2).
1670 * Sets pcap_src->cap_pipe_err on error or EOF.
1672 static ssize_t
1673 cap_pipe_read_data_bytes(capture_src *pcap_src, char *errmsg, size_t errmsgl)
1675 int sel_ret;
1676 int fd = pcap_src->cap_pipe_fd;
1677 #ifdef _WIN32
1678 DWORD sz, bytes_read = 0;
1679 #else /* _WIN32 */
1680 ssize_t sz, bytes_read = 0;
1681 #endif /* _WIN32 */
1682 ssize_t b;
1684 #ifdef LOG_CAPTURE_VERBOSE
1685 ws_debug("cap_pipe_read_data_bytes read %lu of %lu",
1686 pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1687 #endif
1688 sz = pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read;
1689 while (bytes_read < sz) {
1690 if (fd == -1) {
1691 snprintf(errmsg, errmsgl, "Invalid file descriptor.");
1692 pcap_src->cap_pipe_err = PIPNEXIST;
1693 return -1;
1696 sel_ret = cap_pipe_select(fd);
1697 if (sel_ret < 0) {
1698 snprintf(errmsg, errmsgl,
1699 "Unexpected error from select: %s.", g_strerror(errno));
1700 pcap_src->cap_pipe_err = PIPERR;
1701 return -1;
1702 } else if (sel_ret > 0) {
1703 b = cap_pipe_read(fd, pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read+bytes_read,
1704 sz-bytes_read, pcap_src->from_cap_socket);
1705 if (b <= 0) {
1706 if (b == 0) {
1707 snprintf(errmsg, errmsgl,
1708 "End of file reading from pipe or socket.");
1709 pcap_src->cap_pipe_err = PIPEOF;
1710 } else {
1711 #ifdef _WIN32
1713 * On Windows, we only do this for sockets.
1715 DWORD lastError = WSAGetLastError();
1716 errno = lastError;
1717 snprintf(errmsg, errmsgl,
1718 "Error reading from pipe or socket: %s.",
1719 win32strerror(lastError));
1720 #else
1721 snprintf(errmsg, errmsgl,
1722 "Error reading from pipe or socket: %s.",
1723 g_strerror(errno));
1724 #endif
1725 pcap_src->cap_pipe_err = PIPERR;
1727 return -1;
1729 #ifdef _WIN32
1730 bytes_read += (DWORD)b;
1731 #else
1732 bytes_read += b;
1733 #endif
1736 pcap_src->cap_pipe_bytes_read += bytes_read;
1737 #ifdef LOG_CAPTURE_VERBOSE
1738 ws_debug("cap_pipe_read_data_bytes read %lu of %lu",
1739 pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1740 #endif
1741 return bytes_read;
1744 /* Some forward declarations for breaking up cap_pipe_open_live for pcap and pcapng formats */
1745 static void pcap_pipe_open_live(int fd, capture_src *pcap_src,
1746 struct pcap_hdr *hdr,
1747 char *errmsg, size_t errmsgl,
1748 char *secondary_errmsg, size_t secondary_errmsgl);
1749 static void pcapng_pipe_open_live(int fd, capture_src *pcap_src,
1750 char *errmsg, size_t errmsgl);
1751 static int pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src,
1752 char *errmsg, size_t errmsgl);
1754 /* For problems that are probably Not Our Fault. */
1755 static char not_our_bug[] =
1756 "Please report this to the developers of the program writing to the pipe.";
1758 /* Mimic pcap_open_live() for pipe captures
1760 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1761 * open it, and read the header.
1763 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1764 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1765 static void
1766 cap_pipe_open_live(char *pipename,
1767 capture_src *pcap_src,
1768 void *hdr,
1769 char *errmsg, size_t errmsgl,
1770 char *secondary_errmsg, size_t secondary_errmsgl)
1772 #ifndef _WIN32
1773 ws_statb64 pipe_stat;
1774 struct sockaddr_un sa;
1775 #else /* _WIN32 */
1776 guintptr extcap_pipe_handle;
1777 #endif
1778 gboolean extcap_pipe = FALSE;
1779 ssize_t b;
1780 int fd = -1, sel_ret;
1781 size_t bytes_read;
1782 guint32 magic = 0;
1783 pcap_src->cap_pipe_fd = -1;
1784 #ifdef _WIN32
1785 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1786 #endif
1788 ws_debug("cap_pipe_open_live: %s", pipename);
1791 * XXX - this blocks until a pcap per-file header has been written to
1792 * the pipe, so it could block indefinitely.
1794 if (strcmp(pipename, "-") == 0) {
1795 #ifndef _WIN32
1796 fd = 0; /* read from stdin */
1797 #else /* _WIN32 */
1798 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1799 #endif /* _WIN32 */
1800 } else if (!strncmp(pipename, "TCP@", 4)) {
1801 if ((fd = cap_open_socket(pipename, pcap_src, errmsg, errmsgl)) < 0) {
1802 return;
1804 } else {
1805 #ifndef _WIN32
1806 if ( g_strrstr(pipename, EXTCAP_PIPE_PREFIX) != NULL )
1807 extcap_pipe = TRUE;
1809 if (ws_stat64(pipename, &pipe_stat) < 0) {
1810 if (errno == ENOENT || errno == ENOTDIR)
1811 pcap_src->cap_pipe_err = PIPNEXIST;
1812 else {
1813 snprintf(errmsg, errmsgl,
1814 "The capture session could not be initiated "
1815 "due to error getting information on pipe or socket: %s.", g_strerror(errno));
1816 pcap_src->cap_pipe_err = PIPERR;
1818 return;
1820 if (S_ISFIFO(pipe_stat.st_mode)) {
1821 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1822 if (fd == -1) {
1823 snprintf(errmsg, errmsgl,
1824 "The capture session could not be initiated "
1825 "due to error on pipe open: %s.", g_strerror(errno));
1826 pcap_src->cap_pipe_err = PIPERR;
1827 return;
1829 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1830 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1831 if (fd == -1) {
1832 snprintf(errmsg, errmsgl,
1833 "The capture session could not be initiated "
1834 "due to error on socket create: %s.", g_strerror(errno));
1835 pcap_src->cap_pipe_err = PIPERR;
1836 return;
1838 sa.sun_family = AF_UNIX;
1840 * The Single UNIX Specification says:
1842 * The size of sun_path has intentionally been left undefined.
1843 * This is because different implementations use different sizes.
1844 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1845 * of 104. Since most implementations originate from BSD versions,
1846 * the size is typically in the range 92 to 108.
1848 * Applications should not assume a particular length for sun_path
1849 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1851 * It also says
1853 * The <sys/un.h> header shall define the sockaddr_un structure,
1854 * which shall include at least the following members:
1856 * sa_family_t sun_family Address family.
1857 * char sun_path[] Socket pathname.
1859 * so we assume that it's an array, with a specified size,
1860 * and that the size reflects the maximum path length.
1862 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1863 /* Path name too long */
1864 snprintf(errmsg, errmsgl,
1865 "The capture session could not be initiated "
1866 "due to error on socket connect: Path name too long.");
1867 pcap_src->cap_pipe_err = PIPERR;
1868 ws_close(fd);
1869 return;
1871 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1872 if (b == -1) {
1873 snprintf(errmsg, errmsgl,
1874 "The capture session could not be initiated "
1875 "due to error on socket connect: %s.", g_strerror(errno));
1876 pcap_src->cap_pipe_err = PIPERR;
1877 ws_close(fd);
1878 return;
1880 } else {
1881 if (S_ISCHR(pipe_stat.st_mode)) {
1883 * Assume the user specified an interface on a system where
1884 * interfaces are in /dev. Pretend we haven't seen it.
1886 pcap_src->cap_pipe_err = PIPNEXIST;
1887 } else {
1888 snprintf(errmsg, errmsgl,
1889 "The capture session could not be initiated because\n"
1890 "\"%s\" is neither an interface nor a socket nor a pipe.", pipename);
1891 pcap_src->cap_pipe_err = PIPERR;
1893 return;
1896 #else /* _WIN32 */
1897 if (sscanf(pipename, EXTCAP_PIPE_PREFIX "%" SCNuPTR, &extcap_pipe_handle) == 1)
1899 /* The client is already connected to extcap pipe.
1900 * We have inherited the handle from parent process.
1902 extcap_pipe = TRUE;
1903 pcap_src->cap_pipe_h = (HANDLE)extcap_pipe_handle;
1905 else
1907 if (!win32_is_pipe_name(pipename)) {
1908 snprintf(errmsg, errmsgl,
1909 "The capture session could not be initiated because\n"
1910 "\"%s\" is neither an interface nor a pipe.", pipename);
1911 pcap_src->cap_pipe_err = PIPNEXIST;
1912 return;
1915 /* Wait for the pipe to appear */
1916 while (1) {
1917 pcap_src->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1918 OPEN_EXISTING, 0, NULL);
1920 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE)
1921 break;
1923 if (GetLastError() != ERROR_PIPE_BUSY) {
1924 snprintf(errmsg, errmsgl,
1925 "The capture session on \"%s\" could not be started "
1926 "due to error on pipe open: %s.",
1927 pipename, win32strerror(GetLastError()));
1928 pcap_src->cap_pipe_err = PIPERR;
1929 return;
1932 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1933 snprintf(errmsg, errmsgl,
1934 "The capture session on \"%s\" timed out during "
1935 "pipe open: %s.",
1936 pipename, win32strerror(GetLastError()));
1937 pcap_src->cap_pipe_err = PIPERR;
1938 return;
1942 #endif /* _WIN32 */
1945 pcap_src->from_cap_pipe = TRUE;
1948 * We start with a 2KB buffer for packet data, which should be
1949 * large enough for most regular network packets. We increase it,
1950 * up to the maximum size we allow, as necessary.
1952 pcap_src->cap_pipe_databuf = (char*)g_malloc(2048);
1953 pcap_src->cap_pipe_databuf_size = 2048;
1956 * Read the first 4 bytes of data from the pipe.
1958 * If a pcap file is being written to it, that will be
1959 * the pcap magic number.
1961 * If a pcapng file is being written to it, that will be
1962 * the block type of the initial SHB.
1964 #ifdef _WIN32
1966 * On UN*X, we can use select() on pipes or sockets.
1968 * On Windows, we can only use it on sockets; to do non-blocking
1969 * reads from pipes, we currently do reads in a separate thread
1970 * and use GLib asynchronous queues from the main thread to start
1971 * read operations and to wait for them to complete.
1973 if (pcap_src->from_cap_socket)
1974 #endif
1976 bytes_read = 0;
1977 while (bytes_read < sizeof magic) {
1978 sel_ret = cap_pipe_select(fd);
1979 if (sel_ret < 0) {
1980 snprintf(errmsg, errmsgl,
1981 "Unexpected error from select: %s.",
1982 g_strerror(errno));
1983 goto error;
1984 } else if (sel_ret > 0) {
1985 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
1986 sizeof magic-bytes_read,
1987 pcap_src->from_cap_socket);
1988 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1989 if (extcap_pipe && b <= 0)
1990 goto error;
1992 if (b <= 0) {
1993 if (b == 0)
1994 snprintf(errmsg, errmsgl,
1995 "End of file on pipe magic during open.");
1996 else
1997 snprintf(errmsg, errmsgl,
1998 "Error on pipe magic during open: %s.",
1999 g_strerror(errno));
2000 goto error;
2002 bytes_read += b;
2006 #ifdef _WIN32
2007 else {
2008 /* Create a thread to read from this pipe */
2009 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
2011 pipe_read_sync(pcap_src, &magic, sizeof(magic));
2012 /* jump messaging, if extcap had an error, stderr will provide the correct message */
2013 if (pcap_src->cap_pipe_bytes_read <= 0 && extcap_pipe)
2014 goto error;
2016 if (pcap_src->cap_pipe_bytes_read <= 0) {
2017 if (pcap_src->cap_pipe_bytes_read == 0)
2018 snprintf(errmsg, errmsgl,
2019 "End of file on pipe magic during open.");
2020 else
2021 snprintf(errmsg, errmsgl,
2022 "Error on pipe magic during open: %s.",
2023 g_strerror(errno));
2024 goto error;
2027 #endif
2029 switch (magic) {
2030 case PCAP_MAGIC:
2031 case PCAP_NSEC_MAGIC:
2032 /* This is a pcap file.
2033 The host that wrote it has our byte order, and was running
2034 a program using either standard or ss990417 libpcap. */
2035 pcap_src->cap_pipe_info.pcap.byte_swapped = FALSE;
2036 pcap_src->cap_pipe_modified = FALSE;
2037 pcap_src->ts_nsec = magic == PCAP_NSEC_MAGIC;
2038 break;
2039 case PCAP_MODIFIED_MAGIC:
2040 /* This is a pcap file.
2041 The host that wrote it has our byte order, but was running
2042 a program using either ss990915 or ss991029 libpcap. */
2043 pcap_src->cap_pipe_info.pcap.byte_swapped = FALSE;
2044 pcap_src->cap_pipe_modified = TRUE;
2045 break;
2046 case PCAP_SWAPPED_MAGIC:
2047 case PCAP_SWAPPED_NSEC_MAGIC:
2048 /* This is a pcap file.
2049 The host that wrote it has a byte order opposite to ours,
2050 and was running a program using either standard or
2051 ss990417 libpcap. */
2052 pcap_src->cap_pipe_info.pcap.byte_swapped = TRUE;
2053 pcap_src->cap_pipe_modified = FALSE;
2054 pcap_src->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
2055 break;
2056 case PCAP_SWAPPED_MODIFIED_MAGIC:
2057 /* This is a pcap file.
2058 The host that wrote it out has a byte order opposite to
2059 ours, and was running a program using either ss990915
2060 or ss991029 libpcap. */
2061 pcap_src->cap_pipe_info.pcap.byte_swapped = TRUE;
2062 pcap_src->cap_pipe_modified = TRUE;
2063 break;
2064 case BLOCK_TYPE_SHB:
2065 /* This is a pcapng file. */
2066 pcap_src->from_pcapng = TRUE;
2067 pcap_src->cap_pipe_dispatch = pcapng_pipe_dispatch;
2068 pcap_src->cap_pipe_info.pcapng.src_iface_to_global = g_array_new(FALSE, FALSE, sizeof(guint32));
2069 global_capture_opts.use_pcapng = TRUE; /* we can only output in pcapng format */
2070 break;
2071 default:
2072 /* Not a pcapng file, and either not a pcap type we know about
2073 or not a pcap file, either. */
2074 snprintf(errmsg, errmsgl,
2075 "File type is neither a supported pcap nor pcapng format. (magic = 0x%08x)", magic);
2076 snprintf(secondary_errmsg, secondary_errmsgl, "%s",
2077 not_our_bug);
2078 goto error;
2081 if (pcap_src->from_pcapng)
2082 pcapng_pipe_open_live(fd, pcap_src, errmsg, errmsgl);
2083 else
2084 pcap_pipe_open_live(fd, pcap_src, (struct pcap_hdr *) hdr, errmsg, errmsgl,
2085 secondary_errmsg, secondary_errmsgl);
2087 return;
2089 error:
2090 ws_debug("cap_pipe_open_live: error %s", errmsg);
2091 pcap_src->cap_pipe_err = PIPERR;
2092 cap_pipe_close(fd, pcap_src->from_cap_socket);
2093 pcap_src->cap_pipe_fd = -1;
2094 #ifdef _WIN32
2095 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2096 #endif
2100 * Read the part of the pcap file header that follows the magic
2101 * number (we've already read the magic number).
2103 static void
2104 pcap_pipe_open_live(int fd,
2105 capture_src *pcap_src,
2106 struct pcap_hdr *hdr,
2107 char *errmsg, size_t errmsgl,
2108 char *secondary_errmsg, size_t secondary_errmsgl)
2110 size_t bytes_read;
2111 ssize_t b;
2112 int sel_ret;
2115 * We're reading from a pcap file. We've already read the magic
2116 * number; read the rest of the header.
2118 * (Note that struct pcap_hdr is a structure for the part of a
2119 * pcap file header *following the magic number*; it does not
2120 * include the magic number itself.)
2122 #ifdef _WIN32
2123 if (pcap_src->from_cap_socket)
2124 #endif
2126 /* Keep reading until we get the rest of the header. */
2127 bytes_read = 0;
2128 while (bytes_read < sizeof(struct pcap_hdr)) {
2129 sel_ret = cap_pipe_select(fd);
2130 if (sel_ret < 0) {
2131 snprintf(errmsg, errmsgl,
2132 "Unexpected error from select: %s.",
2133 g_strerror(errno));
2134 goto error;
2135 } else if (sel_ret > 0) {
2136 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
2137 sizeof(struct pcap_hdr) - bytes_read,
2138 pcap_src->from_cap_socket);
2139 if (b <= 0) {
2140 if (b == 0)
2141 snprintf(errmsg, errmsgl,
2142 "End of file on pipe header during open.");
2143 else
2144 snprintf(errmsg, errmsgl,
2145 "Error on pipe header during open: %s.",
2146 g_strerror(errno));
2147 snprintf(secondary_errmsg, secondary_errmsgl,
2148 "%s", not_our_bug);
2149 goto error;
2151 bytes_read += b;
2155 #ifdef _WIN32
2156 else {
2157 pipe_read_sync(pcap_src, hdr, sizeof(struct pcap_hdr));
2158 if (pcap_src->cap_pipe_bytes_read <= 0) {
2159 if (pcap_src->cap_pipe_bytes_read == 0)
2160 snprintf(errmsg, errmsgl,
2161 "End of file on pipe header during open.");
2162 else
2163 snprintf(errmsg, errmsgl,
2164 "Error on pipe header header during open: %s.",
2165 g_strerror(errno));
2166 snprintf(secondary_errmsg, secondary_errmsgl, "%s",
2167 not_our_bug);
2168 goto error;
2171 #endif
2173 if (pcap_src->cap_pipe_info.pcap.byte_swapped) {
2174 /* Byte-swap the header fields about which we care. */
2175 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
2176 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
2177 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
2178 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
2181 * The link-layer header type field of the pcap header is
2182 * probably a LINKTYPE_ value, as the vast majority of
2183 * LINKTYPE_ values and their corresponding DLT_ values
2184 * are the same.
2186 * However, in case the file was written by a program
2187 * that used a DLT_ value, rather than a LINKTYPE_ value,
2188 * in one of the cases where the two differ, use dlt_to_linktype()
2189 * to map to a LINKTYPE_ value, just as we use it to map
2190 * the result of pcap_datalink() to a LINKTYPE_ value.
2192 pcap_src->linktype = dlt_to_linktype(hdr->network);
2193 /* Pick the appropriate maximum packet size for the link type */
2194 switch (pcap_src->linktype) {
2196 case 231: /* DLT_DBUS */
2197 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_DBUS;
2198 break;
2200 case 279: /* DLT_EBHSCR */
2201 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_EBHSCR;
2202 break;
2204 case 249: /* DLT_USBPCAP */
2205 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_USBPCAP;
2206 break;
2208 default:
2209 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
2210 break;
2213 if (hdr->version_major < 2) {
2214 snprintf(errmsg, errmsgl,
2215 "The old pcap format version %d.%d is not supported.",
2216 hdr->version_major, hdr->version_minor);
2217 snprintf(secondary_errmsg, secondary_errmsgl, "%s",
2218 not_our_bug);
2219 goto error;
2222 pcap_src->cap_pipe_fd = fd;
2223 return;
2225 error:
2226 ws_debug("pcap_pipe_open_live: error %s", errmsg);
2227 pcap_src->cap_pipe_err = PIPERR;
2228 cap_pipe_close(fd, pcap_src->from_cap_socket);
2229 pcap_src->cap_pipe_fd = -1;
2230 #ifdef _WIN32
2231 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2232 #endif
2236 * Synchronously read the fixed portion of the pcapng section header block
2237 * (we've already read the pcapng block header).
2239 static int
2240 pcapng_read_shb(capture_src *pcap_src,
2241 char *errmsg,
2242 size_t errmsgl)
2244 pcapng_section_header_block_t shb;
2246 #ifdef _WIN32
2247 if (pcap_src->from_cap_socket)
2248 #endif
2250 pcap_src->cap_pipe_bytes_to_read = sizeof(pcapng_block_header_t) + sizeof(pcapng_section_header_block_t);
2251 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2252 return -1;
2255 #ifdef _WIN32
2256 else {
2257 pipe_read_sync(pcap_src, pcap_src->cap_pipe_databuf + sizeof(pcapng_block_header_t),
2258 sizeof(pcapng_section_header_block_t));
2259 if (pcap_src->cap_pipe_bytes_read <= 0) {
2260 if (pcap_src->cap_pipe_bytes_read == 0)
2261 snprintf(errmsg, errmsgl,
2262 "End of file reading from pipe or socket.");
2263 else
2264 snprintf(errmsg, errmsgl,
2265 "Error reading from pipe or socket: %s.",
2266 g_strerror(errno));
2267 return -1;
2269 /* Continuing with STATE_EXPECT_DATA requires reading into cap_pipe_databuf at offset cap_pipe_bytes_read */
2270 pcap_src->cap_pipe_bytes_read = sizeof(pcapng_block_header_t) + sizeof(pcapng_section_header_block_t);
2272 #endif
2273 memcpy(&shb, pcap_src->cap_pipe_databuf + sizeof(pcapng_block_header_t), sizeof(pcapng_section_header_block_t));
2274 switch (shb.magic)
2276 case PCAPNG_MAGIC:
2277 ws_debug("pcapng SHB MAGIC");
2278 break;
2279 case PCAPNG_SWAPPED_MAGIC:
2280 ws_debug("pcapng SHB SWAPPED MAGIC");
2282 * pcapng sources can contain all sorts of block types.
2283 * Rather than add a bunch of complexity to this code (which is
2284 * often privileged), punt and tell the user to swap bytes
2285 * elsewhere.
2287 * XXX - punting means that the Wireshark test suite must be
2288 * modified to:
2290 * 1) have both little-endian and big-endian versions of
2291 * all pcapng files piped to dumpcap;
2293 * 2) pipe the appropriate file to dumpcap, depending on
2294 * the byte order of the host on which the tests are
2295 * being run;
2297 * as per comments in bug 15772 and 15754.
2299 * Are we *really* certain that the complexity added would be
2300 * significant enough to make adding it a security risk? And
2301 * why would this code even be running with any elevated
2302 * privileges if you're capturing from a pipe? We should not
2303 * only have given up all additional privileges if we're reading
2304 * from a pipe, we should give them up in such a fashion that
2305 * we can't reclaim them.
2307 #if G_BYTE_ORDER == G_BIG_ENDIAN
2308 #define OUR_ENDIAN "big"
2309 #define IFACE_ENDIAN "little"
2310 #else
2311 #define OUR_ENDIAN "little"
2312 #define IFACE_ENDIAN "big"
2313 #endif
2314 snprintf(errmsg, errmsgl,
2315 "Interface %u is " IFACE_ENDIAN " endian but we're " OUR_ENDIAN " endian.",
2316 pcap_src->interface_id);
2317 return -1;
2318 default:
2319 /* Not a pcapng type we know about, or not pcapng at all. */
2320 snprintf(errmsg, errmsgl,
2321 "Unrecognized pcapng format or not pcapng data.");
2322 return -1;
2325 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
2327 /* Setup state to capture any options following the section header block */
2328 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2330 return 0;
2334 * Save IDB blocks for playback whenever we change output files, and
2335 * fix LINKTYPE_ values that are really platform-dependent DLT_ values.
2336 * Rewrite EPB and ISB interface IDs.
2338 static gboolean
2339 pcapng_adjust_block(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd)
2341 switch(bh->block_type) {
2342 case BLOCK_TYPE_SHB:
2344 if (global_ld.pcapng_passthrough) {
2346 * We have a single pcapng input. We pass the SHB through when
2347 * writing a single output file and for the first ring buffer
2348 * file. We need to save it for the second and subsequent ring
2349 * buffer files.
2351 g_free(global_ld.saved_shb);
2352 global_ld.saved_shb = (guint8 *) g_memdup2(pd, bh->block_total_length);
2355 * We're dealing with one section at a time, so we can (and must)
2356 * get rid of our old IDBs.
2358 for (unsigned i = 0; i < global_ld.saved_idbs->len; i++) {
2359 saved_idb_t *idb_source = &g_array_index(global_ld.saved_idbs, saved_idb_t, i);
2360 g_free(idb_source->idb);
2362 g_array_set_size(global_ld.saved_idbs, 0);
2363 } else {
2365 * We have a new SHB from this capture source. We need to keep
2366 * global_ld.saved_idbs intact, so we mark IDBs we previously
2367 * collected from this source as deleted.
2369 for (unsigned i = 0; i < pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len; i++) {
2370 guint32 iface_id = g_array_index(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, guint32, i);
2371 saved_idb_t *idb_source = &g_array_index(global_ld.saved_idbs, saved_idb_t, iface_id);
2372 ws_assert(idb_source->interface_id == pcap_src->interface_id);
2373 g_free(idb_source->idb);
2374 memset(idb_source, 0, sizeof(saved_idb_t));
2375 idb_source->deleted = TRUE;
2376 ws_debug("%s: deleted pcapng IDB %u", G_STRFUNC, iface_id);
2379 g_array_set_size(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, 0);
2381 break;
2382 case BLOCK_TYPE_IDB:
2385 * Always gather IDBs. We can remove them or mark them as deleted
2386 * when we get a new SHB.
2388 saved_idb_t idb_source = { 0 };
2389 idb_source.interface_id = pcap_src->interface_id;
2390 idb_source.idb_len = bh->block_total_length;
2391 idb_source.idb = (guint8 *) g_memdup2(pd, idb_source.idb_len);
2392 g_array_append_val(global_ld.saved_idbs, idb_source);
2393 guint32 iface_id = global_ld.saved_idbs->len - 1;
2394 g_array_append_val(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, iface_id);
2395 ws_debug("%s: mapped pcapng IDB %u -> %u from source %u",
2396 G_STRFUNC, pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len - 1, iface_id, pcap_src->interface_id);
2398 break;
2399 case BLOCK_TYPE_EPB:
2400 case BLOCK_TYPE_ISB:
2402 if (global_ld.pcapng_passthrough) {
2403 /* Our input and output interface IDs are the same. */
2404 break;
2406 /* The interface ID is the first 32-bit field after the BH for both EPBs and ISBs. */
2407 guint32 iface_id;
2408 memcpy(&iface_id, pd + sizeof(pcapng_block_header_t), 4);
2409 if (iface_id < pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len) {
2410 memcpy(pd + sizeof(pcapng_block_header_t),
2411 &g_array_index(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, guint32, iface_id), 4);
2412 } else {
2413 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);
2414 return FALSE;
2417 break;
2418 default:
2419 break;
2422 return TRUE;
2426 * Return true if the block contains packet, event, or log data. Return false otherwise.
2428 static bool is_data_block(uint32_t block_type)
2430 // Any block types that lead to calling wtap_read_packet_bytes in
2431 // wiretap/pcapng.c should be listed here.
2432 switch (block_type) {
2433 case BLOCK_TYPE_PB:
2434 case BLOCK_TYPE_EPB:
2435 case BLOCK_TYPE_SPB:
2436 case BLOCK_TYPE_SYSTEMD_JOURNAL_EXPORT:
2437 case BLOCK_TYPE_SYSDIG_EVENT:
2438 case BLOCK_TYPE_SYSDIG_EVENT_V2:
2439 case BLOCK_TYPE_SYSDIG_EVENT_V2_LARGE:
2440 return true;
2441 default:
2442 break;
2444 return false;
2448 * Read the part of the initial pcapng SHB following the block type
2449 * (we've already read the block type).
2451 static void
2452 pcapng_pipe_open_live(int fd,
2453 capture_src *pcap_src,
2454 char *errmsg,
2455 size_t errmsgl)
2457 guint32 type = BLOCK_TYPE_SHB;
2458 pcapng_block_header_t *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2460 ws_debug("pcapng_pipe_open_live: fd %d", fd);
2463 * A pcapng block begins with the block type followed by the block
2464 * total length; we've already read the block type, now read the
2465 * block length.
2467 #ifdef _WIN32
2469 * On UN*X, we can use select() on pipes or sockets.
2471 * On Windows, we can only use it on sockets; to do non-blocking
2472 * reads from pipes, we currently do reads in a separate thread
2473 * and use GLib asynchronous queues from the main thread to start
2474 * read operations and to wait for them to complete.
2476 if (pcap_src->from_cap_socket)
2477 #endif
2479 memcpy(pcap_src->cap_pipe_databuf, &type, sizeof(guint32));
2480 pcap_src->cap_pipe_bytes_read = sizeof(guint32);
2481 pcap_src->cap_pipe_bytes_to_read = sizeof(pcapng_block_header_t);
2482 pcap_src->cap_pipe_fd = fd;
2483 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2484 goto error;
2486 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(pcapng_block_header_t));
2488 #ifdef _WIN32
2489 else {
2490 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
2492 bh->block_type = type;
2493 pipe_read_sync(pcap_src, &bh->block_total_length,
2494 sizeof(bh->block_total_length));
2495 if (pcap_src->cap_pipe_bytes_read <= 0) {
2496 if (pcap_src->cap_pipe_bytes_read == 0)
2497 snprintf(errmsg, errmsgl,
2498 "End of file reading from pipe or socket.");
2499 else
2500 snprintf(errmsg, errmsgl,
2501 "Error reading from pipe or socket: %s.",
2502 g_strerror(errno));
2503 goto error;
2505 pcap_src->cap_pipe_bytes_read = sizeof(pcapng_block_header_t);
2506 memcpy(pcap_src->cap_pipe_databuf, bh, sizeof(pcapng_block_header_t));
2507 pcap_src->cap_pipe_fd = fd;
2509 #endif
2510 if ((bh->block_total_length & 0x03) != 0) {
2511 snprintf(errmsg, errmsgl,
2512 "block_total_length read from pipe is %u, which is not a multiple of 4.",
2513 bh->block_total_length);
2514 goto error;
2516 if (pcapng_read_shb(pcap_src, errmsg, errmsgl)) {
2517 goto error;
2520 return;
2522 error:
2523 ws_debug("pcapng_pipe_open_live: error %s", errmsg);
2524 pcap_src->cap_pipe_err = PIPERR;
2525 cap_pipe_close(fd, pcap_src->from_cap_socket);
2526 pcap_src->cap_pipe_fd = -1;
2527 #ifdef _WIN32
2528 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2529 #endif
2532 /* We read one record from the pipe, take care of byte order in the record
2533 * header, write the record to the capture file, and update capture statistics. */
2534 static int
2535 pcap_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, size_t errmsgl)
2537 struct pcap_pkthdr phdr;
2538 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2539 PD_ERR } result;
2540 #ifdef _WIN32
2541 gpointer q_status;
2542 #endif
2543 ssize_t b;
2544 guint new_bufsize;
2545 pcap_pipe_info_t *pcap_info = &pcap_src->cap_pipe_info.pcap;
2547 #ifdef LOG_CAPTURE_VERBOSE
2548 ws_debug("pcap_pipe_dispatch");
2549 #endif
2551 switch (pcap_src->cap_pipe_state) {
2553 case STATE_EXPECT_REC_HDR:
2554 #ifdef _WIN32
2555 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2556 #endif
2558 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2559 pcap_src->cap_pipe_bytes_to_read = pcap_src->cap_pipe_modified ?
2560 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2561 pcap_src->cap_pipe_bytes_read = 0;
2563 #ifdef _WIN32
2564 pcap_src->cap_pipe_buf = (char *) &pcap_info->rechdr;
2565 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2566 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2568 #endif
2569 /* Fall through */
2571 case STATE_READ_REC_HDR:
2572 #ifdef _WIN32
2573 if (pcap_src->from_cap_socket)
2574 #endif
2576 b = cap_pipe_read(pcap_src->cap_pipe_fd, ((char *)&pcap_info->rechdr)+pcap_src->cap_pipe_bytes_read,
2577 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read, pcap_src->from_cap_socket);
2578 if (b <= 0) {
2579 if (b == 0)
2580 result = PD_PIPE_EOF;
2581 else
2582 result = PD_PIPE_ERR;
2583 break;
2585 #ifdef _WIN32
2586 pcap_src->cap_pipe_bytes_read += (DWORD)b;
2587 #else
2588 pcap_src->cap_pipe_bytes_read += b;
2589 #endif
2591 #ifdef _WIN32
2592 else {
2593 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2594 if (pcap_src->cap_pipe_err == PIPEOF) {
2595 result = PD_PIPE_EOF;
2596 break;
2597 } else if (pcap_src->cap_pipe_err == PIPERR) {
2598 result = PD_PIPE_ERR;
2599 break;
2601 if (!q_status) {
2602 return 0;
2605 #endif
2606 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2607 /* There's still more of the pcap packet header to read. */
2608 return 0;
2610 result = PD_REC_HDR_READ;
2611 break;
2613 case STATE_EXPECT_DATA:
2614 #ifdef _WIN32
2615 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2616 #endif
2618 pcap_src->cap_pipe_state = STATE_READ_DATA;
2619 pcap_src->cap_pipe_bytes_to_read = pcap_info->rechdr.hdr.incl_len;
2620 pcap_src->cap_pipe_bytes_read = 0;
2622 #ifdef _WIN32
2623 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2624 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2625 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2627 #endif
2628 /* Fall through */
2630 case STATE_READ_DATA:
2631 #ifdef _WIN32
2632 if (pcap_src->from_cap_socket)
2633 #endif
2635 b = cap_pipe_read(pcap_src->cap_pipe_fd,
2636 pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read,
2637 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read,
2638 pcap_src->from_cap_socket);
2639 if (b <= 0) {
2640 if (b == 0)
2641 result = PD_PIPE_EOF;
2642 else
2643 result = PD_PIPE_ERR;
2644 break;
2646 #ifdef _WIN32
2647 pcap_src->cap_pipe_bytes_read += (DWORD)b;
2648 #else
2649 pcap_src->cap_pipe_bytes_read += b;
2650 #endif
2652 #ifdef _WIN32
2653 else {
2655 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2656 if (pcap_src->cap_pipe_err == PIPEOF) {
2657 result = PD_PIPE_EOF;
2658 break;
2659 } else if (pcap_src->cap_pipe_err == PIPERR) {
2660 result = PD_PIPE_ERR;
2661 break;
2663 if (!q_status) {
2664 return 0;
2667 #endif /* _WIN32 */
2668 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2669 /* There's still more of the pcap packet data to read. */
2670 return 0;
2672 result = PD_DATA_READ;
2673 break;
2675 default:
2676 snprintf(errmsg, errmsgl,
2677 "pcap_pipe_dispatch: invalid state");
2678 result = PD_ERR;
2680 } /* switch (pcap_src->cap_pipe_state) */
2683 * We've now read as much data as we were expecting, so process it.
2685 switch (result) {
2687 case PD_REC_HDR_READ:
2689 * We've read the packet header, so we know the captured length,
2690 * and thus the number of packet data bytes. Take care of byte order.
2692 cap_pipe_adjust_pcap_header(pcap_src->cap_pipe_info.pcap.byte_swapped, &pcap_info->hdr,
2693 &pcap_info->rechdr.hdr);
2694 if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_max_pkt_size) {
2696 * The record contains more data than the advertised/allowed in the
2697 * pcap header, do not try to read more data (do not change to
2698 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2699 * instead stop with an error.
2701 snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2702 ld->packets_captured+1, pcap_info->rechdr.hdr.incl_len);
2703 break;
2706 if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_databuf_size) {
2708 * Grow the buffer to the packet size, rounded up to a power of
2709 * 2.
2711 new_bufsize = pcap_info->rechdr.hdr.incl_len;
2713 * https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2715 new_bufsize--;
2716 new_bufsize |= new_bufsize >> 1;
2717 new_bufsize |= new_bufsize >> 2;
2718 new_bufsize |= new_bufsize >> 4;
2719 new_bufsize |= new_bufsize >> 8;
2720 new_bufsize |= new_bufsize >> 16;
2721 new_bufsize++;
2722 pcap_src->cap_pipe_databuf = (char*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2723 pcap_src->cap_pipe_databuf_size = new_bufsize;
2726 if (pcap_info->rechdr.hdr.incl_len) {
2728 * The record has some data following the header, try
2729 * to read it next time.
2731 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2732 return 0;
2736 * No data following the record header? Then no more data needs to be
2737 * read and we will fallthrough and emit an empty packet.
2739 /* FALLTHROUGH */
2741 case PD_DATA_READ:
2743 * We've read the full contents of the packet record.
2744 * Fill in a "struct pcap_pkthdr", and process the packet.
2746 phdr.ts.tv_sec = pcap_info->rechdr.hdr.ts_sec;
2747 phdr.ts.tv_usec = pcap_info->rechdr.hdr.ts_usec;
2748 phdr.caplen = pcap_info->rechdr.hdr.incl_len;
2749 phdr.len = pcap_info->rechdr.hdr.orig_len;
2751 if (use_threads) {
2752 capture_loop_queue_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2753 } else {
2754 capture_loop_write_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2758 * Now we want to read the next packet's header.
2760 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2761 return 1;
2763 case PD_PIPE_EOF:
2764 pcap_src->cap_pipe_err = PIPEOF;
2765 return -1;
2767 case PD_PIPE_ERR:
2768 snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2769 #ifdef _WIN32
2770 win32strerror(GetLastError()));
2771 #else
2772 g_strerror(errno));
2773 #endif
2774 /* Fall through */
2775 case PD_ERR:
2776 break;
2779 pcap_src->cap_pipe_err = PIPERR;
2780 /* Return here rather than inside the switch to prevent GCC warning */
2781 return -1;
2784 static int
2785 pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, size_t errmsgl)
2787 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2788 PD_ERR } result;
2789 #ifdef _WIN32
2790 gpointer q_status;
2791 #endif
2792 guint new_bufsize;
2793 pcapng_block_header_t *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2795 #ifdef LOG_CAPTURE_VERBOSE
2796 ws_debug("pcapng_pipe_dispatch");
2797 #endif
2799 switch (pcap_src->cap_pipe_state) {
2801 case STATE_EXPECT_REC_HDR:
2802 #ifdef LOG_CAPTURE_VERBOSE
2803 ws_debug("pcapng_pipe_dispatch STATE_EXPECT_REC_HDR");
2804 #endif
2805 #ifdef _WIN32
2806 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2807 #endif
2809 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2810 pcap_src->cap_pipe_bytes_to_read = sizeof(pcapng_block_header_t);
2811 pcap_src->cap_pipe_bytes_read = 0;
2813 #ifdef _WIN32
2814 if (!pcap_src->from_cap_socket) {
2815 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2816 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2818 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2820 #endif
2821 /* Fall through */
2823 case STATE_READ_REC_HDR:
2824 #ifdef LOG_CAPTURE_VERBOSE
2825 ws_debug("pcapng_pipe_dispatch STATE_READ_REC_HDR");
2826 #endif
2827 #ifdef _WIN32
2828 if (pcap_src->from_cap_socket) {
2829 #endif
2830 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2831 return -1;
2833 #ifdef _WIN32
2834 } else {
2835 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2836 if (pcap_src->cap_pipe_err == PIPEOF) {
2837 result = PD_PIPE_EOF;
2838 break;
2839 } else if (pcap_src->cap_pipe_err == PIPERR) {
2840 result = PD_PIPE_ERR;
2841 break;
2843 if (!q_status) {
2844 return 0;
2847 #endif
2848 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2849 /* There's still more of the pcapng block header to read. */
2850 return 0;
2852 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(pcapng_block_header_t));
2853 result = PD_REC_HDR_READ;
2854 break;
2856 case STATE_EXPECT_DATA:
2857 #ifdef LOG_CAPTURE_VERBOSE
2858 ws_debug("pcapng_pipe_dispatch STATE_EXPECT_DATA");
2859 #endif
2860 #ifdef _WIN32
2861 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2862 #endif
2863 pcap_src->cap_pipe_state = STATE_READ_DATA;
2864 pcap_src->cap_pipe_bytes_to_read = bh->block_total_length;
2866 #ifdef _WIN32
2867 if (!pcap_src->from_cap_socket) {
2868 pcap_src->cap_pipe_bytes_to_read -= pcap_src->cap_pipe_bytes_read;
2869 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf + pcap_src->cap_pipe_bytes_read;
2870 pcap_src->cap_pipe_bytes_read = 0;
2871 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2873 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2875 #endif
2876 /* Fall through */
2878 case STATE_READ_DATA:
2879 #ifdef LOG_CAPTURE_VERBOSE
2880 ws_debug("pcapng_pipe_dispatch STATE_READ_DATA");
2881 #endif
2882 #ifdef _WIN32
2883 if (pcap_src->from_cap_socket) {
2884 #endif
2885 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2886 return -1;
2888 #ifdef _WIN32
2889 } else {
2891 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2892 if (pcap_src->cap_pipe_err == PIPEOF) {
2893 result = PD_PIPE_EOF;
2894 break;
2895 } else if (pcap_src->cap_pipe_err == PIPERR) {
2896 result = PD_PIPE_ERR;
2897 break;
2899 if (!q_status) {
2900 return 0;
2903 #endif /* _WIN32 */
2904 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2905 /* There's still more of the pcap block contents to read. */
2906 return 0;
2908 result = PD_DATA_READ;
2909 break;
2911 default:
2912 snprintf(errmsg, errmsgl,
2913 "pcapng_pipe_dispatch: invalid state");
2914 result = PD_ERR;
2916 } /* switch (pcap_src->cap_pipe_state) */
2919 * We've now read as much data as we were expecting, so process it.
2921 switch (result) {
2923 case PD_REC_HDR_READ:
2925 * We've read the pcapng block header, so we know the block type
2926 * and length.
2928 if (bh->block_type == BLOCK_TYPE_SHB) {
2930 * We need to read the fixed portion of the SHB before to
2931 * get the endianness before we can interpret the block length.
2932 * (The block type of the SHB is byte-order-independent, so that
2933 * an SHB can be recognized before we know the endianness of
2934 * the section.)
2936 * Continue the read process.
2938 pcapng_read_shb(pcap_src, errmsg, errmsgl);
2939 return 1;
2942 if ((bh->block_total_length & 0x03) != 0) {
2943 snprintf(errmsg, errmsgl,
2944 "Total length of pcapng block read from pipe is %u, which is not a multiple of 4.",
2945 bh->block_total_length);
2946 break;
2948 if (is_data_block(bh->block_type) && bh->block_total_length > pcap_src->cap_pipe_max_pkt_size) {
2950 * The record contains more data than the advertised/allowed in the
2951 * pcapng header, do not try to read more data (do not change to
2952 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2953 * instead stop with an error.
2955 snprintf(errmsg, errmsgl, "Block %u type 0x%08x too long (%d bytes)",
2956 ld->packets_captured+1, bh->block_type, bh->block_total_length);
2957 break;
2960 if (bh->block_total_length > pcap_src->cap_pipe_databuf_size) {
2962 * Grow the buffer to the packet size, rounded up to a power of
2963 * 2.
2965 new_bufsize = bh->block_total_length;
2967 * https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2969 new_bufsize--;
2970 new_bufsize |= new_bufsize >> 1;
2971 new_bufsize |= new_bufsize >> 2;
2972 new_bufsize |= new_bufsize >> 4;
2973 new_bufsize |= new_bufsize >> 8;
2974 new_bufsize |= new_bufsize >> 16;
2975 new_bufsize++;
2976 pcap_src->cap_pipe_databuf = (guchar*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2977 pcap_src->cap_pipe_databuf_size = new_bufsize;
2980 /* The record always has at least the block total length following the header */
2981 if (bh->block_total_length < sizeof(pcapng_block_header_t)+sizeof(guint32)) {
2982 snprintf(errmsg, errmsgl,
2983 "malformed pcapng block_total_length < minimum");
2984 pcap_src->cap_pipe_err = PIPEOF;
2985 return -1;
2989 * Now we want to read the block contents.
2991 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2992 return 0;
2994 case PD_DATA_READ:
2996 * We've read the full contents of the block.
2997 * Process the block.
2999 if (use_threads) {
3000 capture_loop_queue_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
3001 } else {
3002 capture_loop_write_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
3006 * Now we want to read the next block's header.
3008 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
3009 return 1;
3011 case PD_PIPE_EOF:
3012 pcap_src->cap_pipe_err = PIPEOF;
3013 return -1;
3015 case PD_PIPE_ERR:
3016 snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
3017 #ifdef _WIN32
3018 win32strerror(GetLastError()));
3019 #else
3020 g_strerror(errno));
3021 #endif
3022 /* Fall through */
3023 case PD_ERR:
3024 break;
3027 pcap_src->cap_pipe_err = PIPERR;
3028 /* Return here rather than inside the switch to prevent GCC warning */
3029 return -1;
3032 /** Open the capture input sources; each one is either a pcap device,
3033 * a capture pipe, or a capture socket.
3034 * Returns TRUE if it succeeds, FALSE otherwise. */
3035 static gboolean
3036 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
3037 char *errmsg, size_t errmsg_len,
3038 char *secondary_errmsg, size_t secondary_errmsg_len)
3040 cap_device_open_status open_status;
3041 gchar open_status_str[PCAP_ERRBUF_SIZE];
3042 gchar *sync_msg_str;
3043 interface_options *interface_opts;
3044 capture_src *pcap_src;
3045 guint i;
3047 if ((use_threads == FALSE) &&
3048 (capture_opts->ifaces->len > 1)) {
3049 snprintf(errmsg, errmsg_len,
3050 "Using threads is required for capturing on multiple interfaces.");
3051 return FALSE;
3054 int pcapng_src_count = 0;
3055 for (i = 0; i < capture_opts->ifaces->len; i++) {
3056 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
3057 pcap_src = g_new0(capture_src, 1);
3058 if (pcap_src == NULL) {
3059 snprintf(errmsg, errmsg_len,
3060 "Could not allocate memory.");
3061 return FALSE;
3064 #ifdef MUST_DO_SELECT
3065 pcap_src->pcap_fd = -1;
3066 #endif
3067 pcap_src->interface_id = i;
3068 pcap_src->linktype = -1;
3069 #ifdef _WIN32
3070 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
3071 #endif
3072 pcap_src->cap_pipe_fd = -1;
3073 pcap_src->cap_pipe_dispatch = pcap_pipe_dispatch;
3074 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
3075 pcap_src->cap_pipe_err = PIPOK;
3076 #ifdef _WIN32
3077 pcap_src->cap_pipe_read_mtx = g_new(GMutex, 1);
3078 g_mutex_init(pcap_src->cap_pipe_read_mtx);
3079 pcap_src->cap_pipe_pending_q = g_async_queue_new();
3080 pcap_src->cap_pipe_done_q = g_async_queue_new();
3081 #endif
3082 g_array_append_val(ld->pcaps, pcap_src);
3084 ws_debug("capture_loop_open_input : %s", interface_opts->name);
3085 pcap_src->pcap_h = open_capture_device(capture_opts, interface_opts,
3086 CAP_READ_TIMEOUT, &open_status, &open_status_str);
3088 if (pcap_src->pcap_h != NULL) {
3089 /* we've opened "iface" as a network device */
3091 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
3092 /* Find out if we're getting nanosecond-precision time stamps */
3093 pcap_src->ts_nsec = have_high_resolution_timestamp(pcap_src->pcap_h);
3094 #endif
3096 #if defined(HAVE_PCAP_SETSAMPLING)
3097 if (interface_opts->sampling_method != CAPTURE_SAMP_NONE) {
3098 struct pcap_samp *samp;
3100 if ((samp = pcap_setsampling(pcap_src->pcap_h)) != NULL) {
3101 switch (interface_opts->sampling_method) {
3102 case CAPTURE_SAMP_BY_COUNT:
3103 samp->method = PCAP_SAMP_1_EVERY_N;
3104 break;
3106 case CAPTURE_SAMP_BY_TIMER:
3107 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
3108 break;
3110 default:
3111 sync_msg_str = ws_strdup_printf(
3112 "Unknown sampling method %d specified,\n"
3113 "continue without packet sampling",
3114 interface_opts->sampling_method);
3115 report_capture_error("Couldn't set the capture "
3116 "sampling", sync_msg_str);
3117 g_free(sync_msg_str);
3119 samp->value = interface_opts->sampling_param;
3120 } else {
3121 report_capture_error("Couldn't set the capture sampling",
3122 "Cannot get packet sampling data structure");
3125 #endif
3127 /* setting the data link type only works on real interfaces */
3128 if (!set_pcap_datalink(pcap_src->pcap_h, interface_opts->linktype,
3129 interface_opts->name,
3130 errmsg, errmsg_len,
3131 secondary_errmsg, secondary_errmsg_len)) {
3132 return FALSE;
3134 pcap_src->linktype = dlt_to_linktype(get_pcap_datalink(pcap_src->pcap_h, interface_opts->name));
3135 } else {
3136 /* We couldn't open "iface" as a network device. */
3137 /* Try to open it as a pipe */
3138 gboolean pipe_err = FALSE;
3139 cap_pipe_open_live(interface_opts->name, pcap_src,
3140 &pcap_src->cap_pipe_info.pcap.hdr,
3141 errmsg, errmsg_len,
3142 secondary_errmsg, secondary_errmsg_len);
3144 #ifdef _WIN32
3145 if (pcap_src->from_cap_socket) {
3146 #endif
3147 if (pcap_src->cap_pipe_fd == -1) {
3148 pipe_err = TRUE;
3150 #ifdef _WIN32
3151 } else {
3152 if (pcap_src->cap_pipe_h == INVALID_HANDLE_VALUE) {
3153 pipe_err = TRUE;
3156 #endif
3158 if (pipe_err) {
3159 if (pcap_src->cap_pipe_err == PIPNEXIST) {
3161 * We tried opening as an interface, and that failed,
3162 * so we tried to open it as a pipe, but the pipe
3163 * doesn't exist. Report the error message for
3164 * the interface.
3166 get_capture_device_open_failure_messages(open_status,
3167 open_status_str,
3168 interface_opts->name,
3169 errmsg,
3170 errmsg_len,
3171 secondary_errmsg,
3172 secondary_errmsg_len);
3175 * Else pipe (or file) does exist and cap_pipe_open_live() has
3176 * filled in errmsg
3178 return FALSE;
3179 } else {
3181 * We tried opening as an interface, and that failed,
3182 * so we tried to open it as a pipe, and that succeeded.
3184 open_status = CAP_DEVICE_OPEN_NO_ERR;
3188 /* XXX - will this work for tshark? */
3189 #ifdef MUST_DO_SELECT
3190 if (!pcap_src->from_cap_pipe) {
3191 pcap_src->pcap_fd = pcap_get_selectable_fd(pcap_src->pcap_h);
3193 #endif
3195 /* Is "open_status" something other than CAP_DEVICE_OPEN_NO_ERR?
3196 If so, "open_capture_device()" returned a warning; print it,
3197 but keep capturing. */
3198 if (open_status != CAP_DEVICE_OPEN_NO_ERR) {
3199 sync_msg_str = ws_strdup_printf("%s.", open_status_str);
3200 report_capture_error(sync_msg_str, "");
3201 g_free(sync_msg_str);
3203 if (pcap_src->from_pcapng) {
3205 * We will use the IDBs from the source (but rewrite the
3206 * interface IDs if there's more than one source.)
3208 pcapng_src_count++;
3209 } else {
3211 * Add our pcapng interface entry.
3213 saved_idb_t idb_source = { 0 };
3214 idb_source.interface_id = i;
3215 g_rw_lock_writer_lock (&ld->saved_shb_idb_lock);
3216 pcap_src->idb_id = global_ld.saved_idbs->len;
3217 g_array_append_val(global_ld.saved_idbs, idb_source);
3218 g_rw_lock_writer_unlock (&ld->saved_shb_idb_lock);
3219 ws_debug("%s: saved capture_opts %u to IDB %u",
3220 G_STRFUNC, i, pcap_src->idb_id);
3225 * Are we capturing from one source that is providing pcapng
3226 * information?
3228 if (capture_opts->ifaces->len == 1 && pcapng_src_count == 1) {
3230 * Yes; pass through SHBs and IDBs from the source, rather
3231 * than generating our own.
3233 ld->pcapng_passthrough = TRUE;
3234 g_rw_lock_writer_lock (&ld->saved_shb_idb_lock);
3235 ws_assert(global_ld.saved_idbs->len == 0);
3236 ws_debug("%s: Pass through SHBs and IDBs directly", G_STRFUNC);
3237 g_rw_lock_writer_unlock (&ld->saved_shb_idb_lock);
3240 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
3241 /* to remove any suid privileges. */
3242 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
3243 /* (euid/egid have already previously been set to ruid/rgid. */
3244 /* (See comment in main() for details) */
3245 #ifndef HAVE_LIBCAP
3246 relinquish_special_privs_perm();
3247 #else
3248 relinquish_all_capabilities();
3249 #endif
3250 return TRUE;
3253 /* close the capture input file (pcap or capture pipe) */
3254 static void capture_loop_close_input(loop_data *ld)
3256 guint i;
3257 capture_src *pcap_src;
3259 ws_debug("capture_loop_close_input");
3261 for (i = 0; i < ld->pcaps->len; i++) {
3262 pcap_src = g_array_index(ld->pcaps, capture_src *, i);
3263 /* Pipe, or capture device? */
3264 if (pcap_src->from_cap_pipe) {
3265 /* Pipe. If open, close the capture pipe "input file". */
3266 if (pcap_src->cap_pipe_fd >= 0) {
3267 cap_pipe_close(pcap_src->cap_pipe_fd, pcap_src->from_cap_socket);
3268 pcap_src->cap_pipe_fd = -1;
3270 #ifdef _WIN32
3271 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE) {
3272 CloseHandle(pcap_src->cap_pipe_h);
3273 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
3275 #endif
3276 if (pcap_src->cap_pipe_databuf != NULL) {
3277 /* Free the buffer. */
3278 g_free(pcap_src->cap_pipe_databuf);
3279 pcap_src->cap_pipe_databuf = NULL;
3281 if (pcap_src->from_pcapng) {
3282 g_array_free(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, TRUE);
3283 pcap_src->cap_pipe_info.pcapng.src_iface_to_global = NULL;
3285 } else {
3286 /* Capture device. If open, close the pcap_t. */
3287 if (pcap_src->pcap_h != NULL) {
3288 ws_debug("capture_loop_close_input: closing %p", (void *)pcap_src->pcap_h);
3289 pcap_close(pcap_src->pcap_h);
3290 pcap_src->pcap_h = NULL;
3295 ld->go = FALSE;
3299 /* init the capture filter */
3300 static initfilter_status_t
3301 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
3302 const gchar * name, const gchar * cfilter)
3304 struct bpf_program fcode;
3306 ws_debug("capture_loop_init_filter: %s", cfilter);
3308 /* capture filters only work on real interfaces */
3309 if (cfilter && !from_cap_pipe) {
3310 /* A capture filter was specified; set it up. */
3311 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
3312 /* Treat this specially - our caller might try to compile this
3313 as a display filter and, if that succeeds, warn the user that
3314 the display and capture filter syntaxes are different. */
3315 return INITFILTER_BAD_FILTER;
3317 if (pcap_setfilter(pcap_h, &fcode) < 0) {
3318 #ifdef HAVE_PCAP_FREECODE
3319 pcap_freecode(&fcode);
3320 #endif
3321 return INITFILTER_OTHER_ERROR;
3323 #ifdef HAVE_PCAP_FREECODE
3324 pcap_freecode(&fcode);
3325 #endif
3328 return INITFILTER_NO_ERROR;
3332 * Write the dumpcap pcapng SHB and IDBs if needed.
3333 * Called from capture_loop_init_output and do_file_switch_or_stop.
3335 static gboolean
3336 capture_loop_init_pcapng_output(capture_options *capture_opts, loop_data *ld,
3337 int *err)
3339 g_rw_lock_reader_lock (&ld->saved_shb_idb_lock);
3341 if (ld->pcapng_passthrough && !ld->saved_shb) {
3342 /* We have a single pcapng capture interface and this is the first or only output file. */
3343 ws_debug("%s: skipping dumpcap SHB and IDBs in favor of source", G_STRFUNC);
3344 g_rw_lock_reader_unlock (&ld->saved_shb_idb_lock);
3345 return TRUE;
3348 gboolean successful = TRUE;
3349 GString *os_info_str = g_string_new("");
3351 *err = 0;
3352 get_os_version_info(os_info_str);
3354 if (ld->saved_shb) {
3355 /* We have a single pcapng capture interface and multiple output files. */
3357 pcapng_block_header_t bh;
3359 memcpy(&bh, ld->saved_shb, sizeof(pcapng_block_header_t));
3361 successful = pcapng_write_block(ld->pdh, ld->saved_shb, bh.block_total_length, &ld->bytes_written, err);
3363 ws_debug("%s: wrote saved passthrough SHB %d", G_STRFUNC, successful);
3364 } else {
3365 GString *cpu_info_str = g_string_new("");
3366 get_cpu_info(cpu_info_str);
3368 successful = pcapng_write_section_header_block(ld->pdh,
3369 capture_comments, /* Comments */
3370 cpu_info_str->str, /* HW */
3371 os_info_str->str, /* OS */
3372 get_appname_and_version(),
3373 -1, /* section_length */
3374 &ld->bytes_written,
3375 err);
3376 ws_debug("%s: wrote dumpcap SHB %d", G_STRFUNC, successful);
3377 g_string_free(cpu_info_str, TRUE);
3380 for (unsigned i = 0; successful && (i < ld->saved_idbs->len); i++) {
3381 saved_idb_t idb_source = g_array_index(ld->saved_idbs, saved_idb_t, i);
3382 if (idb_source.deleted) {
3384 * Our interface is out of scope. Suppose we're writing multiple
3385 * files and a source switches sections. We currently write dummy
3386 * IDBs like so:
3388 * File 1: IDB0, IDB1, IDB2
3389 * [ The source of IDBs 1 and 2 writes an SHB with two new IDBs ]
3390 * [ We switch output files ]
3391 * File 2: IDB0, dummy IDB, dummy IDB, IDB3, IDB4
3393 * It might make more sense to write the original data so that
3394 * so that our IDB lists are more consistent across files.
3396 successful = pcapng_write_interface_description_block(global_ld.pdh,
3397 "Interface went out of scope", /* OPT_COMMENT 1 */
3398 "dummy", /* IDB_NAME 2 */
3399 "Dumpcap dummy interface", /* IDB_DESCRIPTION 3 */
3400 NULL, /* IDB_FILTER 11 */
3401 os_info_str->str, /* IDB_OS 12 */
3402 NULL, /* IDB_HARDWARE 15 */
3405 &(global_ld.bytes_written),
3406 0, /* IDB_IF_SPEED 8 */
3407 6, /* IDB_TSRESOL 9 */
3408 &global_ld.err);
3409 ws_debug("%s: skipping deleted pcapng IDB %u", G_STRFUNC, i);
3410 } else if (idb_source.idb && idb_source.idb_len) {
3411 successful = pcapng_write_block(global_ld.pdh, idb_source.idb, idb_source.idb_len, &ld->bytes_written, err);
3412 ws_debug("%s: wrote pcapng IDB %d", G_STRFUNC, successful);
3413 } else if (idb_source.interface_id < capture_opts->ifaces->len) {
3414 unsigned if_id = idb_source.interface_id;
3415 interface_options *interface_opts = &g_array_index(capture_opts->ifaces, interface_options, if_id);
3416 capture_src *pcap_src = g_array_index(ld->pcaps, capture_src *, if_id);
3417 if (pcap_src->from_cap_pipe) {
3418 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
3419 } else {
3420 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
3422 successful = pcapng_write_interface_description_block(global_ld.pdh,
3423 NULL, /* OPT_COMMENT 1 */
3424 (interface_opts->ifname != NULL) ? interface_opts->ifname : interface_opts->name, /* IDB_NAME 2 */
3425 interface_opts->descr, /* IDB_DESCRIPTION 3 */
3426 interface_opts->cfilter, /* IDB_FILTER 11 */
3427 os_info_str->str, /* IDB_OS 12 */
3428 interface_opts->hardware, /* IDB_HARDWARE 15 */
3429 pcap_src->linktype,
3430 pcap_src->snaplen,
3431 &(global_ld.bytes_written),
3432 0, /* IDB_IF_SPEED 8 */
3433 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3434 &global_ld.err);
3435 ws_debug("%s: wrote capture_opts IDB %d: %d", G_STRFUNC, if_id, successful);
3438 g_rw_lock_reader_unlock (&ld->saved_shb_idb_lock);
3440 g_string_free(os_info_str, TRUE);
3442 return successful;
3445 /* set up to write to the already-opened capture output file/files */
3446 static gboolean
3447 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
3449 int err = 0;
3451 ws_debug("capture_loop_init_output");
3453 if ((capture_opts->use_pcapng == FALSE) &&
3454 (capture_opts->ifaces->len > 1)) {
3455 snprintf(errmsg, errmsg_len,
3456 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
3457 return FALSE;
3460 /* Set up to write to the capture file. */
3461 if (capture_opts->multi_files_on) {
3462 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
3463 } else {
3464 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
3465 if (ld->pdh == NULL) {
3466 err = errno;
3467 } else {
3468 size_t buffsize = IO_BUF_SIZE;
3469 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
3470 ws_statb64 statb;
3472 if (ws_fstat64(ld->save_file_fd, &statb) == 0) {
3473 if (statb.st_blksize > IO_BUF_SIZE) {
3474 buffsize = statb.st_blksize;
3477 #endif
3478 /* Increase the size of the IO buffer */
3479 ld->io_buffer = (char *)g_malloc(buffsize);
3480 setvbuf(ld->pdh, ld->io_buffer, _IOFBF, buffsize);
3481 ws_debug("capture_loop_init_output: buffsize %zu", buffsize);
3484 if (ld->pdh) {
3485 gboolean successful;
3486 if (capture_opts->use_pcapng) {
3487 successful = capture_loop_init_pcapng_output(capture_opts, ld, &err);
3488 } else {
3489 capture_src *pcap_src;
3490 pcap_src = g_array_index(ld->pcaps, capture_src *, 0);
3491 if (pcap_src->from_cap_pipe) {
3492 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
3493 } else {
3494 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
3496 successful = libpcap_write_file_header(ld->pdh, pcap_src->linktype, pcap_src->snaplen,
3497 pcap_src->ts_nsec, &ld->bytes_written, &err);
3499 if (!successful) {
3500 fclose(ld->pdh);
3501 ld->pdh = NULL;
3502 g_free(ld->io_buffer);
3503 ld->io_buffer = NULL;
3507 if (ld->pdh == NULL) {
3508 /* We couldn't set up to write to the capture file. */
3509 /* XXX - use cf_open_error_message from tshark instead? */
3510 if (err < 0) {
3511 snprintf(errmsg, errmsg_len,
3512 "The file to which the capture would be"
3513 " saved (\"%s\") could not be opened: Error %d.",
3514 capture_opts->save_file, err);
3515 } else {
3516 snprintf(errmsg, errmsg_len,
3517 "The file to which the capture would be"
3518 " saved (\"%s\") could not be opened: %s.",
3519 capture_opts->save_file, g_strerror(err));
3521 return FALSE;
3524 return TRUE;
3527 static gboolean
3528 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
3531 unsigned int i;
3532 capture_src *pcap_src;
3533 guint64 end_time = create_timestamp();
3534 gboolean success;
3536 ws_debug("capture_loop_close_output");
3538 if (capture_opts->multi_files_on) {
3539 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
3540 } else {
3541 if (capture_opts->use_pcapng) {
3542 for (i = 0; i < global_ld.pcaps->len; i++) {
3543 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3544 if (!pcap_src->from_cap_pipe) {
3545 guint64 isb_ifrecv, isb_ifdrop;
3546 struct pcap_stat stats;
3548 if (pcap_stats(pcap_src->pcap_h, &stats) >= 0) {
3549 isb_ifrecv = pcap_src->received;
3550 isb_ifdrop = stats.ps_drop + pcap_src->dropped + pcap_src->flushed;
3551 } else {
3552 isb_ifrecv = G_MAXUINT64;
3553 isb_ifdrop = G_MAXUINT64;
3555 pcapng_write_interface_statistics_block(ld->pdh,
3557 &ld->bytes_written,
3558 "Counters provided by dumpcap",
3559 start_time,
3560 end_time,
3561 isb_ifrecv,
3562 isb_ifdrop,
3563 err_close);
3567 if (fclose(ld->pdh) == EOF) {
3568 if (err_close != NULL) {
3569 *err_close = errno;
3571 success = FALSE;
3572 } else {
3573 success = TRUE;
3575 g_free(ld->io_buffer);
3576 ld->io_buffer = NULL;
3577 return success;
3581 /* dispatch incoming packets (pcap or capture pipe)
3583 * Waits for incoming packets to be available, and calls pcap_dispatch()
3584 * to cause them to be processed.
3586 * Returns the number of packets which were processed.
3588 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3589 * packet-batching behaviour does not cause packets to get held back
3590 * indefinitely.
3592 static int
3593 capture_loop_dispatch(loop_data *ld,
3594 char *errmsg, int errmsg_len, capture_src *pcap_src)
3596 int inpkts = 0;
3597 gint packet_count_before;
3598 int sel_ret;
3600 packet_count_before = ld->packets_captured;
3601 if (pcap_src->from_cap_pipe) {
3602 /* dispatch from capture pipe */
3603 #ifdef LOG_CAPTURE_VERBOSE
3604 ws_debug("capture_loop_dispatch: from capture pipe");
3605 #endif
3606 #ifdef _WIN32
3607 if (pcap_src->from_cap_socket) {
3608 #endif
3609 sel_ret = cap_pipe_select(pcap_src->cap_pipe_fd);
3610 if (sel_ret <= 0) {
3611 if (sel_ret < 0 && errno != EINTR) {
3612 snprintf(errmsg, errmsg_len,
3613 "Unexpected error from select: %s", g_strerror(errno));
3614 report_capture_error(errmsg, please_report_bug());
3615 ld->go = FALSE;
3618 #ifdef _WIN32
3619 } else {
3620 /* Windows does not have select() for pipes. */
3621 /* Proceed with _dispatch() which waits for cap_pipe_done_q
3622 * notification from cap_thread_read() when ReadFile() on
3623 * the pipe has read enough bytes. */
3624 sel_ret = 1;
3626 #endif
3627 if (sel_ret > 0) {
3629 * "select()" says we can read from the pipe without blocking
3631 inpkts = pcap_src->cap_pipe_dispatch(ld, pcap_src, errmsg, errmsg_len);
3632 if (inpkts < 0) {
3633 ws_debug("%s: src %u pipe reached EOF or err, rcv: %u drop: %u flush: %u",
3634 G_STRFUNC, pcap_src->interface_id, pcap_src->received, pcap_src->dropped, pcap_src->flushed);
3635 ws_assert(pcap_src->cap_pipe_err != PIPOK);
3639 else
3641 /* dispatch from pcap */
3642 #ifdef MUST_DO_SELECT
3644 * If we have "pcap_get_selectable_fd()", we use it to get the
3645 * descriptor on which to select; if that's -1, it means there
3646 * is no descriptor on which you can do a "select()" (perhaps
3647 * because you're capturing on a special device, and that device's
3648 * driver unfortunately doesn't support "select()", in which case
3649 * we don't do the select - which means it might not be possible
3650 * to stop a capture until a packet arrives. If that's unacceptable,
3651 * plead with whoever supplies the software for that device to add
3652 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3653 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3654 * later, so it can use pcap_breakloop().
3656 #ifdef LOG_CAPTURE_VERBOSE
3657 ws_debug("capture_loop_dispatch: from pcap_dispatch with select");
3658 #endif
3659 if (pcap_src->pcap_fd != -1) {
3660 sel_ret = cap_pipe_select(pcap_src->pcap_fd);
3661 if (sel_ret > 0) {
3663 * "select()" says we can read from it without blocking; go for
3664 * it.
3666 * We don't have pcap_breakloop(), so we only process one packet
3667 * per pcap_dispatch() call, to allow a signal to stop the
3668 * processing immediately, rather than processing all packets
3669 * in a batch before quitting.
3671 if (use_threads) {
3672 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3673 } else {
3674 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3676 if (inpkts < 0) {
3677 if (inpkts == -1) {
3678 /* Error, rather than pcap_breakloop(). */
3679 pcap_src->pcap_err = TRUE;
3681 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3683 } else {
3684 if (sel_ret < 0 && errno != EINTR) {
3685 snprintf(errmsg, errmsg_len,
3686 "Unexpected error from select: %s", g_strerror(errno));
3687 report_capture_error(errmsg, please_report_bug());
3688 ld->go = FALSE;
3692 else
3693 #endif /* MUST_DO_SELECT */
3695 /* dispatch from pcap without select */
3696 #if 1
3697 #ifdef LOG_CAPTURE_VERBOSE
3698 ws_debug("capture_loop_dispatch: from pcap_dispatch");
3699 #endif
3700 #ifdef _WIN32
3702 * On Windows, we don't support asynchronously telling a process to
3703 * stop capturing; instead, we check for an indication on a pipe
3704 * after processing packets. We therefore process only one packet
3705 * at a time, so that we can check the pipe after every packet.
3707 if (use_threads) {
3708 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3709 } else {
3710 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3712 #else
3713 if (use_threads) {
3714 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3715 } else {
3716 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3718 #endif
3719 if (inpkts < 0) {
3720 if (inpkts == -1) {
3721 /* Error, rather than pcap_breakloop(). */
3722 pcap_src->pcap_err = TRUE;
3724 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3726 #else /* pcap_next_ex */
3727 #ifdef LOG_CAPTURE_VERBOSE
3728 ws_debug("capture_loop_dispatch: from pcap_next_ex");
3729 #endif
3730 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3733 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3734 * see https://gitlab.com/wireshark/wireshark/-/wikis/CaptureSetup/WinPcapRemote
3735 * This should be fixed in the WinPcap 4.0 alpha release.
3737 * For reference, an example remote interface:
3738 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3741 /* emulate dispatch from pcap */
3743 int in;
3744 struct pcap_pkthdr *pkt_header;
3745 u_char *pkt_data;
3747 in = 0;
3748 while(ld->go &&
3749 (in = pcap_next_ex(pcap_src->pcap_h, &pkt_header, &pkt_data)) == 1) {
3750 if (use_threads) {
3751 capture_loop_queue_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
3752 } else {
3753 capture_loop_write_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
3757 if (in < 0) {
3758 pcap_src->pcap_err = TRUE;
3759 ld->go = FALSE;
3762 #endif /* pcap_next_ex */
3766 #ifdef LOG_CAPTURE_VERBOSE
3767 ws_debug("capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3768 #endif
3770 return ld->packets_captured - packet_count_before;
3773 #ifdef _WIN32
3774 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3775 * want to grab only the characters between the '{' and '}' delimiters.
3777 * Returns a GString that must be freed with g_string_free(). */
3778 static GString *
3779 isolate_uuid(const char *iface)
3781 gchar *ptr;
3782 GString *gstr;
3784 ptr = strchr(iface, '{');
3785 if (ptr == NULL)
3786 return g_string_new(iface);
3787 gstr = g_string_new(ptr + 1);
3789 ptr = strchr(gstr->str, '}');
3790 if (ptr == NULL)
3791 return gstr;
3793 gstr = g_string_truncate(gstr, ptr - gstr->str);
3794 return gstr;
3796 #endif
3798 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3799 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3800 static gboolean
3801 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3802 char *errmsg, int errmsg_len)
3804 gchar *capfile_name = NULL;
3805 gchar *prefix, *suffix;
3806 gboolean is_tempfile;
3807 GError *err_tempfile = NULL;
3809 ws_debug("capture_loop_open_output: %s",
3810 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3812 if (capture_opts->save_file != NULL) {
3813 /* We return to the caller while the capture is in progress.
3814 * Therefore we need to take a copy of save_file in
3815 * case the caller destroys it after we return.
3817 capfile_name = g_strdup(capture_opts->save_file);
3819 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3820 if (capture_opts->multi_files_on) {
3821 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3822 snprintf(errmsg, errmsg_len,
3823 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3824 g_free(capfile_name);
3825 return FALSE;
3827 if (strcmp(capfile_name, "-") == 0) {
3828 /* write to stdout */
3829 *save_file_fd = 1;
3830 #ifdef _WIN32
3831 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3832 _setmode(1, O_BINARY);
3833 #endif
3834 } else {
3835 /* Try to open the specified FIFO for use as a capture buffer.
3836 Do *not* create it if it doesn't exist. There's nothing
3837 to truncate. If we need to read it, We Have A Problem. */
3838 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY, 0);
3840 } /* if (...output_to_pipe ... */
3842 else {
3843 if (capture_opts->multi_files_on) {
3844 /* ringbuffer is enabled */
3845 *save_file_fd = ringbuf_init(capfile_name,
3846 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3847 capture_opts->group_read_access,
3848 capture_opts->compress_type,
3849 capture_opts->has_nametimenum);
3851 /* capfile_name is unused as the ringbuffer provides its own filename. */
3852 if (*save_file_fd != -1) {
3853 g_free(capfile_name);
3854 capfile_name = NULL;
3856 if (capture_opts->print_file_names) {
3857 if (!ringbuf_set_print_name(capture_opts->print_name_to, NULL)) {
3858 snprintf(errmsg, errmsg_len, "Could not write filenames to %s: %s.\n",
3859 capture_opts->print_name_to,
3860 g_strerror(errno));
3861 g_free(capfile_name);
3862 ringbuf_error_cleanup();
3863 return FALSE;
3866 } else {
3867 /* Try to open/create the specified file for use as a capture buffer. */
3868 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY|O_TRUNC|O_CREAT,
3869 (capture_opts->group_read_access) ? 0640 : 0600);
3872 is_tempfile = FALSE;
3873 } else {
3874 /* Choose a random name for the temporary capture buffer */
3875 if (global_capture_opts.ifaces->len > 1) {
3877 * More than one interface; just use the number of interfaces
3878 * to generate the temporary file name prefix.
3880 prefix = ws_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3881 } else {
3883 * One interface; use its description, if it has one, to generate
3884 * the temporary file name, otherwise use its name.
3886 gchar *basename;
3887 const interface_options *interface_opts;
3889 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
3892 * Do we have a description?
3894 if (interface_opts->descr) {
3896 * Yes - use it.
3898 * Strip off any stuff we shouldn't use in the file name,
3899 * by getting the last component of what would be a file
3900 * name.
3902 basename = g_path_get_basename(interface_opts->descr);
3903 } else {
3905 * No - use the name.
3907 * Strip off any stuff we shouldn't use in the file name,
3908 * by getting the last component of what would be a file
3909 * name.
3911 basename = g_path_get_basename(interface_opts->name);
3912 #ifdef _WIN32
3914 * This is Windows, where we might have an ugly GUID-based
3915 * interface name.
3917 * If it's an ugly GUID-based name, use the generic portion
3918 * of the interface GUID to form the basis of the filename.
3920 if (strncmp("NPF_{", basename, 5) == 0) {
3922 * We have a GUID-based name; extract the GUID digits
3923 * as the basis of the filename.
3925 GString *iface;
3926 iface = isolate_uuid(basename);
3927 g_free(basename);
3928 basename = g_strdup(iface->str);
3929 g_string_free(iface, TRUE);
3931 #endif
3933 /* generate the temp file name prefix */
3934 prefix = g_strconcat("wireshark_", basename, NULL);
3935 g_free(basename);
3938 /* Generate the appropriate suffix. */
3939 if (capture_opts->use_pcapng) {
3940 suffix = ".pcapng";
3941 } else {
3942 suffix = ".pcap";
3944 *save_file_fd = create_tempfile(capture_opts->temp_dir, &capfile_name, prefix, suffix, &err_tempfile);
3945 g_free(prefix);
3946 is_tempfile = TRUE;
3949 /* did we fail to open the output file? */
3950 if (*save_file_fd == -1) {
3951 if (is_tempfile) {
3952 snprintf(errmsg, errmsg_len,
3953 "The temporary file to which the capture would be saved "
3954 "could not be opened: %s.", err_tempfile->message);
3955 g_error_free(err_tempfile);
3956 } else {
3957 if (capture_opts->multi_files_on) {
3958 /* Ensures that the ringbuffer is not used. This ensures that
3959 * !ringbuf_is_initialized() is equivalent to
3960 * capture_opts->save_file not being part of ringbuffer. */
3961 ringbuf_error_cleanup();
3964 snprintf(errmsg, errmsg_len,
3965 "The file to which the capture would be saved (\"%s\") "
3966 "could not be opened: %s.", capfile_name,
3967 g_strerror(errno));
3969 g_free(capfile_name);
3970 return FALSE;
3973 g_free(capture_opts->save_file);
3974 if (!is_tempfile && capture_opts->multi_files_on) {
3975 /* In ringbuffer mode, save_file points to a filename from ringbuffer.c.
3976 * capfile_name was already freed before. */
3977 capture_opts->save_file = (char *)ringbuf_current_filename();
3978 } else {
3979 /* capture_opts_cleanup will g_free(capture_opts->save_file). */
3980 capture_opts->save_file = capfile_name;
3983 return TRUE;
3986 static time_t get_next_time_interval(int interval_s) {
3987 time_t next_time = time(NULL);
3988 next_time -= next_time % interval_s;
3989 next_time += interval_s;
3990 return next_time;
3993 /* Do the work of handling either the file size or file duration capture
3994 conditions being reached, and switching files or stopping. */
3995 static gboolean
3996 do_file_switch_or_stop(capture_options *capture_opts)
3998 gboolean successful;
4000 if (capture_opts->multi_files_on) {
4001 if (capture_opts->has_autostop_files &&
4002 ++global_ld.file_count >= capture_opts->autostop_files) {
4003 /* no files left: stop here */
4004 global_ld.go = FALSE;
4005 return FALSE;
4008 /* Switch to the next ringbuffer file */
4009 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
4010 &global_ld.save_file_fd, &global_ld.err)) {
4012 /* File switch succeeded: reset the conditions */
4013 global_ld.bytes_written = 0;
4014 global_ld.packets_written = 0;
4015 if (capture_opts->use_pcapng) {
4016 successful = capture_loop_init_pcapng_output(capture_opts, &global_ld, &global_ld.err);
4017 } else {
4018 capture_src *pcap_src;
4019 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
4020 successful = libpcap_write_file_header(global_ld.pdh, pcap_src->linktype, pcap_src->snaplen,
4021 pcap_src->ts_nsec, &global_ld.bytes_written, &global_ld.err);
4024 if (!successful) {
4025 fclose(global_ld.pdh);
4026 global_ld.pdh = NULL;
4027 global_ld.go = FALSE;
4028 g_free(global_ld.io_buffer);
4029 global_ld.io_buffer = NULL;
4030 return FALSE;
4032 if (global_ld.file_duration_timer) {
4033 g_timer_reset(global_ld.file_duration_timer);
4035 if (global_ld.next_interval_time) {
4036 global_ld.next_interval_time = get_next_time_interval(global_ld.interval_s);
4038 fflush(global_ld.pdh);
4039 if (global_ld.inpkts_to_sync_pipe) {
4040 if (!quiet)
4041 report_packet_count(global_ld.inpkts_to_sync_pipe);
4042 global_ld.inpkts_to_sync_pipe = 0;
4044 report_new_capture_file(capture_opts->save_file);
4045 } else {
4046 /* File switch failed: stop here */
4047 global_ld.go = FALSE;
4048 return FALSE;
4050 } else {
4051 /* single file, stop now */
4052 global_ld.go = FALSE;
4053 return FALSE;
4055 return TRUE;
4058 static void *
4059 pcap_read_handler(void* arg)
4061 capture_src *pcap_src = (capture_src *)arg;
4062 char errmsg[MSG_MAX_LENGTH+1];
4064 ws_info("Started thread for interface %d.", pcap_src->interface_id);
4066 /* If this is a pipe input it might finish early. */
4067 while (global_ld.go && pcap_src->cap_pipe_err == PIPOK) {
4068 /* dispatch incoming packets */
4069 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_src);
4072 ws_info("Stopped thread for interface %d.", pcap_src->interface_id);
4073 g_thread_exit(NULL);
4074 return (NULL);
4077 /* Try to pop an item off the packet queue and if it exists, write it */
4078 static gboolean
4079 capture_loop_dequeue_packet(void) {
4080 pcap_queue_element *queue_element;
4082 g_async_queue_lock(pcap_queue);
4083 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
4084 if (queue_element) {
4085 if (queue_element->pcap_src->from_pcapng) {
4086 pcap_queue_bytes -= queue_element->u.bh.block_total_length;
4087 } else {
4088 pcap_queue_bytes -= queue_element->u.phdr.caplen;
4090 pcap_queue_packets -= 1;
4092 g_async_queue_unlock(pcap_queue);
4093 if (queue_element) {
4094 if (queue_element->pcap_src->from_pcapng) {
4095 ws_info("Dequeued a block of type 0x%08x of length %d captured on interface %d.",
4096 queue_element->u.bh.block_type, queue_element->u.bh.block_total_length,
4097 queue_element->pcap_src->interface_id);
4099 capture_loop_write_pcapng_cb(queue_element->pcap_src,
4100 &queue_element->u.bh,
4101 queue_element->pd);
4102 } else {
4103 ws_info("Dequeued a packet of length %d captured on interface %d.",
4104 queue_element->u.phdr.caplen, queue_element->pcap_src->interface_id);
4106 capture_loop_write_packet_cb((u_char *) queue_element->pcap_src,
4107 &queue_element->u.phdr,
4108 queue_element->pd);
4110 g_free(queue_element->pd);
4111 g_free(queue_element);
4112 return TRUE;
4114 return FALSE;
4118 * Note: this code will never be run on any OS other than Windows.
4120 * We keep the arguments in case there's something in the future
4121 * that needs to be reported as an NPCAP bug.
4123 static char *
4124 handle_npcap_bug(char *adapter_name _U_, char *cap_err_str _U_)
4126 gboolean have_npcap = FALSE;
4128 #ifdef _WIN32
4129 have_npcap = caplibs_have_npcap();
4130 #endif
4132 if (!have_npcap) {
4134 * We're not using Npcap, so don't recomment a user
4135 * file a bug against Npcap.
4137 return g_strdup("");
4140 return ws_strdup_printf("If you have not removed that adapter, this "
4141 "is probably a known issue in Npcap resulting from "
4142 "the behavior of the Windows networking stack. "
4143 "Work is being done in Npcap to improve the "
4144 "handling of this issue; it does not need to "
4145 "be reported as a Wireshark or Npcap bug.");
4148 /* Do the low-level work of a capture.
4149 Returns TRUE if it succeeds, FALSE otherwise. */
4150 static gboolean
4151 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
4153 #ifdef _WIN32
4154 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
4155 #else
4156 struct timeval upd_time, cur_time;
4157 #endif
4158 int err_close;
4159 int inpkts;
4160 GTimer *autostop_duration_timer = NULL;
4161 gboolean write_ok;
4162 gboolean close_ok;
4163 gboolean cfilter_error = FALSE;
4164 char errmsg[MSG_MAX_LENGTH+1];
4165 char secondary_errmsg[MSG_MAX_LENGTH+1];
4166 capture_src *pcap_src;
4167 interface_options *interface_opts;
4168 guint i, error_index = 0;
4170 *errmsg = '\0';
4171 *secondary_errmsg = '\0';
4173 /* init the loop data */
4174 global_ld.go = TRUE;
4175 global_ld.packets_captured = 0;
4176 #ifdef SIGINFO
4177 global_ld.report_packet_count = FALSE;
4178 #endif
4179 global_ld.inpkts_to_sync_pipe = 0;
4180 global_ld.err = 0; /* no error seen yet */
4181 global_ld.pdh = NULL;
4182 global_ld.save_file_fd = -1;
4183 global_ld.io_buffer = NULL;
4184 global_ld.file_count = 0;
4185 global_ld.file_duration_timer = NULL;
4186 global_ld.next_interval_time = 0;
4187 global_ld.interval_s = 0;
4189 /* We haven't yet gotten the capture statistics. */
4190 *stats_known = FALSE;
4192 ws_info("Capture loop starting ...");
4193 capture_opts_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_DEBUG, capture_opts);
4195 /* open the "input file" from network interface or capture pipe */
4196 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
4197 secondary_errmsg, sizeof(secondary_errmsg))) {
4198 goto error;
4200 for (i = 0; i < capture_opts->ifaces->len; i++) {
4201 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4202 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
4203 /* init the input filter from the network interface (capture pipe will do nothing) */
4205 * When remote capturing WinPCap crashes when the capture filter
4206 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
4207 * string.
4209 switch (capture_loop_init_filter(pcap_src->pcap_h, pcap_src->from_cap_pipe,
4210 interface_opts->name,
4211 interface_opts->cfilter?interface_opts->cfilter:"")) {
4213 case INITFILTER_NO_ERROR:
4214 break;
4216 case INITFILTER_BAD_FILTER:
4217 cfilter_error = TRUE;
4218 error_index = i;
4219 snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_src->pcap_h));
4220 goto error;
4222 case INITFILTER_OTHER_ERROR:
4223 snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
4224 pcap_geterr(pcap_src->pcap_h));
4225 snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report_bug());
4226 goto error;
4230 /* If we're supposed to write to a capture file, open it for output
4231 (temporary/specified name/ringbuffer) */
4232 if (capture_opts->saving_to_file) {
4233 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
4234 errmsg, sizeof(errmsg))) {
4235 goto error;
4238 /* set up to write to the already-opened capture output file/files */
4239 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
4240 sizeof(errmsg))) {
4241 goto error;
4244 /* XXX - capture SIGTERM and close the capture, in case we're on a
4245 Linux 2.0[.x] system and you have to explicitly close the capture
4246 stream in order to turn promiscuous mode off? We need to do that
4247 in other places as well - and I don't think that works all the
4248 time in any case, due to libpcap bugs. */
4250 /* Well, we should be able to start capturing.
4252 Sync out the capture file, so the header makes it to the file system,
4253 and send a "capture started successfully and capture file created"
4254 message to our parent so that they'll open the capture file and
4255 update its windows to indicate that we have a live capture in
4256 progress. */
4257 fflush(global_ld.pdh);
4258 report_new_capture_file(capture_opts->save_file);
4261 if (capture_opts->has_file_interval) {
4262 global_ld.interval_s = capture_opts->file_interval;
4263 global_ld.next_interval_time = get_next_time_interval(global_ld.interval_s);
4265 /* create stop conditions */
4266 if (capture_opts->has_autostop_filesize) {
4267 if (capture_opts->autostop_filesize > UINT32_C(2000000000)) {
4268 capture_opts->autostop_filesize = UINT32_C(2000000000);
4271 if (capture_opts->has_autostop_duration) {
4272 autostop_duration_timer = g_timer_new();
4275 if (capture_opts->multi_files_on) {
4276 if (capture_opts->has_file_duration) {
4277 global_ld.file_duration_timer = g_timer_new();
4281 /* init the time values */
4282 #ifdef _WIN32
4283 upd_time = GetTickCount();
4284 #else
4285 gettimeofday(&upd_time, NULL);
4286 #endif
4287 start_time = create_timestamp();
4288 ws_info("Capture loop running.");
4289 capture_opts_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_DEBUG, capture_opts);
4291 /* WOW, everything is prepared! */
4292 /* please fasten your seat belts, we will enter now the actual capture loop */
4293 if (use_threads) {
4294 pcap_queue = g_async_queue_new();
4295 pcap_queue_bytes = 0;
4296 pcap_queue_packets = 0;
4297 for (i = 0; i < global_ld.pcaps->len; i++) {
4298 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4299 /* XXX - Add an interface name here? */
4300 pcap_src->tid = g_thread_new("Capture read", pcap_read_handler, pcap_src);
4303 while (global_ld.go) {
4304 /* dispatch incoming packets */
4305 if (use_threads) {
4306 gboolean dequeued = capture_loop_dequeue_packet();
4308 if (dequeued) {
4309 inpkts = 1;
4310 } else {
4311 inpkts = 0;
4313 } else {
4314 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
4315 inpkts = capture_loop_dispatch(&global_ld, errmsg,
4316 sizeof(errmsg), pcap_src);
4318 if (inpkts == 0) {
4319 /* Stop capturing if all of our sources are pipes and none of them are open. */
4320 gboolean open_interfaces = FALSE;
4321 for (i = 0; i < global_ld.pcaps->len; i++) {
4322 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4323 if (pcap_src->cap_pipe_err == PIPOK) {
4324 /* True for both non-pipes and open pipes. */
4325 open_interfaces = TRUE;
4328 if (!open_interfaces) {
4329 global_ld.go = FALSE;
4332 #ifdef SIGINFO
4333 /* Were we asked to print packet counts by the SIGINFO handler? */
4334 if (global_ld.report_packet_count) {
4335 fprintf(stderr, "%u packet%s captured\n", global_ld.packets_captured,
4336 plurality(global_ld.packets_captured, "", "s"));
4337 global_ld.report_packet_count = FALSE;
4339 #endif
4341 #ifdef _WIN32
4342 /* any news from our parent (signal pipe)? -> just stop the capture */
4343 if (!signal_pipe_check_running()) {
4344 global_ld.go = FALSE;
4346 #endif
4348 if (inpkts > 0) {
4349 if (capture_opts->output_to_pipe) {
4350 fflush(global_ld.pdh);
4352 } /* inpkts */
4354 /* Only update after an interval so as not to overload slow displays.
4355 * This also prevents too much context-switching between the dumpcap
4356 * and wireshark processes.
4357 * XXX: Should we send updates sooner if there have been lots of
4358 * packets we haven't notified the parent about, such as on fast links?
4360 #ifdef _WIN32
4361 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
4362 if ((cur_time - upd_time) > capture_opts->update_interval) /* wrap just causes an extra update */
4363 #else
4364 gettimeofday(&cur_time, NULL);
4365 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
4366 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + capture_opts->update_interval*1000))
4367 #endif
4370 upd_time = cur_time;
4372 #if 0
4373 if (pcap_stats(pch, stats) >= 0) {
4374 *stats_known = TRUE;
4376 #endif
4377 /* Let the parent process know. */
4378 if (global_ld.inpkts_to_sync_pipe) {
4379 /* do sync here */
4380 fflush(global_ld.pdh);
4382 /* Send our parent a message saying we've written out
4383 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
4384 if (!quiet)
4385 report_packet_count(global_ld.inpkts_to_sync_pipe);
4387 global_ld.inpkts_to_sync_pipe = 0;
4390 /* check capture duration condition */
4391 if (autostop_duration_timer != NULL && g_timer_elapsed(autostop_duration_timer, NULL) >= capture_opts->autostop_duration) {
4392 /* The maximum capture time has elapsed; stop the capture. */
4393 global_ld.go = FALSE;
4394 continue;
4397 /* check capture file duration condition */
4398 if (global_ld.file_duration_timer != NULL && g_timer_elapsed(global_ld.file_duration_timer, NULL) >= capture_opts->file_duration) {
4399 /* duration limit reached, do we have another file? */
4400 if (!do_file_switch_or_stop(capture_opts))
4401 continue;
4402 } /* cnd_file_duration */
4404 /* check capture file interval condition */
4405 if (global_ld.interval_s && time(NULL) >= global_ld.next_interval_time) {
4406 /* end of interval reached, do we have another file? */
4407 if (!do_file_switch_or_stop(capture_opts))
4408 continue;
4409 } /* cnd_file_interval */
4413 ws_info("Capture loop stopping ...");
4414 if (use_threads) {
4416 for (i = 0; i < global_ld.pcaps->len; i++) {
4417 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4418 ws_info("Waiting for thread of interface %u...", pcap_src->interface_id);
4419 g_thread_join(pcap_src->tid);
4420 ws_info("Thread of interface %u terminated.", pcap_src->interface_id);
4422 while (1) {
4423 gboolean dequeued = capture_loop_dequeue_packet();
4424 if (!dequeued) {
4425 break;
4427 if (capture_opts->output_to_pipe) {
4428 fflush(global_ld.pdh);
4434 /* delete stop conditions */
4435 if (global_ld.file_duration_timer != NULL)
4436 g_timer_destroy(global_ld.file_duration_timer);
4437 if (autostop_duration_timer != NULL)
4438 g_timer_destroy(autostop_duration_timer);
4440 /* did we have a pcap (input) error? */
4441 for (i = 0; i < capture_opts->ifaces->len; i++) {
4442 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4443 if (pcap_src->pcap_err) {
4444 /* On Linux, if an interface goes down while you're capturing on it,
4445 you'll get "recvfrom: Network is down".
4446 (At least you will if g_strerror() doesn't show a local translation
4447 of the error.)
4449 Newer versions of libpcap maps that to just
4450 "The interface went down".
4452 On FreeBSD, DragonFly BSD, and macOS, if a network adapter
4453 disappears while you're capturing on it, you'll get
4454 "read: Device not configured" error (ENXIO). (See previous
4455 parenthetical note.)
4457 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
4459 With WinPcap and Npcap, you'll get
4460 "read error: PacketReceivePacket failed" or
4461 "PacketReceivePacket error: The device has been removed. (1617)".
4463 Newer versions of libpcap map some or all of those to just
4464 "The interface disappeared" or something beginning with
4465 "The interface disappeared".
4467 These should *not* be reported to the Wireshark developers,
4468 although, with Npcap, "The interface disappeared" messages
4469 should perhaps be reported to the Npcap developers, at least
4470 until errors of that sort that shouldn't happen are fixed,
4471 if that's possible. */
4472 char *cap_err_str;
4473 char *primary_msg;
4474 char *secondary_msg;
4476 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
4477 cap_err_str = pcap_geterr(pcap_src->pcap_h);
4478 if (strcmp(cap_err_str, "The interface went down") == 0 ||
4479 strcmp(cap_err_str, "recvfrom: Network is down") == 0) {
4480 primary_msg = ws_strdup_printf("The network adapter \"%s\" "
4481 "is no longer running; the "
4482 "capture has stopped.",
4483 interface_opts->display_name);
4484 secondary_msg = g_strdup("");
4485 } else if (strcmp(cap_err_str, "The interface disappeared") == 0 ||
4486 strcmp(cap_err_str, "read: Device not configured") == 0 ||
4487 strcmp(cap_err_str, "read: I/O error") == 0 ||
4488 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
4489 primary_msg = ws_strdup_printf("The network adapter \"%s\" "
4490 "is no longer attached; the "
4491 "capture has stopped.",
4492 interface_opts->display_name);
4493 secondary_msg = g_strdup("");
4494 } else if (g_str_has_prefix(cap_err_str, "The interface disappeared ")) {
4496 * Npcap, if it picks up a recent commit to libpcap, will
4497 * report an error *beginning* with "The interface
4498 * disappeared", with the name of the Windows status code,
4499 * and the corresponding NT status code, after it.
4501 * Those should be reported as Npcap issues.
4503 primary_msg = ws_strdup_printf("The network adapter \"%s\" "
4504 "is no longer attached; the "
4505 "capture has stopped.",
4506 interface_opts->display_name);
4507 secondary_msg = handle_npcap_bug(interface_opts->display_name,
4508 cap_err_str);
4509 } else if (g_str_has_prefix(cap_err_str, "PacketReceivePacket error:") &&
4510 g_str_has_suffix(cap_err_str, "(1617)")) {
4512 * "PacketReceivePacket error: {message in arbitrary language} (1617)",
4513 * which is ERROR_DEVICE_REMOVED.
4515 * Current libpcap/Npcap treat ERROR_GEN_FAILURE as
4516 * "the device is no longer attached"; users are also
4517 * getting ERROR_DEVICE_REMOVED.
4519 * For now, some users appear to be getg ERROR_DEVICE_REMOVED
4520 * in cases where the device *wasn't* removed, so tell
4521 * them to report this as an Npcap issue; I seem to
4522 * remember some discussion between Daniel and somebody
4523 * at Microsoft about the Windows 10 network stack setup/
4524 * teardown code being modified to try to prevent those
4525 * sort of problems popping up, but I can't find that
4526 * discussion.
4528 primary_msg = ws_strdup_printf("The network adapter \"%s\" "
4529 "is no longer attached; the "
4530 "capture has stopped.",
4531 interface_opts->display_name);
4532 secondary_msg = handle_npcap_bug(interface_opts->display_name,
4533 "The interface disappeared (error code ERROR_DEVICE_REMOVED/STATUS_DEVICE_REMOVED)");
4534 } else if (strcmp(cap_err_str, "The other host terminated the connection.") == 0 ||
4535 g_str_has_prefix(cap_err_str, "Is the server properly installed?")) {
4537 * Networking error for a remote capture.
4539 primary_msg = g_strdup(cap_err_str);
4540 secondary_msg = g_strdup("This may be a problem with the "
4541 "remote host on which you are "
4542 "capturing packets.");
4543 } else {
4544 primary_msg = ws_strdup_printf("Error while capturing packets: %s",
4545 cap_err_str);
4546 secondary_msg = g_strdup(please_report_bug());
4548 report_capture_error(primary_msg, secondary_msg);
4549 g_free(primary_msg);
4550 g_free(secondary_msg);
4551 break;
4552 } else if (pcap_src->from_cap_pipe && pcap_src->cap_pipe_err == PIPERR) {
4553 report_capture_error(errmsg, "");
4554 break;
4557 /* did we have an output error while capturing? */
4558 if (global_ld.err == 0) {
4559 write_ok = TRUE;
4560 } else {
4561 capture_loop_get_errmsg(errmsg, sizeof(errmsg), secondary_errmsg,
4562 sizeof(secondary_errmsg),
4563 capture_opts->save_file, global_ld.err, FALSE);
4564 report_capture_error(errmsg, secondary_errmsg);
4565 write_ok = FALSE;
4568 if (capture_opts->saving_to_file) {
4569 /* close the output file */
4570 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
4571 } else
4572 close_ok = TRUE;
4574 /* there might be packets not yet notified to the parent */
4575 /* (do this after closing the file, so all packets are already flushed) */
4576 if (global_ld.inpkts_to_sync_pipe) {
4577 if (!quiet)
4578 report_packet_count(global_ld.inpkts_to_sync_pipe);
4579 global_ld.inpkts_to_sync_pipe = 0;
4582 /* If we've displayed a message about a write error, there's no point
4583 in displaying another message about an error on close. */
4584 if (!close_ok && write_ok) {
4585 capture_loop_get_errmsg(errmsg, sizeof(errmsg), secondary_errmsg,
4586 sizeof(secondary_errmsg),
4587 capture_opts->save_file, err_close, TRUE);
4588 report_capture_error(errmsg, secondary_errmsg);
4592 * XXX We exhibit different behaviour between normal mode and sync mode
4593 * when the pipe is stdin and not already at EOF. If we're a child, the
4594 * parent's stdin isn't closed, so if the user starts another capture,
4595 * cap_pipe_open_live() will very likely not see the expected magic bytes and
4596 * will say "Unrecognized libpcap format". On the other hand, in normal
4597 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
4600 report_capture_count(TRUE);
4602 /* get packet drop statistics from pcap */
4603 for (i = 0; i < capture_opts->ifaces->len; i++) {
4604 guint32 received;
4605 guint32 pcap_dropped = 0;
4607 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4608 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
4609 received = pcap_src->received;
4610 if (pcap_src->pcap_h != NULL) {
4611 ws_assert(!pcap_src->from_cap_pipe);
4612 /* Get the capture statistics, so we know how many packets were dropped. */
4613 if (pcap_stats(pcap_src->pcap_h, stats) >= 0) {
4614 *stats_known = TRUE;
4615 /* Let the parent process know. */
4616 pcap_dropped += stats->ps_drop;
4617 } else {
4618 snprintf(errmsg, sizeof(errmsg),
4619 "Can't get packet-drop statistics: %s",
4620 pcap_geterr(pcap_src->pcap_h));
4621 report_capture_error(errmsg, please_report_bug());
4624 report_packet_drops(received, pcap_dropped, pcap_src->dropped, pcap_src->flushed, stats->ps_ifdrop, interface_opts->display_name);
4627 /* close the input file (pcap or capture pipe) */
4628 capture_loop_close_input(&global_ld);
4630 ws_info("Capture loop stopped.");
4632 /* ok, if the write and the close were successful. */
4633 return write_ok && close_ok;
4635 error:
4636 if (capture_opts->multi_files_on) {
4637 /* cleanup ringbuffer */
4638 ringbuf_error_cleanup();
4639 } else {
4640 /* We can't use the save file, and we have no FILE * for the stream
4641 to close in order to close it, so close the FD directly. */
4642 if (global_ld.save_file_fd != -1) {
4643 ws_close(global_ld.save_file_fd);
4646 /* We couldn't even start the capture, so get rid of the capture
4647 file. */
4648 if (capture_opts->save_file != NULL) {
4649 ws_unlink(capture_opts->save_file);
4652 if (cfilter_error)
4653 report_cfilter_error(capture_opts, error_index, errmsg);
4654 else
4655 report_capture_error(errmsg, secondary_errmsg);
4657 /* close the input file (pcap or cap_pipe) */
4658 capture_loop_close_input(&global_ld);
4660 ws_info("Capture loop stopped with error");
4662 return FALSE;
4666 static void
4667 capture_loop_stop(void)
4669 guint i;
4670 capture_src *pcap_src;
4672 for (i = 0; i < global_ld.pcaps->len; i++) {
4673 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4674 if (pcap_src->pcap_h != NULL)
4675 pcap_breakloop(pcap_src->pcap_h);
4677 global_ld.go = FALSE;
4681 static void
4682 capture_loop_get_errmsg(char *errmsg, size_t errmsglen, char *secondary_errmsg,
4683 size_t secondary_errmsglen, const char *fname,
4684 int err, gboolean is_close)
4686 static const char find_space[] =
4687 "You will need to free up space on that file system"
4688 " or put the capture file on a different file system.";
4690 switch (err) {
4692 case ENOSPC:
4693 snprintf(errmsg, errmsglen,
4694 "Not all the packets could be written to the file"
4695 " to which the capture was being saved\n"
4696 "(\"%s\") because there is no space left on the file system\n"
4697 "on which that file resides.",
4698 fname);
4699 snprintf(secondary_errmsg, secondary_errmsglen, "%s", find_space);
4700 break;
4702 #ifdef EDQUOT
4703 case EDQUOT:
4704 snprintf(errmsg, errmsglen,
4705 "Not all the packets could be written to the file"
4706 " to which the capture was being saved\n"
4707 "(\"%s\") because you are too close to, or over,"
4708 " your disk quota\n"
4709 "on the file system on which that file resides.",
4710 fname);
4711 snprintf(secondary_errmsg, secondary_errmsglen, "%s", find_space);
4712 break;
4713 #endif
4715 default:
4716 if (is_close) {
4717 snprintf(errmsg, errmsglen,
4718 "The file to which the capture was being saved\n"
4719 "(\"%s\") could not be closed: %s.",
4720 fname, g_strerror(err));
4721 } else {
4722 snprintf(errmsg, errmsglen,
4723 "An error occurred while writing to the file"
4724 " to which the capture was being saved\n"
4725 "(\"%s\"): %s.",
4726 fname, g_strerror(err));
4728 snprintf(secondary_errmsg, secondary_errmsglen,
4729 "%s", please_report_bug());
4730 break;
4735 * We wrote one packet. Update some statistics and check if we've met any
4736 * autostop or ring buffer conditions.
4738 static void
4739 capture_loop_wrote_one_packet(capture_src *pcap_src) {
4740 global_ld.packets_captured++;
4741 global_ld.packets_written++;
4742 global_ld.inpkts_to_sync_pipe++;
4744 if (!use_threads) {
4745 pcap_src->received++;
4748 /* check -c NUM */
4749 if (global_capture_opts.has_autostop_packets && global_ld.packets_captured >= global_capture_opts.autostop_packets) {
4750 fflush(global_ld.pdh);
4751 global_ld.go = FALSE;
4752 return;
4754 /* check -a packets:NUM (treat like -c NUM) */
4755 if (global_capture_opts.has_autostop_written_packets && global_ld.packets_captured >= global_capture_opts.autostop_written_packets) {
4756 fflush(global_ld.pdh);
4757 global_ld.go = FALSE;
4758 return;
4760 /* check -b packets:NUM */
4761 if (global_capture_opts.has_file_packets && global_ld.packets_written >= global_capture_opts.file_packets) {
4762 do_file_switch_or_stop(&global_capture_opts);
4763 return;
4765 /* check -a filesize:NUM */
4766 if (global_capture_opts.has_autostop_filesize &&
4767 global_capture_opts.autostop_filesize > 0 &&
4768 global_ld.bytes_written / 1000 >= global_capture_opts.autostop_filesize) {
4769 /* Capture size limit reached, do we have another file? */
4770 do_file_switch_or_stop(&global_capture_opts);
4771 return;
4775 /* one pcapng block was captured, process it */
4776 static void
4777 capture_loop_write_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd)
4779 int err;
4782 * This should never be called if we're not writing pcapng.
4784 ws_assert(global_capture_opts.use_pcapng);
4786 /* We may be called multiple times from pcap_dispatch(); if we've set
4787 the "stop capturing" flag, ignore this packet, as we're not
4788 supposed to be saving any more packets. */
4789 if (!global_ld.go) {
4790 pcap_src->flushed++;
4791 return;
4794 if (!pcapng_adjust_block(pcap_src, bh, pd)) {
4795 ws_info("%s failed to adjust pcapng block.", G_STRFUNC);
4796 ws_assert_not_reached();
4797 return;
4800 if (bh->block_type == BLOCK_TYPE_SHB && !global_ld.pcapng_passthrough) {
4802 * capture_loop_init_pcapng_output should've handled this. We need
4803 * to write ISBs when they're initially read so we shouldn't skip
4804 * them here.
4806 return;
4809 if (global_ld.pdh) {
4810 gboolean successful;
4812 /* We're supposed to write the packet to a file; do so.
4813 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4814 "ld->err" to the error. */
4815 successful = pcapng_write_block(global_ld.pdh,
4817 bh->block_total_length,
4818 &global_ld.bytes_written, &err);
4820 fflush(global_ld.pdh);
4821 if (!successful) {
4822 global_ld.go = FALSE;
4823 global_ld.err = err;
4824 pcap_src->dropped++;
4825 } else if (is_data_block(bh->block_type)) {
4826 /* Count packets for block types that should be dissected, i.e. ones that show up in the packet list. */
4827 ws_debug("Wrote a pcapng block type 0x%04x of length %d captured on interface %u.",
4828 bh->block_type, bh->block_total_length, pcap_src->interface_id);
4829 capture_loop_wrote_one_packet(pcap_src);
4830 } else if (bh->block_type == BLOCK_TYPE_SHB && report_capture_filename) {
4831 ws_debug("Sending SP_FILE on first SHB");
4832 /* SHB is now ready for capture parent to read on SP_FILE message */
4833 sync_pipe_write_string_msg(sync_pipe_fd, SP_FILE, report_capture_filename);
4834 report_capture_filename = NULL;
4839 /* one pcap packet was captured, process it */
4840 static void
4841 capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
4842 const u_char *pd)
4844 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4845 int err;
4846 guint ts_mul = pcap_src->ts_nsec ? 1000000000 : 1000000;
4848 ws_debug("capture_loop_write_packet_cb");
4850 /* We may be called multiple times from pcap_dispatch(); if we've set
4851 the "stop capturing" flag, ignore this packet, as we're not
4852 supposed to be saving any more packets. */
4853 if (!global_ld.go) {
4854 pcap_src->flushed++;
4855 return;
4858 if (global_ld.pdh) {
4859 gboolean successful;
4861 /* We're supposed to write the packet to a file; do so.
4862 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4863 "ld->err" to the error. */
4864 if (global_capture_opts.use_pcapng) {
4865 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
4866 NULL,
4867 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4868 phdr->caplen, phdr->len,
4869 pcap_src->idb_id,
4870 ts_mul,
4871 pd, 0,
4872 &global_ld.bytes_written, &err);
4873 } else {
4874 successful = libpcap_write_packet(global_ld.pdh,
4875 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4876 phdr->caplen, phdr->len,
4878 &global_ld.bytes_written, &err);
4880 if (!successful) {
4881 global_ld.go = FALSE;
4882 global_ld.err = err;
4883 pcap_src->dropped++;
4884 } else {
4885 ws_debug("Wrote a pcap packet of length %d captured on interface %u.",
4886 phdr->caplen, pcap_src->interface_id);
4887 capture_loop_wrote_one_packet(pcap_src);
4892 /* one packet was captured, queue it */
4893 static void
4894 capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
4895 const u_char *pd)
4897 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4898 pcap_queue_element *queue_element;
4899 gboolean limit_reached;
4901 /* We may be called multiple times from pcap_dispatch(); if we've set
4902 the "stop capturing" flag, ignore this packet, as we're not
4903 supposed to be saving any more packets. */
4904 if (!global_ld.go) {
4905 pcap_src->flushed++;
4906 return;
4909 queue_element = g_new(pcap_queue_element, 1);
4910 if (queue_element == NULL) {
4911 pcap_src->dropped++;
4912 return;
4914 queue_element->pcap_src = pcap_src;
4915 queue_element->u.phdr = *phdr;
4916 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4917 if (queue_element->pd == NULL) {
4918 pcap_src->dropped++;
4919 g_free(queue_element);
4920 return;
4922 memcpy(queue_element->pd, pd, phdr->caplen);
4923 g_async_queue_lock(pcap_queue);
4924 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4925 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4926 limit_reached = FALSE;
4927 g_async_queue_push_unlocked(pcap_queue, queue_element);
4928 pcap_queue_bytes += phdr->caplen;
4929 pcap_queue_packets += 1;
4930 } else {
4931 limit_reached = TRUE;
4933 g_async_queue_unlock(pcap_queue);
4934 if (limit_reached) {
4935 pcap_src->dropped++;
4936 g_free(queue_element->pd);
4937 g_free(queue_element);
4938 ws_info("Dropped a packet of length %d captured on interface %u.",
4939 phdr->caplen, pcap_src->interface_id);
4940 } else {
4941 pcap_src->received++;
4942 ws_info("Queued a packet of length %d captured on interface %u.",
4943 phdr->caplen, pcap_src->interface_id);
4945 /* I don't want to hold the mutex over the debug output. So the
4946 output may be wrong */
4947 ws_info("Queue size is now %" PRId64 " bytes (%" PRId64 " packets)",
4948 pcap_queue_bytes, pcap_queue_packets);
4951 /* one pcapng block was captured, queue it */
4952 static void
4953 capture_loop_queue_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd)
4955 pcap_queue_element *queue_element;
4956 gboolean limit_reached;
4958 /* We may be called multiple times from pcap_dispatch(); if we've set
4959 the "stop capturing" flag, ignore this packet, as we're not
4960 supposed to be saving any more packets. */
4961 if (!global_ld.go) {
4962 pcap_src->flushed++;
4963 return;
4966 queue_element = g_new(pcap_queue_element, 1);
4967 if (queue_element == NULL) {
4968 pcap_src->dropped++;
4969 return;
4971 queue_element->pcap_src = pcap_src;
4972 queue_element->u.bh = *bh;
4973 queue_element->pd = (u_char *)g_malloc(bh->block_total_length);
4974 if (queue_element->pd == NULL) {
4975 pcap_src->dropped++;
4976 g_free(queue_element);
4977 return;
4979 memcpy(queue_element->pd, pd, bh->block_total_length);
4980 g_async_queue_lock(pcap_queue);
4981 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4982 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4983 limit_reached = FALSE;
4984 g_async_queue_push_unlocked(pcap_queue, queue_element);
4985 pcap_queue_bytes += bh->block_total_length;
4986 pcap_queue_packets += 1;
4987 } else {
4988 limit_reached = TRUE;
4990 g_async_queue_unlock(pcap_queue);
4991 if (limit_reached) {
4992 pcap_src->dropped++;
4993 g_free(queue_element->pd);
4994 g_free(queue_element);
4995 ws_info("Dropped a packet of length %d captured on interface %u.",
4996 bh->block_total_length, pcap_src->interface_id);
4997 } else {
4998 pcap_src->received++;
4999 ws_info("Queued a block of type 0x%08x of length %d captured on interface %u.",
5000 bh->block_type, bh->block_total_length, pcap_src->interface_id);
5002 /* I don't want to hold the mutex over the debug output. So the
5003 output may be wrong */
5004 ws_info("Queue size is now %" PRId64 " bytes (%" PRId64 " packets)",
5005 pcap_queue_bytes, pcap_queue_packets);
5008 static int
5009 set_80211_channel(const char *iface, const char *opt)
5011 guint32 freq = 0;
5012 int type = -1;
5013 guint32 center_freq1 = 0;
5014 guint32 center_freq2 = 0;
5015 int args;
5016 int ret = 0;
5017 gchar **options = NULL;
5019 options = g_strsplit_set(opt, ",", 4);
5020 for (args = 0; options[args]; args++)
5023 ret = ws80211_init();
5024 if (ret != WS80211_INIT_OK) {
5025 if (ret == WS80211_INIT_NOT_SUPPORTED)
5026 cmdarg_err("Setting 802.11 channels is not supported on this platform");
5027 else
5028 cmdarg_err("Failed to init ws80211: %s", g_strerror(abs(ret)));
5029 ret = 2;
5030 goto out;
5033 if (options[0])
5034 freq = get_nonzero_guint32(options[0], "802.11 channel frequency");
5036 if (args >= 1 && options[1]) {
5037 type = ws80211_str_to_chan_type(options[1]);
5038 if (type == -1) {
5039 cmdarg_err("\"%s\" is not a valid 802.11 channel type", options[1]);
5040 ret = EINVAL;
5041 goto out;
5045 if (args >= 2 && options[2])
5046 center_freq1 = get_nonzero_guint32(options[2], "VHT center frequency");
5048 if (args >= 3 && options[3])
5049 center_freq2 = get_nonzero_guint32(options[3], "VHT center frequency 2");
5051 ret = ws80211_set_freq(iface, freq, type, center_freq1, center_freq2);
5053 if (ret) {
5054 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
5055 ret = 2;
5056 goto out;
5059 if (capture_child)
5060 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
5062 out:
5063 g_strfreev(options);
5064 return ret;
5067 static void
5068 gather_dumpcap_compiled_info(feature_list l)
5070 /* Capture libraries */
5071 gather_caplibs_compile_info(l);
5074 static void
5075 gather_dumpcap_runtime_info(feature_list l)
5077 /* Capture libraries */
5078 gather_caplibs_runtime_info(l);
5081 #define LONGOPT_IFNAME LONGOPT_BASE_APPLICATION+1
5082 #define LONGOPT_IFDESCR LONGOPT_BASE_APPLICATION+2
5083 #define LONGOPT_CAPTURE_COMMENT LONGOPT_BASE_APPLICATION+3
5084 #ifdef _WIN32
5085 #define LONGOPT_SIGNAL_PIPE LONGOPT_BASE_APPLICATION+4
5086 #endif
5088 /* And now our feature presentation... [ fade to music ] */
5090 main(int argc, char *argv[])
5092 char *err_msg;
5093 int opt;
5094 static const struct ws_option long_options[] = {
5095 {"help", ws_no_argument, NULL, 'h'},
5096 {"version", ws_no_argument, NULL, 'v'},
5097 LONGOPT_CAPTURE_COMMON
5098 {"ifname", ws_required_argument, NULL, LONGOPT_IFNAME},
5099 {"ifdescr", ws_required_argument, NULL, LONGOPT_IFDESCR},
5100 {"capture-comment", ws_required_argument, NULL, LONGOPT_CAPTURE_COMMENT},
5101 #ifdef _WIN32
5102 {"signal-pipe", ws_required_argument, NULL, LONGOPT_SIGNAL_PIPE},
5103 #endif
5104 {0, 0, 0, 0 }
5107 gboolean arg_error = FALSE;
5109 #ifndef _WIN32
5110 struct sigaction action, oldaction;
5111 #endif
5113 gboolean stats_known;
5114 struct pcap_stat stats = {0};
5115 gboolean list_interfaces = FALSE;
5116 int caps_queries = 0;
5117 gboolean print_bpf_code = FALSE;
5118 gboolean set_chan = FALSE;
5119 gchar *set_chan_arg = NULL;
5120 gboolean machine_readable = FALSE;
5121 gboolean print_statistics = FALSE;
5122 int status, run_once_args = 0;
5123 gint i;
5124 guint j;
5125 #if defined(__APPLE__) && defined(__LP64__)
5126 struct utsname osinfo;
5127 #endif
5128 GString *str;
5131 * Determine if dumpcap is being requested to run in a special
5132 * capture_child mode by going thru the command line args to see if
5133 * a -Z is present. (-Z is a hidden option).
5135 * The primary result of running in capture_child mode is that
5136 * all messages sent out on stderr are in a special type/len/string
5137 * format to allow message processing by type. These messages include
5138 * error messages if dumpcap fails to start the operation it was
5139 * requested to do, as well as various "status" messages which are sent
5140 * when an actual capture is in progress, and a "success" message sent
5141 * if dumpcap was requested to perform an operation other than a
5142 * capture.
5144 * Capture_child mode would normally be requested by a parent process
5145 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
5146 * to which dumpcap stderr has been redirected. It might also have
5147 * another pipe to obtain dumpcap stdout output; for operations other
5148 * than a capture, that information is formatted specially for easier
5149 * parsing by the parent process.
5151 * Capture_child mode needs to be determined immediately upon
5152 * startup so that any messages generated by dumpcap in this mode
5153 * (eg: during initialization) will be formatted properly.
5156 for (i=1; i<argc; i++) {
5157 if (strcmp("-Z", argv[i]) == 0) {
5158 capture_child = TRUE;
5159 machine_readable = TRUE; /* request machine-readable output */
5160 i++;
5161 if (i >= argc) {
5162 exit_main(1);
5165 if (strcmp(argv[i], SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
5166 // get_positive_int calls cmdarg_err
5167 if (!ws_strtoi(argv[i], NULL, &sync_pipe_fd) || sync_pipe_fd <= 0) {
5168 exit_main(1);
5170 #ifdef _WIN32
5171 /* On UN*X the fd is the same when we fork + exec.
5172 * On Windows the HANDLE value is the same for inherited
5173 * handles in the child process and the parent, although
5174 * not necessarily the fd value from _open_osfhandle.
5175 * https://learn.microsoft.com/en-us/windows/win32/procthread/inheritance
5176 * Also, "64-bit versions of Windows use 32-bit handles for
5177 * interoperability... only the lower 32 bits are significant,
5178 * so it is safe to truncate... or sign-extend the handle."
5179 * https://learn.microsoft.com/en-us/windows/win32/winprog64/interprocess-communication
5181 /* set output pipe to binary mode, avoid ugly text conversions */
5182 sync_pipe_fd = _open_osfhandle( (intptr_t) sync_pipe_fd, _O_BINARY);
5183 #endif
5188 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
5190 /* Initialize log handler early so we can have proper logging during startup. */
5191 ws_log_init_with_writer("dumpcap", dumpcap_log_writer, vcmdarg_err);
5193 /* Early logging command-line initialization. */
5194 ws_log_parse_args(&argc, argv, vcmdarg_err, 1);
5196 #if DEBUG_CHILD_DUMPCAP
5197 /* Assume that if we're specially compiled with dumpcap debugging
5198 * then we want maximum debugging.
5200 if (capture_child) {
5201 ws_log_set_level(LOG_LEVEL_NOISY);
5204 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
5205 fprintf (stderr, "Unable to open debug log file .\n");
5206 exit (1);
5208 #endif
5210 ws_noisy("Finished log init and parsing command line log arguments");
5212 #ifdef _WIN32
5213 create_app_running_mutex();
5216 * Initialize our DLL search path. MUST be called before LoadLibrary
5217 * or g_module_open.
5219 ws_init_dll_search_path();
5221 /* Load wpcap if possible. Do this before collecting the run-time version information */
5222 load_wpcap();
5223 #endif
5225 /* Initialize the version information. */
5226 ws_init_version_info("Dumpcap", gather_dumpcap_compiled_info,
5227 gather_dumpcap_runtime_info);
5229 #ifdef HAVE_PCAP_REMOTE
5230 #define OPTSTRING_r "r"
5231 #define OPTSTRING_u "u"
5232 #else
5233 #define OPTSTRING_r
5234 #define OPTSTRING_u
5235 #endif
5237 #ifdef HAVE_PCAP_SETSAMPLING
5238 #define OPTSTRING_m "m:"
5239 #else
5240 #define OPTSTRING_m
5241 #endif
5243 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:dghk:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
5245 #if defined(__APPLE__) && defined(__LP64__)
5247 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
5248 * a bug workaround - timeouts less than 1 second don't work with libpcap
5249 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
5250 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
5251 * The problem is extremely unlikely to be reintroduced in a future
5252 * release.)
5254 if (uname(&osinfo) == 0) {
5256 * {Mac} OS X/macOS 10.x uses Darwin {x+4}.0.0; 10.x.y uses Darwin
5257 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
5258 * number of 10.0.0, not 10.1.0 - go figure).
5260 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
5261 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
5262 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
5263 need_timeout_workaround = TRUE;
5265 #endif
5267 /* Initialize the pcaps list and IDBs */
5268 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(capture_src *));
5269 global_ld.pcapng_passthrough = FALSE;
5270 global_ld.saved_shb = NULL;
5271 global_ld.saved_idbs = g_array_new(FALSE, TRUE, sizeof(saved_idb_t));
5273 err_msg = ws_init_sockets();
5274 if (err_msg != NULL)
5276 ws_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_ERROR,
5277 "ERROR: %s", err_msg);
5278 g_free(err_msg);
5279 ws_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_ERROR,
5280 "%s", please_report_bug());
5281 exit_main(1);
5284 #ifdef _WIN32
5285 /* Set handler for Ctrl+C key */
5286 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
5287 #else
5288 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
5289 and exit. Do the same with SIGPIPE, in case, for example,
5290 we're writing to our standard output and it's a pipe.
5291 Do the same with SIGHUP if it's not being ignored (if we're
5292 being run under nohup, it might be ignored, in which case we
5293 should leave it ignored).
5295 XXX - apparently, Coverity complained that part of action
5296 wasn't initialized. Perhaps it's running on Linux, where
5297 struct sigaction has an ignored "sa_restorer" element and
5298 where "sa_handler" and "sa_sigaction" might not be two
5299 members of a union. */
5300 memset(&action, 0, sizeof(action));
5301 action.sa_handler = capture_cleanup_handler;
5303 * Arrange that system calls not get restarted, because when
5304 * our signal handler returns we don't want to restart
5305 * a call that was waiting for packets to arrive.
5307 action.sa_flags = 0;
5308 sigemptyset(&action.sa_mask);
5309 sigaction(SIGTERM, &action, NULL);
5310 sigaction(SIGINT, &action, NULL);
5311 sigaction(SIGPIPE, &action, NULL);
5312 sigaction(SIGHUP, NULL, &oldaction);
5313 if (oldaction.sa_handler == SIG_DFL)
5314 sigaction(SIGHUP, &action, NULL);
5316 #ifdef SIGINFO
5317 /* Catch SIGINFO and, if we get it and we're capturing in
5318 quiet mode, report the number of packets we've captured. */
5319 action.sa_handler = report_counts_siginfo;
5320 action.sa_flags = SA_RESTART;
5321 sigemptyset(&action.sa_mask);
5322 sigaction(SIGINFO, &action, NULL);
5323 #endif /* SIGINFO */
5324 #endif /* _WIN32 */
5326 /* ----------------------------------------------------------------- */
5327 /* Privilege and capability handling */
5328 /* Cases: */
5329 /* 1. Running not as root or suid root; no special capabilities. */
5330 /* Action: none */
5331 /* */
5332 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
5333 /* Action: none */
5334 /* */
5335 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
5336 /* Action: */
5337 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
5338 /* capabilities; Drop all other capabilities; */
5339 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5340 /* else: after pcap_open_live() in capture_loop_open_input() */
5341 /* drop all capabilities (NET_RAW and NET_ADMIN); */
5342 /* (Note: this means that the process, although logged in */
5343 /* as root, does not have various permissions such as the */
5344 /* ability to bypass file access permissions). */
5345 /* XXX: Should we just leave capabilities alone in this case */
5346 /* so that user gets expected effect that root can do */
5347 /* anything ?? */
5348 /* */
5349 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
5350 /* Action: */
5351 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5352 /* else: after pcap_open_live() in capture_loop_open_input() */
5353 /* drop suid root (set euid=ruid).(ie: keep suid until after */
5354 /* pcap_open_live). */
5355 /* */
5356 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
5357 /* Action: */
5358 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
5359 /* capabilities; Drop all other capabilities; */
5360 /* Drop suid privileges (euid=ruid); */
5361 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5362 /* else: after pcap_open_live() in capture_loop_open_input() */
5363 /* drop all capabilities (NET_RAW and NET_ADMIN). */
5364 /* */
5365 /* XXX: For some Linux versions/distros with capabilities */
5366 /* a 'normal' process with any capabilities cannot be */
5367 /* 'killed' (signaled) from another (same uid) non-privileged */
5368 /* process. */
5369 /* For example: If (non-suid) Wireshark forks a */
5370 /* child suid dumpcap which acts as described here (case 5), */
5371 /* Wireshark will be unable to kill (signal) the child */
5372 /* dumpcap process until the capabilities have been dropped */
5373 /* (after pcap_open_live()). */
5374 /* This behaviour will apparently be changed in the kernel */
5375 /* to allow the kill (signal) in this case. */
5376 /* See the following for details: */
5377 /* https://www.mail-archive.com/ [wrapped] */
5378 /* linux-security-module@vger.kernel.org/msg02913.html */
5379 /* */
5380 /* It is therefore conceivable that if dumpcap somehow hangs */
5381 /* in pcap_open_live or before that wireshark will not */
5382 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
5383 /* In this case, exiting wireshark will kill the child */
5384 /* dumpcap process. */
5385 /* */
5386 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
5387 /* capabilities; Using libcap. Note: capset cmd (which see) */
5388 /* used to assign capabilities to file. */
5389 /* Action: */
5390 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5391 /* else: after pcap_open_live() in capture_loop_open_input() */
5392 /* drop all capabilities (NET_RAW and NET_ADMIN) */
5393 /* */
5394 /* ToDo: -S (stats) should drop privileges/capabilities when no */
5395 /* longer required (similar to capture). */
5396 /* */
5397 /* ----------------------------------------------------------------- */
5399 init_process_policies();
5401 #ifdef HAVE_LIBCAP
5402 /* If 'started with special privileges' (and using libcap) */
5403 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
5404 /* Set euid/egid = ruid/rgid to remove suid privileges */
5405 relinquish_privs_except_capture();
5406 #endif
5408 /* Set the initial values in the capture options. This might be overwritten
5409 by the command line parameters. */
5410 capture_opts_init(&global_capture_opts, get_interface_list);
5411 /* We always save to a file - if no file was specified, we save to a
5412 temporary file. */
5413 global_capture_opts.saving_to_file = TRUE;
5414 global_capture_opts.has_ring_num_files = TRUE;
5416 /* Pass on capture_child mode for capture_opts */
5417 global_capture_opts.capture_child = capture_child;
5419 /* Now get our args */
5420 while ((opt = ws_getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
5421 switch (opt) {
5422 case 'h': /* Print help and exit */
5423 show_help_header("Capture network packets and dump them into a pcapng or pcap file.");
5424 print_usage(stdout);
5425 exit_main(0);
5426 break;
5427 case 'v': /* Show version and exit */
5428 show_version();
5429 exit_main(0);
5430 break;
5431 /*** capture option specific ***/
5432 case 'a': /* autostop criteria */
5433 case 'b': /* Ringbuffer option */
5434 case 'c': /* Capture x packets */
5435 case 'f': /* capture filter */
5436 case 'g': /* enable group read access on file(s) */
5437 case 'i': /* Use interface x */
5438 case LONGOPT_SET_TSTAMP_TYPE: /* Set capture timestamp type */
5439 case 'n': /* Use pcapng format */
5440 case 'p': /* Don't capture in promiscuous mode */
5441 case 'P': /* Use pcap format */
5442 case 's': /* Set the snapshot (capture) length */
5443 case 'w': /* Write to capture file x */
5444 case 'y': /* Set the pcap data link type */
5445 #ifdef HAVE_PCAP_REMOTE
5446 case 'u': /* Use UDP for data transfer */
5447 case 'r': /* Capture own RPCAP traffic too */
5448 case 'A': /* Authentication */
5449 #endif
5450 #ifdef HAVE_PCAP_SETSAMPLING
5451 case 'm': /* Sampling */
5452 #endif
5453 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
5454 case 'B': /* Buffer size */
5455 #endif
5456 #ifdef HAVE_PCAP_CREATE
5457 case 'I': /* Monitor mode */
5458 #endif
5459 case LONGOPT_COMPRESS_TYPE: /* compress type */
5460 case LONGOPT_CAPTURE_TMPDIR: /* capture temp directory */
5461 case LONGOPT_UPDATE_INTERVAL: /* sync pipe update interval */
5462 status = capture_opts_add_opt(&global_capture_opts, opt, ws_optarg);
5463 if (status != 0) {
5464 exit_main(status);
5466 break;
5467 /*** hidden option: Wireshark child mode (using binary output messages) ***/
5468 case LONGOPT_IFNAME:
5469 if (global_capture_opts.ifaces->len > 0) {
5470 interface_options *interface_opts;
5472 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, global_capture_opts.ifaces->len - 1);
5473 interface_opts->ifname = g_strdup(ws_optarg);
5474 } else {
5475 cmdarg_err("--ifname must be specified after a -i option");
5476 exit_main(1);
5478 break;
5479 case LONGOPT_IFDESCR:
5480 if (global_capture_opts.ifaces->len > 0) {
5481 interface_options *interface_opts;
5483 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, global_capture_opts.ifaces->len - 1);
5484 interface_opts->descr = g_strdup(ws_optarg);
5485 } else {
5486 cmdarg_err("--ifdescr must be specified after a -i option");
5487 exit_main(1);
5489 break;
5490 case LONGOPT_CAPTURE_COMMENT: /* capture comment */
5491 if (capture_comments == NULL) {
5492 capture_comments = g_ptr_array_new_with_free_func(g_free);
5494 g_ptr_array_add(capture_comments, g_strdup(ws_optarg));
5495 break;
5496 case 'Z':
5497 capture_child = TRUE;
5499 * Handled above
5501 break;
5502 #ifdef _WIN32
5503 case LONGOPT_SIGNAL_PIPE:
5504 if (!capture_child) {
5505 /* We have already checked for -Z at the very beginning. */
5506 cmdarg_err("--signal-pipe may only be specified with -Z");
5507 exit_main(1);
5510 * ws_optarg = the control ID, aka the PPID, currently used for the
5511 * signal pipe name.
5513 if (strcmp(ws_optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
5514 sig_pipe_name = ws_strdup_printf(SIGNAL_PIPE_FORMAT, ws_optarg);
5515 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
5516 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
5518 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
5519 ws_info("Signal pipe: Unable to open %s. Dead parent?",
5520 sig_pipe_name);
5521 exit_main(1);
5524 break;
5525 #endif
5526 case 'q': /* Quiet */
5527 quiet = TRUE;
5528 break;
5529 case 't':
5530 use_threads = TRUE;
5531 break;
5532 /*** all non capture option specific ***/
5533 case 'D': /* Print a list of capture devices and exit */
5534 if (!list_interfaces && !caps_queries & !print_statistics) {
5535 run_once_args++;
5537 list_interfaces = TRUE;
5538 break;
5539 case 'L': /* Print list of link-layer types and exit */
5540 if (!list_interfaces && !caps_queries & !print_statistics) {
5541 run_once_args++;
5543 caps_queries |= CAPS_QUERY_LINK_TYPES;
5544 break;
5545 case LONGOPT_LIST_TSTAMP_TYPES:
5546 if (!list_interfaces && !caps_queries & !print_statistics) {
5547 run_once_args++;
5549 caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
5550 break;
5551 case 'd': /* Print BPF code for capture filter and exit */
5552 if (!print_bpf_code) {
5553 print_bpf_code = TRUE;
5554 run_once_args++;
5556 break;
5557 case 'S': /* Print interface statistics once a second */
5558 if (!list_interfaces && !caps_queries & !print_statistics) {
5559 run_once_args++;
5561 print_statistics = TRUE;
5562 break;
5563 case 'k': /* Set wireless channel */
5564 if (!set_chan) {
5565 set_chan = TRUE;
5566 set_chan_arg = ws_optarg;
5567 run_once_args++;
5568 } else {
5569 cmdarg_err("Only one -k flag may be specified");
5570 arg_error = TRUE;
5572 break;
5573 case 'M': /* For -D, -L, and -S, print machine-readable output */
5574 machine_readable = TRUE;
5575 break;
5576 case 'C':
5577 pcap_queue_byte_limit = get_positive_int(ws_optarg, "byte_limit");
5578 break;
5579 case 'N':
5580 pcap_queue_packet_limit = get_positive_int(ws_optarg, "packet_limit");
5581 break;
5582 default:
5583 cmdarg_err("Invalid Option: %s", argv[ws_optind-1]);
5584 /* FALLTHROUGH */
5585 case '?': /* Bad flag - print usage message */
5586 arg_error = TRUE;
5587 break;
5590 if (!arg_error) {
5591 argc -= ws_optind;
5592 argv += ws_optind;
5593 if (argc >= 1) {
5594 /* user specified file name as regular command-line argument */
5595 /* XXX - use it as the capture file name (or something else)? */
5596 argc--;
5597 argv++;
5599 if (argc != 0) {
5601 * Extra command line arguments were specified; complain.
5602 * XXX - interpret as capture filter, as tcpdump and tshark do?
5604 cmdarg_err("Invalid argument: %s", argv[0]);
5605 arg_error = TRUE;
5609 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
5610 use_threads = TRUE;
5612 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
5613 /* Use some default if the user hasn't specified some */
5614 /* XXX: Are these defaults good enough? */
5615 pcap_queue_byte_limit = 1000 * 1000;
5616 pcap_queue_packet_limit = 1000;
5618 if (arg_error) {
5619 print_usage(stderr);
5620 exit_main(1);
5623 if (run_once_args > 1) {
5624 cmdarg_err("Only one of -D, -L, -d, -k or -S may be supplied.");
5625 exit_main(1);
5626 } else if (run_once_args == 1) {
5627 /* We're supposed to print some information, rather than
5628 to capture traffic; did they specify a ring buffer option? */
5629 if (global_capture_opts.multi_files_on) {
5630 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
5631 exit_main(1);
5633 } else {
5634 /* We're supposed to capture traffic; */
5636 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
5637 if (global_capture_opts.ifaces->len > 1) {
5638 use_threads = TRUE;
5639 global_capture_opts.use_pcapng = TRUE;
5642 if (capture_comments &&
5643 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
5644 /* XXX - for ringbuffer, should we apply the comments to each file? */
5645 cmdarg_err("Capture comments can only be set if we capture into a single pcapng file.");
5646 exit_main(1);
5649 /* Was the ring buffer option specified and, if so, does it make sense? */
5650 if (global_capture_opts.multi_files_on) {
5651 /* Ring buffer works only under certain conditions:
5652 a) ring buffer does not work with temporary files;
5653 b) it makes no sense to enable the ring buffer if the maximum
5654 file size is set to "infinite". */
5655 if (global_capture_opts.save_file == NULL) {
5656 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
5657 global_capture_opts.multi_files_on = FALSE;
5659 if (!global_capture_opts.has_autostop_filesize &&
5660 !global_capture_opts.has_file_duration &&
5661 !global_capture_opts.has_file_interval &&
5662 !global_capture_opts.has_file_packets) {
5663 cmdarg_err("Ring buffer requested, but no maximum capture file size, duration "
5664 "interval, or packets were specified.");
5665 #if 0
5666 /* XXX - this must be redesigned as the conditions changed */
5667 global_capture_opts.multi_files_on = FALSE;
5668 #endif
5670 if (global_capture_opts.has_file_duration && global_capture_opts.has_file_interval) {
5671 cmdarg_err("Ring buffer file duration and interval can't be used at the same time.");
5672 exit_main(1);
5678 * "-D" requires no interface to be selected; it's supposed to list
5679 * all interfaces.
5681 if (list_interfaces) {
5682 /* Get the list of interfaces */
5683 GList *if_list;
5684 int err;
5685 gchar *err_str;
5687 if_list = get_interface_list(&err, &err_str);
5688 if (if_list == NULL) {
5689 if (err == 0) {
5691 * If we're being run by another program, just give them
5692 * an empty list of interfaces, don't report this as
5693 * an error; that lets them decide whether to report
5694 * this as an error or not.
5696 if (!machine_readable) {
5697 cmdarg_err("There are no interfaces on which a capture can be done");
5698 exit_main(2);
5700 } else {
5701 cmdarg_err("%s", err_str);
5702 g_free(err_str);
5703 exit_main(2);
5707 if (!machine_readable) {
5708 status = 0;
5709 capture_opts_print_interfaces(if_list);
5712 if (caps_queries) {
5713 if_info_t *if_info;
5714 interface_options *interface_opts;
5715 cap_device_open_status open_status;
5716 gchar *open_status_str;
5717 for (GList *if_entry = if_list; if_entry != NULL; if_entry = g_list_next(if_entry)) {
5718 if_info = (if_info_t *)if_entry->data;
5720 interface_opts = interface_opts_from_if_info(&global_capture_opts, if_info);
5722 if_info->caps = get_if_capabilities(interface_opts, &open_status, &open_status_str);
5724 if (!machine_readable) {
5725 if (if_info->caps == NULL) {
5726 cmdarg_err("The capabilities of the capture device "
5727 "\"%s\" could not be obtained (%s).\n%s",
5728 interface_opts->name, open_status_str,
5729 get_pcap_failure_secondary_error_message(open_status, open_status_str));
5730 g_free(open_status_str);
5731 /* Break after one error, as when printing selected
5732 * interface capabilities. (XXX: We could print all
5733 * the primary status strings, and only the unique
5734 * set of secondary messages / suggestions; printing
5735 * the same long secondary error is a lot.)
5737 interface_opts_free(interface_opts);
5738 g_free(interface_opts);
5739 break;
5740 } else {
5741 status = capture_opts_print_if_capabilities(if_info->caps, interface_opts, caps_queries);
5742 if (status != 0) {
5743 interface_opts_free(interface_opts);
5744 g_free(interface_opts);
5745 break;
5748 } else {
5749 if (if_info->caps == NULL) {
5750 if_info->caps = g_new0(if_capabilities_t, 1);
5751 if_info->caps->primary_msg = open_status_str;
5752 if_info->caps->secondary_msg = g_strdup(get_pcap_failure_secondary_error_message(open_status, open_status_str));
5754 if_info->caps->status = open_status;
5757 interface_opts_free(interface_opts);
5758 g_free(interface_opts);
5762 if (machine_readable) {
5763 status = print_machine_readable_interfaces(if_list, caps_queries, print_statistics);
5765 free_interface_list(if_list);
5766 if (!print_statistics) {
5767 exit_main(status);
5772 * "-S" requires no interface to be selected; it gives statistics
5773 * for all interfaces.
5775 if (print_statistics) {
5776 status = print_statistics_loop(machine_readable);
5777 exit_main(status);
5780 if (set_chan) {
5781 interface_options *interface_opts;
5783 if (global_capture_opts.ifaces->len != 1) {
5784 cmdarg_err("Need one interface");
5785 exit_main(2);
5788 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
5789 status = set_80211_channel(interface_opts->name, set_chan_arg);
5790 exit_main(status);
5794 * "-L", "-d", and capturing act on a particular interface, so we have to
5795 * have an interface; if none was specified, pick a default.
5797 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
5798 if (status != 0) {
5799 /* cmdarg_err() already called .... */
5800 exit_main(status);
5803 if (caps_queries) {
5804 /* Get the list of link-layer and/or timestamp types for the capture device. */
5805 if_capabilities_t *caps;
5806 cap_device_open_status open_status;
5807 gchar *open_status_str;
5808 guint ii;
5810 if (machine_readable) {
5811 json_dumper dumper = {
5812 .output_file = stdout,
5813 .flags = JSON_DUMPER_FLAGS_NO_DEBUG,
5814 // Don't abort on failure
5816 json_dumper_begin_array(&dumper);
5817 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
5818 interface_options *interface_opts;
5820 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, ii);
5822 json_dumper_begin_object(&dumper);
5823 json_dumper_set_member_name(&dumper, interface_opts->name);
5825 json_dumper_begin_object(&dumper);
5827 open_status = CAP_DEVICE_OPEN_NO_ERR;
5828 caps = get_if_capabilities(interface_opts, &open_status, &open_status_str);
5829 if (caps == NULL) {
5830 json_dumper_set_member_name(&dumper, "status");
5831 json_dumper_value_anyf(&dumper, "%i", open_status);
5832 json_dumper_set_member_name(&dumper, "primary_msg");
5833 json_dumper_value_string(&dumper, open_status_str);
5834 g_free(open_status_str);
5835 } else {
5836 caps->status = open_status;
5837 print_machine_readable_if_capabilities(&dumper, caps, caps_queries);
5838 free_if_capabilities(caps);
5840 json_dumper_end_object(&dumper);
5841 json_dumper_end_object(&dumper);
5843 json_dumper_end_array(&dumper);
5844 if (json_dumper_finish(&dumper)) {
5845 status = 0;
5846 if (capture_child) {
5847 /* Let our parent know we succeeded. */
5848 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
5850 } else {
5851 status = 2;
5852 if (capture_child) {
5853 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, "Unexpected JSON error", "");
5856 } else {
5857 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
5858 interface_options *interface_opts;
5860 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, ii);
5862 caps = get_if_capabilities(interface_opts, &open_status, &open_status_str);
5863 if (caps == NULL) {
5864 if (capture_child) {
5865 char *error_msg = ws_strdup_printf("The capabilities of the capture device "
5866 "\"%s\" could not be obtained (%s)",
5867 interface_opts->name, open_status_str);
5868 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, error_msg,
5869 get_pcap_failure_secondary_error_message(open_status, open_status_str));
5870 g_free(error_msg);
5872 else {
5873 cmdarg_err("The capabilities of the capture device "
5874 "\"%s\" could not be obtained (%s).\n%s",
5875 interface_opts->name, open_status_str,
5876 get_pcap_failure_secondary_error_message(open_status, open_status_str));
5878 g_free(open_status_str);
5879 exit_main(2);
5882 /* XXX: We might want to print also the interface name */
5883 status = capture_opts_print_if_capabilities(caps,
5884 interface_opts,
5885 caps_queries);
5886 free_if_capabilities(caps);
5887 if (status != 0)
5888 break;
5891 exit_main(status);
5894 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
5895 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5896 interface_options *interface_opts;
5898 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5899 if (interface_opts->timestamp_type) {
5900 interface_opts->timestamp_type_id = pcap_tstamp_type_name_to_val(interface_opts->timestamp_type);
5901 if (interface_opts->timestamp_type_id < 0) {
5902 cmdarg_err("Invalid argument to option: --time-stamp-type=%s", interface_opts->timestamp_type);
5903 exit_main(1);
5907 #endif
5909 /* We're supposed to do a capture, or print the BPF code for a filter. */
5911 /* Let the user know what interfaces were chosen. */
5912 if (capture_child) {
5913 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5914 interface_options *interface_opts;
5916 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5917 ws_debug("Interface: %s\n", interface_opts->name);
5919 } else {
5920 str = g_string_new("");
5921 #ifdef _WIN32
5922 if (global_capture_opts.ifaces->len < 2)
5923 #else
5924 if (global_capture_opts.ifaces->len < 4)
5925 #endif
5927 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5928 interface_options *interface_opts;
5930 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5931 if (j > 0) {
5932 if (global_capture_opts.ifaces->len > 2) {
5933 g_string_append_printf(str, ",");
5935 g_string_append_printf(str, " ");
5936 if (j == global_capture_opts.ifaces->len - 1) {
5937 g_string_append_printf(str, "and ");
5940 if (interface_opts->ifname != NULL) {
5942 * Re-generate the display name based on the strins
5943 * we were handed.
5945 g_free(interface_opts->display_name);
5946 if (interface_opts->descr != NULL) {
5947 #ifdef _WIN32
5948 interface_opts->display_name = ws_strdup_printf("%s",
5949 interface_opts->descr);
5950 #else
5951 interface_opts->display_name = ws_strdup_printf("%s: %s",
5952 interface_opts->descr, interface_opts->ifname);
5953 #endif
5954 } else {
5955 interface_opts->display_name = ws_strdup_printf("%s",
5956 interface_opts->ifname);
5959 g_string_append_printf(str, "'%s'", interface_opts->display_name);
5961 } else {
5962 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
5964 fprintf(stderr, "Capturing on %s\n", str->str);
5965 g_string_free(str, TRUE);
5968 /* Process the snapshot length, as that affects the generated BPF code. */
5969 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
5971 if (print_bpf_code) {
5972 show_filter_code(&global_capture_opts);
5973 exit_main(0);
5976 /* We're supposed to do a capture. Process the ring buffer arguments. */
5977 capture_opts_trim_ring_num_files(&global_capture_opts);
5979 /* flush stderr prior to starting the main capture loop */
5980 fflush(stderr);
5982 /* Now start the capture. */
5983 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
5984 /* capture ok */
5985 exit_main(0);
5986 } else {
5987 /* capture failed */
5988 exit_main(1);
5990 return 0; /* never here, make compiler happy */
5993 static void
5994 dumpcap_log_writer(const char *domain, enum ws_log_level level,
5995 const char *file, long line, const char *func,
5996 const char *fatal_msg _U_,
5997 ws_log_manifest_t *mft,
5998 const char *user_format, va_list user_ap,
5999 void *user_data _U_)
6001 if (ws_log_msg_is_active(domain, level)) {
6002 /* log messages go to stderr or */
6003 /* to parent especially formatted if dumpcap running as child. */
6004 #ifdef DEBUG_CHILD_DUMPCAP
6005 va_list user_ap_copy;
6006 va_copy(user_ap_copy, user_ap);
6007 #endif
6008 if (capture_child) {
6009 /* Format the log mesage as the numeric level, followed
6010 * by a colon and then a string matching the standard log
6011 * string. In the future perhaps we serialize file, line,
6012 * and func (which can be NULL) instead.
6014 GString *msg = g_string_new(NULL);
6015 g_string_append_printf(msg, "%u:", level);
6016 if (file != NULL) {
6017 g_string_append_printf(msg, "%s", file);
6018 if (line >= 0) {
6019 g_string_append_printf(msg, ":%ld", line);
6022 g_string_append(msg, " --");
6023 if (func != NULL) {
6024 g_string_append_printf(msg, " %s():", func);
6026 g_string_append_c(msg, ' ');
6027 g_string_append_vprintf(msg, user_format, user_ap);
6029 sync_pipe_write_string_msg(sync_pipe_fd, SP_LOG_MSG, msg->str);
6030 g_string_free(msg, TRUE);
6031 } else {
6032 ws_log_console_writer(domain, level, file, line, func, mft, user_format, user_ap);
6034 #ifdef DEBUG_CHILD_DUMPCAP
6035 ws_log_file_writer(debug_log, domain, level, file, line, func, mft, user_format, user_ap_copy);
6036 va_end(user_ap_copy);
6037 #endif
6042 /****************************************************************************************************************/
6043 /* indication report routines */
6046 static void
6047 report_packet_count(unsigned int packet_count)
6049 static unsigned int count = 0;
6051 if (capture_child) {
6052 ws_debug("Packets: %u", packet_count);
6053 sync_pipe_write_uint_msg(sync_pipe_fd, SP_PACKET_COUNT, packet_count);
6054 } else {
6055 count += packet_count;
6056 fprintf(stderr, "\rPackets: %u ", count);
6057 /* stderr could be line buffered */
6058 fflush(stderr);
6062 static void
6063 report_new_capture_file(const char *filename)
6065 if (capture_child) {
6066 ws_debug("File: %s", filename);
6067 if (global_ld.pcapng_passthrough) {
6068 /* Save filename for sending SP_FILE to capture parent after SHB is passed-through */
6069 ws_debug("Delaying SP_FILE until first SHB");
6070 report_capture_filename = filename;
6071 } else {
6072 sync_pipe_write_string_msg(sync_pipe_fd, SP_FILE, filename);
6074 } else {
6075 #ifdef SIGINFO
6077 * Prevent a SIGINFO handler from writing to the standard error
6078 * while we're doing so; instead, have it just set a flag telling
6079 * us to print that information when we're done.
6081 infodelay = TRUE;
6082 #endif /* SIGINFO */
6083 fprintf(stderr, "File: %s\n", filename);
6084 /* stderr could be line buffered */
6085 fflush(stderr);
6087 #ifdef SIGINFO
6089 * Allow SIGINFO handlers to write.
6091 infodelay = FALSE;
6094 * If a SIGINFO handler asked us to write out capture counts, do so.
6096 if (infoprint)
6097 report_counts_for_siginfo();
6098 #endif /* SIGINFO */
6102 static void
6103 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
6105 interface_options *interface_opts;
6106 char tmp[MSG_MAX_LENGTH+1+6];
6108 if (i < capture_opts->ifaces->len) {
6109 if (capture_child) {
6110 snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
6111 ws_debug("Capture filter error: %s", errmsg);
6112 sync_pipe_write_string_msg(sync_pipe_fd, SP_BAD_FILTER, tmp);
6113 } else {
6115 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
6116 * the error message below.
6118 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
6119 cmdarg_err(
6120 "Invalid capture filter \"%s\" for interface '%s'.\n"
6121 "\n"
6122 "That string isn't a valid capture filter (%s).\n"
6123 "See the User's Guide for a description of the capture filter syntax.",
6124 interface_opts->cfilter, interface_opts->name, errmsg);
6129 static void
6130 report_capture_error(const char *error_msg, const char *secondary_error_msg)
6132 if (capture_child) {
6133 ws_debug("Primary Error: %s", error_msg);
6134 ws_debug("Secondary Error: %s", secondary_error_msg);
6135 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, error_msg, secondary_error_msg);
6136 } else {
6137 cmdarg_err("%s", error_msg);
6138 if (secondary_error_msg[0] != '\0')
6139 cmdarg_err_cont("%s", secondary_error_msg);
6143 static void
6144 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
6146 guint32 total_drops = pcap_drops + drops + flushed;
6148 if (capture_child) {
6149 char* tmp = ws_strdup_printf("%u:%s", total_drops, name);
6151 ws_debug("Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
6152 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
6153 sync_pipe_write_string_msg(sync_pipe_fd, SP_DROPS, tmp);
6154 g_free(tmp);
6155 } else {
6156 fprintf(stderr,
6157 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
6158 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
6159 received ? 100.0 * received / (received + total_drops) : 0.0);
6160 /* stderr could be line buffered */
6161 fflush(stderr);
6166 /************************************************************************************************/
6167 /* signal_pipe handling */
6170 #ifdef _WIN32
6171 static gboolean
6172 signal_pipe_check_running(void)
6174 /* any news from our parent? -> just stop the capture */
6175 DWORD avail = 0;
6176 gboolean result;
6178 /* if we are running standalone, no check required */
6179 if (!capture_child) {
6180 return TRUE;
6183 if (!sig_pipe_name || !sig_pipe_handle) {
6184 /* This shouldn't happen */
6185 ws_info("Signal pipe: No name or handle");
6186 return FALSE;
6190 * XXX - We should have the process ID of the parent (from the "-Z" flag)
6191 * at this point. Should we check to see if the parent is still alive,
6192 * e.g. by using OpenProcess?
6195 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
6197 if (!result || avail > 0) {
6198 /* peek failed or some bytes really available */
6199 /* (if not piping from stdin this would fail) */
6200 ws_info("Signal pipe: Stop capture: %s", sig_pipe_name);
6201 ws_debug("Signal pipe: %s (%p) result: %u avail: %lu", sig_pipe_name,
6202 sig_pipe_handle, result, avail);
6203 return FALSE;
6204 } else {
6205 /* pipe ok and no bytes available */
6206 return TRUE;
6209 #endif
6212 * Editor modelines - https://www.wireshark.org/tools/modelines.html
6214 * Local variables:
6215 * c-basic-offset: 4
6216 * tab-width: 8
6217 * indent-tabs-mode: nil
6218 * End:
6220 * vi: set shiftwidth=4 tabstop=8 expandtab:
6221 * :indentSize=4:tabSize=8:noTabs=true: