Revert "TODO: smb2: simplify preauth_hash calculation..."
[wireshark-sm.git] / dumpcap.c
blob56f79f83461f62c81c1de08dc4bdf0e8c9430213
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/cmdarg_err.h>
37 #include <wsutil/strtoi.h>
38 #include <cli_main.h>
39 #include <wsutil/version_info.h>
41 #include <wsutil/socket.h>
42 #include <wsutil/wslog.h>
43 #include <wsutil/file_util.h>
45 #ifdef HAVE_LIBCAP
46 # include <sys/prctl.h>
47 # include <sys/capability.h>
48 #endif
50 #include "ringbuffer.h"
52 #include "capture/capture_ifinfo.h"
53 #include "capture/capture-pcap-util.h"
54 #include "capture/capture-pcap-util-int.h"
55 #ifdef _WIN32
56 #include "capture/capture-wpcap.h"
57 #endif /* _WIN32 */
59 #include "writecap/pcapio.h"
61 #ifndef _WIN32
62 #include <sys/un.h>
63 #endif
65 #include <wsutil/clopts_common.h>
66 #include <wsutil/privileges.h>
68 #include "sync_pipe.h"
70 #include "capture_opts.h"
71 #include <capture/capture_session.h>
72 #include <capture/capture_sync.h>
74 #include "wsutil/tempfile.h"
75 #include "wsutil/file_util.h"
76 #include "wsutil/cpu_info.h"
77 #include "wsutil/os_version_info.h"
78 #include "wsutil/str_util.h"
79 #include "wsutil/inet_addr.h"
80 #include "wsutil/time_util.h"
81 #include "wsutil/please_report_bug.h"
82 #include "wsutil/glib-compat.h"
83 #include <wsutil/json_dumper.h>
84 #include <wsutil/ws_assert.h>
86 #include "capture/ws80211_utils.h"
88 #include "extcap.h"
91 * Get information about libpcap format from "wiretap/libpcap.h".
92 * Get information about pcapng format from "wiretap/pcapng_module.h".
93 * XXX - can we just use pcap_open_offline() to read the pipe?
95 #include "wiretap/libpcap.h"
96 #include "wiretap/pcapng_module.h"
97 #include "wiretap/pcapng.h"
100 * Define these for extra logging. Note that when dumpcap is spawned as
101 * a child process, logs are sent to the parent via the sync pipe.
102 * The parent will pass along the Capchild domain log level settings,
103 * so "--log-debug Capchild" or "--log-level debug" can be used to get
104 * debugging from dumpcap sent to the parent.
106 //#define DEBUG_DUMPCAP /* Waits for keypress on quitting on Windows */
107 //#define DEBUG_CHILD_DUMPCAP /* Writes logs to file */
109 #ifdef _WIN32
110 #include "wsutil/win32-utils.h"
111 #ifdef DEBUG_DUMPCAP
112 #include <conio.h> /* _getch() */
113 #endif
114 #endif
116 #ifdef DEBUG_CHILD_DUMPCAP
117 FILE *debug_log; /* for logging debug messages to */
118 /* a file if DEBUG_CHILD_DUMPCAP */
119 /* is defined */
120 #include <stdarg.h> /* va_copy */
121 #endif
123 static GAsyncQueue *pcap_queue;
124 static gint64 pcap_queue_bytes;
125 static gint64 pcap_queue_packets;
126 static gint64 pcap_queue_byte_limit;
127 static gint64 pcap_queue_packet_limit;
129 static gboolean capture_child; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
130 static const char *report_capture_filename; /* capture child file name */
131 #ifdef _WIN32
132 static gchar *sig_pipe_name;
133 static HANDLE sig_pipe_handle;
134 static gboolean signal_pipe_check_running(void);
135 #endif
136 static int sync_pipe_fd = 2;
138 #ifdef ENABLE_ASAN
139 /* This has public visibility so that if compiled with shared libasan (the
140 * gcc default) function interposition occurs.
142 WS_DLL_PUBLIC int
143 __lsan_is_turned_off(void)
145 /* If we're in capture child mode, don't run a LSan report and
146 * send it to stderr, because it isn't properly formatted for
147 * the sync pipe.
148 * We could, if debugging variables are set, send the reports
149 * elsewhere instead, by calling __sanitizer_set_report_path()
150 * or __sanitizer_set_report_fd()
152 if (capture_child) {
153 return 1;
155 #ifdef HAVE_LIBCAP
156 /* LSan dies with a fatal error without explanation if it can't ptrace.
157 * Normally, the "dumpable" attribute (which also controls ptracing)
158 * is set to 1 (SUID_DUMP_USER, process is dumpable.) However, it is
159 * reset to the current value in /proc/sys/fs/suid_dumpable in the
160 * following circumstances: euid/egid changes, fsuid/fsgid changes,
161 * execve of a setuid or setgid program that changes the euid or egid,
162 * execve of a program with capabilities exceeding those already
163 * permitted for the process.
165 * Unless we're running as root, one of those applies to dumpcap.
167 * The default value of /proc/sys/fs/suid_dumpable is 0, SUID_DUMP_DISABLE.
168 * In such a case, LeakSanitizer temporarily sets the value to 1 to
169 * allow ptracing, and then sets it back to 0.
171 * Another possible value, used by Ubuntu, Fedora, etc., is 2,
172 * which creates dumps readable by root only. For security reasons,
173 * unprivileged programs are not allowed to change the value to 2.
174 * (See https://nvd.nist.gov/vuln/detail/CVE-2006-2451 )
176 * LSan does not check for the value 2 and change dumpable to 1 in that
177 * case, possibly because if it did it could not change it back to 2
178 * and would have to either leave the process dumpable or change it to 0.
180 * The usual way to control the family of sanitizers is through environment
181 * variables. However, complicating things, changing the dumpable attribute
182 * to 0 or 2 changes the ownership of files in /proc/[pid] (including
183 * /proc/self ) to root:root, in particular /proc/[pid]/environ, and so
184 * ASAN_OPTIONS=detect_leaks=0 has no effect. (Unless the process has
185 * CAP_SYS_PTRACE, which allows tracing of any process, but that's also
186 * a security risk and we'll have dropped that with other privileges.)
188 * So if prctl(PR_GET_DUMPABLE) returns 2, we know that the process will
189 * die with a fatal error if it attempts to run LSan, so don't.
191 * See proc(5), prctl(2), ptrace(2), and
192 * https://github.com/google/sanitizers/issues/1306
193 * https://github.com/llvm/llvm-project/issues/55944
195 if (prctl(PR_GET_DUMPABLE) == 2) {
196 ws_debug("Not running LeakSanitizer because /proc/sys/fs/suid_dumpable is 2");
197 return 1;
199 #endif
200 return 0;
203 WS_DLL_PUBLIC const char*
204 __asan_default_options(void)
206 /* By default don't override our exit code if there's a leak or error.
207 * We particularly don't want to do this if running as a capture child,
208 * because capture/capture_sync doesn't expect the ASan exit codes.
210 return "exitcode=0";
212 #endif
214 #ifdef SIGINFO
215 static gboolean infodelay; /* if TRUE, don't print capture info in SIGINFO handler */
216 static gboolean infoprint; /* if TRUE, print capture info after clearing infodelay */
217 #endif /* SIGINFO */
219 /** Stop a low-level capture (stops the capture child). */
220 static void capture_loop_stop(void);
221 /** Close a pipe, or socket if \a from_socket is TRUE */
222 static void cap_pipe_close(int pipe_fd, gboolean from_socket);
224 #if defined (__linux__)
225 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
226 * in pcap_dispatch(); on the other hand, select() works just fine there.
227 * Hence we use a select for that come what may.
229 * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
230 * internally, and, with TPACKET_V3, once that's supported, it'll
231 * support timeouts, at least as I understand the way the code works.
233 #define MUST_DO_SELECT
234 #endif
236 /** init the capture filter */
237 typedef enum {
238 INITFILTER_NO_ERROR,
239 INITFILTER_BAD_FILTER,
240 INITFILTER_OTHER_ERROR
241 } initfilter_status_t;
243 typedef enum {
244 STATE_EXPECT_REC_HDR,
245 STATE_READ_REC_HDR,
246 STATE_EXPECT_DATA,
247 STATE_READ_DATA
248 } cap_pipe_state_t;
250 typedef enum {
251 PIPOK,
252 PIPEOF,
253 PIPERR,
254 PIPNEXIST
255 } cap_pipe_err_t;
257 typedef struct _pcap_pipe_info {
258 gboolean byte_swapped; /**< TRUE if data in the pipe is byte swapped. */
259 struct pcap_hdr hdr; /**< Pcap header when capturing from a pipe */
260 struct pcaprec_modified_hdr rechdr; /**< Pcap record header when capturing from a pipe */
261 } pcap_pipe_info_t;
263 typedef struct _pcapng_pipe_info {
264 pcapng_block_header_t bh; /**< Pcapng general block header when capturing from a pipe */
265 GArray *src_iface_to_global; /**< Int array mapping local IDB numbers to global_ld.interface_data */
266 } pcapng_pipe_info_t;
268 struct _loop_data; /* forward declaration so we can use it in the cap_pipe_dispatch function pointer */
271 * A source of packets from which we're capturing.
273 typedef struct _capture_src {
274 guint32 received;
275 guint32 dropped;
276 guint32 flushed;
277 pcap_t *pcap_h;
278 #ifdef MUST_DO_SELECT
279 int pcap_fd; /**< pcap file descriptor */
280 #endif
281 gboolean pcap_err;
282 guint interface_id;
283 guint idb_id; /**< If from_pcapng is false, the output IDB interface ID. Otherwise the mapping in src_iface_to_global is used. */
284 GThread *tid;
285 int snaplen;
286 int linktype;
287 gboolean ts_nsec; /**< TRUE if we're using nanosecond precision. */
288 /**< capture pipe (unix only "input file") */
289 gboolean from_cap_pipe; /**< TRUE if we are capturing data from a capture pipe */
290 gboolean from_cap_socket; /**< TRUE if we're capturing from socket */
291 gboolean from_pcapng; /**< TRUE if we're capturing from pcapng format */
292 union {
293 pcap_pipe_info_t pcap; /**< Pcap info when capturing from a pipe */
294 pcapng_pipe_info_t pcapng; /**< Pcapng info when capturing from a pipe */
295 } cap_pipe_info;
296 #ifdef _WIN32
297 HANDLE cap_pipe_h; /**< The handle of the capture pipe */
298 #endif
299 int cap_pipe_fd; /**< the file descriptor of the capture pipe */
300 gboolean cap_pipe_modified; /**< TRUE if data in the pipe uses modified pcap headers */
301 char * cap_pipe_databuf; /**< Pointer to the data buffer we've allocated */
302 size_t cap_pipe_databuf_size; /**< Current size of the data buffer */
303 guint cap_pipe_max_pkt_size; /**< Maximum packet size allowed */
304 #if defined(_WIN32)
305 char * cap_pipe_buf; /**< Pointer to the buffer we read into */
306 DWORD cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
307 DWORD cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
308 #else
309 size_t cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
310 size_t cap_pipe_bytes_read; /**< Used by cap_pipe_dispatch */
311 #endif
312 int (*cap_pipe_dispatch)(struct _loop_data *, struct _capture_src *, char *, size_t);
313 cap_pipe_state_t cap_pipe_state;
314 cap_pipe_err_t cap_pipe_err;
316 #if defined(_WIN32)
317 GMutex *cap_pipe_read_mtx;
318 GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
319 #endif
320 } capture_src;
322 typedef struct _saved_idb {
323 gboolean deleted;
324 guint interface_id; /* capture_src->interface_id for the associated SHB */
325 guint8 *idb; /* If non-NULL, IDB read from capture_src. This is an interface specified on the command line otherwise. */
326 guint idb_len;
327 } saved_idb_t;
330 * Global capture loop state.
332 typedef struct _loop_data {
333 /* common */
334 gboolean go; /**< TRUE as long as we're supposed to keep capturing */
335 int err; /**< if non-zero, error seen while capturing */
336 gint packets_captured; /**< Number of packets we have already captured */
337 guint inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
338 #ifdef SIGINFO
339 gboolean report_packet_count; /**< Set by SIGINFO handler; print packet count */
340 #endif
341 GArray *pcaps; /**< Array of capture_src's on which we're capturing */
342 gboolean pcapng_passthrough; /**< We have one source and it's pcapng. Pass its SHB and IDBs through. */
343 guint8 *saved_shb; /**< SHB to write when we have one pcapng input */
344 GArray *saved_idbs; /**< Array of saved_idb_t, written when we have a new section or output file. */
345 GRWLock saved_shb_idb_lock; /**< Saved IDB RW mutex */
346 /* output file(s) */
347 FILE *pdh;
348 int save_file_fd;
349 char *io_buffer; /**< Our IO buffer if we increase the size from the standard size */
350 guint64 bytes_written; /**< Bytes written for the current file. */
351 /* autostop conditions */
352 int packets_written; /**< Packets written for the current file. */
353 int file_count;
354 /* ring buffer conditions */
355 GTimer *file_duration_timer;
356 time_t next_interval_time;
357 int interval_s;
358 } loop_data;
360 typedef struct _pcap_queue_element {
361 capture_src *pcap_src;
362 union {
363 struct pcap_pkthdr phdr;
364 pcapng_block_header_t bh;
365 } u;
366 u_char *pd;
367 } pcap_queue_element;
370 * This needs to be static, so that the SIGINT handler can clear the "go"
371 * flag and for saved_shb_idb_lock.
373 static loop_data global_ld;
376 * Timeout, in milliseconds, for reads from the stream of captured packets
377 * from a capture device.
379 * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
380 * 64-bit applications, with sub-second timeouts not to work. The bug is
381 * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
383 #if defined(__APPLE__) && defined(__LP64__)
384 static gboolean need_timeout_workaround;
386 #define CAP_READ_TIMEOUT (need_timeout_workaround ? 1000 : 250)
387 #else
388 #define CAP_READ_TIMEOUT 250
389 #endif
392 * Timeout, in microseconds, for reads from the stream of captured packets
393 * from a pipe. Pipes don't have the same problem that BPF devices do
394 * in Mac OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
395 * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
396 * of the offending versions of Snow Leopard.
398 * On Windows this value is converted to milliseconds and passed to
399 * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
400 * will return immediately.
402 #if defined(_WIN32)
403 #define PIPE_READ_TIMEOUT 100000
404 #else
405 #define PIPE_READ_TIMEOUT 250000
406 #endif
408 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
410 static void
411 dumpcap_log_writer(const char *domain, enum ws_log_level level,
412 const char *file, long line, const char *func,
413 const char *fatal_msg, ws_log_manifest_t *mft,
414 const char *user_format, va_list user_ap,
415 void *user_data);
417 /* capture related options */
418 static capture_options global_capture_opts;
419 static GPtrArray *capture_comments;
420 static gboolean quiet;
421 static gboolean use_threads;
422 static guint64 start_time;
424 static void capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
425 const u_char *pd);
426 static void capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
427 const u_char *pd);
428 static void capture_loop_write_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd);
429 static void capture_loop_queue_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd);
430 static void capture_loop_get_errmsg(char *errmsg, size_t errmsglen,
431 char *secondary_errmsg,
432 size_t secondary_errmsglen,
433 const char *fname, int err,
434 gboolean is_close);
436 WS_NORETURN static void exit_main(int err);
438 static void report_new_capture_file(const char *filename);
439 static void report_packet_count(unsigned int packet_count);
440 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
441 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
442 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
444 #define MSG_MAX_LENGTH 4096
446 static void
447 print_usage(FILE *output)
449 fprintf(output, "\nUsage: dumpcap [options] ...\n");
450 fprintf(output, "\n");
451 fprintf(output, "Capture interface:\n");
452 fprintf(output, " -i <interface>, --interface <interface>\n");
453 fprintf(output, " name or idx of interface (def: first non-loopback),\n"
454 " or for remote capturing, use one of these formats:\n"
455 " rpcap://<host>/<interface>\n"
456 " TCP@<host>:<port>\n");
457 fprintf(output, " --ifname <name> name to use in the capture file for a pipe from which\n");
458 fprintf(output, " we're capturing\n");
459 fprintf(output, " --ifdescr <description>\n");
460 fprintf(output, " description to use in the capture file for a pipe\n");
461 fprintf(output, " from which we're capturing\n");
462 fprintf(output, " -f <capture filter> packet filter in libpcap filter syntax\n");
463 fprintf(output, " -s <snaplen>, --snapshot-length <snaplen>\n");
464 #ifdef HAVE_PCAP_CREATE
465 fprintf(output, " packet snapshot length (def: appropriate maximum)\n");
466 #else
467 fprintf(output, " packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
468 #endif
469 fprintf(output, " -p, --no-promiscuous-mode\n");
470 fprintf(output, " don't capture in promiscuous mode\n");
471 #ifdef HAVE_PCAP_CREATE
472 fprintf(output, " -I, --monitor-mode capture in monitor mode, if available\n");
473 #endif
474 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
475 fprintf(output, " -B <buffer size>, --buffer-size <buffer size>\n");
476 fprintf(output, " size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
477 #endif
478 fprintf(output, " -y <link type>, --linktype <link type>\n");
479 fprintf(output, " link layer type (def: first appropriate)\n");
480 fprintf(output, " --time-stamp-type <type> timestamp method for interface\n");
481 fprintf(output, " -D, --list-interfaces print list of interfaces and exit\n");
482 fprintf(output, " -L, --list-data-link-types\n");
483 fprintf(output, " print list of link-layer types of iface and exit\n");
484 fprintf(output, " --list-time-stamp-types print list of timestamp types for iface and exit\n");
485 fprintf(output, " --update-interval interval between updates with new packets (def: %dms)\n", DEFAULT_UPDATE_INTERVAL);
486 fprintf(output, " -d print generated BPF code for capture filter\n");
487 fprintf(output, " -k <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
488 fprintf(output, " set channel on wifi interface\n");
489 fprintf(output, " -S print statistics for each interface once per second\n");
490 fprintf(output, " -M for -D, -L, and -S, produce machine-readable output\n");
491 fprintf(output, "\n");
492 #ifdef HAVE_PCAP_REMOTE
493 fprintf(output, "RPCAP options:\n");
494 fprintf(output, " -r don't ignore own RPCAP traffic in capture\n");
495 fprintf(output, " -u use UDP for RPCAP data transfer\n");
496 fprintf(output, " -A <user>:<password> use RPCAP password authentication\n");
497 #ifdef HAVE_PCAP_SETSAMPLING
498 fprintf(output, " -m <sampling type> use packet sampling\n");
499 fprintf(output, " count:NUM - capture one packet of every NUM\n");
500 fprintf(output, " timer:NUM - capture no more than 1 packet in NUM ms\n");
501 #endif
502 #endif
503 fprintf(output, "Stop conditions:\n");
504 fprintf(output, " -c <packet count> stop after n packets (def: infinite)\n");
505 fprintf(output, " -a <autostop cond.> ..., --autostop <autostop cond.> ...\n");
506 fprintf(output, " duration:NUM - stop after NUM seconds\n");
507 fprintf(output, " filesize:NUM - stop this file after NUM kB\n");
508 fprintf(output, " files:NUM - stop after NUM files\n");
509 fprintf(output, " packets:NUM - stop after NUM packets\n");
510 /*fprintf(output, "\n");*/
511 fprintf(output, "Output (files):\n");
512 fprintf(output, " -w <filename> name of file to save (def: tempfile)\n");
513 fprintf(output, " -g enable group read access on the output file(s)\n");
514 fprintf(output, " -b <ringbuffer opt.> ..., --ring-buffer <ringbuffer opt.>\n");
515 fprintf(output, " duration:NUM - switch to next file after NUM secs\n");
516 fprintf(output, " filesize:NUM - switch to next file after NUM kB\n");
517 fprintf(output, " files:NUM - ringbuffer: replace after NUM files\n");
518 fprintf(output, " packets:NUM - ringbuffer: replace after NUM packets\n");
519 fprintf(output, " interval:NUM - switch to next file when the time is\n");
520 fprintf(output, " an exact multiple of NUM secs\n");
521 fprintf(output, " printname:FILE - print filename to FILE when written\n");
522 fprintf(output, " (can use 'stdout' or 'stderr')\n");
523 fprintf(output, " -n use pcapng format instead of pcap (default)\n");
524 fprintf(output, " -P use libpcap format instead of pcapng\n");
525 fprintf(output, " --capture-comment <comment>\n");
526 fprintf(output, " add a capture comment to the output file\n");
527 fprintf(output, " (only for pcapng)\n");
528 fprintf(output, " --temp-dir <directory> write temporary files to this directory\n");
529 fprintf(output, " (default: %s)\n", g_get_tmp_dir());
530 fprintf(output, "\n");
532 ws_log_print_usage(output);
533 fprintf(output, "\n");
535 fprintf(output, "Miscellaneous:\n");
536 fprintf(output, " -N <packet_limit> maximum number of packets buffered within dumpcap\n");
537 fprintf(output, " -C <byte_limit> maximum number of bytes used for buffering packets\n");
538 fprintf(output, " within dumpcap\n");
539 fprintf(output, " -t use a separate thread per interface\n");
540 fprintf(output, " -q don't report packet capture counts\n");
541 fprintf(output, " -v, --version print version information and exit\n");
542 fprintf(output, " -h, --help display this help and exit\n");
543 fprintf(output, "\n");
544 #ifdef __linux__
545 fprintf(output, "Dumpcap can benefit from an enabled BPF JIT compiler if available.\n");
546 fprintf(output, "You might want to enable it by executing:\n");
547 fprintf(output, " \"echo 1 > /proc/sys/net/core/bpf_jit_enable\"\n");
548 fprintf(output, "Note that this can make your system less secure!\n");
549 fprintf(output, "\n");
550 #endif
551 fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
552 fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
553 fprintf(output, "\n");
554 fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
558 * Report an error in command-line arguments.
559 * If we're a capture child, send a message back to the parent, otherwise
560 * just print it.
562 static void
563 dumpcap_cmdarg_err(const char *fmt, va_list ap)
565 if (capture_child) {
566 gchar *msg;
567 /* Generate a 'special format' message back to parent */
568 msg = ws_strdup_vprintf(fmt, ap);
569 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, msg, "");
570 g_free(msg);
571 } else {
572 fprintf(stderr, "dumpcap: ");
573 vfprintf(stderr, fmt, ap);
574 fprintf(stderr, "\n");
579 * Report additional information for an error in command-line arguments.
580 * If we're a capture child, send a message back to the parent, otherwise
581 * just print it.
583 static void
584 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
586 if (capture_child) {
587 gchar *msg;
588 msg = ws_strdup_vprintf(fmt, ap);
589 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, msg, "");
590 g_free(msg);
591 } else {
592 vfprintf(stderr, fmt, ap);
593 fprintf(stderr, "\n");
597 #ifdef HAVE_LIBCAP
598 static void
599 #if 0 /* Set to enable capability debugging */
600 /* see 'man cap_to_text()' for explanation of output */
601 /* '=' means 'all= ' ie: no capabilities */
602 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
603 /* .... */
604 print_caps(const char *pfx) {
605 cap_t caps = cap_get_proc();
606 ws_debug("%s: EUID: %d Capabilities: %s", pfx, geteuid(), cap_to_text(caps, NULL));
607 cap_free(caps);
609 #else
610 print_caps(const char *pfx _U_) {
612 #endif
614 static void
615 relinquish_all_capabilities(void)
617 /* Drop any and all capabilities this process may have. */
618 /* Allowed whether or not process has any privileges. */
619 cap_t caps = cap_init(); /* all capabilities initialized to off */
620 print_caps("Pre-clear");
621 if (cap_set_proc(caps)) {
622 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
624 print_caps("Post-clear");
625 cap_free(caps);
627 #endif
629 static void
630 get_capture_device_open_failure_messages(cap_device_open_status open_status,
631 const char *open_status_str,
632 const char *iface,
633 char *errmsg, size_t errmsg_len,
634 char *secondary_errmsg,
635 size_t secondary_errmsg_len)
637 switch (open_status) {
639 case CAP_DEVICE_OPEN_ERROR_NO_SUCH_DEVICE:
640 snprintf(errmsg, errmsg_len,
641 "There is no device named \"%s\".\n(%s)",
642 iface, open_status_str);
643 break;
645 case CAP_DEVICE_OPEN_ERROR_RFMON_NOTSUP:
646 snprintf(errmsg, errmsg_len,
647 "Capturing in monitor mode is not supported on device \"%s\".\n(%s)",
648 iface, open_status_str);
649 break;
651 case CAP_DEVICE_OPEN_ERROR_PERM_DENIED:
652 snprintf(errmsg, errmsg_len,
653 "You do not have permission to capture on device \"%s\".\n(%s)",
654 iface, open_status_str);
655 break;
657 case CAP_DEVICE_OPEN_ERROR_IFACE_NOT_UP:
658 snprintf(errmsg, errmsg_len,
659 "Device \"%s\" is not up.\n(%s)",
660 iface, open_status_str);
661 break;
663 case CAP_DEVICE_OPEN_ERROR_PROMISC_PERM_DENIED:
664 snprintf(errmsg, errmsg_len,
665 "You do not have permission to capture in promiscuous mode on device \"%s\".\n(%s)",
666 iface, open_status_str);
667 break;
669 case CAP_DEVICE_OPEN_ERROR_OTHER:
670 default:
671 snprintf(errmsg, errmsg_len,
672 "The capture session could not be initiated on capture device \"%s\".\n(%s)",
673 iface, open_status_str);
674 break;
676 snprintf(secondary_errmsg, secondary_errmsg_len, "%s",
677 get_pcap_failure_secondary_error_message(open_status, open_status_str));
680 static gboolean
681 compile_capture_filter(const char *iface, pcap_t *pcap_h,
682 struct bpf_program *fcode, const char *cfilter)
684 bpf_u_int32 netnum, netmask;
685 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
687 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
689 * Well, we can't get the netmask for this interface; it's used
690 * only for filters that check for broadcast IP addresses, so
691 * we just punt and use 0. It might be nice to warn the user,
692 * but that's a pain in a GUI application, as it'd involve popping
693 * up a message box, and it's not clear how often this would make
694 * a difference (only filters that check for IP broadcast addresses
695 * use the netmask).
697 /*cmdarg_err(
698 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
699 netmask = 0;
703 * Sigh. Older versions of libpcap don't properly declare the
704 * third argument to pcap_compile() as a const pointer. Cast
705 * away the warning.
707 DIAG_OFF(cast-qual)
708 if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
709 return FALSE;
710 DIAG_ON(cast-qual)
711 return TRUE;
714 static gboolean
715 show_filter_code(capture_options *capture_opts)
717 interface_options *interface_opts;
718 pcap_t *pcap_h;
719 cap_device_open_status open_status;
720 gchar open_status_str[PCAP_ERRBUF_SIZE];
721 char errmsg[MSG_MAX_LENGTH+1];
722 char secondary_errmsg[MSG_MAX_LENGTH+1];
723 struct bpf_program fcode;
724 struct bpf_insn *insn;
725 u_int i;
726 guint j;
728 for (j = 0; j < capture_opts->ifaces->len; j++) {
729 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, j);
730 pcap_h = open_capture_device(capture_opts, interface_opts,
731 CAP_READ_TIMEOUT, &open_status, &open_status_str);
732 if (pcap_h == NULL) {
733 /* Open failed; get messages */
734 get_capture_device_open_failure_messages(open_status, open_status_str,
735 interface_opts->name,
736 errmsg, sizeof errmsg,
737 secondary_errmsg,
738 sizeof secondary_errmsg);
739 /* And report them */
740 report_capture_error(errmsg, secondary_errmsg);
741 return FALSE;
744 /* Set the link-layer type. */
745 if (!set_pcap_datalink(pcap_h, interface_opts->linktype, interface_opts->name,
746 errmsg, sizeof errmsg,
747 secondary_errmsg, sizeof secondary_errmsg)) {
748 pcap_close(pcap_h);
749 report_capture_error(errmsg, secondary_errmsg);
750 return FALSE;
753 /* OK, try to compile the capture filter. */
754 if (!compile_capture_filter(interface_opts->name, pcap_h, &fcode,
755 interface_opts->cfilter)) {
756 snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_h));
757 pcap_close(pcap_h);
758 report_cfilter_error(capture_opts, j, errmsg);
759 return FALSE;
761 pcap_close(pcap_h);
763 /* Now print the filter code. */
764 insn = fcode.bf_insns;
766 for (i = 0; i < fcode.bf_len; insn++, i++)
767 printf("%s\n", bpf_image(insn, i));
769 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
770 /* to remove any suid privileges. */
771 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
772 /* (euid/egid have already previously been set to ruid/rgid. */
773 /* (See comment in main() for details) */
774 #ifndef HAVE_LIBCAP
775 relinquish_special_privs_perm();
776 #else
777 relinquish_all_capabilities();
778 #endif
779 if (capture_child) {
780 /* Let our parent know we succeeded. */
781 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
783 return TRUE;
786 static void
787 print_machine_readable_if_capabilities(json_dumper *dumper, if_capabilities_t *caps, int queries);
790 * Output a machine readable list of the interfaces
791 * This list is retrieved by the sync_interface_list_open() function
792 * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
794 static int
795 print_machine_readable_interfaces(GList *if_list, int caps_queries, bool print_statistics)
797 GList *if_entry;
798 if_info_t *if_info;
799 GSList *addr;
800 if_addr_t *if_addr;
801 char addr_str[WS_INET6_ADDRSTRLEN];
802 int status;
804 json_dumper dumper = {
805 .output_string = g_string_new(NULL),
806 .flags = JSON_DUMPER_FLAGS_NO_DEBUG,
807 // Don't abort on failure
809 json_dumper_begin_array(&dumper);
812 * Print the contents of the if_entry struct in a parseable format (JSON)
814 for (if_entry = g_list_first(if_list); if_entry != NULL;
815 if_entry = g_list_next(if_entry)) {
816 if_info = (if_info_t *)if_entry->data;
818 json_dumper_begin_object(&dumper);
819 json_dumper_set_member_name(&dumper, if_info->name);
821 json_dumper_begin_object(&dumper);
823 json_dumper_set_member_name(&dumper, "friendly_name");
824 json_dumper_value_string(&dumper, if_info->friendly_name);
826 json_dumper_set_member_name(&dumper, "vendor_description");
827 json_dumper_value_string(&dumper, if_info->vendor_description);
829 json_dumper_set_member_name(&dumper, "type");
830 json_dumper_value_anyf(&dumper, "%i", if_info->type);
832 json_dumper_set_member_name(&dumper, "addrs");
834 json_dumper_begin_array(&dumper);
835 for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
836 addr = g_slist_next(addr)) {
838 if_addr = (if_addr_t *)addr->data;
839 switch(if_addr->ifat_type) {
840 case IF_AT_IPv4:
841 json_dumper_value_string(&dumper, ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str, sizeof(addr_str)));
842 break;
843 case IF_AT_IPv6:
844 json_dumper_value_string(&dumper, ws_inet_ntop6(&if_addr->addr.ip6_addr, addr_str, sizeof(addr_str)));
845 break;
846 default:
847 json_dumper_value_anyf(&dumper, "<type unknown %i>", if_addr->ifat_type);
850 json_dumper_end_array(&dumper);
852 json_dumper_set_member_name(&dumper, "loopback");
853 json_dumper_value_anyf(&dumper, "%s", if_info->loopback ? "true" : "false");
855 json_dumper_set_member_name(&dumper, "extcap");
856 json_dumper_value_string(&dumper, if_info->extcap);
858 if (if_info->caps && caps_queries) {
859 json_dumper_set_member_name(&dumper, "caps");
860 json_dumper_begin_object(&dumper);
861 print_machine_readable_if_capabilities(&dumper, if_info->caps, caps_queries);
862 json_dumper_end_object(&dumper);
864 json_dumper_end_object(&dumper);
865 json_dumper_end_object(&dumper);
867 json_dumper_end_array(&dumper);
868 if (json_dumper_finish(&dumper)) {
869 status = 0;
870 if (capture_child) {
871 if (print_statistics) {
872 sync_pipe_write_string_msg(sync_pipe_fd, SP_IFACE_LIST, dumper.output_string->str);
873 } else {
874 /* Let our parent know we succeeded. */
875 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
876 printf("%s", dumper.output_string->str);
879 } else {
880 status = 2;
881 if (capture_child) {
882 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, "Unexpected JSON error", "");
885 g_string_free(dumper.output_string, TRUE);
886 return status;
890 * If you change the machine-readable output format of this function,
891 * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
893 static void
894 print_machine_readable_if_capabilities(json_dumper *dumper, if_capabilities_t *caps, int queries)
896 GList *lt_entry, *ts_entry;
897 const gchar *desc_str;
899 json_dumper_set_member_name(dumper, "status");
900 json_dumper_value_anyf(dumper, "%i", caps->status);
901 if (caps->primary_msg) {
902 json_dumper_set_member_name(dumper, "primary_msg");
903 json_dumper_value_string(dumper, caps->primary_msg);
906 if (queries & CAPS_QUERY_LINK_TYPES) {
907 json_dumper_set_member_name(dumper, "rfmon");
908 json_dumper_value_anyf(dumper, "%s", caps->can_set_rfmon ? "true" : "false");
909 json_dumper_set_member_name(dumper, "data_link_types");
910 json_dumper_begin_array(dumper);
911 for (lt_entry = caps->data_link_types; lt_entry != NULL;
912 lt_entry = g_list_next(lt_entry)) {
913 data_link_info_t *data_link_info = (data_link_info_t *)lt_entry->data;
914 if (data_link_info->description != NULL)
915 desc_str = data_link_info->description;
916 else
917 desc_str = "(not supported)";
918 json_dumper_begin_object(dumper);
919 json_dumper_set_member_name(dumper, "dlt");
920 json_dumper_value_anyf(dumper, "%d", data_link_info->dlt);
921 json_dumper_set_member_name(dumper, "name");
922 json_dumper_value_string(dumper, data_link_info->name);
923 json_dumper_set_member_name(dumper, "description");
924 json_dumper_value_string(dumper, desc_str);
925 json_dumper_end_object(dumper);
927 json_dumper_end_array(dumper);
929 json_dumper_set_member_name(dumper, "data_link_types_rfmon");
930 json_dumper_begin_array(dumper);
931 for (lt_entry = caps->data_link_types_rfmon; lt_entry != NULL;
932 lt_entry = g_list_next(lt_entry)) {
933 data_link_info_t *data_link_info = (data_link_info_t *)lt_entry->data;
934 if (data_link_info->description != NULL)
935 desc_str = data_link_info->description;
936 else
937 desc_str = "(not supported)";
938 json_dumper_begin_object(dumper);
939 json_dumper_set_member_name(dumper, "dlt");
940 json_dumper_value_anyf(dumper, "%d", data_link_info->dlt);
941 json_dumper_set_member_name(dumper, "name");
942 json_dumper_value_string(dumper, data_link_info->name);
943 json_dumper_set_member_name(dumper, "description");
944 json_dumper_value_string(dumper, desc_str);
945 json_dumper_end_object(dumper);
947 json_dumper_end_array(dumper);
949 if (queries & CAPS_QUERY_TIMESTAMP_TYPES) {
950 json_dumper_set_member_name(dumper, "timestamp_types");
951 json_dumper_begin_array(dumper);
952 for (ts_entry = caps->timestamp_types; ts_entry != NULL;
953 ts_entry = g_list_next(ts_entry)) {
954 timestamp_info_t *timestamp = (timestamp_info_t *)ts_entry->data;
955 if (timestamp->description != NULL)
956 desc_str = timestamp->description;
957 else
958 desc_str = "(none)";
959 json_dumper_begin_object(dumper);
960 json_dumper_set_member_name(dumper, "name");
961 json_dumper_value_string(dumper, timestamp->name);
962 json_dumper_set_member_name(dumper, "description");
963 json_dumper_value_string(dumper, desc_str);
964 json_dumper_end_object(dumper);
966 json_dumper_end_array(dumper);
970 typedef struct {
971 char *name;
972 pcap_t *pch;
973 } if_stat_t;
975 /* Print the number of packets captured for each interface until we're killed. */
976 static int
977 print_statistics_loop(gboolean machine_readable)
979 GList *if_list, *if_entry, *stat_list = NULL, *stat_entry;
980 if_info_t *if_info;
981 if_stat_t *if_stat;
982 int err;
983 gchar *err_str;
984 pcap_t *pch;
985 char errbuf[PCAP_ERRBUF_SIZE];
986 struct pcap_stat ps;
988 if_list = get_interface_list(&err, &err_str);
989 if (if_list == NULL) {
990 if (err == 0) {
991 cmdarg_err("There are no interfaces on which a capture can be done");
992 err = WS_EXIT_NO_INTERFACES;
994 else {
995 cmdarg_err("%s", err_str);
996 g_free(err_str);
998 return err;
1001 for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1002 if_info = (if_info_t *)if_entry->data;
1004 #ifdef __linux__
1005 /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
1006 * connections. We avoid collecting stats on them.
1008 if (!strncmp(if_info->name, "nf", 2)) {
1009 ws_debug("Skipping interface %s for stats", if_info->name);
1010 continue;
1012 #endif
1014 #ifdef HAVE_PCAP_OPEN
1016 * If we're opening a remote device, use pcap_open(); that's currently
1017 * the only open routine that supports remote devices.
1019 if (strncmp(if_info->name, "rpcap://", 8) == 0)
1020 pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1021 else
1022 #endif
1023 pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1025 if (pch) {
1026 if_stat = g_new(if_stat_t, 1);
1027 if_stat->name = g_strdup(if_info->name);
1028 if_stat->pch = pch;
1029 stat_list = g_list_append(stat_list, if_stat);
1033 if (!stat_list) {
1034 cmdarg_err("There are no interfaces on which a capture can be done");
1035 return 2;
1038 if (capture_child) {
1039 /* Let our parent know we succeeded. */
1040 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
1043 if (!machine_readable) {
1044 printf("%-15s %10s %10s\n", "Interface", "Received",
1045 "Dropped");
1048 global_ld.go = TRUE;
1049 while (global_ld.go) {
1050 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1051 if_stat = (if_stat_t *)stat_entry->data;
1052 /* XXX - what if this fails? */
1053 if (pcap_stats(if_stat->pch, &ps) == 0) {
1054 if (!machine_readable) {
1055 printf("%-15s %10u %10u\n", if_stat->name,
1056 ps.ps_recv, ps.ps_drop);
1057 } else {
1058 printf("%s\t%u\t%u\n", if_stat->name,
1059 ps.ps_recv, ps.ps_drop);
1060 fflush(stdout);
1064 #ifdef _WIN32
1065 /* If we have a dummy signal pipe check it */
1066 if (!signal_pipe_check_running()) {
1067 global_ld.go = FALSE;
1069 Sleep(1 * 1000);
1070 #else
1071 sleep(1);
1072 #endif
1075 /* XXX - Not reached. Should we look for 'q' in stdin? */
1076 for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1077 if_stat = (if_stat_t *)stat_entry->data;
1078 pcap_close(if_stat->pch);
1079 g_free(if_stat->name);
1080 g_free(if_stat);
1082 g_list_free(stat_list);
1083 free_interface_list(if_list);
1085 return 0;
1089 #ifdef _WIN32
1090 static BOOL WINAPI
1091 capture_cleanup_handler(DWORD dwCtrlType)
1093 /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1094 Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1095 is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1096 like SIGTERM at least when the machine's shutting down.
1098 For now, if we're running as a command rather than a capture child,
1099 we handle all but CTRL_LOGOFF_EVENT as indications that we should
1100 clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1101 in that way on UN*X.
1103 If we're not running as a capture child, we might be running as
1104 a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1105 user logs out. (XXX - can we explicitly check whether we're
1106 running as a service?) */
1108 ws_info("Console: Control signal");
1109 ws_debug("Console: Control signal, CtrlType: %lu", dwCtrlType);
1111 /* Keep capture running if we're a service and a user logs off */
1112 if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1113 capture_loop_stop();
1114 return TRUE;
1115 } else {
1116 return FALSE;
1119 #else
1120 static void
1121 capture_cleanup_handler(int signum _U_)
1123 /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1124 SIGTERM. We assume that if the user wanted it to keep running
1125 after they logged out, they'd have nohupped it. */
1127 capture_loop_stop();
1129 #endif
1132 static void
1133 report_capture_count(gboolean reportit)
1135 /* Don't print this if we're a capture child. */
1136 if (!capture_child && reportit) {
1137 fprintf(stderr, "\rPackets captured: %d\n", global_ld.packets_captured);
1138 /* stderr could be line buffered */
1139 fflush(stderr);
1144 #ifdef SIGINFO
1145 static void
1146 report_counts_for_siginfo(void)
1148 report_capture_count(quiet);
1149 infoprint = FALSE; /* we just reported it */
1152 static void
1153 report_counts_siginfo(int signum _U_)
1155 int sav_errno = errno;
1157 /* If we've been told to delay printing, just set a flag asking
1158 that we print counts (if we're supposed to), otherwise print
1159 the count of packets captured (if we're supposed to). */
1160 if (infodelay)
1161 infoprint = TRUE;
1162 else
1163 report_counts_for_siginfo();
1164 errno = sav_errno;
1166 #endif /* SIGINFO */
1168 static void
1169 exit_main(int status)
1171 ws_cleanup_sockets();
1173 #ifdef _WIN32
1174 /* can be helpful for debugging */
1175 #ifdef DEBUG_DUMPCAP
1176 printf("Press any key\n");
1177 _getch();
1178 #endif
1180 #endif /* _WIN32 */
1182 if (ringbuf_is_initialized()) {
1183 /* save_file is managed by ringbuffer, be sure to release the memory and
1184 * avoid capture_opts_cleanup from double-freeing 'save_file'. */
1185 ringbuf_free();
1186 global_capture_opts.save_file = NULL;
1189 capture_opts_cleanup(&global_capture_opts);
1190 exit(status);
1193 #ifdef HAVE_LIBCAP
1195 * If we were linked with libcap (not related to libpcap), make sure we have
1196 * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1197 * (See comment in main() for details)
1199 static void
1200 relinquish_privs_except_capture(void)
1202 /* If 'started_with_special_privs' (ie: suid) then enable for
1203 * ourself the NET_ADMIN and NET_RAW capabilities and then
1204 * drop our suid privileges.
1206 * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1207 * stuff we don't need (and shouldn't have).
1208 * CAP_NET_RAW: Packet capture (raw sockets).
1211 if (started_with_special_privs()) {
1212 cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1213 int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1215 cap_t caps = cap_init(); /* all capabilities initialized to off */
1217 print_caps("Pre drop, pre set");
1219 if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1220 cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1223 cap_set_flag(caps, CAP_PERMITTED, cl_len, cap_list, CAP_SET);
1224 cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1226 if (cap_set_proc(caps)) {
1227 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1229 print_caps("Pre drop, post set");
1231 relinquish_special_privs_perm();
1233 print_caps("Post drop, pre set");
1234 cap_set_flag(caps, CAP_EFFECTIVE, cl_len, cap_list, CAP_SET);
1235 if (cap_set_proc(caps)) {
1236 cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1238 print_caps("Post drop, post set");
1240 cap_free(caps);
1244 #endif /* HAVE_LIBCAP */
1246 /* Map DLT_ values, as returned by pcap_datalink(), to LINKTYPE_ values,
1247 as are written to capture files.
1249 Most of the time, a DLT_ value and the corresponding LINKYPE_ value
1250 are the same, but there are some cases, where a numeric value as
1251 a DLT_ doesn't uniquely identify a particular link-layer header type,
1252 where they differ, so that the values in files *do* identify
1253 particular link-layer header types. */
1255 /* LINKTYPE_ values that don't match corresponding DLT_ values on
1256 all platforms. */
1257 #define LINKTYPE_ATM_RFC1483 100
1258 #define LINKTYPE_RAW 101
1259 #define LINKTYPE_SLIP_BSDOS 102
1260 #define LINKTYPE_PPP_BSDOS 103
1261 #define LINKTYPE_C_HDLC 104
1262 #define LINKTYPE_IEEE802_11 105
1263 #define LINKTYPE_ATM_CLIP 106
1264 #define LINKTYPE_FRELAY 107
1265 #define LINKTYPE_LOOP 108
1266 #define LINKTYPE_ENC 109
1267 #define LINKTYPE_NETBSD_HDLC 112
1268 #define LINKTYPE_PFSYNC 246
1269 #define LINKTYPE_PKTAP 258
1271 static int
1272 dlt_to_linktype(int dlt)
1274 /* DLT_NULL through DLT_FDDI have the same numeric value on
1275 all platforms, so the corresponding LINKTYPE_s have the
1276 same numeric values. */
1277 if (dlt >= DLT_NULL && dlt <= DLT_FDDI)
1278 return (dlt);
1280 #if defined(DLT_PFSYNC) && DLT_PFSYNC != LINKTYPE_PFSYNC
1281 /* DLT_PFSYNC has a value on several platforms that's in the
1282 non-matching range, a value on FreeBSD that's in the high
1283 matching range and that's *not* equal to LINKTYPE_PFSYNC,
1284 and has a value on the rmaining platforms that's equal
1285 to LINKTYPE_PFSYNC, which is in the high matching range.
1287 Map it to LINKTYPE_PFSYNC if it's not equal to LINKTYPE_PFSYNC. */
1288 if (dlt == DLT_PFSYNC)
1289 return (LINKTYPE_PFSYNC);
1290 #endif
1292 /* DLT_PKTAP is defined as DLT_USER2 - which is in the high
1293 matching range - on Darwin because Apple used DLT_USER2
1294 on systems that users ran, not just as an internal thing.
1296 We map it to LINKTYPE_PKTAP if it's not equal to LINKTYPE_PKTAP
1297 so that DLT_PKTAP captures from Apple machines can be read by
1298 software that either doesn't handle DLT_USER2 or that handles it
1299 as something other than Apple PKTAP. */
1300 #if defined(DLT_PKTAP) && DLT_PKTAP != LINKTYPE_PKTAP
1301 if (dlt == DLT_PKTAP)
1302 return (LINKTYPE_PKTAP);
1303 #endif
1305 /* For all other DLT_s with values beyond 104, the value
1306 of the corresponding LINKTYPE_ is the same. */
1307 if (dlt >= 104)
1308 return (dlt);
1310 /* These DLT_ values have different values on different
1311 platforms, so we assigned them LINKTYPE_ values just
1312 below the lower bound of the high matchig range;
1313 those values should never be equal to any DLT_
1314 values, so that should avoid collisions.
1316 That way, for example, "raw IP" packets will have
1317 LINKTYPE_RAW as the code in all savefiles for
1318 which the code that writes them maps to that
1319 value, regardless of the platform on which they
1320 were written, so they should be readable on all
1321 platforms without having to determine on which
1322 platform they were written.
1324 We map the DLT_ values on this platform, whatever
1325 it might be, to the corresponding LINKTYPE_ values. */
1326 #ifdef DLT_ATM_RFC1483
1327 if (dlt == DLT_ATM_RFC1483)
1328 return (LINKTYPE_ATM_RFC1483);
1329 #endif
1330 #ifdef DLT_RAW
1331 if (dlt == DLT_RAW)
1332 return (LINKTYPE_RAW);
1333 #endif
1334 #ifdef DLT_SLIP_BSDOS
1335 if (dlt == DLT_SLIP_BSDOS)
1336 return (LINKTYPE_SLIP_BSDOS);
1337 #endif
1338 #ifdef DLT_PPP_BSDOS
1339 if (dlt == DLT_PPP_BSDOS)
1340 return (LINKTYPE_PPP_BSDOS);
1341 #endif
1343 /* These DLT_ values were originally defined on some platform,
1344 and weren't defined on other platforms.
1346 At least some of those values, on at least one platform,
1347 collide with the values of other DLT_s on other platforms,
1348 e.g. DLT_LOOP, so we don't just define them, on all
1349 platforms, as having the same value as on the original
1350 platform.
1352 Therefore, we assigned new LINKTYPE_ values to them, and,
1353 on the platforms where they weren't originally defined,
1354 define the DLT_s to have the same value as the corresponding
1355 LINKTYPE_.
1357 This means that, for capture files with the original
1358 platform's DLT_ value rather than the LINKTYPE_ value
1359 as a link-layer type, we will recognize those types
1360 on that platform, but not on other platforms. */
1361 #ifdef DLT_FR
1362 /* BSD/OS Frame Relay */
1363 if (dlt == DLT_FR)
1364 return (LINKTYPE_FRELAY);
1365 #endif
1366 #if defined(DLT_HDLC) && DLT_HDLC != LINKTYPE_NETBSD_HDLC
1367 /* NetBSD HDLC */
1368 if (dlt == DLT_HDLC)
1369 return (LINKTYPE_NETBSD_HDLC);
1370 #endif
1371 #if defined(DLT_C_HDLC) && DLT_C_HDLC != LINKTYPE_C_HDLC
1372 /* BSD/OS Cisco HDLC */
1373 if (dlt == DLT_C_HDLC)
1374 return (LINKTYPE_C_HDLC);
1375 #endif
1376 #if defined(DLT_LOOP) && DLT_LOOP != LINKTYPE_LOOP
1377 /* OpenBSD DLT_LOOP */
1378 if (dlt == DLT_LOOP)
1379 return (LINKTYPE_LOOP);
1380 #endif
1381 #if defined(DLT_ENC) && DLT_ENC != LINKTYPE_ENC
1382 /* OpenBSD DLT_ENC */
1383 if (dlt == DLT_ENC)
1384 return (LINKTYPE_ENC);
1385 #endif
1387 /* These DLT_ values are not on all platforms, but, so far,
1388 there don't appear to be any platforms that define
1389 other DLT_s with those values; we map them to
1390 different LINKTYPE_ values anyway, just in case. */
1391 #ifdef DLT_ATM_CLIP
1392 /* Linux ATM Classical IP */
1393 if (dlt == DLT_ATM_CLIP)
1394 return (LINKTYPE_ATM_CLIP);
1395 #endif
1397 /* Treat all other DLT_s as having the same value as the
1398 corresponding LINKTYPE_. */
1399 return (dlt);
1402 /* Take care of byte order in the libpcap headers read from pipes.
1403 * (function taken from wiretap/libpcap.c) */
1404 static void
1405 cap_pipe_adjust_pcap_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1407 if (byte_swapped) {
1408 /* Byte-swap the record header fields. */
1409 rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1410 rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1411 rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1412 rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1415 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1416 swapped, in order to match the BPF header layout.
1418 Unfortunately, some files were, according to a comment in the "libpcap"
1419 source, written with version 2.3 in their headers but without the
1420 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1421 would make no sense - we assume that we need to swap them. */
1422 if (hdr->version_major == 2 &&
1423 (hdr->version_minor < 3 ||
1424 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1425 guint32 temp;
1427 temp = rechdr->orig_len;
1428 rechdr->orig_len = rechdr->incl_len;
1429 rechdr->incl_len = temp;
1433 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1434 * or just read().
1436 static ssize_t
1437 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1439 #ifdef _WIN32
1440 if (from_socket) {
1441 return recv(pipe_fd, buf, (int)sz, 0);
1442 } else {
1443 return -1;
1445 #else
1446 return ws_read(pipe_fd, buf, sz);
1447 #endif
1450 #if defined(_WIN32)
1452 * Thread function that reads from a pipe and pushes the data
1453 * to the main application thread.
1456 * XXX Right now we use async queues for basic signaling. The main thread
1457 * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1458 * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1459 * Iff the read is successful cap_pipe_read pushes an item onto
1460 * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1461 * the queues themselves (yet).
1463 * We might want to move some of the cap_pipe_dispatch logic here so that
1464 * we can let cap_thread_read run independently, queuing up multiple reads
1465 * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1467 static void *cap_thread_read(void *arg)
1469 capture_src *pcap_src;
1470 #ifdef _WIN32
1471 BOOL res;
1472 DWORD last_err, bytes_read;
1473 #else /* _WIN32 */
1474 size_t bytes_read;
1475 #endif /* _WIN32 */
1477 pcap_src = (capture_src *)arg;
1478 while (pcap_src->cap_pipe_err == PIPOK) {
1479 g_async_queue_pop(pcap_src->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1480 g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1481 bytes_read = 0;
1482 while (bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1483 if ((pcap_src->from_cap_socket)
1484 #ifndef _WIN32
1485 || 1
1486 #endif
1489 ssize_t b;
1490 b = cap_pipe_read(pcap_src->cap_pipe_fd, pcap_src->cap_pipe_buf+bytes_read,
1491 pcap_src->cap_pipe_bytes_to_read - bytes_read, pcap_src->from_cap_socket);
1492 if (b <= 0) {
1493 if (b == 0) {
1494 pcap_src->cap_pipe_err = PIPEOF;
1495 bytes_read = 0;
1496 break;
1497 } else {
1498 pcap_src->cap_pipe_err = PIPERR;
1499 bytes_read = -1;
1500 break;
1502 } else {
1503 bytes_read += (DWORD)b;
1506 #ifdef _WIN32
1507 else
1509 /* If we try to use read() on a named pipe on Windows with partial
1510 * data it appears to return EOF.
1512 DWORD b;
1513 res = ReadFile(pcap_src->cap_pipe_h, pcap_src->cap_pipe_buf+bytes_read,
1514 pcap_src->cap_pipe_bytes_to_read - bytes_read,
1515 &b, NULL);
1517 bytes_read += b;
1518 if (!res) {
1519 last_err = GetLastError();
1520 if (last_err == ERROR_MORE_DATA) {
1521 continue;
1522 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1523 pcap_src->cap_pipe_err = PIPEOF;
1524 bytes_read = 0;
1525 break;
1527 pcap_src->cap_pipe_err = PIPERR;
1528 bytes_read = -1;
1529 break;
1530 } else if (b == 0 && pcap_src->cap_pipe_bytes_to_read > 0) {
1531 pcap_src->cap_pipe_err = PIPEOF;
1532 bytes_read = 0;
1533 break;
1536 #endif /*_WIN32 */
1538 pcap_src->cap_pipe_bytes_read = bytes_read;
1539 if (pcap_src->cap_pipe_bytes_read >= pcap_src->cap_pipe_bytes_to_read) {
1540 g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1542 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1544 /* Post to queue if we didn't read enough data as the main thread waits for the message */
1545 g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1546 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1547 /* There's still more of the record to read. */
1548 g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1550 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1551 return NULL;
1555 * Do a blocking read from a pipe within the main thread, by pushing
1556 * the read onto the pipe queue and then popping it off that queue;
1557 * the pipe will block until the pushed read completes.
1559 * We do it with another thread because we can't use select() on
1560 * pipes on Windows, as we can on UN*Xes, we can only use it on
1561 * sockets.
1563 void
1564 pipe_read_sync(capture_src *pcap_src, void *buf, DWORD nbytes)
1566 pcap_src->cap_pipe_buf = (char *) buf;
1567 pcap_src->cap_pipe_bytes_read = 0;
1568 pcap_src->cap_pipe_bytes_to_read = nbytes;
1569 /* We don't have to worry about cap_pipe_read_mtx here */
1570 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1571 g_async_queue_pop(pcap_src->cap_pipe_done_q);
1573 #endif
1575 /* Provide select() functionality for a single file descriptor
1576 * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1578 * Returns the same values as select.
1580 static int
1581 cap_pipe_select(int pipe_fd)
1583 fd_set rfds;
1584 struct timeval timeout;
1586 FD_ZERO(&rfds);
1587 FD_SET(pipe_fd, &rfds);
1589 timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1590 timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1592 return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1595 #define DEF_TCP_PORT 19000
1597 static int
1598 cap_open_socket(char *pipename, capture_src *pcap_src, char *errmsg, size_t errmsgl)
1600 struct sockaddr_storage sa;
1601 socklen_t sa_len;
1602 int fd;
1604 /* Skip the initial "TCP@" in the pipename. */
1605 if (ws_socket_ptoa(&sa, pipename + 4, DEF_TCP_PORT) < 0) {
1606 snprintf(errmsg, errmsgl,
1607 "The capture session could not be initiated because"
1608 "\"%s\" is not a valid socket specification", pipename);
1609 pcap_src->cap_pipe_err = PIPERR;
1610 return -1;
1613 if ((fd = (int)socket(sa.ss_family, SOCK_STREAM, 0)) < 0) {
1614 snprintf(errmsg, errmsgl,
1615 "The capture session could not be initiated because"
1616 " the socket couldn't be created due to the socket error: \n"
1617 #ifdef _WIN32
1618 " %s", win32strerror(WSAGetLastError()));
1619 #else
1620 " %d: %s", errno, g_strerror(errno));
1621 #endif
1622 pcap_src->cap_pipe_err = PIPERR;
1623 return -1;
1626 if (sa.ss_family == AF_INET6)
1627 sa_len = sizeof(struct sockaddr_in6);
1628 else
1629 sa_len = sizeof(struct sockaddr_in);
1630 if (connect(fd, (struct sockaddr *)&sa, sa_len) < 0) {
1631 snprintf(errmsg, errmsgl,
1632 "The capture session could not be initiated because"
1633 " the socket couldn't be connected due to the socket error: \n"
1634 #ifdef _WIN32
1635 " %s", win32strerror(WSAGetLastError()));
1636 #else
1637 " %d: %s", errno, g_strerror(errno));
1638 #endif
1639 pcap_src->cap_pipe_err = PIPERR;
1641 cap_pipe_close(fd, TRUE);
1642 return -1;
1645 pcap_src->from_cap_socket = TRUE;
1646 return fd;
1649 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1650 * otherwise.
1652 static void
1653 cap_pipe_close(int pipe_fd, gboolean from_socket)
1655 #ifdef _WIN32
1656 if (from_socket) {
1657 closesocket(pipe_fd);
1659 #else
1660 (void) from_socket; /* Mark unused, similar to Q_UNUSED */
1661 ws_close(pipe_fd);
1662 #endif
1665 /** Read bytes from a capture source, which is assumed to be a pipe or
1666 * socket.
1668 * Returns -1, or the number of bytes read similar to read(2).
1669 * Sets pcap_src->cap_pipe_err on error or EOF.
1671 static ssize_t
1672 cap_pipe_read_data_bytes(capture_src *pcap_src, char *errmsg, size_t errmsgl)
1674 int sel_ret;
1675 int fd = pcap_src->cap_pipe_fd;
1676 #ifdef _WIN32
1677 DWORD sz, bytes_read = 0;
1678 #else /* _WIN32 */
1679 ssize_t sz, bytes_read = 0;
1680 #endif /* _WIN32 */
1681 ssize_t b;
1683 #ifdef LOG_CAPTURE_VERBOSE
1684 ws_debug("cap_pipe_read_data_bytes read %lu of %lu",
1685 pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1686 #endif
1687 sz = pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read;
1688 while (bytes_read < sz) {
1689 if (fd == -1) {
1690 snprintf(errmsg, errmsgl, "Invalid file descriptor.");
1691 pcap_src->cap_pipe_err = PIPNEXIST;
1692 return -1;
1695 sel_ret = cap_pipe_select(fd);
1696 if (sel_ret < 0) {
1697 snprintf(errmsg, errmsgl,
1698 "Unexpected error from select: %s.", g_strerror(errno));
1699 pcap_src->cap_pipe_err = PIPERR;
1700 return -1;
1701 } else if (sel_ret > 0) {
1702 b = cap_pipe_read(fd, pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read+bytes_read,
1703 sz-bytes_read, pcap_src->from_cap_socket);
1704 if (b <= 0) {
1705 if (b == 0) {
1706 snprintf(errmsg, errmsgl,
1707 "End of file reading from pipe or socket.");
1708 pcap_src->cap_pipe_err = PIPEOF;
1709 } else {
1710 #ifdef _WIN32
1712 * On Windows, we only do this for sockets.
1714 DWORD lastError = WSAGetLastError();
1715 errno = lastError;
1716 snprintf(errmsg, errmsgl,
1717 "Error reading from pipe or socket: %s.",
1718 win32strerror(lastError));
1719 #else
1720 snprintf(errmsg, errmsgl,
1721 "Error reading from pipe or socket: %s.",
1722 g_strerror(errno));
1723 #endif
1724 pcap_src->cap_pipe_err = PIPERR;
1726 return -1;
1728 #ifdef _WIN32
1729 bytes_read += (DWORD)b;
1730 #else
1731 bytes_read += b;
1732 #endif
1735 pcap_src->cap_pipe_bytes_read += bytes_read;
1736 #ifdef LOG_CAPTURE_VERBOSE
1737 ws_debug("cap_pipe_read_data_bytes read %lu of %lu",
1738 pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1739 #endif
1740 return bytes_read;
1743 /* Some forward declarations for breaking up cap_pipe_open_live for pcap and pcapng formats */
1744 static void pcap_pipe_open_live(int fd, capture_src *pcap_src,
1745 struct pcap_hdr *hdr,
1746 char *errmsg, size_t errmsgl,
1747 char *secondary_errmsg, size_t secondary_errmsgl);
1748 static void pcapng_pipe_open_live(int fd, capture_src *pcap_src,
1749 char *errmsg, size_t errmsgl);
1750 static int pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src,
1751 char *errmsg, size_t errmsgl);
1753 /* For problems that are probably Not Our Fault. */
1754 static char not_our_bug[] =
1755 "Please report this to the developers of the program writing to the pipe.";
1757 /* Mimic pcap_open_live() for pipe captures
1759 * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1760 * open it, and read the header.
1762 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1763 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1764 static void
1765 cap_pipe_open_live(char *pipename,
1766 capture_src *pcap_src,
1767 void *hdr,
1768 char *errmsg, size_t errmsgl,
1769 char *secondary_errmsg, size_t secondary_errmsgl)
1771 #ifndef _WIN32
1772 ws_statb64 pipe_stat;
1773 struct sockaddr_un sa;
1774 #else /* _WIN32 */
1775 guintptr extcap_pipe_handle;
1776 #endif
1777 gboolean extcap_pipe = FALSE;
1778 ssize_t b;
1779 int fd = -1, sel_ret;
1780 size_t bytes_read;
1781 guint32 magic = 0;
1782 pcap_src->cap_pipe_fd = -1;
1783 #ifdef _WIN32
1784 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1785 #endif
1787 ws_debug("cap_pipe_open_live: %s", pipename);
1790 * XXX - this blocks until a pcap per-file header has been written to
1791 * the pipe, so it could block indefinitely.
1793 if (strcmp(pipename, "-") == 0) {
1794 #ifndef _WIN32
1795 fd = 0; /* read from stdin */
1796 #else /* _WIN32 */
1797 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1798 #endif /* _WIN32 */
1799 } else if (!strncmp(pipename, "TCP@", 4)) {
1800 if ((fd = cap_open_socket(pipename, pcap_src, errmsg, errmsgl)) < 0) {
1801 return;
1803 } else {
1804 #ifndef _WIN32
1805 if ( g_strrstr(pipename, EXTCAP_PIPE_PREFIX) != NULL )
1806 extcap_pipe = TRUE;
1808 if (ws_stat64(pipename, &pipe_stat) < 0) {
1809 if (errno == ENOENT || errno == ENOTDIR)
1810 pcap_src->cap_pipe_err = PIPNEXIST;
1811 else {
1812 snprintf(errmsg, errmsgl,
1813 "The capture session could not be initiated "
1814 "due to error getting information on pipe or socket: %s.", g_strerror(errno));
1815 pcap_src->cap_pipe_err = PIPERR;
1817 return;
1819 if (S_ISFIFO(pipe_stat.st_mode)) {
1820 fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1821 if (fd == -1) {
1822 snprintf(errmsg, errmsgl,
1823 "The capture session could not be initiated "
1824 "due to error on pipe open: %s.", g_strerror(errno));
1825 pcap_src->cap_pipe_err = PIPERR;
1826 return;
1828 } else if (S_ISSOCK(pipe_stat.st_mode)) {
1829 fd = socket(AF_UNIX, SOCK_STREAM, 0);
1830 if (fd == -1) {
1831 snprintf(errmsg, errmsgl,
1832 "The capture session could not be initiated "
1833 "due to error on socket create: %s.", g_strerror(errno));
1834 pcap_src->cap_pipe_err = PIPERR;
1835 return;
1837 sa.sun_family = AF_UNIX;
1839 * The Single UNIX Specification says:
1841 * The size of sun_path has intentionally been left undefined.
1842 * This is because different implementations use different sizes.
1843 * For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1844 * of 104. Since most implementations originate from BSD versions,
1845 * the size is typically in the range 92 to 108.
1847 * Applications should not assume a particular length for sun_path
1848 * or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1850 * It also says
1852 * The <sys/un.h> header shall define the sockaddr_un structure,
1853 * which shall include at least the following members:
1855 * sa_family_t sun_family Address family.
1856 * char sun_path[] Socket pathname.
1858 * so we assume that it's an array, with a specified size,
1859 * and that the size reflects the maximum path length.
1861 if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1862 /* Path name too long */
1863 snprintf(errmsg, errmsgl,
1864 "The capture session could not be initiated "
1865 "due to error on socket connect: Path name too long.");
1866 pcap_src->cap_pipe_err = PIPERR;
1867 ws_close(fd);
1868 return;
1870 b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1871 if (b == -1) {
1872 snprintf(errmsg, errmsgl,
1873 "The capture session could not be initiated "
1874 "due to error on socket connect: %s.", g_strerror(errno));
1875 pcap_src->cap_pipe_err = PIPERR;
1876 ws_close(fd);
1877 return;
1879 } else {
1880 if (S_ISCHR(pipe_stat.st_mode)) {
1882 * Assume the user specified an interface on a system where
1883 * interfaces are in /dev. Pretend we haven't seen it.
1885 pcap_src->cap_pipe_err = PIPNEXIST;
1886 } else {
1887 snprintf(errmsg, errmsgl,
1888 "The capture session could not be initiated because\n"
1889 "\"%s\" is neither an interface nor a socket nor a pipe.", pipename);
1890 pcap_src->cap_pipe_err = PIPERR;
1892 return;
1895 #else /* _WIN32 */
1896 if (sscanf(pipename, EXTCAP_PIPE_PREFIX "%" SCNuPTR, &extcap_pipe_handle) == 1)
1898 /* The client is already connected to extcap pipe.
1899 * We have inherited the handle from parent process.
1901 extcap_pipe = TRUE;
1902 pcap_src->cap_pipe_h = (HANDLE)extcap_pipe_handle;
1904 else
1906 if (!win32_is_pipe_name(pipename)) {
1907 snprintf(errmsg, errmsgl,
1908 "The capture session could not be initiated because\n"
1909 "\"%s\" is neither an interface nor a pipe.", pipename);
1910 pcap_src->cap_pipe_err = PIPNEXIST;
1911 return;
1914 /* Wait for the pipe to appear */
1915 while (1) {
1916 pcap_src->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1917 OPEN_EXISTING, 0, NULL);
1919 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE)
1920 break;
1922 if (GetLastError() != ERROR_PIPE_BUSY) {
1923 snprintf(errmsg, errmsgl,
1924 "The capture session on \"%s\" could not be started "
1925 "due to error on pipe open: %s.",
1926 pipename, win32strerror(GetLastError()));
1927 pcap_src->cap_pipe_err = PIPERR;
1928 return;
1931 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1932 snprintf(errmsg, errmsgl,
1933 "The capture session on \"%s\" timed out during "
1934 "pipe open: %s.",
1935 pipename, win32strerror(GetLastError()));
1936 pcap_src->cap_pipe_err = PIPERR;
1937 return;
1941 #endif /* _WIN32 */
1944 pcap_src->from_cap_pipe = TRUE;
1947 * We start with a 2KB buffer for packet data, which should be
1948 * large enough for most regular network packets. We increase it,
1949 * up to the maximum size we allow, as necessary.
1951 pcap_src->cap_pipe_databuf = (char*)g_malloc(2048);
1952 pcap_src->cap_pipe_databuf_size = 2048;
1955 * Read the first 4 bytes of data from the pipe.
1957 * If a pcap file is being written to it, that will be
1958 * the pcap magic number.
1960 * If a pcapng file is being written to it, that will be
1961 * the block type of the initial SHB.
1963 #ifdef _WIN32
1965 * On UN*X, we can use select() on pipes or sockets.
1967 * On Windows, we can only use it on sockets; to do non-blocking
1968 * reads from pipes, we currently do reads in a separate thread
1969 * and use GLib asynchronous queues from the main thread to start
1970 * read operations and to wait for them to complete.
1972 if (pcap_src->from_cap_socket)
1973 #endif
1975 bytes_read = 0;
1976 while (bytes_read < sizeof magic) {
1977 sel_ret = cap_pipe_select(fd);
1978 if (sel_ret < 0) {
1979 snprintf(errmsg, errmsgl,
1980 "Unexpected error from select: %s.",
1981 g_strerror(errno));
1982 goto error;
1983 } else if (sel_ret > 0) {
1984 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
1985 sizeof magic-bytes_read,
1986 pcap_src->from_cap_socket);
1987 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1988 if (extcap_pipe && b <= 0)
1989 goto error;
1991 if (b <= 0) {
1992 if (b == 0)
1993 snprintf(errmsg, errmsgl,
1994 "End of file on pipe magic during open.");
1995 else
1996 snprintf(errmsg, errmsgl,
1997 "Error on pipe magic during open: %s.",
1998 g_strerror(errno));
1999 goto error;
2001 bytes_read += b;
2005 #ifdef _WIN32
2006 else {
2007 /* Create a thread to read from this pipe */
2008 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
2010 pipe_read_sync(pcap_src, &magic, sizeof(magic));
2011 /* jump messaging, if extcap had an error, stderr will provide the correct message */
2012 if (pcap_src->cap_pipe_bytes_read <= 0 && extcap_pipe)
2013 goto error;
2015 if (pcap_src->cap_pipe_bytes_read <= 0) {
2016 if (pcap_src->cap_pipe_bytes_read == 0)
2017 snprintf(errmsg, errmsgl,
2018 "End of file on pipe magic during open.");
2019 else
2020 snprintf(errmsg, errmsgl,
2021 "Error on pipe magic during open: %s.",
2022 g_strerror(errno));
2023 goto error;
2026 #endif
2028 switch (magic) {
2029 case PCAP_MAGIC:
2030 case PCAP_NSEC_MAGIC:
2031 /* This is a pcap file.
2032 The host that wrote it has our byte order, and was running
2033 a program using either standard or ss990417 libpcap. */
2034 pcap_src->cap_pipe_info.pcap.byte_swapped = FALSE;
2035 pcap_src->cap_pipe_modified = FALSE;
2036 pcap_src->ts_nsec = magic == PCAP_NSEC_MAGIC;
2037 break;
2038 case PCAP_MODIFIED_MAGIC:
2039 /* This is a pcap file.
2040 The host that wrote it has our byte order, but was running
2041 a program using either ss990915 or ss991029 libpcap. */
2042 pcap_src->cap_pipe_info.pcap.byte_swapped = FALSE;
2043 pcap_src->cap_pipe_modified = TRUE;
2044 break;
2045 case PCAP_SWAPPED_MAGIC:
2046 case PCAP_SWAPPED_NSEC_MAGIC:
2047 /* This is a pcap file.
2048 The host that wrote it has a byte order opposite to ours,
2049 and was running a program using either standard or
2050 ss990417 libpcap. */
2051 pcap_src->cap_pipe_info.pcap.byte_swapped = TRUE;
2052 pcap_src->cap_pipe_modified = FALSE;
2053 pcap_src->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
2054 break;
2055 case PCAP_SWAPPED_MODIFIED_MAGIC:
2056 /* This is a pcap file.
2057 The host that wrote it out has a byte order opposite to
2058 ours, and was running a program using either ss990915
2059 or ss991029 libpcap. */
2060 pcap_src->cap_pipe_info.pcap.byte_swapped = TRUE;
2061 pcap_src->cap_pipe_modified = TRUE;
2062 break;
2063 case BLOCK_TYPE_SHB:
2064 /* This is a pcapng file. */
2065 pcap_src->from_pcapng = TRUE;
2066 pcap_src->cap_pipe_dispatch = pcapng_pipe_dispatch;
2067 pcap_src->cap_pipe_info.pcapng.src_iface_to_global = g_array_new(FALSE, FALSE, sizeof(guint32));
2068 global_capture_opts.use_pcapng = TRUE; /* we can only output in pcapng format */
2069 break;
2070 default:
2071 /* Not a pcapng file, and either not a pcap type we know about
2072 or not a pcap file, either. */
2073 snprintf(errmsg, errmsgl,
2074 "File type is neither a supported pcap nor pcapng format. (magic = 0x%08x)", magic);
2075 snprintf(secondary_errmsg, secondary_errmsgl, "%s",
2076 not_our_bug);
2077 goto error;
2080 if (pcap_src->from_pcapng)
2081 pcapng_pipe_open_live(fd, pcap_src, errmsg, errmsgl);
2082 else
2083 pcap_pipe_open_live(fd, pcap_src, (struct pcap_hdr *) hdr, errmsg, errmsgl,
2084 secondary_errmsg, secondary_errmsgl);
2086 return;
2088 error:
2089 ws_debug("cap_pipe_open_live: error %s", errmsg);
2090 pcap_src->cap_pipe_err = PIPERR;
2091 cap_pipe_close(fd, pcap_src->from_cap_socket);
2092 pcap_src->cap_pipe_fd = -1;
2093 #ifdef _WIN32
2094 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2095 #endif
2099 * Read the part of the pcap file header that follows the magic
2100 * number (we've already read the magic number).
2102 static void
2103 pcap_pipe_open_live(int fd,
2104 capture_src *pcap_src,
2105 struct pcap_hdr *hdr,
2106 char *errmsg, size_t errmsgl,
2107 char *secondary_errmsg, size_t secondary_errmsgl)
2109 size_t bytes_read;
2110 ssize_t b;
2111 int sel_ret;
2114 * We're reading from a pcap file. We've already read the magic
2115 * number; read the rest of the header.
2117 * (Note that struct pcap_hdr is a structure for the part of a
2118 * pcap file header *following the magic number*; it does not
2119 * include the magic number itself.)
2121 #ifdef _WIN32
2122 if (pcap_src->from_cap_socket)
2123 #endif
2125 /* Keep reading until we get the rest of the header. */
2126 bytes_read = 0;
2127 while (bytes_read < sizeof(struct pcap_hdr)) {
2128 sel_ret = cap_pipe_select(fd);
2129 if (sel_ret < 0) {
2130 snprintf(errmsg, errmsgl,
2131 "Unexpected error from select: %s.",
2132 g_strerror(errno));
2133 goto error;
2134 } else if (sel_ret > 0) {
2135 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
2136 sizeof(struct pcap_hdr) - bytes_read,
2137 pcap_src->from_cap_socket);
2138 if (b <= 0) {
2139 if (b == 0)
2140 snprintf(errmsg, errmsgl,
2141 "End of file on pipe header during open.");
2142 else
2143 snprintf(errmsg, errmsgl,
2144 "Error on pipe header during open: %s.",
2145 g_strerror(errno));
2146 snprintf(secondary_errmsg, secondary_errmsgl,
2147 "%s", not_our_bug);
2148 goto error;
2150 bytes_read += b;
2154 #ifdef _WIN32
2155 else {
2156 pipe_read_sync(pcap_src, hdr, sizeof(struct pcap_hdr));
2157 if (pcap_src->cap_pipe_bytes_read <= 0) {
2158 if (pcap_src->cap_pipe_bytes_read == 0)
2159 snprintf(errmsg, errmsgl,
2160 "End of file on pipe header during open.");
2161 else
2162 snprintf(errmsg, errmsgl,
2163 "Error on pipe header header during open: %s.",
2164 g_strerror(errno));
2165 snprintf(secondary_errmsg, secondary_errmsgl, "%s",
2166 not_our_bug);
2167 goto error;
2170 #endif
2172 if (pcap_src->cap_pipe_info.pcap.byte_swapped) {
2173 /* Byte-swap the header fields about which we care. */
2174 hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
2175 hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
2176 hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
2177 hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
2180 * The link-layer header type field of the pcap header is
2181 * probably a LINKTYPE_ value, as the vast majority of
2182 * LINKTYPE_ values and their corresponding DLT_ values
2183 * are the same.
2185 * However, in case the file was written by a program
2186 * that used a DLT_ value, rather than a LINKTYPE_ value,
2187 * in one of the cases where the two differ, use dlt_to_linktype()
2188 * to map to a LINKTYPE_ value, just as we use it to map
2189 * the result of pcap_datalink() to a LINKTYPE_ value.
2191 pcap_src->linktype = dlt_to_linktype(hdr->network);
2192 /* Pick the appropriate maximum packet size for the link type */
2193 switch (pcap_src->linktype) {
2195 case 231: /* DLT_DBUS */
2196 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_DBUS;
2197 break;
2199 case 279: /* DLT_EBHSCR */
2200 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_EBHSCR;
2201 break;
2203 case 249: /* DLT_USBPCAP */
2204 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_USBPCAP;
2205 break;
2207 default:
2208 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
2209 break;
2212 if (hdr->version_major < 2) {
2213 snprintf(errmsg, errmsgl,
2214 "The old pcap format version %d.%d is not supported.",
2215 hdr->version_major, hdr->version_minor);
2216 snprintf(secondary_errmsg, secondary_errmsgl, "%s",
2217 not_our_bug);
2218 goto error;
2221 pcap_src->cap_pipe_fd = fd;
2222 return;
2224 error:
2225 ws_debug("pcap_pipe_open_live: error %s", errmsg);
2226 pcap_src->cap_pipe_err = PIPERR;
2227 cap_pipe_close(fd, pcap_src->from_cap_socket);
2228 pcap_src->cap_pipe_fd = -1;
2229 #ifdef _WIN32
2230 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2231 #endif
2235 * Synchronously read the fixed portion of the pcapng section header block
2236 * (we've already read the pcapng block header).
2238 static int
2239 pcapng_read_shb(capture_src *pcap_src,
2240 char *errmsg,
2241 size_t errmsgl)
2243 pcapng_section_header_block_t shb;
2245 #ifdef _WIN32
2246 if (pcap_src->from_cap_socket)
2247 #endif
2249 pcap_src->cap_pipe_bytes_to_read = sizeof(pcapng_block_header_t) + sizeof(pcapng_section_header_block_t);
2250 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2251 return -1;
2254 #ifdef _WIN32
2255 else {
2256 pipe_read_sync(pcap_src, pcap_src->cap_pipe_databuf + sizeof(pcapng_block_header_t),
2257 sizeof(pcapng_section_header_block_t));
2258 if (pcap_src->cap_pipe_bytes_read <= 0) {
2259 if (pcap_src->cap_pipe_bytes_read == 0)
2260 snprintf(errmsg, errmsgl,
2261 "End of file reading from pipe or socket.");
2262 else
2263 snprintf(errmsg, errmsgl,
2264 "Error reading from pipe or socket: %s.",
2265 g_strerror(errno));
2266 return -1;
2268 /* Continuing with STATE_EXPECT_DATA requires reading into cap_pipe_databuf at offset cap_pipe_bytes_read */
2269 pcap_src->cap_pipe_bytes_read = sizeof(pcapng_block_header_t) + sizeof(pcapng_section_header_block_t);
2271 #endif
2272 memcpy(&shb, pcap_src->cap_pipe_databuf + sizeof(pcapng_block_header_t), sizeof(pcapng_section_header_block_t));
2273 switch (shb.magic)
2275 case PCAPNG_MAGIC:
2276 ws_debug("pcapng SHB MAGIC");
2277 break;
2278 case PCAPNG_SWAPPED_MAGIC:
2279 ws_debug("pcapng SHB SWAPPED MAGIC");
2281 * pcapng sources can contain all sorts of block types.
2282 * Rather than add a bunch of complexity to this code (which is
2283 * often privileged), punt and tell the user to swap bytes
2284 * elsewhere.
2286 * XXX - punting means that the Wireshark test suite must be
2287 * modified to:
2289 * 1) have both little-endian and big-endian versions of
2290 * all pcapng files piped to dumpcap;
2292 * 2) pipe the appropriate file to dumpcap, depending on
2293 * the byte order of the host on which the tests are
2294 * being run;
2296 * as per comments in bug 15772 and 15754.
2298 * Are we *really* certain that the complexity added would be
2299 * significant enough to make adding it a security risk? And
2300 * why would this code even be running with any elevated
2301 * privileges if you're capturing from a pipe? We should not
2302 * only have given up all additional privileges if we're reading
2303 * from a pipe, we should give them up in such a fashion that
2304 * we can't reclaim them.
2306 #if G_BYTE_ORDER == G_BIG_ENDIAN
2307 #define OUR_ENDIAN "big"
2308 #define IFACE_ENDIAN "little"
2309 #else
2310 #define OUR_ENDIAN "little"
2311 #define IFACE_ENDIAN "big"
2312 #endif
2313 snprintf(errmsg, errmsgl,
2314 "Interface %u is " IFACE_ENDIAN " endian but we're " OUR_ENDIAN " endian.",
2315 pcap_src->interface_id);
2316 return -1;
2317 default:
2318 /* Not a pcapng type we know about, or not pcapng at all. */
2319 snprintf(errmsg, errmsgl,
2320 "Unrecognized pcapng format or not pcapng data.");
2321 return -1;
2324 pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
2326 /* Setup state to capture any options following the section header block */
2327 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2329 return 0;
2333 * Save IDB blocks for playback whenever we change output files, and
2334 * fix LINKTYPE_ values that are really platform-dependent DLT_ values.
2335 * Rewrite EPB and ISB interface IDs.
2337 static gboolean
2338 pcapng_adjust_block(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd)
2340 switch(bh->block_type) {
2341 case BLOCK_TYPE_SHB:
2343 if (global_ld.pcapng_passthrough) {
2345 * We have a single pcapng input. We pass the SHB through when
2346 * writing a single output file and for the first ring buffer
2347 * file. We need to save it for the second and subsequent ring
2348 * buffer files.
2350 g_free(global_ld.saved_shb);
2351 global_ld.saved_shb = (guint8 *) g_memdup2(pd, bh->block_total_length);
2354 * We're dealing with one section at a time, so we can (and must)
2355 * get rid of our old IDBs.
2357 for (unsigned i = 0; i < global_ld.saved_idbs->len; i++) {
2358 saved_idb_t *idb_source = &g_array_index(global_ld.saved_idbs, saved_idb_t, i);
2359 g_free(idb_source->idb);
2361 g_array_set_size(global_ld.saved_idbs, 0);
2362 } else {
2364 * We have a new SHB from this capture source. We need to keep
2365 * global_ld.saved_idbs intact, so we mark IDBs we previously
2366 * collected from this source as deleted.
2368 for (unsigned i = 0; i < pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len; i++) {
2369 guint32 iface_id = g_array_index(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, guint32, i);
2370 saved_idb_t *idb_source = &g_array_index(global_ld.saved_idbs, saved_idb_t, iface_id);
2371 ws_assert(idb_source->interface_id == pcap_src->interface_id);
2372 g_free(idb_source->idb);
2373 memset(idb_source, 0, sizeof(saved_idb_t));
2374 idb_source->deleted = TRUE;
2375 ws_debug("%s: deleted pcapng IDB %u", G_STRFUNC, iface_id);
2378 g_array_set_size(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, 0);
2380 break;
2381 case BLOCK_TYPE_IDB:
2384 * Always gather IDBs. We can remove them or mark them as deleted
2385 * when we get a new SHB.
2387 saved_idb_t idb_source = { 0 };
2388 idb_source.interface_id = pcap_src->interface_id;
2389 idb_source.idb_len = bh->block_total_length;
2390 idb_source.idb = (guint8 *) g_memdup2(pd, idb_source.idb_len);
2391 g_array_append_val(global_ld.saved_idbs, idb_source);
2392 guint32 iface_id = global_ld.saved_idbs->len - 1;
2393 g_array_append_val(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, iface_id);
2394 ws_debug("%s: mapped pcapng IDB %u -> %u from source %u",
2395 G_STRFUNC, pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len - 1, iface_id, pcap_src->interface_id);
2397 break;
2398 case BLOCK_TYPE_EPB:
2399 case BLOCK_TYPE_ISB:
2401 if (global_ld.pcapng_passthrough) {
2402 /* Our input and output interface IDs are the same. */
2403 break;
2405 /* The interface ID is the first 32-bit field after the BH for both EPBs and ISBs. */
2406 guint32 iface_id;
2407 memcpy(&iface_id, pd + sizeof(pcapng_block_header_t), 4);
2408 if (iface_id < pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len) {
2409 memcpy(pd + sizeof(pcapng_block_header_t),
2410 &g_array_index(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, guint32, iface_id), 4);
2411 } else {
2412 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);
2413 return FALSE;
2416 break;
2417 default:
2418 break;
2421 return TRUE;
2425 * Return true if the block contains packet, event, or log data. Return false otherwise.
2427 static bool is_data_block(uint32_t block_type)
2429 // Any block types that lead to calling wtap_read_packet_bytes in
2430 // wiretap/pcapng.c should be listed here.
2431 switch (block_type) {
2432 case BLOCK_TYPE_PB:
2433 case BLOCK_TYPE_EPB:
2434 case BLOCK_TYPE_SPB:
2435 case BLOCK_TYPE_SYSTEMD_JOURNAL_EXPORT:
2436 case BLOCK_TYPE_SYSDIG_EVENT:
2437 case BLOCK_TYPE_SYSDIG_EVENT_V2:
2438 case BLOCK_TYPE_SYSDIG_EVENT_V2_LARGE:
2439 return true;
2440 default:
2441 break;
2443 return false;
2447 * Read the part of the initial pcapng SHB following the block type
2448 * (we've already read the block type).
2450 static void
2451 pcapng_pipe_open_live(int fd,
2452 capture_src *pcap_src,
2453 char *errmsg,
2454 size_t errmsgl)
2456 guint32 type = BLOCK_TYPE_SHB;
2457 pcapng_block_header_t *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2459 ws_debug("pcapng_pipe_open_live: fd %d", fd);
2462 * A pcapng block begins with the block type followed by the block
2463 * total length; we've already read the block type, now read the
2464 * block length.
2466 #ifdef _WIN32
2468 * On UN*X, we can use select() on pipes or sockets.
2470 * On Windows, we can only use it on sockets; to do non-blocking
2471 * reads from pipes, we currently do reads in a separate thread
2472 * and use GLib asynchronous queues from the main thread to start
2473 * read operations and to wait for them to complete.
2475 if (pcap_src->from_cap_socket)
2476 #endif
2478 memcpy(pcap_src->cap_pipe_databuf, &type, sizeof(guint32));
2479 pcap_src->cap_pipe_bytes_read = sizeof(guint32);
2480 pcap_src->cap_pipe_bytes_to_read = sizeof(pcapng_block_header_t);
2481 pcap_src->cap_pipe_fd = fd;
2482 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2483 goto error;
2485 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(pcapng_block_header_t));
2487 #ifdef _WIN32
2488 else {
2489 g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
2491 bh->block_type = type;
2492 pipe_read_sync(pcap_src, &bh->block_total_length,
2493 sizeof(bh->block_total_length));
2494 if (pcap_src->cap_pipe_bytes_read <= 0) {
2495 if (pcap_src->cap_pipe_bytes_read == 0)
2496 snprintf(errmsg, errmsgl,
2497 "End of file reading from pipe or socket.");
2498 else
2499 snprintf(errmsg, errmsgl,
2500 "Error reading from pipe or socket: %s.",
2501 g_strerror(errno));
2502 goto error;
2504 pcap_src->cap_pipe_bytes_read = sizeof(pcapng_block_header_t);
2505 memcpy(pcap_src->cap_pipe_databuf, bh, sizeof(pcapng_block_header_t));
2506 pcap_src->cap_pipe_fd = fd;
2508 #endif
2509 if ((bh->block_total_length & 0x03) != 0) {
2510 snprintf(errmsg, errmsgl,
2511 "block_total_length read from pipe is %u, which is not a multiple of 4.",
2512 bh->block_total_length);
2513 goto error;
2515 if (pcapng_read_shb(pcap_src, errmsg, errmsgl)) {
2516 goto error;
2519 return;
2521 error:
2522 ws_debug("pcapng_pipe_open_live: error %s", errmsg);
2523 pcap_src->cap_pipe_err = PIPERR;
2524 cap_pipe_close(fd, pcap_src->from_cap_socket);
2525 pcap_src->cap_pipe_fd = -1;
2526 #ifdef _WIN32
2527 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2528 #endif
2531 /* We read one record from the pipe, take care of byte order in the record
2532 * header, write the record to the capture file, and update capture statistics. */
2533 static int
2534 pcap_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, size_t errmsgl)
2536 struct pcap_pkthdr phdr;
2537 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2538 PD_ERR } result;
2539 #ifdef _WIN32
2540 gpointer q_status;
2541 #endif
2542 ssize_t b;
2543 guint new_bufsize;
2544 pcap_pipe_info_t *pcap_info = &pcap_src->cap_pipe_info.pcap;
2546 #ifdef LOG_CAPTURE_VERBOSE
2547 ws_debug("pcap_pipe_dispatch");
2548 #endif
2550 switch (pcap_src->cap_pipe_state) {
2552 case STATE_EXPECT_REC_HDR:
2553 #ifdef _WIN32
2554 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2555 #endif
2557 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2558 pcap_src->cap_pipe_bytes_to_read = pcap_src->cap_pipe_modified ?
2559 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2560 pcap_src->cap_pipe_bytes_read = 0;
2562 #ifdef _WIN32
2563 pcap_src->cap_pipe_buf = (char *) &pcap_info->rechdr;
2564 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2565 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2567 #endif
2568 /* Fall through */
2570 case STATE_READ_REC_HDR:
2571 #ifdef _WIN32
2572 if (pcap_src->from_cap_socket)
2573 #endif
2575 b = cap_pipe_read(pcap_src->cap_pipe_fd, ((char *)&pcap_info->rechdr)+pcap_src->cap_pipe_bytes_read,
2576 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read, pcap_src->from_cap_socket);
2577 if (b <= 0) {
2578 if (b == 0)
2579 result = PD_PIPE_EOF;
2580 else
2581 result = PD_PIPE_ERR;
2582 break;
2584 #ifdef _WIN32
2585 pcap_src->cap_pipe_bytes_read += (DWORD)b;
2586 #else
2587 pcap_src->cap_pipe_bytes_read += b;
2588 #endif
2590 #ifdef _WIN32
2591 else {
2592 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2593 if (pcap_src->cap_pipe_err == PIPEOF) {
2594 result = PD_PIPE_EOF;
2595 break;
2596 } else if (pcap_src->cap_pipe_err == PIPERR) {
2597 result = PD_PIPE_ERR;
2598 break;
2600 if (!q_status) {
2601 return 0;
2604 #endif
2605 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2606 /* There's still more of the pcap packet header to read. */
2607 return 0;
2609 result = PD_REC_HDR_READ;
2610 break;
2612 case STATE_EXPECT_DATA:
2613 #ifdef _WIN32
2614 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2615 #endif
2617 pcap_src->cap_pipe_state = STATE_READ_DATA;
2618 pcap_src->cap_pipe_bytes_to_read = pcap_info->rechdr.hdr.incl_len;
2619 pcap_src->cap_pipe_bytes_read = 0;
2621 #ifdef _WIN32
2622 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2623 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2624 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2626 #endif
2627 /* Fall through */
2629 case STATE_READ_DATA:
2630 #ifdef _WIN32
2631 if (pcap_src->from_cap_socket)
2632 #endif
2634 b = cap_pipe_read(pcap_src->cap_pipe_fd,
2635 pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read,
2636 pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read,
2637 pcap_src->from_cap_socket);
2638 if (b <= 0) {
2639 if (b == 0)
2640 result = PD_PIPE_EOF;
2641 else
2642 result = PD_PIPE_ERR;
2643 break;
2645 #ifdef _WIN32
2646 pcap_src->cap_pipe_bytes_read += (DWORD)b;
2647 #else
2648 pcap_src->cap_pipe_bytes_read += b;
2649 #endif
2651 #ifdef _WIN32
2652 else {
2654 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2655 if (pcap_src->cap_pipe_err == PIPEOF) {
2656 result = PD_PIPE_EOF;
2657 break;
2658 } else if (pcap_src->cap_pipe_err == PIPERR) {
2659 result = PD_PIPE_ERR;
2660 break;
2662 if (!q_status) {
2663 return 0;
2666 #endif /* _WIN32 */
2667 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2668 /* There's still more of the pcap packet data to read. */
2669 return 0;
2671 result = PD_DATA_READ;
2672 break;
2674 default:
2675 snprintf(errmsg, errmsgl,
2676 "pcap_pipe_dispatch: invalid state");
2677 result = PD_ERR;
2679 } /* switch (pcap_src->cap_pipe_state) */
2682 * We've now read as much data as we were expecting, so process it.
2684 switch (result) {
2686 case PD_REC_HDR_READ:
2688 * We've read the packet header, so we know the captured length,
2689 * and thus the number of packet data bytes. Take care of byte order.
2691 cap_pipe_adjust_pcap_header(pcap_src->cap_pipe_info.pcap.byte_swapped, &pcap_info->hdr,
2692 &pcap_info->rechdr.hdr);
2693 if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_max_pkt_size) {
2695 * The record contains more data than the advertised/allowed in the
2696 * pcap header, do not try to read more data (do not change to
2697 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2698 * instead stop with an error.
2700 snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2701 ld->packets_captured+1, pcap_info->rechdr.hdr.incl_len);
2702 break;
2705 if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_databuf_size) {
2707 * Grow the buffer to the packet size, rounded up to a power of
2708 * 2.
2710 new_bufsize = pcap_info->rechdr.hdr.incl_len;
2712 * https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2714 new_bufsize--;
2715 new_bufsize |= new_bufsize >> 1;
2716 new_bufsize |= new_bufsize >> 2;
2717 new_bufsize |= new_bufsize >> 4;
2718 new_bufsize |= new_bufsize >> 8;
2719 new_bufsize |= new_bufsize >> 16;
2720 new_bufsize++;
2721 pcap_src->cap_pipe_databuf = (char*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2722 pcap_src->cap_pipe_databuf_size = new_bufsize;
2725 if (pcap_info->rechdr.hdr.incl_len) {
2727 * The record has some data following the header, try
2728 * to read it next time.
2730 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2731 return 0;
2735 * No data following the record header? Then no more data needs to be
2736 * read and we will fallthrough and emit an empty packet.
2738 /* FALLTHROUGH */
2740 case PD_DATA_READ:
2742 * We've read the full contents of the packet record.
2743 * Fill in a "struct pcap_pkthdr", and process the packet.
2745 phdr.ts.tv_sec = pcap_info->rechdr.hdr.ts_sec;
2746 phdr.ts.tv_usec = pcap_info->rechdr.hdr.ts_usec;
2747 phdr.caplen = pcap_info->rechdr.hdr.incl_len;
2748 phdr.len = pcap_info->rechdr.hdr.orig_len;
2750 if (use_threads) {
2751 capture_loop_queue_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2752 } else {
2753 capture_loop_write_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2757 * Now we want to read the next packet's header.
2759 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2760 return 1;
2762 case PD_PIPE_EOF:
2763 pcap_src->cap_pipe_err = PIPEOF;
2764 return -1;
2766 case PD_PIPE_ERR:
2767 snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2768 #ifdef _WIN32
2769 win32strerror(GetLastError()));
2770 #else
2771 g_strerror(errno));
2772 #endif
2773 /* Fall through */
2774 case PD_ERR:
2775 break;
2778 pcap_src->cap_pipe_err = PIPERR;
2779 /* Return here rather than inside the switch to prevent GCC warning */
2780 return -1;
2783 static int
2784 pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, size_t errmsgl)
2786 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2787 PD_ERR } result;
2788 #ifdef _WIN32
2789 gpointer q_status;
2790 #endif
2791 guint new_bufsize;
2792 pcapng_block_header_t *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2794 #ifdef LOG_CAPTURE_VERBOSE
2795 ws_debug("pcapng_pipe_dispatch");
2796 #endif
2798 switch (pcap_src->cap_pipe_state) {
2800 case STATE_EXPECT_REC_HDR:
2801 #ifdef LOG_CAPTURE_VERBOSE
2802 ws_debug("pcapng_pipe_dispatch STATE_EXPECT_REC_HDR");
2803 #endif
2804 #ifdef _WIN32
2805 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2806 #endif
2808 pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2809 pcap_src->cap_pipe_bytes_to_read = sizeof(pcapng_block_header_t);
2810 pcap_src->cap_pipe_bytes_read = 0;
2812 #ifdef _WIN32
2813 if (!pcap_src->from_cap_socket) {
2814 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2815 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2817 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2819 #endif
2820 /* Fall through */
2822 case STATE_READ_REC_HDR:
2823 #ifdef LOG_CAPTURE_VERBOSE
2824 ws_debug("pcapng_pipe_dispatch STATE_READ_REC_HDR");
2825 #endif
2826 #ifdef _WIN32
2827 if (pcap_src->from_cap_socket) {
2828 #endif
2829 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2830 return -1;
2832 #ifdef _WIN32
2833 } else {
2834 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2835 if (pcap_src->cap_pipe_err == PIPEOF) {
2836 result = PD_PIPE_EOF;
2837 break;
2838 } else if (pcap_src->cap_pipe_err == PIPERR) {
2839 result = PD_PIPE_ERR;
2840 break;
2842 if (!q_status) {
2843 return 0;
2846 #endif
2847 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2848 /* There's still more of the pcapng block header to read. */
2849 return 0;
2851 memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(pcapng_block_header_t));
2852 result = PD_REC_HDR_READ;
2853 break;
2855 case STATE_EXPECT_DATA:
2856 #ifdef LOG_CAPTURE_VERBOSE
2857 ws_debug("pcapng_pipe_dispatch STATE_EXPECT_DATA");
2858 #endif
2859 #ifdef _WIN32
2860 if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2861 #endif
2862 pcap_src->cap_pipe_state = STATE_READ_DATA;
2863 pcap_src->cap_pipe_bytes_to_read = bh->block_total_length;
2865 #ifdef _WIN32
2866 if (!pcap_src->from_cap_socket) {
2867 pcap_src->cap_pipe_bytes_to_read -= pcap_src->cap_pipe_bytes_read;
2868 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf + pcap_src->cap_pipe_bytes_read;
2869 pcap_src->cap_pipe_bytes_read = 0;
2870 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2872 g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2874 #endif
2875 /* Fall through */
2877 case STATE_READ_DATA:
2878 #ifdef LOG_CAPTURE_VERBOSE
2879 ws_debug("pcapng_pipe_dispatch STATE_READ_DATA");
2880 #endif
2881 #ifdef _WIN32
2882 if (pcap_src->from_cap_socket) {
2883 #endif
2884 if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2885 return -1;
2887 #ifdef _WIN32
2888 } else {
2890 q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2891 if (pcap_src->cap_pipe_err == PIPEOF) {
2892 result = PD_PIPE_EOF;
2893 break;
2894 } else if (pcap_src->cap_pipe_err == PIPERR) {
2895 result = PD_PIPE_ERR;
2896 break;
2898 if (!q_status) {
2899 return 0;
2902 #endif /* _WIN32 */
2903 if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2904 /* There's still more of the pcap block contents to read. */
2905 return 0;
2907 result = PD_DATA_READ;
2908 break;
2910 default:
2911 snprintf(errmsg, errmsgl,
2912 "pcapng_pipe_dispatch: invalid state");
2913 result = PD_ERR;
2915 } /* switch (pcap_src->cap_pipe_state) */
2918 * We've now read as much data as we were expecting, so process it.
2920 switch (result) {
2922 case PD_REC_HDR_READ:
2924 * We've read the pcapng block header, so we know the block type
2925 * and length.
2927 if (bh->block_type == BLOCK_TYPE_SHB) {
2929 * We need to read the fixed portion of the SHB before to
2930 * get the endianness before we can interpret the block length.
2931 * (The block type of the SHB is byte-order-independent, so that
2932 * an SHB can be recognized before we know the endianness of
2933 * the section.)
2935 * Continue the read process.
2937 pcapng_read_shb(pcap_src, errmsg, errmsgl);
2938 return 1;
2941 if ((bh->block_total_length & 0x03) != 0) {
2942 snprintf(errmsg, errmsgl,
2943 "Total length of pcapng block read from pipe is %u, which is not a multiple of 4.",
2944 bh->block_total_length);
2945 break;
2947 if (is_data_block(bh->block_type) && bh->block_total_length > pcap_src->cap_pipe_max_pkt_size) {
2949 * The record contains more data than the advertised/allowed in the
2950 * pcapng header, do not try to read more data (do not change to
2951 * STATE_EXPECT_DATA) as that would not fit in the buffer and
2952 * instead stop with an error.
2954 snprintf(errmsg, errmsgl, "Block %u type 0x%08x too long (%d bytes)",
2955 ld->packets_captured+1, bh->block_type, bh->block_total_length);
2956 break;
2959 if (bh->block_total_length > pcap_src->cap_pipe_databuf_size) {
2961 * Grow the buffer to the packet size, rounded up to a power of
2962 * 2.
2964 new_bufsize = bh->block_total_length;
2966 * https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2968 new_bufsize--;
2969 new_bufsize |= new_bufsize >> 1;
2970 new_bufsize |= new_bufsize >> 2;
2971 new_bufsize |= new_bufsize >> 4;
2972 new_bufsize |= new_bufsize >> 8;
2973 new_bufsize |= new_bufsize >> 16;
2974 new_bufsize++;
2975 pcap_src->cap_pipe_databuf = (guchar*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2976 pcap_src->cap_pipe_databuf_size = new_bufsize;
2979 /* The record always has at least the block total length following the header */
2980 if (bh->block_total_length < sizeof(pcapng_block_header_t)+sizeof(guint32)) {
2981 snprintf(errmsg, errmsgl,
2982 "malformed pcapng block_total_length < minimum");
2983 pcap_src->cap_pipe_err = PIPEOF;
2984 return -1;
2988 * Now we want to read the block contents.
2990 pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2991 return 0;
2993 case PD_DATA_READ:
2995 * We've read the full contents of the block.
2996 * Process the block.
2998 if (use_threads) {
2999 capture_loop_queue_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
3000 } else {
3001 capture_loop_write_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
3005 * Now we want to read the next block's header.
3007 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
3008 return 1;
3010 case PD_PIPE_EOF:
3011 pcap_src->cap_pipe_err = PIPEOF;
3012 return -1;
3014 case PD_PIPE_ERR:
3015 snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
3016 #ifdef _WIN32
3017 win32strerror(GetLastError()));
3018 #else
3019 g_strerror(errno));
3020 #endif
3021 /* Fall through */
3022 case PD_ERR:
3023 break;
3026 pcap_src->cap_pipe_err = PIPERR;
3027 /* Return here rather than inside the switch to prevent GCC warning */
3028 return -1;
3031 /** Open the capture input sources; each one is either a pcap device,
3032 * a capture pipe, or a capture socket.
3033 * Returns TRUE if it succeeds, FALSE otherwise. */
3034 static gboolean
3035 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
3036 char *errmsg, size_t errmsg_len,
3037 char *secondary_errmsg, size_t secondary_errmsg_len)
3039 cap_device_open_status open_status;
3040 gchar open_status_str[PCAP_ERRBUF_SIZE];
3041 gchar *sync_msg_str;
3042 interface_options *interface_opts;
3043 capture_src *pcap_src;
3044 guint i;
3046 if ((use_threads == FALSE) &&
3047 (capture_opts->ifaces->len > 1)) {
3048 snprintf(errmsg, errmsg_len,
3049 "Using threads is required for capturing on multiple interfaces.");
3050 return FALSE;
3053 int pcapng_src_count = 0;
3054 for (i = 0; i < capture_opts->ifaces->len; i++) {
3055 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
3056 pcap_src = g_new0(capture_src, 1);
3057 if (pcap_src == NULL) {
3058 snprintf(errmsg, errmsg_len,
3059 "Could not allocate memory.");
3060 return FALSE;
3063 #ifdef MUST_DO_SELECT
3064 pcap_src->pcap_fd = -1;
3065 #endif
3066 pcap_src->interface_id = i;
3067 pcap_src->linktype = -1;
3068 #ifdef _WIN32
3069 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
3070 #endif
3071 pcap_src->cap_pipe_fd = -1;
3072 pcap_src->cap_pipe_dispatch = pcap_pipe_dispatch;
3073 pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
3074 pcap_src->cap_pipe_err = PIPOK;
3075 #ifdef _WIN32
3076 pcap_src->cap_pipe_read_mtx = g_new(GMutex, 1);
3077 g_mutex_init(pcap_src->cap_pipe_read_mtx);
3078 pcap_src->cap_pipe_pending_q = g_async_queue_new();
3079 pcap_src->cap_pipe_done_q = g_async_queue_new();
3080 #endif
3081 g_array_append_val(ld->pcaps, pcap_src);
3083 ws_debug("capture_loop_open_input : %s", interface_opts->name);
3084 pcap_src->pcap_h = open_capture_device(capture_opts, interface_opts,
3085 CAP_READ_TIMEOUT, &open_status, &open_status_str);
3087 if (pcap_src->pcap_h != NULL) {
3088 /* we've opened "iface" as a network device */
3090 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
3091 /* Find out if we're getting nanosecond-precision time stamps */
3092 pcap_src->ts_nsec = have_high_resolution_timestamp(pcap_src->pcap_h);
3093 #endif
3095 #if defined(HAVE_PCAP_SETSAMPLING)
3096 if (interface_opts->sampling_method != CAPTURE_SAMP_NONE) {
3097 struct pcap_samp *samp;
3099 if ((samp = pcap_setsampling(pcap_src->pcap_h)) != NULL) {
3100 switch (interface_opts->sampling_method) {
3101 case CAPTURE_SAMP_BY_COUNT:
3102 samp->method = PCAP_SAMP_1_EVERY_N;
3103 break;
3105 case CAPTURE_SAMP_BY_TIMER:
3106 samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
3107 break;
3109 default:
3110 sync_msg_str = ws_strdup_printf(
3111 "Unknown sampling method %d specified,\n"
3112 "continue without packet sampling",
3113 interface_opts->sampling_method);
3114 report_capture_error("Couldn't set the capture "
3115 "sampling", sync_msg_str);
3116 g_free(sync_msg_str);
3118 samp->value = interface_opts->sampling_param;
3119 } else {
3120 report_capture_error("Couldn't set the capture sampling",
3121 "Cannot get packet sampling data structure");
3124 #endif
3126 /* setting the data link type only works on real interfaces */
3127 if (!set_pcap_datalink(pcap_src->pcap_h, interface_opts->linktype,
3128 interface_opts->name,
3129 errmsg, errmsg_len,
3130 secondary_errmsg, secondary_errmsg_len)) {
3131 return FALSE;
3133 pcap_src->linktype = dlt_to_linktype(get_pcap_datalink(pcap_src->pcap_h, interface_opts->name));
3134 } else {
3135 /* We couldn't open "iface" as a network device. */
3136 /* Try to open it as a pipe */
3137 gboolean pipe_err = FALSE;
3138 cap_pipe_open_live(interface_opts->name, pcap_src,
3139 &pcap_src->cap_pipe_info.pcap.hdr,
3140 errmsg, errmsg_len,
3141 secondary_errmsg, secondary_errmsg_len);
3143 #ifdef _WIN32
3144 if (pcap_src->from_cap_socket) {
3145 #endif
3146 if (pcap_src->cap_pipe_fd == -1) {
3147 pipe_err = TRUE;
3149 #ifdef _WIN32
3150 } else {
3151 if (pcap_src->cap_pipe_h == INVALID_HANDLE_VALUE) {
3152 pipe_err = TRUE;
3155 #endif
3157 if (pipe_err) {
3158 if (pcap_src->cap_pipe_err == PIPNEXIST) {
3160 * We tried opening as an interface, and that failed,
3161 * so we tried to open it as a pipe, but the pipe
3162 * doesn't exist. Report the error message for
3163 * the interface.
3165 get_capture_device_open_failure_messages(open_status,
3166 open_status_str,
3167 interface_opts->name,
3168 errmsg,
3169 errmsg_len,
3170 secondary_errmsg,
3171 secondary_errmsg_len);
3174 * Else pipe (or file) does exist and cap_pipe_open_live() has
3175 * filled in errmsg
3177 return FALSE;
3178 } else {
3180 * We tried opening as an interface, and that failed,
3181 * so we tried to open it as a pipe, and that succeeded.
3183 open_status = CAP_DEVICE_OPEN_NO_ERR;
3187 /* XXX - will this work for tshark? */
3188 #ifdef MUST_DO_SELECT
3189 if (!pcap_src->from_cap_pipe) {
3190 pcap_src->pcap_fd = pcap_get_selectable_fd(pcap_src->pcap_h);
3192 #endif
3194 /* Is "open_status" something other than CAP_DEVICE_OPEN_NO_ERR?
3195 If so, "open_capture_device()" returned a warning; print it,
3196 but keep capturing. */
3197 if (open_status != CAP_DEVICE_OPEN_NO_ERR) {
3198 sync_msg_str = ws_strdup_printf("%s.", open_status_str);
3199 report_capture_error(sync_msg_str, "");
3200 g_free(sync_msg_str);
3202 if (pcap_src->from_pcapng) {
3204 * We will use the IDBs from the source (but rewrite the
3205 * interface IDs if there's more than one source.)
3207 pcapng_src_count++;
3208 } else {
3210 * Add our pcapng interface entry.
3212 saved_idb_t idb_source = { 0 };
3213 idb_source.interface_id = i;
3214 g_rw_lock_writer_lock (&ld->saved_shb_idb_lock);
3215 pcap_src->idb_id = global_ld.saved_idbs->len;
3216 g_array_append_val(global_ld.saved_idbs, idb_source);
3217 g_rw_lock_writer_unlock (&ld->saved_shb_idb_lock);
3218 ws_debug("%s: saved capture_opts %u to IDB %u",
3219 G_STRFUNC, i, pcap_src->idb_id);
3224 * Are we capturing from one source that is providing pcapng
3225 * information?
3227 if (capture_opts->ifaces->len == 1 && pcapng_src_count == 1) {
3229 * Yes; pass through SHBs and IDBs from the source, rather
3230 * than generating our own.
3232 ld->pcapng_passthrough = TRUE;
3233 g_rw_lock_writer_lock (&ld->saved_shb_idb_lock);
3234 ws_assert(global_ld.saved_idbs->len == 0);
3235 ws_debug("%s: Pass through SHBs and IDBs directly", G_STRFUNC);
3236 g_rw_lock_writer_unlock (&ld->saved_shb_idb_lock);
3239 /* If not using libcap: we now can now set euid/egid to ruid/rgid */
3240 /* to remove any suid privileges. */
3241 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities */
3242 /* (euid/egid have already previously been set to ruid/rgid. */
3243 /* (See comment in main() for details) */
3244 #ifndef HAVE_LIBCAP
3245 relinquish_special_privs_perm();
3246 #else
3247 relinquish_all_capabilities();
3248 #endif
3249 return TRUE;
3252 /* close the capture input file (pcap or capture pipe) */
3253 static void capture_loop_close_input(loop_data *ld)
3255 guint i;
3256 capture_src *pcap_src;
3258 ws_debug("capture_loop_close_input");
3260 for (i = 0; i < ld->pcaps->len; i++) {
3261 pcap_src = g_array_index(ld->pcaps, capture_src *, i);
3262 /* Pipe, or capture device? */
3263 if (pcap_src->from_cap_pipe) {
3264 /* Pipe. If open, close the capture pipe "input file". */
3265 if (pcap_src->cap_pipe_fd >= 0) {
3266 cap_pipe_close(pcap_src->cap_pipe_fd, pcap_src->from_cap_socket);
3267 pcap_src->cap_pipe_fd = -1;
3269 #ifdef _WIN32
3270 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE) {
3271 CloseHandle(pcap_src->cap_pipe_h);
3272 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
3274 #endif
3275 if (pcap_src->cap_pipe_databuf != NULL) {
3276 /* Free the buffer. */
3277 g_free(pcap_src->cap_pipe_databuf);
3278 pcap_src->cap_pipe_databuf = NULL;
3280 if (pcap_src->from_pcapng) {
3281 g_array_free(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, TRUE);
3282 pcap_src->cap_pipe_info.pcapng.src_iface_to_global = NULL;
3284 } else {
3285 /* Capture device. If open, close the pcap_t. */
3286 if (pcap_src->pcap_h != NULL) {
3287 ws_debug("capture_loop_close_input: closing %p", (void *)pcap_src->pcap_h);
3288 pcap_close(pcap_src->pcap_h);
3289 pcap_src->pcap_h = NULL;
3294 ld->go = FALSE;
3298 /* init the capture filter */
3299 static initfilter_status_t
3300 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
3301 const gchar * name, const gchar * cfilter)
3303 struct bpf_program fcode;
3305 ws_debug("capture_loop_init_filter: %s", cfilter);
3307 /* capture filters only work on real interfaces */
3308 if (cfilter && !from_cap_pipe) {
3309 /* A capture filter was specified; set it up. */
3310 if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
3311 /* Treat this specially - our caller might try to compile this
3312 as a display filter and, if that succeeds, warn the user that
3313 the display and capture filter syntaxes are different. */
3314 return INITFILTER_BAD_FILTER;
3316 if (pcap_setfilter(pcap_h, &fcode) < 0) {
3317 #ifdef HAVE_PCAP_FREECODE
3318 pcap_freecode(&fcode);
3319 #endif
3320 return INITFILTER_OTHER_ERROR;
3322 #ifdef HAVE_PCAP_FREECODE
3323 pcap_freecode(&fcode);
3324 #endif
3327 return INITFILTER_NO_ERROR;
3331 * Write the dumpcap pcapng SHB and IDBs if needed.
3332 * Called from capture_loop_init_output and do_file_switch_or_stop.
3334 static gboolean
3335 capture_loop_init_pcapng_output(capture_options *capture_opts, loop_data *ld,
3336 int *err)
3338 g_rw_lock_reader_lock (&ld->saved_shb_idb_lock);
3340 if (ld->pcapng_passthrough && !ld->saved_shb) {
3341 /* We have a single pcapng capture interface and this is the first or only output file. */
3342 ws_debug("%s: skipping dumpcap SHB and IDBs in favor of source", G_STRFUNC);
3343 g_rw_lock_reader_unlock (&ld->saved_shb_idb_lock);
3344 return TRUE;
3347 gboolean successful = TRUE;
3348 GString *os_info_str = g_string_new("");
3350 *err = 0;
3351 get_os_version_info(os_info_str);
3353 if (ld->saved_shb) {
3354 /* We have a single pcapng capture interface and multiple output files. */
3356 pcapng_block_header_t bh;
3358 memcpy(&bh, ld->saved_shb, sizeof(pcapng_block_header_t));
3360 successful = pcapng_write_block(ld->pdh, ld->saved_shb, bh.block_total_length, &ld->bytes_written, err);
3362 ws_debug("%s: wrote saved passthrough SHB %d", G_STRFUNC, successful);
3363 } else {
3364 GString *cpu_info_str = g_string_new("");
3365 get_cpu_info(cpu_info_str);
3367 successful = pcapng_write_section_header_block(ld->pdh,
3368 capture_comments, /* Comments */
3369 cpu_info_str->str, /* HW */
3370 os_info_str->str, /* OS */
3371 get_appname_and_version(),
3372 -1, /* section_length */
3373 &ld->bytes_written,
3374 err);
3375 ws_debug("%s: wrote dumpcap SHB %d", G_STRFUNC, successful);
3376 g_string_free(cpu_info_str, TRUE);
3379 for (unsigned i = 0; successful && (i < ld->saved_idbs->len); i++) {
3380 saved_idb_t idb_source = g_array_index(ld->saved_idbs, saved_idb_t, i);
3381 if (idb_source.deleted) {
3383 * Our interface is out of scope. Suppose we're writing multiple
3384 * files and a source switches sections. We currently write dummy
3385 * IDBs like so:
3387 * File 1: IDB0, IDB1, IDB2
3388 * [ The source of IDBs 1 and 2 writes an SHB with two new IDBs ]
3389 * [ We switch output files ]
3390 * File 2: IDB0, dummy IDB, dummy IDB, IDB3, IDB4
3392 * It might make more sense to write the original data so that
3393 * so that our IDB lists are more consistent across files.
3395 successful = pcapng_write_interface_description_block(global_ld.pdh,
3396 "Interface went out of scope", /* OPT_COMMENT 1 */
3397 "dummy", /* IDB_NAME 2 */
3398 "Dumpcap dummy interface", /* IDB_DESCRIPTION 3 */
3399 NULL, /* IDB_FILTER 11 */
3400 os_info_str->str, /* IDB_OS 12 */
3401 NULL, /* IDB_HARDWARE 15 */
3404 &(global_ld.bytes_written),
3405 0, /* IDB_IF_SPEED 8 */
3406 6, /* IDB_TSRESOL 9 */
3407 &global_ld.err);
3408 ws_debug("%s: skipping deleted pcapng IDB %u", G_STRFUNC, i);
3409 } else if (idb_source.idb && idb_source.idb_len) {
3410 successful = pcapng_write_block(global_ld.pdh, idb_source.idb, idb_source.idb_len, &ld->bytes_written, err);
3411 ws_debug("%s: wrote pcapng IDB %d", G_STRFUNC, successful);
3412 } else if (idb_source.interface_id < capture_opts->ifaces->len) {
3413 unsigned if_id = idb_source.interface_id;
3414 interface_options *interface_opts = &g_array_index(capture_opts->ifaces, interface_options, if_id);
3415 capture_src *pcap_src = g_array_index(ld->pcaps, capture_src *, if_id);
3416 if (pcap_src->from_cap_pipe) {
3417 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
3418 } else {
3419 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
3421 successful = pcapng_write_interface_description_block(global_ld.pdh,
3422 NULL, /* OPT_COMMENT 1 */
3423 (interface_opts->ifname != NULL) ? interface_opts->ifname : interface_opts->name, /* IDB_NAME 2 */
3424 interface_opts->descr, /* IDB_DESCRIPTION 3 */
3425 interface_opts->cfilter, /* IDB_FILTER 11 */
3426 os_info_str->str, /* IDB_OS 12 */
3427 interface_opts->hardware, /* IDB_HARDWARE 15 */
3428 pcap_src->linktype,
3429 pcap_src->snaplen,
3430 &(global_ld.bytes_written),
3431 0, /* IDB_IF_SPEED 8 */
3432 pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL 9 */
3433 &global_ld.err);
3434 ws_debug("%s: wrote capture_opts IDB %d: %d", G_STRFUNC, if_id, successful);
3437 g_rw_lock_reader_unlock (&ld->saved_shb_idb_lock);
3439 g_string_free(os_info_str, TRUE);
3441 return successful;
3444 /* set up to write to the already-opened capture output file/files */
3445 static gboolean
3446 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
3448 int err = 0;
3450 ws_debug("capture_loop_init_output");
3452 if ((capture_opts->use_pcapng == FALSE) &&
3453 (capture_opts->ifaces->len > 1)) {
3454 snprintf(errmsg, errmsg_len,
3455 "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
3456 return FALSE;
3459 /* Set up to write to the capture file. */
3460 if (capture_opts->multi_files_on) {
3461 ld->pdh = ringbuf_init_libpcap_fdopen(&err);
3462 } else {
3463 ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
3464 if (ld->pdh == NULL) {
3465 err = errno;
3466 } else {
3467 size_t buffsize = IO_BUF_SIZE;
3468 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
3469 ws_statb64 statb;
3471 if (ws_fstat64(ld->save_file_fd, &statb) == 0) {
3472 if (statb.st_blksize > IO_BUF_SIZE) {
3473 buffsize = statb.st_blksize;
3476 #endif
3477 /* Increase the size of the IO buffer */
3478 ld->io_buffer = (char *)g_malloc(buffsize);
3479 setvbuf(ld->pdh, ld->io_buffer, _IOFBF, buffsize);
3480 ws_debug("capture_loop_init_output: buffsize %zu", buffsize);
3483 if (ld->pdh) {
3484 gboolean successful;
3485 if (capture_opts->use_pcapng) {
3486 successful = capture_loop_init_pcapng_output(capture_opts, ld, &err);
3487 } else {
3488 capture_src *pcap_src;
3489 pcap_src = g_array_index(ld->pcaps, capture_src *, 0);
3490 if (pcap_src->from_cap_pipe) {
3491 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
3492 } else {
3493 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
3495 successful = libpcap_write_file_header(ld->pdh, pcap_src->linktype, pcap_src->snaplen,
3496 pcap_src->ts_nsec, &ld->bytes_written, &err);
3498 if (!successful) {
3499 fclose(ld->pdh);
3500 ld->pdh = NULL;
3501 g_free(ld->io_buffer);
3502 ld->io_buffer = NULL;
3506 if (ld->pdh == NULL) {
3507 /* We couldn't set up to write to the capture file. */
3508 /* XXX - use cf_open_error_message from tshark instead? */
3509 if (err < 0) {
3510 snprintf(errmsg, errmsg_len,
3511 "The file to which the capture would be"
3512 " saved (\"%s\") could not be opened: Error %d.",
3513 capture_opts->save_file, err);
3514 } else {
3515 snprintf(errmsg, errmsg_len,
3516 "The file to which the capture would be"
3517 " saved (\"%s\") could not be opened: %s.",
3518 capture_opts->save_file, g_strerror(err));
3520 return FALSE;
3523 return TRUE;
3526 static gboolean
3527 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
3530 unsigned int i;
3531 capture_src *pcap_src;
3532 guint64 end_time = create_timestamp();
3533 gboolean success;
3535 ws_debug("capture_loop_close_output");
3537 if (capture_opts->multi_files_on) {
3538 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
3539 } else {
3540 if (capture_opts->use_pcapng) {
3541 for (i = 0; i < global_ld.pcaps->len; i++) {
3542 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3543 if (!pcap_src->from_cap_pipe) {
3544 guint64 isb_ifrecv, isb_ifdrop;
3545 struct pcap_stat stats;
3547 if (pcap_stats(pcap_src->pcap_h, &stats) >= 0) {
3548 isb_ifrecv = pcap_src->received;
3549 isb_ifdrop = stats.ps_drop + pcap_src->dropped + pcap_src->flushed;
3550 } else {
3551 isb_ifrecv = G_MAXUINT64;
3552 isb_ifdrop = G_MAXUINT64;
3554 pcapng_write_interface_statistics_block(ld->pdh,
3556 &ld->bytes_written,
3557 "Counters provided by dumpcap",
3558 start_time,
3559 end_time,
3560 isb_ifrecv,
3561 isb_ifdrop,
3562 err_close);
3566 if (fclose(ld->pdh) == EOF) {
3567 if (err_close != NULL) {
3568 *err_close = errno;
3570 success = FALSE;
3571 } else {
3572 success = TRUE;
3574 g_free(ld->io_buffer);
3575 ld->io_buffer = NULL;
3576 return success;
3580 /* dispatch incoming packets (pcap or capture pipe)
3582 * Waits for incoming packets to be available, and calls pcap_dispatch()
3583 * to cause them to be processed.
3585 * Returns the number of packets which were processed.
3587 * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3588 * packet-batching behaviour does not cause packets to get held back
3589 * indefinitely.
3591 static int
3592 capture_loop_dispatch(loop_data *ld,
3593 char *errmsg, int errmsg_len, capture_src *pcap_src)
3595 int inpkts = 0;
3596 gint packet_count_before;
3597 int sel_ret;
3599 packet_count_before = ld->packets_captured;
3600 if (pcap_src->from_cap_pipe) {
3601 /* dispatch from capture pipe */
3602 #ifdef LOG_CAPTURE_VERBOSE
3603 ws_debug("capture_loop_dispatch: from capture pipe");
3604 #endif
3605 #ifdef _WIN32
3606 if (pcap_src->from_cap_socket) {
3607 #endif
3608 sel_ret = cap_pipe_select(pcap_src->cap_pipe_fd);
3609 if (sel_ret <= 0) {
3610 if (sel_ret < 0 && errno != EINTR) {
3611 snprintf(errmsg, errmsg_len,
3612 "Unexpected error from select: %s", g_strerror(errno));
3613 report_capture_error(errmsg, please_report_bug());
3614 ld->go = FALSE;
3617 #ifdef _WIN32
3618 } else {
3619 /* Windows does not have select() for pipes. */
3620 /* Proceed with _dispatch() which waits for cap_pipe_done_q
3621 * notification from cap_thread_read() when ReadFile() on
3622 * the pipe has read enough bytes. */
3623 sel_ret = 1;
3625 #endif
3626 if (sel_ret > 0) {
3628 * "select()" says we can read from the pipe without blocking
3630 inpkts = pcap_src->cap_pipe_dispatch(ld, pcap_src, errmsg, errmsg_len);
3631 if (inpkts < 0) {
3632 ws_debug("%s: src %u pipe reached EOF or err, rcv: %u drop: %u flush: %u",
3633 G_STRFUNC, pcap_src->interface_id, pcap_src->received, pcap_src->dropped, pcap_src->flushed);
3634 ws_assert(pcap_src->cap_pipe_err != PIPOK);
3638 else
3640 /* dispatch from pcap */
3641 #ifdef MUST_DO_SELECT
3643 * If we have "pcap_get_selectable_fd()", we use it to get the
3644 * descriptor on which to select; if that's -1, it means there
3645 * is no descriptor on which you can do a "select()" (perhaps
3646 * because you're capturing on a special device, and that device's
3647 * driver unfortunately doesn't support "select()", in which case
3648 * we don't do the select - which means it might not be possible
3649 * to stop a capture until a packet arrives. If that's unacceptable,
3650 * plead with whoever supplies the software for that device to add
3651 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3652 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3653 * later, so it can use pcap_breakloop().
3655 #ifdef LOG_CAPTURE_VERBOSE
3656 ws_debug("capture_loop_dispatch: from pcap_dispatch with select");
3657 #endif
3658 if (pcap_src->pcap_fd != -1) {
3659 sel_ret = cap_pipe_select(pcap_src->pcap_fd);
3660 if (sel_ret > 0) {
3662 * "select()" says we can read from it without blocking; go for
3663 * it.
3665 * We don't have pcap_breakloop(), so we only process one packet
3666 * per pcap_dispatch() call, to allow a signal to stop the
3667 * processing immediately, rather than processing all packets
3668 * in a batch before quitting.
3670 if (use_threads) {
3671 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3672 } else {
3673 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3675 if (inpkts < 0) {
3676 if (inpkts == -1) {
3677 /* Error, rather than pcap_breakloop(). */
3678 pcap_src->pcap_err = TRUE;
3680 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3682 } else {
3683 if (sel_ret < 0 && errno != EINTR) {
3684 snprintf(errmsg, errmsg_len,
3685 "Unexpected error from select: %s", g_strerror(errno));
3686 report_capture_error(errmsg, please_report_bug());
3687 ld->go = FALSE;
3691 else
3692 #endif /* MUST_DO_SELECT */
3694 /* dispatch from pcap without select */
3695 #if 1
3696 #ifdef LOG_CAPTURE_VERBOSE
3697 ws_debug("capture_loop_dispatch: from pcap_dispatch");
3698 #endif
3699 #ifdef _WIN32
3701 * On Windows, we don't support asynchronously telling a process to
3702 * stop capturing; instead, we check for an indication on a pipe
3703 * after processing packets. We therefore process only one packet
3704 * at a time, so that we can check the pipe after every packet.
3706 if (use_threads) {
3707 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3708 } else {
3709 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3711 #else
3712 if (use_threads) {
3713 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3714 } else {
3715 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3717 #endif
3718 if (inpkts < 0) {
3719 if (inpkts == -1) {
3720 /* Error, rather than pcap_breakloop(). */
3721 pcap_src->pcap_err = TRUE;
3723 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3725 #else /* pcap_next_ex */
3726 #ifdef LOG_CAPTURE_VERBOSE
3727 ws_debug("capture_loop_dispatch: from pcap_next_ex");
3728 #endif
3729 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3732 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3733 * see https://gitlab.com/wireshark/wireshark/-/wikis/CaptureSetup/WinPcapRemote
3734 * This should be fixed in the WinPcap 4.0 alpha release.
3736 * For reference, an example remote interface:
3737 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3740 /* emulate dispatch from pcap */
3742 int in;
3743 struct pcap_pkthdr *pkt_header;
3744 u_char *pkt_data;
3746 in = 0;
3747 while(ld->go &&
3748 (in = pcap_next_ex(pcap_src->pcap_h, &pkt_header, &pkt_data)) == 1) {
3749 if (use_threads) {
3750 capture_loop_queue_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
3751 } else {
3752 capture_loop_write_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
3756 if (in < 0) {
3757 pcap_src->pcap_err = TRUE;
3758 ld->go = FALSE;
3761 #endif /* pcap_next_ex */
3765 #ifdef LOG_CAPTURE_VERBOSE
3766 ws_debug("capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3767 #endif
3769 return ld->packets_captured - packet_count_before;
3772 #ifdef _WIN32
3773 /* Isolate the Universally Unique Identifier from the interface. Basically, we
3774 * want to grab only the characters between the '{' and '}' delimiters.
3776 * Returns a GString that must be freed with g_string_free(). */
3777 static GString *
3778 isolate_uuid(const char *iface)
3780 gchar *ptr;
3781 GString *gstr;
3783 ptr = strchr(iface, '{');
3784 if (ptr == NULL)
3785 return g_string_new(iface);
3786 gstr = g_string_new(ptr + 1);
3788 ptr = strchr(gstr->str, '}');
3789 if (ptr == NULL)
3790 return gstr;
3792 gstr = g_string_truncate(gstr, ptr - gstr->str);
3793 return gstr;
3795 #endif
3797 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3798 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3799 static gboolean
3800 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3801 char *errmsg, int errmsg_len)
3803 gchar *capfile_name = NULL;
3804 gchar *prefix, *suffix;
3805 gboolean is_tempfile;
3806 GError *err_tempfile = NULL;
3808 ws_debug("capture_loop_open_output: %s",
3809 (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3811 if (capture_opts->save_file != NULL) {
3812 /* We return to the caller while the capture is in progress.
3813 * Therefore we need to take a copy of save_file in
3814 * case the caller destroys it after we return.
3816 capfile_name = g_strdup(capture_opts->save_file);
3818 if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3819 if (capture_opts->multi_files_on) {
3820 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3821 snprintf(errmsg, errmsg_len,
3822 "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3823 g_free(capfile_name);
3824 return FALSE;
3826 if (strcmp(capfile_name, "-") == 0) {
3827 /* write to stdout */
3828 *save_file_fd = 1;
3829 #ifdef _WIN32
3830 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF) */
3831 _setmode(1, O_BINARY);
3832 #endif
3833 } else {
3834 /* Try to open the specified FIFO for use as a capture buffer.
3835 Do *not* create it if it doesn't exist. There's nothing
3836 to truncate. If we need to read it, We Have A Problem. */
3837 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY, 0);
3839 } /* if (...output_to_pipe ... */
3841 else {
3842 if (capture_opts->multi_files_on) {
3843 /* ringbuffer is enabled */
3844 *save_file_fd = ringbuf_init(capfile_name,
3845 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3846 capture_opts->group_read_access,
3847 capture_opts->compress_type,
3848 capture_opts->has_nametimenum);
3850 /* capfile_name is unused as the ringbuffer provides its own filename. */
3851 if (*save_file_fd != -1) {
3852 g_free(capfile_name);
3853 capfile_name = NULL;
3855 if (capture_opts->print_file_names) {
3856 if (!ringbuf_set_print_name(capture_opts->print_name_to, NULL)) {
3857 snprintf(errmsg, errmsg_len, "Could not write filenames to %s: %s.\n",
3858 capture_opts->print_name_to,
3859 g_strerror(errno));
3860 g_free(capfile_name);
3861 ringbuf_error_cleanup();
3862 return FALSE;
3865 } else {
3866 /* Try to open/create the specified file for use as a capture buffer. */
3867 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY|O_TRUNC|O_CREAT,
3868 (capture_opts->group_read_access) ? 0640 : 0600);
3871 is_tempfile = FALSE;
3872 } else {
3873 /* Choose a random name for the temporary capture buffer */
3874 if (global_capture_opts.ifaces->len > 1) {
3876 * More than one interface; just use the number of interfaces
3877 * to generate the temporary file name prefix.
3879 prefix = ws_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3880 } else {
3882 * One interface; use its description, if it has one, to generate
3883 * the temporary file name, otherwise use its name.
3885 gchar *basename;
3886 const interface_options *interface_opts;
3888 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
3891 * Do we have a description?
3893 if (interface_opts->descr) {
3895 * Yes - use it.
3897 * Strip off any stuff we shouldn't use in the file name,
3898 * by getting the last component of what would be a file
3899 * name.
3901 basename = g_path_get_basename(interface_opts->descr);
3902 } else {
3904 * No - use the name.
3906 * Strip off any stuff we shouldn't use in the file name,
3907 * by getting the last component of what would be a file
3908 * name.
3910 basename = g_path_get_basename(interface_opts->name);
3911 #ifdef _WIN32
3913 * This is Windows, where we might have an ugly GUID-based
3914 * interface name.
3916 * If it's an ugly GUID-based name, use the generic portion
3917 * of the interface GUID to form the basis of the filename.
3919 if (strncmp("NPF_{", basename, 5) == 0) {
3921 * We have a GUID-based name; extract the GUID digits
3922 * as the basis of the filename.
3924 GString *iface;
3925 iface = isolate_uuid(basename);
3926 g_free(basename);
3927 basename = g_strdup(iface->str);
3928 g_string_free(iface, TRUE);
3930 #endif
3932 /* generate the temp file name prefix */
3933 prefix = g_strconcat("wireshark_", basename, NULL);
3934 g_free(basename);
3937 /* Generate the appropriate suffix. */
3938 if (capture_opts->use_pcapng) {
3939 suffix = ".pcapng";
3940 } else {
3941 suffix = ".pcap";
3943 *save_file_fd = create_tempfile(capture_opts->temp_dir, &capfile_name, prefix, suffix, &err_tempfile);
3944 g_free(prefix);
3945 is_tempfile = TRUE;
3948 /* did we fail to open the output file? */
3949 if (*save_file_fd == -1) {
3950 if (is_tempfile) {
3951 snprintf(errmsg, errmsg_len,
3952 "The temporary file to which the capture would be saved "
3953 "could not be opened: %s.", err_tempfile->message);
3954 g_error_free(err_tempfile);
3955 } else {
3956 if (capture_opts->multi_files_on) {
3957 /* Ensures that the ringbuffer is not used. This ensures that
3958 * !ringbuf_is_initialized() is equivalent to
3959 * capture_opts->save_file not being part of ringbuffer. */
3960 ringbuf_error_cleanup();
3963 snprintf(errmsg, errmsg_len,
3964 "The file to which the capture would be saved (\"%s\") "
3965 "could not be opened: %s.", capfile_name,
3966 g_strerror(errno));
3968 g_free(capfile_name);
3969 return FALSE;
3972 g_free(capture_opts->save_file);
3973 if (!is_tempfile && capture_opts->multi_files_on) {
3974 /* In ringbuffer mode, save_file points to a filename from ringbuffer.c.
3975 * capfile_name was already freed before. */
3976 capture_opts->save_file = (char *)ringbuf_current_filename();
3977 } else {
3978 /* capture_opts_cleanup will g_free(capture_opts->save_file). */
3979 capture_opts->save_file = capfile_name;
3982 return TRUE;
3985 static time_t get_next_time_interval(int interval_s) {
3986 time_t next_time = time(NULL);
3987 next_time -= next_time % interval_s;
3988 next_time += interval_s;
3989 return next_time;
3992 /* Do the work of handling either the file size or file duration capture
3993 conditions being reached, and switching files or stopping. */
3994 static gboolean
3995 do_file_switch_or_stop(capture_options *capture_opts)
3997 gboolean successful;
3999 if (capture_opts->multi_files_on) {
4000 if (capture_opts->has_autostop_files &&
4001 ++global_ld.file_count >= capture_opts->autostop_files) {
4002 /* no files left: stop here */
4003 global_ld.go = FALSE;
4004 return FALSE;
4007 /* Switch to the next ringbuffer file */
4008 if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
4009 &global_ld.save_file_fd, &global_ld.err)) {
4011 /* File switch succeeded: reset the conditions */
4012 global_ld.bytes_written = 0;
4013 global_ld.packets_written = 0;
4014 if (capture_opts->use_pcapng) {
4015 successful = capture_loop_init_pcapng_output(capture_opts, &global_ld, &global_ld.err);
4016 } else {
4017 capture_src *pcap_src;
4018 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
4019 successful = libpcap_write_file_header(global_ld.pdh, pcap_src->linktype, pcap_src->snaplen,
4020 pcap_src->ts_nsec, &global_ld.bytes_written, &global_ld.err);
4023 if (!successful) {
4024 fclose(global_ld.pdh);
4025 global_ld.pdh = NULL;
4026 global_ld.go = FALSE;
4027 g_free(global_ld.io_buffer);
4028 global_ld.io_buffer = NULL;
4029 return FALSE;
4031 if (global_ld.file_duration_timer) {
4032 g_timer_reset(global_ld.file_duration_timer);
4034 if (global_ld.next_interval_time) {
4035 global_ld.next_interval_time = get_next_time_interval(global_ld.interval_s);
4037 fflush(global_ld.pdh);
4038 if (global_ld.inpkts_to_sync_pipe) {
4039 if (!quiet)
4040 report_packet_count(global_ld.inpkts_to_sync_pipe);
4041 global_ld.inpkts_to_sync_pipe = 0;
4043 report_new_capture_file(capture_opts->save_file);
4044 } else {
4045 /* File switch failed: stop here */
4046 global_ld.go = FALSE;
4047 return FALSE;
4049 } else {
4050 /* single file, stop now */
4051 global_ld.go = FALSE;
4052 return FALSE;
4054 return TRUE;
4057 static void *
4058 pcap_read_handler(void* arg)
4060 capture_src *pcap_src = (capture_src *)arg;
4061 char errmsg[MSG_MAX_LENGTH+1];
4063 ws_info("Started thread for interface %d.", pcap_src->interface_id);
4065 /* If this is a pipe input it might finish early. */
4066 while (global_ld.go && pcap_src->cap_pipe_err == PIPOK) {
4067 /* dispatch incoming packets */
4068 capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_src);
4071 ws_info("Stopped thread for interface %d.", pcap_src->interface_id);
4072 g_thread_exit(NULL);
4073 return (NULL);
4076 /* Try to pop an item off the packet queue and if it exists, write it */
4077 static gboolean
4078 capture_loop_dequeue_packet(void) {
4079 pcap_queue_element *queue_element;
4081 g_async_queue_lock(pcap_queue);
4082 queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
4083 if (queue_element) {
4084 if (queue_element->pcap_src->from_pcapng) {
4085 pcap_queue_bytes -= queue_element->u.bh.block_total_length;
4086 } else {
4087 pcap_queue_bytes -= queue_element->u.phdr.caplen;
4089 pcap_queue_packets -= 1;
4091 g_async_queue_unlock(pcap_queue);
4092 if (queue_element) {
4093 if (queue_element->pcap_src->from_pcapng) {
4094 ws_info("Dequeued a block of type 0x%08x of length %d captured on interface %d.",
4095 queue_element->u.bh.block_type, queue_element->u.bh.block_total_length,
4096 queue_element->pcap_src->interface_id);
4098 capture_loop_write_pcapng_cb(queue_element->pcap_src,
4099 &queue_element->u.bh,
4100 queue_element->pd);
4101 } else {
4102 ws_info("Dequeued a packet of length %d captured on interface %d.",
4103 queue_element->u.phdr.caplen, queue_element->pcap_src->interface_id);
4105 capture_loop_write_packet_cb((u_char *) queue_element->pcap_src,
4106 &queue_element->u.phdr,
4107 queue_element->pd);
4109 g_free(queue_element->pd);
4110 g_free(queue_element);
4111 return TRUE;
4113 return FALSE;
4117 * Note: this code will never be run on any OS other than Windows.
4119 * We keep the arguments in case there's something in the future
4120 * that needs to be reported as an NPCAP bug.
4122 static char *
4123 handle_npcap_bug(char *adapter_name _U_, char *cap_err_str _U_)
4125 gboolean have_npcap = FALSE;
4127 #ifdef _WIN32
4128 have_npcap = caplibs_have_npcap();
4129 #endif
4131 if (!have_npcap) {
4133 * We're not using Npcap, so don't recomment a user
4134 * file a bug against Npcap.
4136 return g_strdup("");
4139 return ws_strdup_printf("If you have not removed that adapter, this "
4140 "is probably a known issue in Npcap resulting from "
4141 "the behavior of the Windows networking stack. "
4142 "Work is being done in Npcap to improve the "
4143 "handling of this issue; it does not need to "
4144 "be reported as a Wireshark or Npcap bug.");
4147 /* Do the low-level work of a capture.
4148 Returns TRUE if it succeeds, FALSE otherwise. */
4149 static gboolean
4150 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
4152 #ifdef _WIN32
4153 DWORD upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
4154 #else
4155 struct timeval upd_time, cur_time;
4156 #endif
4157 int err_close;
4158 int inpkts;
4159 GTimer *autostop_duration_timer = NULL;
4160 gboolean write_ok;
4161 gboolean close_ok;
4162 gboolean cfilter_error = FALSE;
4163 char errmsg[MSG_MAX_LENGTH+1];
4164 char secondary_errmsg[MSG_MAX_LENGTH+1];
4165 capture_src *pcap_src;
4166 interface_options *interface_opts;
4167 guint i, error_index = 0;
4169 *errmsg = '\0';
4170 *secondary_errmsg = '\0';
4172 /* init the loop data */
4173 global_ld.go = TRUE;
4174 global_ld.packets_captured = 0;
4175 #ifdef SIGINFO
4176 global_ld.report_packet_count = FALSE;
4177 #endif
4178 global_ld.inpkts_to_sync_pipe = 0;
4179 global_ld.err = 0; /* no error seen yet */
4180 global_ld.pdh = NULL;
4181 global_ld.save_file_fd = -1;
4182 global_ld.io_buffer = NULL;
4183 global_ld.file_count = 0;
4184 global_ld.file_duration_timer = NULL;
4185 global_ld.next_interval_time = 0;
4186 global_ld.interval_s = 0;
4188 /* We haven't yet gotten the capture statistics. */
4189 *stats_known = FALSE;
4191 ws_info("Capture loop starting ...");
4192 capture_opts_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_DEBUG, capture_opts);
4194 /* open the "input file" from network interface or capture pipe */
4195 if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
4196 secondary_errmsg, sizeof(secondary_errmsg))) {
4197 goto error;
4199 for (i = 0; i < capture_opts->ifaces->len; i++) {
4200 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4201 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
4202 /* init the input filter from the network interface (capture pipe will do nothing) */
4204 * When remote capturing WinPCap crashes when the capture filter
4205 * is NULL. This might be a bug in WPCap. Therefore we provide an empty
4206 * string.
4208 switch (capture_loop_init_filter(pcap_src->pcap_h, pcap_src->from_cap_pipe,
4209 interface_opts->name,
4210 interface_opts->cfilter?interface_opts->cfilter:"")) {
4212 case INITFILTER_NO_ERROR:
4213 break;
4215 case INITFILTER_BAD_FILTER:
4216 cfilter_error = TRUE;
4217 error_index = i;
4218 snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_src->pcap_h));
4219 goto error;
4221 case INITFILTER_OTHER_ERROR:
4222 snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
4223 pcap_geterr(pcap_src->pcap_h));
4224 snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report_bug());
4225 goto error;
4229 /* If we're supposed to write to a capture file, open it for output
4230 (temporary/specified name/ringbuffer) */
4231 if (capture_opts->saving_to_file) {
4232 if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
4233 errmsg, sizeof(errmsg))) {
4234 goto error;
4237 /* set up to write to the already-opened capture output file/files */
4238 if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
4239 sizeof(errmsg))) {
4240 goto error;
4243 /* XXX - capture SIGTERM and close the capture, in case we're on a
4244 Linux 2.0[.x] system and you have to explicitly close the capture
4245 stream in order to turn promiscuous mode off? We need to do that
4246 in other places as well - and I don't think that works all the
4247 time in any case, due to libpcap bugs. */
4249 /* Well, we should be able to start capturing.
4251 Sync out the capture file, so the header makes it to the file system,
4252 and send a "capture started successfully and capture file created"
4253 message to our parent so that they'll open the capture file and
4254 update its windows to indicate that we have a live capture in
4255 progress. */
4256 fflush(global_ld.pdh);
4257 report_new_capture_file(capture_opts->save_file);
4260 if (capture_opts->has_file_interval) {
4261 global_ld.interval_s = capture_opts->file_interval;
4262 global_ld.next_interval_time = get_next_time_interval(global_ld.interval_s);
4264 /* create stop conditions */
4265 if (capture_opts->has_autostop_filesize) {
4266 if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
4267 capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
4270 if (capture_opts->has_autostop_duration) {
4271 autostop_duration_timer = g_timer_new();
4274 if (capture_opts->multi_files_on) {
4275 if (capture_opts->has_file_duration) {
4276 global_ld.file_duration_timer = g_timer_new();
4280 /* init the time values */
4281 #ifdef _WIN32
4282 upd_time = GetTickCount();
4283 #else
4284 gettimeofday(&upd_time, NULL);
4285 #endif
4286 start_time = create_timestamp();
4287 ws_info("Capture loop running.");
4288 capture_opts_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_DEBUG, capture_opts);
4290 /* WOW, everything is prepared! */
4291 /* please fasten your seat belts, we will enter now the actual capture loop */
4292 if (use_threads) {
4293 pcap_queue = g_async_queue_new();
4294 pcap_queue_bytes = 0;
4295 pcap_queue_packets = 0;
4296 for (i = 0; i < global_ld.pcaps->len; i++) {
4297 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4298 /* XXX - Add an interface name here? */
4299 pcap_src->tid = g_thread_new("Capture read", pcap_read_handler, pcap_src);
4302 while (global_ld.go) {
4303 /* dispatch incoming packets */
4304 if (use_threads) {
4305 gboolean dequeued = capture_loop_dequeue_packet();
4307 if (dequeued) {
4308 inpkts = 1;
4309 } else {
4310 inpkts = 0;
4312 } else {
4313 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
4314 inpkts = capture_loop_dispatch(&global_ld, errmsg,
4315 sizeof(errmsg), pcap_src);
4317 if (inpkts == 0) {
4318 /* Stop capturing if all of our sources are pipes and none of them are open. */
4319 gboolean open_interfaces = FALSE;
4320 for (i = 0; i < global_ld.pcaps->len; i++) {
4321 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4322 if (pcap_src->cap_pipe_err == PIPOK) {
4323 /* True for both non-pipes and open pipes. */
4324 open_interfaces = TRUE;
4327 if (!open_interfaces) {
4328 global_ld.go = FALSE;
4331 #ifdef SIGINFO
4332 /* Were we asked to print packet counts by the SIGINFO handler? */
4333 if (global_ld.report_packet_count) {
4334 fprintf(stderr, "%u packet%s captured\n", global_ld.packets_captured,
4335 plurality(global_ld.packets_captured, "", "s"));
4336 global_ld.report_packet_count = FALSE;
4338 #endif
4340 #ifdef _WIN32
4341 /* any news from our parent (signal pipe)? -> just stop the capture */
4342 if (!signal_pipe_check_running()) {
4343 global_ld.go = FALSE;
4345 #endif
4347 if (inpkts > 0) {
4348 if (capture_opts->output_to_pipe) {
4349 fflush(global_ld.pdh);
4351 } /* inpkts */
4353 /* Only update after an interval so as not to overload slow displays.
4354 * This also prevents too much context-switching between the dumpcap
4355 * and wireshark processes.
4356 * XXX: Should we send updates sooner if there have been lots of
4357 * packets we haven't notified the parent about, such as on fast links?
4359 #ifdef _WIN32
4360 cur_time = GetTickCount(); /* Note: wraps to 0 if sys runs for 49.7 days */
4361 if ((cur_time - upd_time) > capture_opts->update_interval) /* wrap just causes an extra update */
4362 #else
4363 gettimeofday(&cur_time, NULL);
4364 if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
4365 ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + capture_opts->update_interval*1000))
4366 #endif
4369 upd_time = cur_time;
4371 #if 0
4372 if (pcap_stats(pch, stats) >= 0) {
4373 *stats_known = TRUE;
4375 #endif
4376 /* Let the parent process know. */
4377 if (global_ld.inpkts_to_sync_pipe) {
4378 /* do sync here */
4379 fflush(global_ld.pdh);
4381 /* Send our parent a message saying we've written out
4382 "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
4383 if (!quiet)
4384 report_packet_count(global_ld.inpkts_to_sync_pipe);
4386 global_ld.inpkts_to_sync_pipe = 0;
4389 /* check capture duration condition */
4390 if (autostop_duration_timer != NULL && g_timer_elapsed(autostop_duration_timer, NULL) >= capture_opts->autostop_duration) {
4391 /* The maximum capture time has elapsed; stop the capture. */
4392 global_ld.go = FALSE;
4393 continue;
4396 /* check capture file duration condition */
4397 if (global_ld.file_duration_timer != NULL && g_timer_elapsed(global_ld.file_duration_timer, NULL) >= capture_opts->file_duration) {
4398 /* duration limit reached, do we have another file? */
4399 if (!do_file_switch_or_stop(capture_opts))
4400 continue;
4401 } /* cnd_file_duration */
4403 /* check capture file interval condition */
4404 if (global_ld.interval_s && time(NULL) >= global_ld.next_interval_time) {
4405 /* end of interval reached, do we have another file? */
4406 if (!do_file_switch_or_stop(capture_opts))
4407 continue;
4408 } /* cnd_file_interval */
4412 ws_info("Capture loop stopping ...");
4413 if (use_threads) {
4415 for (i = 0; i < global_ld.pcaps->len; i++) {
4416 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4417 ws_info("Waiting for thread of interface %u...", pcap_src->interface_id);
4418 g_thread_join(pcap_src->tid);
4419 ws_info("Thread of interface %u terminated.", pcap_src->interface_id);
4421 while (1) {
4422 gboolean dequeued = capture_loop_dequeue_packet();
4423 if (!dequeued) {
4424 break;
4426 if (capture_opts->output_to_pipe) {
4427 fflush(global_ld.pdh);
4433 /* delete stop conditions */
4434 if (global_ld.file_duration_timer != NULL)
4435 g_timer_destroy(global_ld.file_duration_timer);
4436 if (autostop_duration_timer != NULL)
4437 g_timer_destroy(autostop_duration_timer);
4439 /* did we have a pcap (input) error? */
4440 for (i = 0; i < capture_opts->ifaces->len; i++) {
4441 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4442 if (pcap_src->pcap_err) {
4443 /* On Linux, if an interface goes down while you're capturing on it,
4444 you'll get "recvfrom: Network is down".
4445 (At least you will if g_strerror() doesn't show a local translation
4446 of the error.)
4448 Newer versions of libpcap maps that to just
4449 "The interface went down".
4451 On FreeBSD, DragonFly BSD, and macOS, if a network adapter
4452 disappears while you're capturing on it, you'll get
4453 "read: Device not configured" error (ENXIO). (See previous
4454 parenthetical note.)
4456 On OpenBSD, you get "read: I/O error" (EIO) in the same case.
4458 With WinPcap and Npcap, you'll get
4459 "read error: PacketReceivePacket failed" or
4460 "PacketReceivePacket error: The device has been removed. (1617)".
4462 Newer versions of libpcap map some or all of those to just
4463 "The interface disappeared" or something beginning with
4464 "The interface disappeared".
4466 These should *not* be reported to the Wireshark developers,
4467 although, with Npcap, "The interface disappeared" messages
4468 should perhaps be reported to the Npcap developers, at least
4469 until errors of that sort that shouldn't happen are fixed,
4470 if that's possible. */
4471 char *cap_err_str;
4472 char *primary_msg;
4473 char *secondary_msg;
4475 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
4476 cap_err_str = pcap_geterr(pcap_src->pcap_h);
4477 if (strcmp(cap_err_str, "The interface went down") == 0 ||
4478 strcmp(cap_err_str, "recvfrom: Network is down") == 0) {
4479 primary_msg = ws_strdup_printf("The network adapter \"%s\" "
4480 "is no longer running; the "
4481 "capture has stopped.",
4482 interface_opts->display_name);
4483 secondary_msg = g_strdup("");
4484 } else if (strcmp(cap_err_str, "The interface disappeared") == 0 ||
4485 strcmp(cap_err_str, "read: Device not configured") == 0 ||
4486 strcmp(cap_err_str, "read: I/O error") == 0 ||
4487 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
4488 primary_msg = ws_strdup_printf("The network adapter \"%s\" "
4489 "is no longer attached; the "
4490 "capture has stopped.",
4491 interface_opts->display_name);
4492 secondary_msg = g_strdup("");
4493 } else if (g_str_has_prefix(cap_err_str, "The interface disappeared ")) {
4495 * Npcap, if it picks up a recent commit to libpcap, will
4496 * report an error *beginning* with "The interface
4497 * disappeared", with the name of the Windows status code,
4498 * and the corresponding NT status code, after it.
4500 * Those should be reported as Npcap issues.
4502 primary_msg = ws_strdup_printf("The network adapter \"%s\" "
4503 "is no longer attached; the "
4504 "capture has stopped.",
4505 interface_opts->display_name);
4506 secondary_msg = handle_npcap_bug(interface_opts->display_name,
4507 cap_err_str);
4508 } else if (g_str_has_prefix(cap_err_str, "PacketReceivePacket error:") &&
4509 g_str_has_suffix(cap_err_str, "(1617)")) {
4511 * "PacketReceivePacket error: {message in arbitrary language} (1617)",
4512 * which is ERROR_DEVICE_REMOVED.
4514 * Current libpcap/Npcap treat ERROR_GEN_FAILURE as
4515 * "the device is no longer attached"; users are also
4516 * getting ERROR_DEVICE_REMOVED.
4518 * For now, some users appear to be getg ERROR_DEVICE_REMOVED
4519 * in cases where the device *wasn't* removed, so tell
4520 * them to report this as an Npcap issue; I seem to
4521 * remember some discussion between Daniel and somebody
4522 * at Microsoft about the Windows 10 network stack setup/
4523 * teardown code being modified to try to prevent those
4524 * sort of problems popping up, but I can't find that
4525 * discussion.
4527 primary_msg = ws_strdup_printf("The network adapter \"%s\" "
4528 "is no longer attached; the "
4529 "capture has stopped.",
4530 interface_opts->display_name);
4531 secondary_msg = handle_npcap_bug(interface_opts->display_name,
4532 "The interface disappeared (error code ERROR_DEVICE_REMOVED/STATUS_DEVICE_REMOVED)");
4533 } else if (strcmp(cap_err_str, "The other host terminated the connection.") == 0 ||
4534 g_str_has_prefix(cap_err_str, "Is the server properly installed?")) {
4536 * Networking error for a remote capture.
4538 primary_msg = g_strdup(cap_err_str);
4539 secondary_msg = g_strdup("This may be a problem with the "
4540 "remote host on which you are "
4541 "capturing packets.");
4542 } else {
4543 primary_msg = ws_strdup_printf("Error while capturing packets: %s",
4544 cap_err_str);
4545 secondary_msg = g_strdup(please_report_bug());
4547 report_capture_error(primary_msg, secondary_msg);
4548 g_free(primary_msg);
4549 g_free(secondary_msg);
4550 break;
4551 } else if (pcap_src->from_cap_pipe && pcap_src->cap_pipe_err == PIPERR) {
4552 report_capture_error(errmsg, "");
4553 break;
4556 /* did we have an output error while capturing? */
4557 if (global_ld.err == 0) {
4558 write_ok = TRUE;
4559 } else {
4560 capture_loop_get_errmsg(errmsg, sizeof(errmsg), secondary_errmsg,
4561 sizeof(secondary_errmsg),
4562 capture_opts->save_file, global_ld.err, FALSE);
4563 report_capture_error(errmsg, secondary_errmsg);
4564 write_ok = FALSE;
4567 if (capture_opts->saving_to_file) {
4568 /* close the output file */
4569 close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
4570 } else
4571 close_ok = TRUE;
4573 /* there might be packets not yet notified to the parent */
4574 /* (do this after closing the file, so all packets are already flushed) */
4575 if (global_ld.inpkts_to_sync_pipe) {
4576 if (!quiet)
4577 report_packet_count(global_ld.inpkts_to_sync_pipe);
4578 global_ld.inpkts_to_sync_pipe = 0;
4581 /* If we've displayed a message about a write error, there's no point
4582 in displaying another message about an error on close. */
4583 if (!close_ok && write_ok) {
4584 capture_loop_get_errmsg(errmsg, sizeof(errmsg), secondary_errmsg,
4585 sizeof(secondary_errmsg),
4586 capture_opts->save_file, err_close, TRUE);
4587 report_capture_error(errmsg, secondary_errmsg);
4591 * XXX We exhibit different behaviour between normal mode and sync mode
4592 * when the pipe is stdin and not already at EOF. If we're a child, the
4593 * parent's stdin isn't closed, so if the user starts another capture,
4594 * cap_pipe_open_live() will very likely not see the expected magic bytes and
4595 * will say "Unrecognized libpcap format". On the other hand, in normal
4596 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
4599 report_capture_count(TRUE);
4601 /* get packet drop statistics from pcap */
4602 for (i = 0; i < capture_opts->ifaces->len; i++) {
4603 guint32 received;
4604 guint32 pcap_dropped = 0;
4606 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4607 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
4608 received = pcap_src->received;
4609 if (pcap_src->pcap_h != NULL) {
4610 ws_assert(!pcap_src->from_cap_pipe);
4611 /* Get the capture statistics, so we know how many packets were dropped. */
4612 if (pcap_stats(pcap_src->pcap_h, stats) >= 0) {
4613 *stats_known = TRUE;
4614 /* Let the parent process know. */
4615 pcap_dropped += stats->ps_drop;
4616 } else {
4617 snprintf(errmsg, sizeof(errmsg),
4618 "Can't get packet-drop statistics: %s",
4619 pcap_geterr(pcap_src->pcap_h));
4620 report_capture_error(errmsg, please_report_bug());
4623 report_packet_drops(received, pcap_dropped, pcap_src->dropped, pcap_src->flushed, stats->ps_ifdrop, interface_opts->display_name);
4626 /* close the input file (pcap or capture pipe) */
4627 capture_loop_close_input(&global_ld);
4629 ws_info("Capture loop stopped.");
4631 /* ok, if the write and the close were successful. */
4632 return write_ok && close_ok;
4634 error:
4635 if (capture_opts->multi_files_on) {
4636 /* cleanup ringbuffer */
4637 ringbuf_error_cleanup();
4638 } else {
4639 /* We can't use the save file, and we have no FILE * for the stream
4640 to close in order to close it, so close the FD directly. */
4641 if (global_ld.save_file_fd != -1) {
4642 ws_close(global_ld.save_file_fd);
4645 /* We couldn't even start the capture, so get rid of the capture
4646 file. */
4647 if (capture_opts->save_file != NULL) {
4648 ws_unlink(capture_opts->save_file);
4651 if (cfilter_error)
4652 report_cfilter_error(capture_opts, error_index, errmsg);
4653 else
4654 report_capture_error(errmsg, secondary_errmsg);
4656 /* close the input file (pcap or cap_pipe) */
4657 capture_loop_close_input(&global_ld);
4659 ws_info("Capture loop stopped with error");
4661 return FALSE;
4665 static void
4666 capture_loop_stop(void)
4668 guint i;
4669 capture_src *pcap_src;
4671 for (i = 0; i < global_ld.pcaps->len; i++) {
4672 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4673 if (pcap_src->pcap_h != NULL)
4674 pcap_breakloop(pcap_src->pcap_h);
4676 global_ld.go = FALSE;
4680 static void
4681 capture_loop_get_errmsg(char *errmsg, size_t errmsglen, char *secondary_errmsg,
4682 size_t secondary_errmsglen, const char *fname,
4683 int err, gboolean is_close)
4685 static const char find_space[] =
4686 "You will need to free up space on that file system"
4687 " or put the capture file on a different file system.";
4689 switch (err) {
4691 case ENOSPC:
4692 snprintf(errmsg, errmsglen,
4693 "Not all the packets could be written to the file"
4694 " to which the capture was being saved\n"
4695 "(\"%s\") because there is no space left on the file system\n"
4696 "on which that file resides.",
4697 fname);
4698 snprintf(secondary_errmsg, secondary_errmsglen, "%s", find_space);
4699 break;
4701 #ifdef EDQUOT
4702 case EDQUOT:
4703 snprintf(errmsg, errmsglen,
4704 "Not all the packets could be written to the file"
4705 " to which the capture was being saved\n"
4706 "(\"%s\") because you are too close to, or over,"
4707 " your disk quota\n"
4708 "on the file system on which that file resides.",
4709 fname);
4710 snprintf(secondary_errmsg, secondary_errmsglen, "%s", find_space);
4711 break;
4712 #endif
4714 default:
4715 if (is_close) {
4716 snprintf(errmsg, errmsglen,
4717 "The file to which the capture was being saved\n"
4718 "(\"%s\") could not be closed: %s.",
4719 fname, g_strerror(err));
4720 } else {
4721 snprintf(errmsg, errmsglen,
4722 "An error occurred while writing to the file"
4723 " to which the capture was being saved\n"
4724 "(\"%s\"): %s.",
4725 fname, g_strerror(err));
4727 snprintf(secondary_errmsg, secondary_errmsglen,
4728 "%s", please_report_bug());
4729 break;
4734 * We wrote one packet. Update some statistics and check if we've met any
4735 * autostop or ring buffer conditions.
4737 static void
4738 capture_loop_wrote_one_packet(capture_src *pcap_src) {
4739 global_ld.packets_captured++;
4740 global_ld.packets_written++;
4741 global_ld.inpkts_to_sync_pipe++;
4743 if (!use_threads) {
4744 pcap_src->received++;
4747 /* check -c NUM */
4748 if (global_capture_opts.has_autostop_packets && global_ld.packets_captured >= global_capture_opts.autostop_packets) {
4749 fflush(global_ld.pdh);
4750 global_ld.go = FALSE;
4751 return;
4753 /* check -a packets:NUM (treat like -c NUM) */
4754 if (global_capture_opts.has_autostop_written_packets && global_ld.packets_captured >= global_capture_opts.autostop_written_packets) {
4755 fflush(global_ld.pdh);
4756 global_ld.go = FALSE;
4757 return;
4759 /* check -b packets:NUM */
4760 if (global_capture_opts.has_file_packets && global_ld.packets_written >= global_capture_opts.file_packets) {
4761 do_file_switch_or_stop(&global_capture_opts);
4762 return;
4764 /* check -a filesize:NUM */
4765 if (global_capture_opts.has_autostop_filesize &&
4766 global_capture_opts.autostop_filesize > 0 &&
4767 global_ld.bytes_written / 1000 >= global_capture_opts.autostop_filesize) {
4768 /* Capture size limit reached, do we have another file? */
4769 do_file_switch_or_stop(&global_capture_opts);
4770 return;
4774 /* one pcapng block was captured, process it */
4775 static void
4776 capture_loop_write_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd)
4778 int err;
4781 * This should never be called if we're not writing pcapng.
4783 ws_assert(global_capture_opts.use_pcapng);
4785 /* We may be called multiple times from pcap_dispatch(); if we've set
4786 the "stop capturing" flag, ignore this packet, as we're not
4787 supposed to be saving any more packets. */
4788 if (!global_ld.go) {
4789 pcap_src->flushed++;
4790 return;
4793 if (!pcapng_adjust_block(pcap_src, bh, pd)) {
4794 ws_info("%s failed to adjust pcapng block.", G_STRFUNC);
4795 ws_assert_not_reached();
4796 return;
4799 if (bh->block_type == BLOCK_TYPE_SHB && !global_ld.pcapng_passthrough) {
4801 * capture_loop_init_pcapng_output should've handled this. We need
4802 * to write ISBs when they're initially read so we shouldn't skip
4803 * them here.
4805 return;
4808 if (global_ld.pdh) {
4809 gboolean successful;
4811 /* We're supposed to write the packet to a file; do so.
4812 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4813 "ld->err" to the error. */
4814 successful = pcapng_write_block(global_ld.pdh,
4816 bh->block_total_length,
4817 &global_ld.bytes_written, &err);
4819 fflush(global_ld.pdh);
4820 if (!successful) {
4821 global_ld.go = FALSE;
4822 global_ld.err = err;
4823 pcap_src->dropped++;
4824 } else if (is_data_block(bh->block_type)) {
4825 /* Count packets for block types that should be dissected, i.e. ones that show up in the packet list. */
4826 ws_debug("Wrote a pcapng block type 0x%04x of length %d captured on interface %u.",
4827 bh->block_type, bh->block_total_length, pcap_src->interface_id);
4828 capture_loop_wrote_one_packet(pcap_src);
4829 } else if (bh->block_type == BLOCK_TYPE_SHB && report_capture_filename) {
4830 ws_debug("Sending SP_FILE on first SHB");
4831 /* SHB is now ready for capture parent to read on SP_FILE message */
4832 sync_pipe_write_string_msg(sync_pipe_fd, SP_FILE, report_capture_filename);
4833 report_capture_filename = NULL;
4838 /* one pcap packet was captured, process it */
4839 static void
4840 capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
4841 const u_char *pd)
4843 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4844 int err;
4845 guint ts_mul = pcap_src->ts_nsec ? 1000000000 : 1000000;
4847 ws_debug("capture_loop_write_packet_cb");
4849 /* We may be called multiple times from pcap_dispatch(); if we've set
4850 the "stop capturing" flag, ignore this packet, as we're not
4851 supposed to be saving any more packets. */
4852 if (!global_ld.go) {
4853 pcap_src->flushed++;
4854 return;
4857 if (global_ld.pdh) {
4858 gboolean successful;
4860 /* We're supposed to write the packet to a file; do so.
4861 If this fails, set "ld->go" to FALSE, to stop the capture, and set
4862 "ld->err" to the error. */
4863 if (global_capture_opts.use_pcapng) {
4864 successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
4865 NULL,
4866 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4867 phdr->caplen, phdr->len,
4868 pcap_src->idb_id,
4869 ts_mul,
4870 pd, 0,
4871 &global_ld.bytes_written, &err);
4872 } else {
4873 successful = libpcap_write_packet(global_ld.pdh,
4874 phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4875 phdr->caplen, phdr->len,
4877 &global_ld.bytes_written, &err);
4879 if (!successful) {
4880 global_ld.go = FALSE;
4881 global_ld.err = err;
4882 pcap_src->dropped++;
4883 } else {
4884 ws_debug("Wrote a pcap packet of length %d captured on interface %u.",
4885 phdr->caplen, pcap_src->interface_id);
4886 capture_loop_wrote_one_packet(pcap_src);
4891 /* one packet was captured, queue it */
4892 static void
4893 capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
4894 const u_char *pd)
4896 capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4897 pcap_queue_element *queue_element;
4898 gboolean limit_reached;
4900 /* We may be called multiple times from pcap_dispatch(); if we've set
4901 the "stop capturing" flag, ignore this packet, as we're not
4902 supposed to be saving any more packets. */
4903 if (!global_ld.go) {
4904 pcap_src->flushed++;
4905 return;
4908 queue_element = g_new(pcap_queue_element, 1);
4909 if (queue_element == NULL) {
4910 pcap_src->dropped++;
4911 return;
4913 queue_element->pcap_src = pcap_src;
4914 queue_element->u.phdr = *phdr;
4915 queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4916 if (queue_element->pd == NULL) {
4917 pcap_src->dropped++;
4918 g_free(queue_element);
4919 return;
4921 memcpy(queue_element->pd, pd, phdr->caplen);
4922 g_async_queue_lock(pcap_queue);
4923 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4924 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4925 limit_reached = FALSE;
4926 g_async_queue_push_unlocked(pcap_queue, queue_element);
4927 pcap_queue_bytes += phdr->caplen;
4928 pcap_queue_packets += 1;
4929 } else {
4930 limit_reached = TRUE;
4932 g_async_queue_unlock(pcap_queue);
4933 if (limit_reached) {
4934 pcap_src->dropped++;
4935 g_free(queue_element->pd);
4936 g_free(queue_element);
4937 ws_info("Dropped a packet of length %d captured on interface %u.",
4938 phdr->caplen, pcap_src->interface_id);
4939 } else {
4940 pcap_src->received++;
4941 ws_info("Queued a packet of length %d captured on interface %u.",
4942 phdr->caplen, pcap_src->interface_id);
4944 /* I don't want to hold the mutex over the debug output. So the
4945 output may be wrong */
4946 ws_info("Queue size is now %" PRId64 " bytes (%" PRId64 " packets)",
4947 pcap_queue_bytes, pcap_queue_packets);
4950 /* one pcapng block was captured, queue it */
4951 static void
4952 capture_loop_queue_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd)
4954 pcap_queue_element *queue_element;
4955 gboolean limit_reached;
4957 /* We may be called multiple times from pcap_dispatch(); if we've set
4958 the "stop capturing" flag, ignore this packet, as we're not
4959 supposed to be saving any more packets. */
4960 if (!global_ld.go) {
4961 pcap_src->flushed++;
4962 return;
4965 queue_element = g_new(pcap_queue_element, 1);
4966 if (queue_element == NULL) {
4967 pcap_src->dropped++;
4968 return;
4970 queue_element->pcap_src = pcap_src;
4971 queue_element->u.bh = *bh;
4972 queue_element->pd = (u_char *)g_malloc(bh->block_total_length);
4973 if (queue_element->pd == NULL) {
4974 pcap_src->dropped++;
4975 g_free(queue_element);
4976 return;
4978 memcpy(queue_element->pd, pd, bh->block_total_length);
4979 g_async_queue_lock(pcap_queue);
4980 if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4981 ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4982 limit_reached = FALSE;
4983 g_async_queue_push_unlocked(pcap_queue, queue_element);
4984 pcap_queue_bytes += bh->block_total_length;
4985 pcap_queue_packets += 1;
4986 } else {
4987 limit_reached = TRUE;
4989 g_async_queue_unlock(pcap_queue);
4990 if (limit_reached) {
4991 pcap_src->dropped++;
4992 g_free(queue_element->pd);
4993 g_free(queue_element);
4994 ws_info("Dropped a packet of length %d captured on interface %u.",
4995 bh->block_total_length, pcap_src->interface_id);
4996 } else {
4997 pcap_src->received++;
4998 ws_info("Queued a block of type 0x%08x of length %d captured on interface %u.",
4999 bh->block_type, bh->block_total_length, pcap_src->interface_id);
5001 /* I don't want to hold the mutex over the debug output. So the
5002 output may be wrong */
5003 ws_info("Queue size is now %" PRId64 " bytes (%" PRId64 " packets)",
5004 pcap_queue_bytes, pcap_queue_packets);
5007 static int
5008 set_80211_channel(const char *iface, const char *opt)
5010 guint32 freq = 0;
5011 int type = -1;
5012 guint32 center_freq1 = 0;
5013 guint32 center_freq2 = 0;
5014 int args;
5015 int ret = 0;
5016 gchar **options = NULL;
5018 options = g_strsplit_set(opt, ",", 4);
5019 for (args = 0; options[args]; args++)
5022 ret = ws80211_init();
5023 if (ret != WS80211_INIT_OK) {
5024 if (ret == WS80211_INIT_NOT_SUPPORTED)
5025 cmdarg_err("Setting 802.11 channels is not supported on this platform");
5026 else
5027 cmdarg_err("Failed to init ws80211: %s", g_strerror(abs(ret)));
5028 ret = 2;
5029 goto out;
5032 if (options[0])
5033 freq = get_nonzero_guint32(options[0], "802.11 channel frequency");
5035 if (args >= 1 && options[1]) {
5036 type = ws80211_str_to_chan_type(options[1]);
5037 if (type == -1) {
5038 cmdarg_err("\"%s\" is not a valid 802.11 channel type", options[1]);
5039 ret = EINVAL;
5040 goto out;
5044 if (args >= 2 && options[2])
5045 center_freq1 = get_nonzero_guint32(options[2], "VHT center frequency");
5047 if (args >= 3 && options[3])
5048 center_freq2 = get_nonzero_guint32(options[3], "VHT center frequency 2");
5050 ret = ws80211_set_freq(iface, freq, type, center_freq1, center_freq2);
5052 if (ret) {
5053 cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
5054 ret = 2;
5055 goto out;
5058 if (capture_child)
5059 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
5061 out:
5062 g_strfreev(options);
5063 return ret;
5066 static void
5067 gather_dumpcap_compiled_info(feature_list l)
5069 /* Capture libraries */
5070 gather_caplibs_compile_info(l);
5073 static void
5074 gather_dumpcap_runtime_info(feature_list l)
5076 /* Capture libraries */
5077 gather_caplibs_runtime_info(l);
5080 #define LONGOPT_IFNAME LONGOPT_BASE_APPLICATION+1
5081 #define LONGOPT_IFDESCR LONGOPT_BASE_APPLICATION+2
5082 #define LONGOPT_CAPTURE_COMMENT LONGOPT_BASE_APPLICATION+3
5083 #ifdef _WIN32
5084 #define LONGOPT_SIGNAL_PIPE LONGOPT_BASE_APPLICATION+4
5085 #endif
5087 /* And now our feature presentation... [ fade to music ] */
5089 main(int argc, char *argv[])
5091 char *err_msg;
5092 int opt;
5093 static const struct ws_option long_options[] = {
5094 {"help", ws_no_argument, NULL, 'h'},
5095 {"version", ws_no_argument, NULL, 'v'},
5096 LONGOPT_CAPTURE_COMMON
5097 {"ifname", ws_required_argument, NULL, LONGOPT_IFNAME},
5098 {"ifdescr", ws_required_argument, NULL, LONGOPT_IFDESCR},
5099 {"capture-comment", ws_required_argument, NULL, LONGOPT_CAPTURE_COMMENT},
5100 #ifdef _WIN32
5101 {"signal-pipe", ws_required_argument, NULL, LONGOPT_SIGNAL_PIPE},
5102 #endif
5103 {0, 0, 0, 0 }
5106 gboolean arg_error = FALSE;
5108 #ifndef _WIN32
5109 struct sigaction action, oldaction;
5110 #endif
5112 gboolean stats_known;
5113 struct pcap_stat stats = {0};
5114 gboolean list_interfaces = FALSE;
5115 int caps_queries = 0;
5116 gboolean print_bpf_code = FALSE;
5117 gboolean set_chan = FALSE;
5118 gchar *set_chan_arg = NULL;
5119 gboolean machine_readable = FALSE;
5120 gboolean print_statistics = FALSE;
5121 int status, run_once_args = 0;
5122 gint i;
5123 guint j;
5124 #if defined(__APPLE__) && defined(__LP64__)
5125 struct utsname osinfo;
5126 #endif
5127 GString *str;
5130 * Determine if dumpcap is being requested to run in a special
5131 * capture_child mode by going thru the command line args to see if
5132 * a -Z is present. (-Z is a hidden option).
5134 * The primary result of running in capture_child mode is that
5135 * all messages sent out on stderr are in a special type/len/string
5136 * format to allow message processing by type. These messages include
5137 * error messages if dumpcap fails to start the operation it was
5138 * requested to do, as well as various "status" messages which are sent
5139 * when an actual capture is in progress, and a "success" message sent
5140 * if dumpcap was requested to perform an operation other than a
5141 * capture.
5143 * Capture_child mode would normally be requested by a parent process
5144 * which invokes dumpcap and obtains dumpcap stderr output via a pipe
5145 * to which dumpcap stderr has been redirected. It might also have
5146 * another pipe to obtain dumpcap stdout output; for operations other
5147 * than a capture, that information is formatted specially for easier
5148 * parsing by the parent process.
5150 * Capture_child mode needs to be determined immediately upon
5151 * startup so that any messages generated by dumpcap in this mode
5152 * (eg: during initialization) will be formatted properly.
5155 for (i=1; i<argc; i++) {
5156 if (strcmp("-Z", argv[i]) == 0) {
5157 capture_child = TRUE;
5158 machine_readable = TRUE; /* request machine-readable output */
5159 i++;
5160 if (i >= argc) {
5161 exit_main(1);
5164 if (strcmp(argv[i], SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
5165 // get_positive_int calls cmdarg_err
5166 if (!ws_strtoi(argv[i], NULL, &sync_pipe_fd) || sync_pipe_fd <= 0) {
5167 exit_main(1);
5169 #ifdef _WIN32
5170 /* On UN*X the fd is the same when we fork + exec.
5171 * On Windows the HANDLE value is the same for inherited
5172 * handles in the child process and the parent, although
5173 * not necessarily the fd value from _open_osfhandle.
5174 * https://learn.microsoft.com/en-us/windows/win32/procthread/inheritance
5175 * Also, "64-bit versions of Windows use 32-bit handles for
5176 * interoperability... only the lower 32 bits are significant,
5177 * so it is safe to truncate... or sign-extend the handle."
5178 * https://learn.microsoft.com/en-us/windows/win32/winprog64/interprocess-communication
5180 /* set output pipe to binary mode, avoid ugly text conversions */
5181 sync_pipe_fd = _open_osfhandle( (intptr_t) sync_pipe_fd, _O_BINARY);
5182 #endif
5187 cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
5189 /* Initialize log handler early so we can have proper logging during startup. */
5190 ws_log_init_with_writer("dumpcap", dumpcap_log_writer, vcmdarg_err);
5192 /* Early logging command-line initialization. */
5193 ws_log_parse_args(&argc, argv, vcmdarg_err, 1);
5195 #if DEBUG_CHILD_DUMPCAP
5196 /* Assume that if we're specially compiled with dumpcap debugging
5197 * then we want maximum debugging.
5199 if (capture_child) {
5200 ws_log_set_level(LOG_LEVEL_NOISY);
5203 if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
5204 fprintf (stderr, "Unable to open debug log file .\n");
5205 exit (1);
5207 #endif
5209 ws_noisy("Finished log init and parsing command line log arguments");
5211 #ifdef _WIN32
5212 create_app_running_mutex();
5215 * Initialize our DLL search path. MUST be called before LoadLibrary
5216 * or g_module_open.
5218 ws_init_dll_search_path();
5220 /* Load wpcap if possible. Do this before collecting the run-time version information */
5221 load_wpcap();
5222 #endif
5224 /* Initialize the version information. */
5225 ws_init_version_info("Dumpcap", gather_dumpcap_compiled_info,
5226 gather_dumpcap_runtime_info);
5228 #ifdef HAVE_PCAP_REMOTE
5229 #define OPTSTRING_r "r"
5230 #define OPTSTRING_u "u"
5231 #else
5232 #define OPTSTRING_r
5233 #define OPTSTRING_u
5234 #endif
5236 #ifdef HAVE_PCAP_SETSAMPLING
5237 #define OPTSTRING_m "m:"
5238 #else
5239 #define OPTSTRING_m
5240 #endif
5242 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:dghk:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
5244 #if defined(__APPLE__) && defined(__LP64__)
5246 * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4? If so, we need
5247 * a bug workaround - timeouts less than 1 second don't work with libpcap
5248 * in 64-bit code. (The bug was introduced in 10.6, fixed in 10.6.2,
5249 * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
5250 * The problem is extremely unlikely to be reintroduced in a future
5251 * release.)
5253 if (uname(&osinfo) == 0) {
5255 * {Mac} OS X/macOS 10.x uses Darwin {x+4}.0.0; 10.x.y uses Darwin
5256 * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
5257 * number of 10.0.0, not 10.1.0 - go figure).
5259 if (strcmp(osinfo.release, "10.0.0") == 0 || /* 10.6, 10.6.1 */
5260 strcmp(osinfo.release, "10.3.0") == 0 || /* 10.6.3 */
5261 strcmp(osinfo.release, "10.4.0") == 0) /* 10.6.4 */
5262 need_timeout_workaround = TRUE;
5264 #endif
5266 /* Initialize the pcaps list and IDBs */
5267 global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(capture_src *));
5268 global_ld.pcapng_passthrough = FALSE;
5269 global_ld.saved_shb = NULL;
5270 global_ld.saved_idbs = g_array_new(FALSE, TRUE, sizeof(saved_idb_t));
5272 err_msg = ws_init_sockets();
5273 if (err_msg != NULL)
5275 ws_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_ERROR,
5276 "ERROR: %s", err_msg);
5277 g_free(err_msg);
5278 ws_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_ERROR,
5279 "%s", please_report_bug());
5280 exit_main(1);
5283 #ifdef _WIN32
5284 /* Set handler for Ctrl+C key */
5285 SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
5286 #else
5287 /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
5288 and exit. Do the same with SIGPIPE, in case, for example,
5289 we're writing to our standard output and it's a pipe.
5290 Do the same with SIGHUP if it's not being ignored (if we're
5291 being run under nohup, it might be ignored, in which case we
5292 should leave it ignored).
5294 XXX - apparently, Coverity complained that part of action
5295 wasn't initialized. Perhaps it's running on Linux, where
5296 struct sigaction has an ignored "sa_restorer" element and
5297 where "sa_handler" and "sa_sigaction" might not be two
5298 members of a union. */
5299 memset(&action, 0, sizeof(action));
5300 action.sa_handler = capture_cleanup_handler;
5302 * Arrange that system calls not get restarted, because when
5303 * our signal handler returns we don't want to restart
5304 * a call that was waiting for packets to arrive.
5306 action.sa_flags = 0;
5307 sigemptyset(&action.sa_mask);
5308 sigaction(SIGTERM, &action, NULL);
5309 sigaction(SIGINT, &action, NULL);
5310 sigaction(SIGPIPE, &action, NULL);
5311 sigaction(SIGHUP, NULL, &oldaction);
5312 if (oldaction.sa_handler == SIG_DFL)
5313 sigaction(SIGHUP, &action, NULL);
5315 #ifdef SIGINFO
5316 /* Catch SIGINFO and, if we get it and we're capturing in
5317 quiet mode, report the number of packets we've captured. */
5318 action.sa_handler = report_counts_siginfo;
5319 action.sa_flags = SA_RESTART;
5320 sigemptyset(&action.sa_mask);
5321 sigaction(SIGINFO, &action, NULL);
5322 #endif /* SIGINFO */
5323 #endif /* _WIN32 */
5325 /* ----------------------------------------------------------------- */
5326 /* Privilege and capability handling */
5327 /* Cases: */
5328 /* 1. Running not as root or suid root; no special capabilities. */
5329 /* Action: none */
5330 /* */
5331 /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap. */
5332 /* Action: none */
5333 /* */
5334 /* 3. Running logged in as root (euid=0; ruid=0). Using libcap. */
5335 /* Action: */
5336 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
5337 /* capabilities; Drop all other capabilities; */
5338 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5339 /* else: after pcap_open_live() in capture_loop_open_input() */
5340 /* drop all capabilities (NET_RAW and NET_ADMIN); */
5341 /* (Note: this means that the process, although logged in */
5342 /* as root, does not have various permissions such as the */
5343 /* ability to bypass file access permissions). */
5344 /* XXX: Should we just leave capabilities alone in this case */
5345 /* so that user gets expected effect that root can do */
5346 /* anything ?? */
5347 /* */
5348 /* 4. Running as suid root (euid=0, ruid=n); Not using libcap. */
5349 /* Action: */
5350 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5351 /* else: after pcap_open_live() in capture_loop_open_input() */
5352 /* drop suid root (set euid=ruid).(ie: keep suid until after */
5353 /* pcap_open_live). */
5354 /* */
5355 /* 5. Running as suid root (euid=0, ruid=n); Using libcap. */
5356 /* Action: */
5357 /* - Near start of program: Enable NET_RAW and NET_ADMIN */
5358 /* capabilities; Drop all other capabilities; */
5359 /* Drop suid privileges (euid=ruid); */
5360 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5361 /* else: after pcap_open_live() in capture_loop_open_input() */
5362 /* drop all capabilities (NET_RAW and NET_ADMIN). */
5363 /* */
5364 /* XXX: For some Linux versions/distros with capabilities */
5365 /* a 'normal' process with any capabilities cannot be */
5366 /* 'killed' (signaled) from another (same uid) non-privileged */
5367 /* process. */
5368 /* For example: If (non-suid) Wireshark forks a */
5369 /* child suid dumpcap which acts as described here (case 5), */
5370 /* Wireshark will be unable to kill (signal) the child */
5371 /* dumpcap process until the capabilities have been dropped */
5372 /* (after pcap_open_live()). */
5373 /* This behaviour will apparently be changed in the kernel */
5374 /* to allow the kill (signal) in this case. */
5375 /* See the following for details: */
5376 /* https://www.mail-archive.com/ [wrapped] */
5377 /* linux-security-module@vger.kernel.org/msg02913.html */
5378 /* */
5379 /* It is therefore conceivable that if dumpcap somehow hangs */
5380 /* in pcap_open_live or before that wireshark will not */
5381 /* be able to stop dumpcap using a signal (INT, TERM, etc). */
5382 /* In this case, exiting wireshark will kill the child */
5383 /* dumpcap process. */
5384 /* */
5385 /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN */
5386 /* capabilities; Using libcap. Note: capset cmd (which see) */
5387 /* used to assign capabilities to file. */
5388 /* Action: */
5389 /* - If not -w (ie: doing -S or -D, etc) run to completion; */
5390 /* else: after pcap_open_live() in capture_loop_open_input() */
5391 /* drop all capabilities (NET_RAW and NET_ADMIN) */
5392 /* */
5393 /* ToDo: -S (stats) should drop privileges/capabilities when no */
5394 /* longer required (similar to capture). */
5395 /* */
5396 /* ----------------------------------------------------------------- */
5398 init_process_policies();
5400 #ifdef HAVE_LIBCAP
5401 /* If 'started with special privileges' (and using libcap) */
5402 /* Set to keep only NET_RAW and NET_ADMIN capabilities; */
5403 /* Set euid/egid = ruid/rgid to remove suid privileges */
5404 relinquish_privs_except_capture();
5405 #endif
5407 /* Set the initial values in the capture options. This might be overwritten
5408 by the command line parameters. */
5409 capture_opts_init(&global_capture_opts, get_interface_list);
5410 /* We always save to a file - if no file was specified, we save to a
5411 temporary file. */
5412 global_capture_opts.saving_to_file = TRUE;
5413 global_capture_opts.has_ring_num_files = TRUE;
5415 /* Pass on capture_child mode for capture_opts */
5416 global_capture_opts.capture_child = capture_child;
5418 /* Now get our args */
5419 while ((opt = ws_getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
5420 switch (opt) {
5421 case 'h': /* Print help and exit */
5422 show_help_header("Capture network packets and dump them into a pcapng or pcap file.");
5423 print_usage(stdout);
5424 exit_main(0);
5425 break;
5426 case 'v': /* Show version and exit */
5427 show_version();
5428 exit_main(0);
5429 break;
5430 /*** capture option specific ***/
5431 case 'a': /* autostop criteria */
5432 case 'b': /* Ringbuffer option */
5433 case 'c': /* Capture x packets */
5434 case 'f': /* capture filter */
5435 case 'g': /* enable group read access on file(s) */
5436 case 'i': /* Use interface x */
5437 case LONGOPT_SET_TSTAMP_TYPE: /* Set capture timestamp type */
5438 case 'n': /* Use pcapng format */
5439 case 'p': /* Don't capture in promiscuous mode */
5440 case 'P': /* Use pcap format */
5441 case 's': /* Set the snapshot (capture) length */
5442 case 'w': /* Write to capture file x */
5443 case 'y': /* Set the pcap data link type */
5444 #ifdef HAVE_PCAP_REMOTE
5445 case 'u': /* Use UDP for data transfer */
5446 case 'r': /* Capture own RPCAP traffic too */
5447 case 'A': /* Authentication */
5448 #endif
5449 #ifdef HAVE_PCAP_SETSAMPLING
5450 case 'm': /* Sampling */
5451 #endif
5452 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
5453 case 'B': /* Buffer size */
5454 #endif
5455 #ifdef HAVE_PCAP_CREATE
5456 case 'I': /* Monitor mode */
5457 #endif
5458 case LONGOPT_COMPRESS_TYPE: /* compress type */
5459 case LONGOPT_CAPTURE_TMPDIR: /* capture temp directory */
5460 case LONGOPT_UPDATE_INTERVAL: /* sync pipe update interval */
5461 status = capture_opts_add_opt(&global_capture_opts, opt, ws_optarg);
5462 if (status != 0) {
5463 exit_main(status);
5465 break;
5466 /*** hidden option: Wireshark child mode (using binary output messages) ***/
5467 case LONGOPT_IFNAME:
5468 if (global_capture_opts.ifaces->len > 0) {
5469 interface_options *interface_opts;
5471 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, global_capture_opts.ifaces->len - 1);
5472 interface_opts->ifname = g_strdup(ws_optarg);
5473 } else {
5474 cmdarg_err("--ifname must be specified after a -i option");
5475 exit_main(1);
5477 break;
5478 case LONGOPT_IFDESCR:
5479 if (global_capture_opts.ifaces->len > 0) {
5480 interface_options *interface_opts;
5482 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, global_capture_opts.ifaces->len - 1);
5483 interface_opts->descr = g_strdup(ws_optarg);
5484 } else {
5485 cmdarg_err("--ifdescr must be specified after a -i option");
5486 exit_main(1);
5488 break;
5489 case LONGOPT_CAPTURE_COMMENT: /* capture comment */
5490 if (capture_comments == NULL) {
5491 capture_comments = g_ptr_array_new_with_free_func(g_free);
5493 g_ptr_array_add(capture_comments, g_strdup(ws_optarg));
5494 break;
5495 case 'Z':
5496 capture_child = TRUE;
5498 * Handled above
5500 break;
5501 #ifdef _WIN32
5502 case LONGOPT_SIGNAL_PIPE:
5503 if (!capture_child) {
5504 /* We have already checked for -Z at the very beginning. */
5505 cmdarg_err("--signal-pipe may only be specified with -Z");
5506 exit_main(1);
5509 * ws_optarg = the control ID, aka the PPID, currently used for the
5510 * signal pipe name.
5512 if (strcmp(ws_optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
5513 sig_pipe_name = ws_strdup_printf(SIGNAL_PIPE_FORMAT, ws_optarg);
5514 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
5515 GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
5517 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
5518 ws_info("Signal pipe: Unable to open %s. Dead parent?",
5519 sig_pipe_name);
5520 exit_main(1);
5523 break;
5524 #endif
5525 case 'q': /* Quiet */
5526 quiet = TRUE;
5527 break;
5528 case 't':
5529 use_threads = TRUE;
5530 break;
5531 /*** all non capture option specific ***/
5532 case 'D': /* Print a list of capture devices and exit */
5533 if (!list_interfaces && !caps_queries & !print_statistics) {
5534 run_once_args++;
5536 list_interfaces = TRUE;
5537 break;
5538 case 'L': /* Print list of link-layer types and exit */
5539 if (!list_interfaces && !caps_queries & !print_statistics) {
5540 run_once_args++;
5542 caps_queries |= CAPS_QUERY_LINK_TYPES;
5543 break;
5544 case LONGOPT_LIST_TSTAMP_TYPES:
5545 if (!list_interfaces && !caps_queries & !print_statistics) {
5546 run_once_args++;
5548 caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
5549 break;
5550 case 'd': /* Print BPF code for capture filter and exit */
5551 if (!print_bpf_code) {
5552 print_bpf_code = TRUE;
5553 run_once_args++;
5555 break;
5556 case 'S': /* Print interface statistics once a second */
5557 if (!list_interfaces && !caps_queries & !print_statistics) {
5558 run_once_args++;
5560 print_statistics = TRUE;
5561 break;
5562 case 'k': /* Set wireless channel */
5563 if (!set_chan) {
5564 set_chan = TRUE;
5565 set_chan_arg = ws_optarg;
5566 run_once_args++;
5567 } else {
5568 cmdarg_err("Only one -k flag may be specified");
5569 arg_error = TRUE;
5571 break;
5572 case 'M': /* For -D, -L, and -S, print machine-readable output */
5573 machine_readable = TRUE;
5574 break;
5575 case 'C':
5576 pcap_queue_byte_limit = get_positive_int(ws_optarg, "byte_limit");
5577 break;
5578 case 'N':
5579 pcap_queue_packet_limit = get_positive_int(ws_optarg, "packet_limit");
5580 break;
5581 default:
5582 cmdarg_err("Invalid Option: %s", argv[ws_optind-1]);
5583 /* FALLTHROUGH */
5584 case '?': /* Bad flag - print usage message */
5585 arg_error = TRUE;
5586 break;
5589 if (!arg_error) {
5590 argc -= ws_optind;
5591 argv += ws_optind;
5592 if (argc >= 1) {
5593 /* user specified file name as regular command-line argument */
5594 /* XXX - use it as the capture file name (or something else)? */
5595 argc--;
5596 argv++;
5598 if (argc != 0) {
5600 * Extra command line arguments were specified; complain.
5601 * XXX - interpret as capture filter, as tcpdump and tshark do?
5603 cmdarg_err("Invalid argument: %s", argv[0]);
5604 arg_error = TRUE;
5608 if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
5609 use_threads = TRUE;
5611 if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
5612 /* Use some default if the user hasn't specified some */
5613 /* XXX: Are these defaults good enough? */
5614 pcap_queue_byte_limit = 1000 * 1000;
5615 pcap_queue_packet_limit = 1000;
5617 if (arg_error) {
5618 print_usage(stderr);
5619 exit_main(1);
5622 if (run_once_args > 1) {
5623 cmdarg_err("Only one of -D, -L, -d, -k or -S may be supplied.");
5624 exit_main(1);
5625 } else if (run_once_args == 1) {
5626 /* We're supposed to print some information, rather than
5627 to capture traffic; did they specify a ring buffer option? */
5628 if (global_capture_opts.multi_files_on) {
5629 cmdarg_err("Ring buffer requested, but a capture isn't being done.");
5630 exit_main(1);
5632 } else {
5633 /* We're supposed to capture traffic; */
5635 /* Are we capturing on multiple interface? If so, use threads and pcapng. */
5636 if (global_capture_opts.ifaces->len > 1) {
5637 use_threads = TRUE;
5638 global_capture_opts.use_pcapng = TRUE;
5641 if (capture_comments &&
5642 (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
5643 /* XXX - for ringbuffer, should we apply the comments to each file? */
5644 cmdarg_err("Capture comments can only be set if we capture into a single pcapng file.");
5645 exit_main(1);
5648 /* Was the ring buffer option specified and, if so, does it make sense? */
5649 if (global_capture_opts.multi_files_on) {
5650 /* Ring buffer works only under certain conditions:
5651 a) ring buffer does not work with temporary files;
5652 b) it makes no sense to enable the ring buffer if the maximum
5653 file size is set to "infinite". */
5654 if (global_capture_opts.save_file == NULL) {
5655 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
5656 global_capture_opts.multi_files_on = FALSE;
5658 if (!global_capture_opts.has_autostop_filesize &&
5659 !global_capture_opts.has_file_duration &&
5660 !global_capture_opts.has_file_interval &&
5661 !global_capture_opts.has_file_packets) {
5662 cmdarg_err("Ring buffer requested, but no maximum capture file size, duration "
5663 "interval, or packets were specified.");
5664 #if 0
5665 /* XXX - this must be redesigned as the conditions changed */
5666 global_capture_opts.multi_files_on = FALSE;
5667 #endif
5669 if (global_capture_opts.has_file_duration && global_capture_opts.has_file_interval) {
5670 cmdarg_err("Ring buffer file duration and interval can't be used at the same time.");
5671 exit_main(1);
5677 * "-D" requires no interface to be selected; it's supposed to list
5678 * all interfaces.
5680 if (list_interfaces) {
5681 /* Get the list of interfaces */
5682 GList *if_list;
5683 int err;
5684 gchar *err_str;
5686 if_list = get_interface_list(&err, &err_str);
5687 if (if_list == NULL) {
5688 if (err == 0) {
5690 * If we're being run by another program, just give them
5691 * an empty list of interfaces, don't report this as
5692 * an error; that lets them decide whether to report
5693 * this as an error or not.
5695 if (!machine_readable) {
5696 cmdarg_err("There are no interfaces on which a capture can be done");
5697 exit_main(2);
5699 } else {
5700 cmdarg_err("%s", err_str);
5701 g_free(err_str);
5702 exit_main(2);
5706 if (!machine_readable) {
5707 status = 0;
5708 capture_opts_print_interfaces(if_list);
5711 if (caps_queries) {
5712 if_info_t *if_info;
5713 interface_options *interface_opts;
5714 cap_device_open_status open_status;
5715 gchar *open_status_str;
5716 for (GList *if_entry = if_list; if_entry != NULL; if_entry = g_list_next(if_entry)) {
5717 if_info = (if_info_t *)if_entry->data;
5719 interface_opts = interface_opts_from_if_info(&global_capture_opts, if_info);
5721 if_info->caps = get_if_capabilities(interface_opts, &open_status, &open_status_str);
5723 if (!machine_readable) {
5724 if (if_info->caps == NULL) {
5725 cmdarg_err("The capabilities of the capture device "
5726 "\"%s\" could not be obtained (%s).\n%s",
5727 interface_opts->name, open_status_str,
5728 get_pcap_failure_secondary_error_message(open_status, open_status_str));
5729 g_free(open_status_str);
5730 /* Break after one error, as when printing selected
5731 * interface capabilities. (XXX: We could print all
5732 * the primary status strings, and only the unique
5733 * set of secondary messages / suggestions; printing
5734 * the same long secondary error is a lot.)
5736 interface_opts_free(interface_opts);
5737 g_free(interface_opts);
5738 break;
5739 } else {
5740 status = capture_opts_print_if_capabilities(if_info->caps, interface_opts, caps_queries);
5741 if (status != 0) {
5742 interface_opts_free(interface_opts);
5743 g_free(interface_opts);
5744 break;
5747 } else {
5748 if (if_info->caps == NULL) {
5749 if_info->caps = g_new0(if_capabilities_t, 1);
5750 if_info->caps->primary_msg = open_status_str;
5751 if_info->caps->secondary_msg = g_strdup(get_pcap_failure_secondary_error_message(open_status, open_status_str));
5753 if_info->caps->status = open_status;
5756 interface_opts_free(interface_opts);
5757 g_free(interface_opts);
5761 if (machine_readable) {
5762 status = print_machine_readable_interfaces(if_list, caps_queries, print_statistics);
5764 free_interface_list(if_list);
5765 if (!print_statistics) {
5766 exit_main(status);
5771 * "-S" requires no interface to be selected; it gives statistics
5772 * for all interfaces.
5774 if (print_statistics) {
5775 status = print_statistics_loop(machine_readable);
5776 exit_main(status);
5779 if (set_chan) {
5780 interface_options *interface_opts;
5782 if (global_capture_opts.ifaces->len != 1) {
5783 cmdarg_err("Need one interface");
5784 exit_main(2);
5787 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
5788 status = set_80211_channel(interface_opts->name, set_chan_arg);
5789 exit_main(status);
5793 * "-L", "-d", and capturing act on a particular interface, so we have to
5794 * have an interface; if none was specified, pick a default.
5796 status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
5797 if (status != 0) {
5798 /* cmdarg_err() already called .... */
5799 exit_main(status);
5802 if (caps_queries) {
5803 /* Get the list of link-layer and/or timestamp types for the capture device. */
5804 if_capabilities_t *caps;
5805 cap_device_open_status open_status;
5806 gchar *open_status_str;
5807 guint ii;
5809 if (machine_readable) {
5810 json_dumper dumper = {
5811 .output_file = stdout,
5812 .flags = JSON_DUMPER_FLAGS_NO_DEBUG,
5813 // Don't abort on failure
5815 json_dumper_begin_array(&dumper);
5816 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
5817 interface_options *interface_opts;
5819 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, ii);
5821 json_dumper_begin_object(&dumper);
5822 json_dumper_set_member_name(&dumper, interface_opts->name);
5824 json_dumper_begin_object(&dumper);
5826 open_status = CAP_DEVICE_OPEN_NO_ERR;
5827 caps = get_if_capabilities(interface_opts, &open_status, &open_status_str);
5828 if (caps == NULL) {
5829 json_dumper_set_member_name(&dumper, "status");
5830 json_dumper_value_anyf(&dumper, "%i", open_status);
5831 json_dumper_set_member_name(&dumper, "primary_msg");
5832 json_dumper_value_string(&dumper, open_status_str);
5833 g_free(open_status_str);
5834 } else {
5835 caps->status = open_status;
5836 print_machine_readable_if_capabilities(&dumper, caps, caps_queries);
5837 free_if_capabilities(caps);
5839 json_dumper_end_object(&dumper);
5840 json_dumper_end_object(&dumper);
5842 json_dumper_end_array(&dumper);
5843 if (json_dumper_finish(&dumper)) {
5844 status = 0;
5845 if (capture_child) {
5846 /* Let our parent know we succeeded. */
5847 sync_pipe_write_string_msg(sync_pipe_fd, SP_SUCCESS, NULL);
5849 } else {
5850 status = 2;
5851 if (capture_child) {
5852 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, "Unexpected JSON error", "");
5855 } else {
5856 for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
5857 interface_options *interface_opts;
5859 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, ii);
5861 caps = get_if_capabilities(interface_opts, &open_status, &open_status_str);
5862 if (caps == NULL) {
5863 if (capture_child) {
5864 char *error_msg = ws_strdup_printf("The capabilities of the capture device "
5865 "\"%s\" could not be obtained (%s)",
5866 interface_opts->name, open_status_str);
5867 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, error_msg,
5868 get_pcap_failure_secondary_error_message(open_status, open_status_str));
5869 g_free(error_msg);
5871 else {
5872 cmdarg_err("The capabilities of the capture device "
5873 "\"%s\" could not be obtained (%s).\n%s",
5874 interface_opts->name, open_status_str,
5875 get_pcap_failure_secondary_error_message(open_status, open_status_str));
5877 g_free(open_status_str);
5878 exit_main(2);
5881 /* XXX: We might want to print also the interface name */
5882 status = capture_opts_print_if_capabilities(caps,
5883 interface_opts,
5884 caps_queries);
5885 free_if_capabilities(caps);
5886 if (status != 0)
5887 break;
5890 exit_main(status);
5893 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
5894 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5895 interface_options *interface_opts;
5897 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5898 if (interface_opts->timestamp_type) {
5899 interface_opts->timestamp_type_id = pcap_tstamp_type_name_to_val(interface_opts->timestamp_type);
5900 if (interface_opts->timestamp_type_id < 0) {
5901 cmdarg_err("Invalid argument to option: --time-stamp-type=%s", interface_opts->timestamp_type);
5902 exit_main(1);
5906 #endif
5908 /* We're supposed to do a capture, or print the BPF code for a filter. */
5910 /* Let the user know what interfaces were chosen. */
5911 if (capture_child) {
5912 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5913 interface_options *interface_opts;
5915 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5916 ws_debug("Interface: %s\n", interface_opts->name);
5918 } else {
5919 str = g_string_new("");
5920 #ifdef _WIN32
5921 if (global_capture_opts.ifaces->len < 2)
5922 #else
5923 if (global_capture_opts.ifaces->len < 4)
5924 #endif
5926 for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5927 interface_options *interface_opts;
5929 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5930 if (j > 0) {
5931 if (global_capture_opts.ifaces->len > 2) {
5932 g_string_append_printf(str, ",");
5934 g_string_append_printf(str, " ");
5935 if (j == global_capture_opts.ifaces->len - 1) {
5936 g_string_append_printf(str, "and ");
5939 if (interface_opts->ifname != NULL) {
5941 * Re-generate the display name based on the strins
5942 * we were handed.
5944 g_free(interface_opts->display_name);
5945 if (interface_opts->descr != NULL) {
5946 #ifdef _WIN32
5947 interface_opts->display_name = ws_strdup_printf("%s",
5948 interface_opts->descr);
5949 #else
5950 interface_opts->display_name = ws_strdup_printf("%s: %s",
5951 interface_opts->descr, interface_opts->ifname);
5952 #endif
5953 } else {
5954 interface_opts->display_name = ws_strdup_printf("%s",
5955 interface_opts->ifname);
5958 g_string_append_printf(str, "'%s'", interface_opts->display_name);
5960 } else {
5961 g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
5963 fprintf(stderr, "Capturing on %s\n", str->str);
5964 g_string_free(str, TRUE);
5967 /* Process the snapshot length, as that affects the generated BPF code. */
5968 capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
5970 if (print_bpf_code) {
5971 show_filter_code(&global_capture_opts);
5972 exit_main(0);
5975 /* We're supposed to do a capture. Process the ring buffer arguments. */
5976 capture_opts_trim_ring_num_files(&global_capture_opts);
5978 /* flush stderr prior to starting the main capture loop */
5979 fflush(stderr);
5981 /* Now start the capture. */
5982 if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
5983 /* capture ok */
5984 exit_main(0);
5985 } else {
5986 /* capture failed */
5987 exit_main(1);
5989 return 0; /* never here, make compiler happy */
5992 static void
5993 dumpcap_log_writer(const char *domain, enum ws_log_level level,
5994 const char *file, long line, const char *func,
5995 const char *fatal_msg _U_,
5996 ws_log_manifest_t *mft,
5997 const char *user_format, va_list user_ap,
5998 void *user_data _U_)
6000 if (ws_log_msg_is_active(domain, level)) {
6001 /* log messages go to stderr or */
6002 /* to parent especially formatted if dumpcap running as child. */
6003 #ifdef DEBUG_CHILD_DUMPCAP
6004 va_list user_ap_copy;
6005 va_copy(user_ap_copy, user_ap);
6006 #endif
6007 if (capture_child) {
6008 /* Format the log mesage as the numeric level, followed
6009 * by a colon and then a string matching the standard log
6010 * string. In the future perhaps we serialize file, line,
6011 * and func (which can be NULL) instead.
6013 GString *msg = g_string_new(NULL);
6014 g_string_append_printf(msg, "%u:", level);
6015 if (file != NULL) {
6016 g_string_append_printf(msg, "%s", file);
6017 if (line >= 0) {
6018 g_string_append_printf(msg, ":%ld", line);
6021 g_string_append(msg, " --");
6022 if (func != NULL) {
6023 g_string_append_printf(msg, " %s():", func);
6025 g_string_append_c(msg, ' ');
6026 g_string_append_vprintf(msg, user_format, user_ap);
6028 sync_pipe_write_string_msg(sync_pipe_fd, SP_LOG_MSG, msg->str);
6029 g_string_free(msg, TRUE);
6030 } else {
6031 ws_log_console_writer(domain, level, file, line, func, mft, user_format, user_ap);
6033 #ifdef DEBUG_CHILD_DUMPCAP
6034 ws_log_file_writer(debug_log, domain, level, file, line, func, mft, user_format, user_ap_copy);
6035 va_end(user_ap_copy);
6036 #endif
6041 /****************************************************************************************************************/
6042 /* indication report routines */
6045 static void
6046 report_packet_count(unsigned int packet_count)
6048 static unsigned int count = 0;
6050 if (capture_child) {
6051 ws_debug("Packets: %u", packet_count);
6052 sync_pipe_write_uint_msg(sync_pipe_fd, SP_PACKET_COUNT, packet_count);
6053 } else {
6054 count += packet_count;
6055 fprintf(stderr, "\rPackets: %u ", count);
6056 /* stderr could be line buffered */
6057 fflush(stderr);
6061 static void
6062 report_new_capture_file(const char *filename)
6064 if (capture_child) {
6065 ws_debug("File: %s", filename);
6066 if (global_ld.pcapng_passthrough) {
6067 /* Save filename for sending SP_FILE to capture parent after SHB is passed-through */
6068 ws_debug("Delaying SP_FILE until first SHB");
6069 report_capture_filename = filename;
6070 } else {
6071 sync_pipe_write_string_msg(sync_pipe_fd, SP_FILE, filename);
6073 } else {
6074 #ifdef SIGINFO
6076 * Prevent a SIGINFO handler from writing to the standard error
6077 * while we're doing so; instead, have it just set a flag telling
6078 * us to print that information when we're done.
6080 infodelay = TRUE;
6081 #endif /* SIGINFO */
6082 fprintf(stderr, "File: %s\n", filename);
6083 /* stderr could be line buffered */
6084 fflush(stderr);
6086 #ifdef SIGINFO
6088 * Allow SIGINFO handlers to write.
6090 infodelay = FALSE;
6093 * If a SIGINFO handler asked us to write out capture counts, do so.
6095 if (infoprint)
6096 report_counts_for_siginfo();
6097 #endif /* SIGINFO */
6101 static void
6102 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
6104 interface_options *interface_opts;
6105 char tmp[MSG_MAX_LENGTH+1+6];
6107 if (i < capture_opts->ifaces->len) {
6108 if (capture_child) {
6109 snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
6110 ws_debug("Capture filter error: %s", errmsg);
6111 sync_pipe_write_string_msg(sync_pipe_fd, SP_BAD_FILTER, tmp);
6112 } else {
6114 * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
6115 * the error message below.
6117 interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
6118 cmdarg_err(
6119 "Invalid capture filter \"%s\" for interface '%s'.\n"
6120 "\n"
6121 "That string isn't a valid capture filter (%s).\n"
6122 "See the User's Guide for a description of the capture filter syntax.",
6123 interface_opts->cfilter, interface_opts->name, errmsg);
6128 static void
6129 report_capture_error(const char *error_msg, const char *secondary_error_msg)
6131 if (capture_child) {
6132 ws_debug("Primary Error: %s", error_msg);
6133 ws_debug("Secondary Error: %s", secondary_error_msg);
6134 sync_pipe_write_errmsgs_to_parent(sync_pipe_fd, error_msg, secondary_error_msg);
6135 } else {
6136 cmdarg_err("%s", error_msg);
6137 if (secondary_error_msg[0] != '\0')
6138 cmdarg_err_cont("%s", secondary_error_msg);
6142 static void
6143 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
6145 guint32 total_drops = pcap_drops + drops + flushed;
6147 if (capture_child) {
6148 char* tmp = ws_strdup_printf("%u:%s", total_drops, name);
6150 ws_debug("Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
6151 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
6152 sync_pipe_write_string_msg(sync_pipe_fd, SP_DROPS, tmp);
6153 g_free(tmp);
6154 } else {
6155 fprintf(stderr,
6156 "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
6157 name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
6158 received ? 100.0 * received / (received + total_drops) : 0.0);
6159 /* stderr could be line buffered */
6160 fflush(stderr);
6165 /************************************************************************************************/
6166 /* signal_pipe handling */
6169 #ifdef _WIN32
6170 static gboolean
6171 signal_pipe_check_running(void)
6173 /* any news from our parent? -> just stop the capture */
6174 DWORD avail = 0;
6175 gboolean result;
6177 /* if we are running standalone, no check required */
6178 if (!capture_child) {
6179 return TRUE;
6182 if (!sig_pipe_name || !sig_pipe_handle) {
6183 /* This shouldn't happen */
6184 ws_info("Signal pipe: No name or handle");
6185 return FALSE;
6189 * XXX - We should have the process ID of the parent (from the "-Z" flag)
6190 * at this point. Should we check to see if the parent is still alive,
6191 * e.g. by using OpenProcess?
6194 result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
6196 if (!result || avail > 0) {
6197 /* peek failed or some bytes really available */
6198 /* (if not piping from stdin this would fail) */
6199 ws_info("Signal pipe: Stop capture: %s", sig_pipe_name);
6200 ws_debug("Signal pipe: %s (%p) result: %u avail: %lu", sig_pipe_name,
6201 sig_pipe_handle, result, avail);
6202 return FALSE;
6203 } else {
6204 /* pipe ok and no bytes available */
6205 return TRUE;
6208 #endif
6211 * Editor modelines - https://www.wireshark.org/tools/modelines.html
6213 * Local variables:
6214 * c-basic-offset: 4
6215 * tab-width: 8
6216 * indent-tabs-mode: nil
6217 * End:
6219 * vi: set shiftwidth=4 tabstop=8 expandtab:
6220 * :indentSize=4:tabSize=8:noTabs=true: