1 /* dumpcap.c
2  *
3  * Wireshark - Network traffic analyzer
4  * By Gerald Combs <gerald@wireshark.org>
5  * Copyright 1998 Gerald Combs
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  */
9 
10 #include <config.h>
11 #define WS_LOG_DOMAIN LOG_DOMAIN_CAPCHILD
12 
13 #include <stdio.h>
14 #include <stdlib.h> /* for exit() */
15 #include <glib.h>
16 
17 #include <string.h>
18 
19 #include <sys/types.h>
20 
21 #ifdef HAVE_NETINET_IN_H
22 #include <netinet/in.h>
23 #endif
24 
25 #include <wsutil/ws_getopt.h>
26 
27 #if defined(__APPLE__) && defined(__LP64__)
28 #include <sys/utsname.h>
29 #endif
30 
31 #include <signal.h>
32 #include <errno.h>
33 
34 #include <ui/cmdarg_err.h>
35 #include <wsutil/strtoi.h>
36 #include <cli_main.h>
37 #include <ui/version_info.h>
38 
39 #include <wsutil/socket.h>
40 #include <wsutil/wslog.h>
41 
42 #ifdef HAVE_LIBCAP
43 # include <sys/prctl.h>
44 # include <sys/capability.h>
45 #endif
46 
47 #include "ringbuffer.h"
48 
49 #include "capture/capture_ifinfo.h"
50 #include "capture/capture-pcap-util.h"
51 #include "capture/capture-pcap-util-int.h"
52 #ifdef _WIN32
53 #include "capture/capture-wpcap.h"
54 #endif /* _WIN32 */
55 
56 #include "writecap/pcapio.h"
57 
58 #ifndef _WIN32
59 #include <sys/un.h>
60 #endif
61 
62 #include <ui/clopts_common.h>
63 #include <wsutil/privileges.h>
64 
65 #include "sync_pipe.h"
66 
67 #include "capture_opts.h"
68 #include <capture/capture_session.h>
69 #include <capture/capture_sync.h>
70 
71 #include "wsutil/tempfile.h"
72 #include "wsutil/file_util.h"
73 #include "wsutil/cpu_info.h"
74 #include "wsutil/os_version_info.h"
75 #include "wsutil/str_util.h"
76 #include "wsutil/inet_addr.h"
77 #include "wsutil/time_util.h"
78 #include "wsutil/please_report_bug.h"
79 #include "wsutil/glib-compat.h"
80 #include <wsutil/ws_assert.h>
81 
82 #include "capture/ws80211_utils.h"
83 
84 #include "extcap.h"
85 
86 /*
87  * Get information about libpcap format from "wiretap/libpcap.h".
88  * Get information about pcapng format from "wiretap/pcapng_module.h".
89  * XXX - can we just use pcap_open_offline() to read the pipe?
90  */
91 #include "wiretap/libpcap.h"
92 #include "wiretap/pcapng_module.h"
93 #include "wiretap/pcapng.h"
94 
95 /**#define DEBUG_DUMPCAP**/
96 /**#define DEBUG_CHILD_DUMPCAP**/
97 
98 #ifdef _WIN32
99 #include "wsutil/win32-utils.h"
100 #ifdef DEBUG_DUMPCAP
101 #include <conio.h>          /* _getch() */
102 #endif
103 #endif
104 
105 #ifdef DEBUG_CHILD_DUMPCAP
106 FILE *debug_log;   /* for logging debug messages to  */
107                    /*  a file if DEBUG_CHILD_DUMPCAP */
108                    /*  is defined                    */
109 #endif
110 
111 static GAsyncQueue *pcap_queue;
112 static gint64 pcap_queue_bytes;
113 static gint64 pcap_queue_packets;
114 static gint64 pcap_queue_byte_limit = 0;
115 static gint64 pcap_queue_packet_limit = 0;
116 
117 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
118 static const char *report_capture_filename = NULL; /* capture child file name */
119 #ifdef _WIN32
120 static gchar *sig_pipe_name = NULL;
121 static HANDLE sig_pipe_handle = NULL;
122 static gboolean signal_pipe_check_running(void);
123 #endif
124 
125 #ifdef SIGINFO
126 static gboolean infodelay;      /* if TRUE, don't print capture info in SIGINFO handler */
127 static gboolean infoprint;      /* if TRUE, print capture info after clearing infodelay */
128 #endif /* SIGINFO */
129 
130 /** Stop a low-level capture (stops the capture child). */
131 static void capture_loop_stop(void);
132 /** Close a pipe, or socket if \a from_socket is TRUE */
133 static void cap_pipe_close(int pipe_fd, gboolean from_socket);
134 
135 #if defined (__linux__)
136 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
137  * in pcap_dispatch(); on the other hand, select() works just fine there.
138  * Hence we use a select for that come what may.
139  *
140  * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
141  * internally, and, with TPACKET_V3, once that's supported, it'll
142  * support timeouts, at least as I understand the way the code works.
143  */
144 #define MUST_DO_SELECT
145 #endif
146 
147 /** init the capture filter */
148 typedef enum {
149     INITFILTER_NO_ERROR,
150     INITFILTER_BAD_FILTER,
151     INITFILTER_OTHER_ERROR
152 } initfilter_status_t;
153 
154 typedef enum {
155     STATE_EXPECT_REC_HDR,
156     STATE_READ_REC_HDR,
157     STATE_EXPECT_DATA,
158     STATE_READ_DATA
159 } cap_pipe_state_t;
160 
161 typedef enum {
162     PIPOK,
163     PIPEOF,
164     PIPERR,
165     PIPNEXIST
166 } cap_pipe_err_t;
167 
168 typedef struct _pcap_pipe_info {
169     gboolean                     byte_swapped; /**< TRUE if data in the pipe is byte swapped. */
170     struct pcap_hdr              hdr;          /**< Pcap header when capturing from a pipe */
171     struct pcaprec_modified_hdr  rechdr;       /**< Pcap record header when capturing from a pipe */
172 } pcap_pipe_info_t;
173 
174 typedef struct _pcapng_pipe_info {
175     pcapng_block_header_t bh;                  /**< Pcapng general block header when capturing from a pipe */
176     GArray *src_iface_to_global;               /**< Int array mapping local IDB numbers to global_ld.interface_data */
177 } pcapng_pipe_info_t;
178 
179 struct _loop_data; /* forward declaration so we can use it in the cap_pipe_dispatch function pointer */
180 
181 /*
182  * A source of packets from which we're capturing.
183  */
184 typedef struct _capture_src {
185     guint32                      received;
186     guint32                      dropped;
187     guint32                      flushed;
188     pcap_t                      *pcap_h;
189 #ifdef MUST_DO_SELECT
190     int                          pcap_fd;                /**< pcap file descriptor */
191 #endif
192     gboolean                     pcap_err;
193     guint                        interface_id;
194     GThread                     *tid;
195     int                          snaplen;
196     int                          linktype;
197     gboolean                     ts_nsec;                /**< TRUE if we're using nanosecond precision. */
198                                                          /**< capture pipe (unix only "input file") */
199     gboolean                     from_cap_pipe;          /**< TRUE if we are capturing data from a capture pipe */
200     gboolean                     from_cap_socket;        /**< TRUE if we're capturing from socket */
201     gboolean                     from_pcapng;            /**< TRUE if we're capturing from pcapng format */
202     union {
203         pcap_pipe_info_t         pcap;                   /**< Pcap info when capturing from a pipe */
204         pcapng_pipe_info_t       pcapng;                 /**< Pcapng info when capturing from a pipe */
205     } cap_pipe_info;
206 #ifdef _WIN32
207     HANDLE                       cap_pipe_h;             /**< The handle of the capture pipe */
208 #endif
209     int                          cap_pipe_fd;            /**< the file descriptor of the capture pipe */
210     gboolean                     cap_pipe_modified;      /**< TRUE if data in the pipe uses modified pcap headers */
211     char *                       cap_pipe_databuf;       /**< Pointer to the data buffer we've allocated */
212     size_t                       cap_pipe_databuf_size;  /**< Current size of the data buffer */
213     guint                        cap_pipe_max_pkt_size;  /**< Maximum packet size allowed */
214 #if defined(_WIN32)
215     char *                       cap_pipe_buf;           /**< Pointer to the buffer we read into */
216     DWORD                        cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
217     DWORD                        cap_pipe_bytes_read;    /**< Used by cap_pipe_dispatch */
218 #else
219     size_t                       cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
220     size_t                       cap_pipe_bytes_read;    /**< Used by cap_pipe_dispatch */
221 #endif
222     int (*cap_pipe_dispatch)(struct _loop_data *, struct _capture_src *, char *, size_t);
223     cap_pipe_state_t cap_pipe_state;
224     cap_pipe_err_t cap_pipe_err;
225 
226 #if defined(_WIN32)
227     GMutex                      *cap_pipe_read_mtx;
228     GAsyncQueue                 *cap_pipe_pending_q, *cap_pipe_done_q;
229 #endif
230 } capture_src;
231 
232 typedef struct _saved_idb {
233     gboolean deleted;
234     guint interface_id; /* capture_src->interface_id for the associated SHB */
235     guint8 *idb;        /* If non-NULL, IDB read from capture_src. This is an interface specified on the command line otherwise. */
236     guint idb_len;
237 } saved_idb_t;
238 
239 /*
240  * Global capture loop state.
241  */
242 typedef struct _loop_data {
243     /* common */
244     gboolean  go;                  /**< TRUE as long as we're supposed to keep capturing */
245     int       err;                 /**< if non-zero, error seen while capturing */
246     gint      packets_captured;    /**< Number of packets we have already captured */
247     guint     inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
248 #ifdef SIGINFO
249     gboolean  report_packet_count; /**< Set by SIGINFO handler; print packet count */
250 #endif
251     GArray   *pcaps;               /**< Array of capture_src's on which we're capturing */
252     gboolean  pcapng_passthrough;  /**< We have one source and it's pcapng. Pass its SHB and IDBs through. */
253     guint8   *saved_shb;           /**< SHB to write when we have one pcapng input */
254     GArray   *saved_idbs;          /**< Array of saved_idb_t, written when we have a new section or output file. */
255     GRWLock   saved_shb_idb_lock;  /**< Saved IDB RW mutex */
256     /* output file(s) */
257     FILE     *pdh;
258     int       save_file_fd;
259     char     *io_buffer;           /**< Our IO buffer if we increase the size from the standard size */
260     guint64   bytes_written;       /**< Bytes written for the current file. */
261     /* autostop conditions */
262     int       packets_written;     /**< Packets written for the current file. */
263     int       file_count;
264     /* ring buffer conditions */
265     GTimer  *file_duration_timer;
266     time_t   next_interval_time;
267     int      interval_s;
268 } loop_data;
269 
270 typedef struct _pcap_queue_element {
271     capture_src        *pcap_src;
272     union {
273         struct pcap_pkthdr  phdr;
274         pcapng_block_header_t  bh;
275     } u;
276     u_char             *pd;
277 } pcap_queue_element;
278 
279 /*
280  * This needs to be static, so that the SIGINT handler can clear the "go"
281  * flag and for saved_shb_idb_lock.
282  */
283 static loop_data   global_ld;
284 
285 /*
286  * Timeout, in milliseconds, for reads from the stream of captured packets
287  * from a capture device.
288  *
289  * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
290  * 64-bit applications, with sub-second timeouts not to work.  The bug is
291  * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
292  */
293 #if defined(__APPLE__) && defined(__LP64__)
294 static gboolean need_timeout_workaround;
295 
296 #define CAP_READ_TIMEOUT        (need_timeout_workaround ? 1000 : 250)
297 #else
298 #define CAP_READ_TIMEOUT        250
299 #endif
300 
301 /*
302  * Timeout, in microseconds, for reads from the stream of captured packets
303  * from a pipe.  Pipes don't have the same problem that BPF devices do
304  * in Mac OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
305  * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
306  * of the offending versions of Snow Leopard.
307  *
308  * On Windows this value is converted to milliseconds and passed to
309  * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
310  * will return immediately.
311  */
312 #if defined(_WIN32)
313 #define PIPE_READ_TIMEOUT   100000
314 #else
315 #define PIPE_READ_TIMEOUT   250000
316 #endif
317 
318 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
319 
320 static void
321 dumpcap_log_writer(const char *domain, enum ws_log_level level,
322                                    ws_log_time_t timestamp,
323                                    const char *file, int line, const char *func,
324                                    const char *user_format, va_list user_ap,
325                                    void *user_data);
326 
327 /* capture related options */
328 static capture_options global_capture_opts;
329 static GPtrArray *capture_comments = NULL;
330 static gboolean quiet = FALSE;
331 static gboolean use_threads = FALSE;
332 static guint64 start_time;
333 
334 static void capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
335                                          const u_char *pd);
336 static void capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
337                                          const u_char *pd);
338 static void capture_loop_write_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd);
339 static void capture_loop_queue_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd);
340 static void capture_loop_get_errmsg(char *errmsg, size_t errmsglen,
341                                     char *secondary_errmsg,
342                                     size_t secondary_errmsglen,
343                                     const char *fname, int err,
344                                     gboolean is_close);
345 
346 static void WS_NORETURN exit_main(int err);
347 
348 static void report_new_capture_file(const char *filename);
349 static void report_packet_count(unsigned int packet_count);
350 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
351 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
352 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
353 
354 #define MSG_MAX_LENGTH 4096
355 
356 static void
print_usage(FILE * output)357 print_usage(FILE *output)
358 {
359     fprintf(output, "\nUsage: dumpcap [options] ...\n");
360     fprintf(output, "\n");
361     fprintf(output, "Capture interface:\n");
362     fprintf(output, "  -i <interface>, --interface <interface>\n");
363     fprintf(output, "                           name or idx of interface (def: first non-loopback),\n"
364                     "                           or for remote capturing, use one of these formats:\n"
365                     "                               rpcap://<host>/<interface>\n"
366                     "                               TCP@<host>:<port>\n");
367     fprintf(output, "  --ifname <name>          name to use in the capture file for a pipe from which\n");
368     fprintf(output, "                           we're capturing\n");
369     fprintf(output, "  --ifdescr <description>\n");
370     fprintf(output, "                           description to use in the capture file for a pipe\n");
371     fprintf(output, "                           from which we're capturing\n");
372     fprintf(output, "  -f <capture filter>      packet filter in libpcap filter syntax\n");
373     fprintf(output, "  -s <snaplen>, --snapshot-length <snaplen>\n");
374 #ifdef HAVE_PCAP_CREATE
375     fprintf(output, "                           packet snapshot length (def: appropriate maximum)\n");
376 #else
377     fprintf(output, "                           packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
378 #endif
379     fprintf(output, "  -p, --no-promiscuous-mode\n");
380     fprintf(output, "                           don't capture in promiscuous mode\n");
381 #ifdef HAVE_PCAP_CREATE
382     fprintf(output, "  -I, --monitor-mode       capture in monitor mode, if available\n");
383 #endif
384 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
385     fprintf(output, "  -B <buffer size>, --buffer-size <buffer size>\n");
386     fprintf(output, "                           size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
387 #endif
388     fprintf(output, "  -y <link type>, --linktype <link type>\n");
389     fprintf(output, "                           link layer type (def: first appropriate)\n");
390     fprintf(output, "  --time-stamp-type <type> timestamp method for interface\n");
391     fprintf(output, "  -D, --list-interfaces    print list of interfaces and exit\n");
392     fprintf(output, "  -L, --list-data-link-types\n");
393     fprintf(output, "                           print list of link-layer types of iface and exit\n");
394     fprintf(output, "  --list-time-stamp-types  print list of timestamp types for iface and exit\n");
395     fprintf(output, "  -d                       print generated BPF code for capture filter\n");
396     fprintf(output, "  -k <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
397     fprintf(output, "                           set channel on wifi interface\n");
398     fprintf(output, "  -S                       print statistics for each interface once per second\n");
399     fprintf(output, "  -M                       for -D, -L, and -S, produce machine-readable output\n");
400     fprintf(output, "\n");
401 #ifdef HAVE_PCAP_REMOTE
402     fprintf(output, "RPCAP options:\n");
403     fprintf(output, "  -r                       don't ignore own RPCAP traffic in capture\n");
404     fprintf(output, "  -u                       use UDP for RPCAP data transfer\n");
405     fprintf(output, "  -A <user>:<password>     use RPCAP password authentication\n");
406 #ifdef HAVE_PCAP_SETSAMPLING
407     fprintf(output, "  -m <sampling type>       use packet sampling\n");
408     fprintf(output, "                           count:NUM - capture one packet of every NUM\n");
409     fprintf(output, "                           timer:NUM - capture no more than 1 packet in NUM ms\n");
410 #endif
411 #endif
412     fprintf(output, "Stop conditions:\n");
413     fprintf(output, "  -c <packet count>        stop after n packets (def: infinite)\n");
414     fprintf(output, "  -a <autostop cond.> ..., --autostop <autostop cond.> ...\n");
415     fprintf(output, "                           duration:NUM - stop after NUM seconds\n");
416     fprintf(output, "                           filesize:NUM - stop this file after NUM kB\n");
417     fprintf(output, "                              files:NUM - stop after NUM files\n");
418     fprintf(output, "                            packets:NUM - stop after NUM packets\n");
419     /*fprintf(output, "\n");*/
420     fprintf(output, "Output (files):\n");
421     fprintf(output, "  -w <filename>            name of file to save (def: tempfile)\n");
422     fprintf(output, "  -g                       enable group read access on the output file(s)\n");
423     fprintf(output, "  -b <ringbuffer opt.> ..., --ring-buffer <ringbuffer opt.>\n");
424     fprintf(output, "                           duration:NUM - switch to next file after NUM secs\n");
425     fprintf(output, "                           filesize:NUM - switch to next file after NUM kB\n");
426     fprintf(output, "                              files:NUM - ringbuffer: replace after NUM files\n");
427     fprintf(output, "                            packets:NUM - ringbuffer: replace after NUM packets\n");
428     fprintf(output, "                           interval:NUM - switch to next file when the time is\n");
429     fprintf(output, "                                          an exact multiple of NUM secs\n");
430     fprintf(output, "                          printname:FILE - print filename to FILE when written\n");
431     fprintf(output, "                                           (can use 'stdout' or 'stderr')\n");
432     fprintf(output, "  -n                       use pcapng format instead of pcap (default)\n");
433     fprintf(output, "  -P                       use libpcap format instead of pcapng\n");
434     fprintf(output, "  --capture-comment <comment>\n");
435     fprintf(output, "                           add a capture comment to the output file\n");
436     fprintf(output, "                           (only for pcapng)\n");
437     fprintf(output, "\n");
438 
439     ws_log_print_usage(output);
440 
441     fprintf(output, "Miscellaneous:\n");
442     fprintf(output, "  -N <packet_limit>        maximum number of packets buffered within dumpcap\n");
443     fprintf(output, "  -C <byte_limit>          maximum number of bytes used for buffering packets\n");
444     fprintf(output, "                           within dumpcap\n");
445     fprintf(output, "  -t                       use a separate thread per interface\n");
446     fprintf(output, "  -q                       don't report packet capture counts\n");
447     fprintf(output, "  -v, --version            print version information and exit\n");
448     fprintf(output, "  -h, --help               display this help and exit\n");
449     fprintf(output, "\n");
450 #ifdef __linux__
451     fprintf(output, "Dumpcap can benefit from an enabled BPF JIT compiler if available.\n");
452     fprintf(output, "You might want to enable it by executing:\n");
453     fprintf(output, " \"echo 1 > /proc/sys/net/core/bpf_jit_enable\"\n");
454     fprintf(output, "Note that this can make your system less secure!\n");
455     fprintf(output, "\n");
456 #endif
457     fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
458     fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
459     fprintf(output, "\n");
460     fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
461 }
462 
463 /*
464  * Report an error in command-line arguments.
465  * If we're a capture child, send a message back to the parent, otherwise
466  * just print it.
467  */
468 static void
dumpcap_cmdarg_err(const char * fmt,va_list ap)469 dumpcap_cmdarg_err(const char *fmt, va_list ap)
470 {
471     if (capture_child) {
472         gchar *msg;
473         /* Generate a 'special format' message back to parent */
474         msg = g_strdup_vprintf(fmt, ap);
475         sync_pipe_errmsg_to_parent(2, msg, "");
476         g_free(msg);
477     } else {
478         fprintf(stderr, "dumpcap: ");
479         vfprintf(stderr, fmt, ap);
480         fprintf(stderr, "\n");
481     }
482 }
483 
484 /*
485  * Report additional information for an error in command-line arguments.
486  * If we're a capture child, send a message back to the parent, otherwise
487  * just print it.
488  */
489 static void
dumpcap_cmdarg_err_cont(const char * fmt,va_list ap)490 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
491 {
492     if (capture_child) {
493         gchar *msg;
494         msg = g_strdup_vprintf(fmt, ap);
495         sync_pipe_errmsg_to_parent(2, msg, "");
496         g_free(msg);
497     } else {
498         vfprintf(stderr, fmt, ap);
499         fprintf(stderr, "\n");
500     }
501 }
502 
503 #ifdef HAVE_LIBCAP
504 static void
505 #if 0 /* Set to enable capability debugging */
506 /* see 'man cap_to_text()' for explanation of output                         */
507 /* '='   means 'all= '  ie: no capabilities                                  */
508 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
509 /* ....                                                                      */
510 print_caps(const char *pfx) {
511     cap_t caps = cap_get_proc();
512     ws_debug("%s: EUID: %d  Capabilities: %s", pfx, geteuid(), cap_to_text(caps, NULL));
513     cap_free(caps);
514 }
515 #else
print_caps(const char * pfx _U_)516 print_caps(const char *pfx _U_) {
517 }
518 #endif
519 
520 static void
relinquish_all_capabilities(void)521 relinquish_all_capabilities(void)
522 {
523     /* Drop any and all capabilities this process may have.            */
524     /* Allowed whether or not process has any privileges.              */
525     cap_t caps = cap_init();    /* all capabilities initialized to off */
526     print_caps("Pre-clear");
527     if (cap_set_proc(caps)) {
528         cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
529     }
530     print_caps("Post-clear");
531     cap_free(caps);
532 }
533 #endif
534 
535 /*
536  * Platform-dependent suggestions for fixing permissions.
537  */
538 #if defined(__linux__)
539   #define PLATFORM_PERMISSIONS_SUGGESTION \
540     "\n\n" \
541     "On Debian and Debian derivatives such as Ubuntu, if you have " \
542     "installed Wireshark from a package, try running" \
543     "\n\n" \
544     "    sudo dpkg-reconfigure wireshark-common" \
545     "\n\n" \
546     "selecting \"<Yes>\" in response to the question" \
547     "\n\n" \
548     "    Should non-superusers be able to capture packets?" \
549     "\n\n" \
550     "adding yourself to the \"wireshark\" group by running" \
551     "\n\n" \
552     "    sudo usermod -a -G wireshark {your username}" \
553     "\n\n" \
554     "and then logging out and logging back in again."
555 #elif defined(__APPLE__)
556   #define PLATFORM_PERMISSIONS_SUGGESTION \
557     "\n\n" \
558     "If you installed Wireshark using the package from wireshark.org, " \
559     "close this dialog and click on the \"installing ChmodBPF\" link in " \
560     "\"You can fix this by installing ChmodBPF.\" on the main screen, " \
561     "and then complete the installation procedure."
562 #else
563   #define PLATFORM_PERMISSIONS_SUGGESTION
564 #endif
565 
566 static const char *
get_pcap_failure_secondary_error_message(cap_device_open_status open_status,const char * open_status_str)567 get_pcap_failure_secondary_error_message(cap_device_open_status open_status,
568                                          const char *open_status_str)
569 {
570 #ifdef _WIN32
571     /*
572      * On Windows, first make sure they *have* Npcap installed.
573      */
574     if (!has_wpcap) {
575         return
576             "In order to capture packets, Npcap or WinPcap must be installed. See\n"
577             "\n"
578             "        https://nmap.org/npcap/\n"
579             "\n"
580             "for a downloadable version of Npcap and for instructions on how to\n"
581             "install it.";
582     }
583 #endif
584 
585     /*
586      * OK, now just return a largely platform-independent error that might
587      * have platform-specific suggestions at the end (for example, suggestions
588      * for how to get permission to capture).
589      */
590     if (open_status == CAP_DEVICE_OPEN_ERR_GENERIC) {
591         /*
592          * We don't know what kind of error it is.  See if there's a hint
593          * in the error string; if not, throw all generic suggestions at
594          * the user.
595          */
596         static const char promisc_failed[] =
597             "failed to set hardware filter to promiscuous mode";
598 
599         /*
600          * Does the error string begin with the error produced by WinPcap
601          * and Npcap if attempting to set promiscuous mode fails?
602          * (Note that this string could have a specific error message
603          * from an NDIS error after the initial part, so we do a prefix
604          * check rather than an exact match check.)
605          */
606         if (strncmp(open_status_str, promisc_failed, sizeof promisc_failed - 1) == 0) {
607             /*
608              * Yes.  Suggest that the user turn off promiscuous mode on that
609              * device.
610              */
611             return
612                    "Please turn off promiscuous mode for this device";
613         } else {
614             return
615                    "Please check to make sure you have sufficient permissions, and that you have "
616                    "the proper interface or pipe specified."
617                    PLATFORM_PERMISSIONS_SUGGESTION;
618         }
619     } else if (open_status == CAP_DEVICE_OPEN_ERR_PERMISSIONS) {
620         /*
621          * This is a permissions error, so no need to specify any other
622          * warnings.
623          */
624         return
625                "Please check to make sure you have sufficient permissions."
626                PLATFORM_PERMISSIONS_SUGGESTION;
627     } else {
628         /*
629          * This is not a permissons error, so no need to suggest
630          * checking permissions.
631          */
632         return
633             "Please check that you have the proper interface or pipe specified.";
634     }
635 }
636 
637 static void
get_capture_device_open_failure_messages(cap_device_open_status open_status,const char * open_status_str,const char * iface,char * errmsg,size_t errmsg_len,char * secondary_errmsg,size_t secondary_errmsg_len)638 get_capture_device_open_failure_messages(cap_device_open_status open_status,
639                                          const char *open_status_str,
640                                          const char *iface,
641                                          char *errmsg, size_t errmsg_len,
642                                          char *secondary_errmsg,
643                                          size_t secondary_errmsg_len)
644 {
645     g_snprintf(errmsg, (gulong) errmsg_len,
646                "The capture session could not be initiated on capture device \"%s\" (%s).",
647                iface, open_status_str);
648     g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, "%s",
649                get_pcap_failure_secondary_error_message(open_status, open_status_str));
650 }
651 
652 static gboolean
compile_capture_filter(const char * iface,pcap_t * pcap_h,struct bpf_program * fcode,const char * cfilter)653 compile_capture_filter(const char *iface, pcap_t *pcap_h,
654                        struct bpf_program *fcode, const char *cfilter)
655 {
656     bpf_u_int32 netnum, netmask;
657     gchar       lookup_net_err_str[PCAP_ERRBUF_SIZE];
658 
659     if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
660         /*
661          * Well, we can't get the netmask for this interface; it's used
662          * only for filters that check for broadcast IP addresses, so
663          * we just punt and use 0.  It might be nice to warn the user,
664          * but that's a pain in a GUI application, as it'd involve popping
665          * up a message box, and it's not clear how often this would make
666          * a difference (only filters that check for IP broadcast addresses
667          * use the netmask).
668          */
669         /*cmdarg_err(
670           "Warning:  Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
671         netmask = 0;
672     }
673 
674     /*
675      * Sigh.  Older versions of libpcap don't properly declare the
676      * third argument to pcap_compile() as a const pointer.  Cast
677      * away the warning.
678      */
679 DIAG_OFF(cast-qual)
680     if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
681         return FALSE;
682 DIAG_ON(cast-qual)
683     return TRUE;
684 }
685 
686 static gboolean
show_filter_code(capture_options * capture_opts)687 show_filter_code(capture_options *capture_opts)
688 {
689     interface_options *interface_opts;
690     pcap_t *pcap_h;
691     cap_device_open_status open_status;
692     gchar open_status_str[PCAP_ERRBUF_SIZE];
693     char errmsg[MSG_MAX_LENGTH+1];
694     char secondary_errmsg[MSG_MAX_LENGTH+1];
695     struct bpf_program fcode;
696     struct bpf_insn *insn;
697     u_int i;
698     guint j;
699 
700     for (j = 0; j < capture_opts->ifaces->len; j++) {
701         interface_opts = &g_array_index(capture_opts->ifaces, interface_options, j);
702         pcap_h = open_capture_device(capture_opts, interface_opts,
703             CAP_READ_TIMEOUT, &open_status, &open_status_str);
704         if (pcap_h == NULL) {
705             /* Open failed; get messages */
706             get_capture_device_open_failure_messages(open_status, open_status_str,
707                                                      interface_opts->name,
708                                                      errmsg, sizeof errmsg,
709                                                      secondary_errmsg,
710                                                      sizeof secondary_errmsg);
711             /* And report them */
712             report_capture_error(errmsg, secondary_errmsg);
713             return FALSE;
714         }
715 
716         /* Set the link-layer type. */
717         if (!set_pcap_datalink(pcap_h, interface_opts->linktype, interface_opts->name,
718                                errmsg, sizeof errmsg,
719                                secondary_errmsg, sizeof secondary_errmsg)) {
720             pcap_close(pcap_h);
721             report_capture_error(errmsg, secondary_errmsg);
722             return FALSE;
723         }
724 
725         /* OK, try to compile the capture filter. */
726         if (!compile_capture_filter(interface_opts->name, pcap_h, &fcode,
727                                     interface_opts->cfilter)) {
728             g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_h));
729             pcap_close(pcap_h);
730             report_cfilter_error(capture_opts, j, errmsg);
731             return FALSE;
732         }
733         pcap_close(pcap_h);
734 
735         /* Now print the filter code. */
736         insn = fcode.bf_insns;
737 
738         for (i = 0; i < fcode.bf_len; insn++, i++)
739             printf("%s\n", bpf_image(insn, i));
740     }
741     /* If not using libcap: we now can now set euid/egid to ruid/rgid         */
742     /*  to remove any suid privileges.                                        */
743     /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities  */
744     /*  (euid/egid have already previously been set to ruid/rgid.             */
745     /* (See comment in main() for details)                                    */
746 #ifndef HAVE_LIBCAP
747     relinquish_special_privs_perm();
748 #else
749     relinquish_all_capabilities();
750 #endif
751     if (capture_child) {
752         /* Let our parent know we succeeded. */
753         pipe_write_block(2, SP_SUCCESS, NULL);
754     }
755     return TRUE;
756 }
757 
758 /*
759  * capture_interface_list() is expected to do the right thing to get
760  * a list of interfaces.
761  *
762  * In most of the programs in the Wireshark suite, "the right thing"
763  * is to run dumpcap and ask it for the list, because dumpcap may
764  * be the only program in the suite with enough privileges to get
765  * the list.
766  *
767  * In dumpcap itself, however, we obviously can't run dumpcap to
768  * ask for the list.  Therefore, our capture_interface_list() should
769  * just call get_interface_list().
770  */
771 GList *
capture_interface_list(int * err,char ** err_str,void (* update_cb)(void)_U_)772 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
773 {
774     return get_interface_list(err, err_str);
775 }
776 
777 /*
778  * Output a machine readable list of the interfaces
779  * This list is retrieved by the sync_interface_list_open() function
780  * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
781  */
782 static void
print_machine_readable_interfaces(GList * if_list)783 print_machine_readable_interfaces(GList *if_list)
784 {
785     int         i;
786     GList       *if_entry;
787     if_info_t   *if_info;
788     GSList      *addr;
789     if_addr_t   *if_addr;
790     char        addr_str[WS_INET6_ADDRSTRLEN];
791 
792     if (capture_child) {
793         /* Let our parent know we succeeded. */
794         pipe_write_block(2, SP_SUCCESS, NULL);
795     }
796 
797     i = 1;  /* Interface id number */
798     for (if_entry = g_list_first(if_list); if_entry != NULL;
799          if_entry = g_list_next(if_entry)) {
800         if_info = (if_info_t *)if_entry->data;
801         printf("%d. %s\t", i++, if_info->name);
802 
803         /*
804          * Print the contents of the if_entry struct in a parseable format.
805          * Each if_entry element is tab-separated.  Addresses are comma-
806          * separated.
807          */
808         /* XXX - Make sure our description doesn't contain a tab */
809         if (if_info->vendor_description != NULL)
810             printf("%s\t", if_info->vendor_description);
811         else
812             printf("\t");
813 
814         /* XXX - Make sure our friendly name doesn't contain a tab */
815         if (if_info->friendly_name != NULL)
816             printf("%s\t", if_info->friendly_name);
817         else
818             printf("\t");
819 
820         printf("%i\t", if_info->type);
821 
822         for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
823                     addr = g_slist_next(addr)) {
824             if (addr != g_slist_nth(if_info->addrs, 0))
825                 printf(",");
826 
827             if_addr = (if_addr_t *)addr->data;
828             switch(if_addr->ifat_type) {
829             case IF_AT_IPv4:
830                 printf("%s", ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str, sizeof(addr_str)));
831                 break;
832             case IF_AT_IPv6:
833                 printf("%s", ws_inet_ntop6(&if_addr->addr.ip6_addr, addr_str, sizeof(addr_str)));
834                 break;
835             default:
836                 printf("<type unknown %i>", if_addr->ifat_type);
837             }
838         }
839 
840         if (if_info->loopback)
841             printf("\tloopback");
842         else
843             printf("\tnetwork");
844         printf("\t%s", if_info->extcap);
845         printf("\n");
846     }
847 }
848 
849 /*
850  * If you change the machine-readable output format of this function,
851  * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
852  */
853 static void
print_machine_readable_if_capabilities(if_capabilities_t * caps,int queries)854 print_machine_readable_if_capabilities(if_capabilities_t *caps, int queries)
855 {
856     GList *lt_entry, *ts_entry;
857     const gchar *desc_str;
858 
859     if (capture_child) {
860         /* Let our parent know we succeeded. */
861         pipe_write_block(2, SP_SUCCESS, NULL);
862     }
863 
864     if (queries & CAPS_QUERY_LINK_TYPES) {
865         if (caps->can_set_rfmon)
866             printf("1\n");
867         else
868             printf("0\n");
869         for (lt_entry = caps->data_link_types; lt_entry != NULL;
870              lt_entry = g_list_next(lt_entry)) {
871           data_link_info_t *data_link_info = (data_link_info_t *)lt_entry->data;
872           if (data_link_info->description != NULL)
873             desc_str = data_link_info->description;
874           else
875             desc_str = "(not supported)";
876           printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
877                  desc_str);
878         }
879     }
880     printf("\n");
881     if (queries & CAPS_QUERY_TIMESTAMP_TYPES) {
882         for (ts_entry = caps->timestamp_types; ts_entry != NULL;
883              ts_entry = g_list_next(ts_entry)) {
884           timestamp_info_t *timestamp = (timestamp_info_t *)ts_entry->data;
885           if (timestamp->description != NULL)
886             desc_str = timestamp->description;
887           else
888             desc_str = "(none)";
889           printf("%s\t%s\n", timestamp->name, desc_str);
890         }
891     }
892 }
893 
894 typedef struct {
895     char *name;
896     pcap_t *pch;
897 } if_stat_t;
898 
899 /* Print the number of packets captured for each interface until we're killed. */
900 static int
print_statistics_loop(gboolean machine_readable)901 print_statistics_loop(gboolean machine_readable)
902 {
903     GList       *if_list, *if_entry, *stat_list = NULL, *stat_entry;
904     if_info_t   *if_info;
905     if_stat_t   *if_stat;
906     int         err;
907     gchar       *err_str;
908     pcap_t      *pch;
909     char        errbuf[PCAP_ERRBUF_SIZE];
910     struct pcap_stat ps;
911 
912     if_list = get_interface_list(&err, &err_str);
913     if (if_list == NULL) {
914        if (err == 0)
915             cmdarg_err("There are no interfaces on which a capture can be done");
916         else {
917             cmdarg_err("%s", err_str);
918             g_free(err_str);
919         }
920         return err;
921     }
922 
923     for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
924         if_info = (if_info_t *)if_entry->data;
925 
926 #ifdef __linux__
927         /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
928          * connections. We avoid collecting stats on them.
929          */
930         if (!strncmp(if_info->name, "nf", 2)) {
931             ws_debug("Skipping interface %s for stats", if_info->name);
932             continue;
933         }
934 #endif
935 
936 #ifdef HAVE_PCAP_OPEN
937         pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
938 #else
939         pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
940 #endif
941 
942         if (pch) {
943             if_stat = g_new(if_stat_t, 1);
944             if_stat->name = g_strdup(if_info->name);
945             if_stat->pch = pch;
946             stat_list = g_list_append(stat_list, if_stat);
947         }
948     }
949 
950     if (!stat_list) {
951         cmdarg_err("There are no interfaces on which a capture can be done");
952         return 2;
953     }
954 
955     if (capture_child) {
956         /* Let our parent know we succeeded. */
957         pipe_write_block(2, SP_SUCCESS, NULL);
958     }
959 
960     if (!machine_readable) {
961         printf("%-15s  %10s  %10s\n", "Interface", "Received",
962             "Dropped");
963     }
964 
965     global_ld.go = TRUE;
966     while (global_ld.go) {
967         for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
968             if_stat = (if_stat_t *)stat_entry->data;
969             pcap_stats(if_stat->pch, &ps);
970 
971             if (!machine_readable) {
972                 printf("%-15s  %10u  %10u\n", if_stat->name,
973                     ps.ps_recv, ps.ps_drop);
974             } else {
975                 printf("%s\t%u\t%u\n", if_stat->name,
976                     ps.ps_recv, ps.ps_drop);
977                 fflush(stdout);
978             }
979         }
980 #ifdef _WIN32
981         /* If we have a dummy signal pipe check it */
982         if (!signal_pipe_check_running()) {
983             global_ld.go = FALSE;
984         }
985         Sleep(1 * 1000);
986 #else
987         sleep(1);
988 #endif
989     }
990 
991     /* XXX - Not reached.  Should we look for 'q' in stdin? */
992     for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
993         if_stat = (if_stat_t *)stat_entry->data;
994         pcap_close(if_stat->pch);
995         g_free(if_stat->name);
996         g_free(if_stat);
997     }
998     g_list_free(stat_list);
999     free_interface_list(if_list);
1000 
1001     return 0;
1002 }
1003 
1004 
1005 #ifdef _WIN32
1006 static BOOL WINAPI
capture_cleanup_handler(DWORD dwCtrlType)1007 capture_cleanup_handler(DWORD dwCtrlType)
1008 {
1009     /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1010        Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1011        is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1012        like SIGTERM at least when the machine's shutting down.
1013 
1014        For now, if we're running as a command rather than a capture child,
1015        we handle all but CTRL_LOGOFF_EVENT as indications that we should
1016        clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1017        in that way on UN*X.
1018 
1019        If we're not running as a capture child, we might be running as
1020        a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1021        user logs out.  (XXX - can we explicitly check whether we're
1022        running as a service?) */
1023 
1024     ws_info("Console: Control signal");
1025     ws_debug("Console: Control signal, CtrlType: %lu", dwCtrlType);
1026 
1027     /* Keep capture running if we're a service and a user logs off */
1028     if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1029         capture_loop_stop();
1030         return TRUE;
1031     } else {
1032         return FALSE;
1033     }
1034 }
1035 #else
1036 static void
capture_cleanup_handler(int signum _U_)1037 capture_cleanup_handler(int signum _U_)
1038 {
1039     /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1040        SIGTERM.  We assume that if the user wanted it to keep running
1041        after they logged out, they'd have nohupped it. */
1042 
1043     capture_loop_stop();
1044 }
1045 #endif
1046 
1047 
1048 static void
report_capture_count(gboolean reportit)1049 report_capture_count(gboolean reportit)
1050 {
1051     /* Don't print this if we're a capture child. */
1052     if (!capture_child && reportit) {
1053         fprintf(stderr, "\rPackets captured: %d\n", global_ld.packets_captured);
1054         /* stderr could be line buffered */
1055         fflush(stderr);
1056     }
1057 }
1058 
1059 
1060 #ifdef SIGINFO
1061 static void
report_counts_for_siginfo(void)1062 report_counts_for_siginfo(void)
1063 {
1064     report_capture_count(quiet);
1065     infoprint = FALSE; /* we just reported it */
1066 }
1067 
1068 static void
report_counts_siginfo(int signum _U_)1069 report_counts_siginfo(int signum _U_)
1070 {
1071     int sav_errno = errno;
1072 
1073     /* If we've been told to delay printing, just set a flag asking
1074        that we print counts (if we're supposed to), otherwise print
1075        the count of packets captured (if we're supposed to). */
1076     if (infodelay)
1077         infoprint = TRUE;
1078     else
1079         report_counts_for_siginfo();
1080     errno = sav_errno;
1081 }
1082 #endif /* SIGINFO */
1083 
1084 static void
exit_main(int status)1085 exit_main(int status)
1086 {
1087     ws_cleanup_sockets();
1088 
1089 #ifdef _WIN32
1090     /* can be helpful for debugging */
1091 #ifdef DEBUG_DUMPCAP
1092     printf("Press any key\n");
1093     _getch();
1094 #endif
1095 
1096 #endif /* _WIN32 */
1097 
1098     if (ringbuf_is_initialized()) {
1099         /* save_file is managed by ringbuffer, be sure to release the memory and
1100          * avoid capture_opts_cleanup from double-freeing 'save_file'. */
1101         ringbuf_free();
1102         global_capture_opts.save_file = NULL;
1103     }
1104 
1105     capture_opts_cleanup(&global_capture_opts);
1106     exit(status);
1107 }
1108 
1109 #ifdef HAVE_LIBCAP
1110 /*
1111  * If we were linked with libcap (not related to libpcap), make sure we have
1112  * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1113  * (See comment in main() for details)
1114  */
1115 static void
relinquish_privs_except_capture(void)1116 relinquish_privs_except_capture(void)
1117 {
1118     /* If 'started_with_special_privs' (ie: suid) then enable for
1119      *  ourself the  NET_ADMIN and NET_RAW capabilities and then
1120      *  drop our suid privileges.
1121      *
1122      * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1123      *                stuff we don't need (and shouldn't have).
1124      * CAP_NET_RAW:   Packet capture (raw sockets).
1125      */
1126 
1127     if (started_with_special_privs()) {
1128         cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1129         int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1130 
1131         cap_t caps = cap_init();    /* all capabilities initialized to off */
1132 
1133         print_caps("Pre drop, pre set");
1134 
1135         if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1136             cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1137         }
1138 
1139         cap_set_flag(caps, CAP_PERMITTED,   cl_len, cap_list, CAP_SET);
1140         cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1141 
1142         if (cap_set_proc(caps)) {
1143             cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1144         }
1145         print_caps("Pre drop, post set");
1146 
1147         relinquish_special_privs_perm();
1148 
1149         print_caps("Post drop, pre set");
1150         cap_set_flag(caps, CAP_EFFECTIVE,   cl_len, cap_list, CAP_SET);
1151         if (cap_set_proc(caps)) {
1152             cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1153         }
1154         print_caps("Post drop, post set");
1155 
1156         cap_free(caps);
1157     }
1158 }
1159 
1160 #endif /* HAVE_LIBCAP */
1161 
1162 /* Take care of byte order in the libpcap headers read from pipes.
1163  * (function taken from wiretap/libpcap.c) */
1164 static void
cap_pipe_adjust_pcap_header(gboolean byte_swapped,struct pcap_hdr * hdr,struct pcaprec_hdr * rechdr)1165 cap_pipe_adjust_pcap_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1166 {
1167     if (byte_swapped) {
1168         /* Byte-swap the record header fields. */
1169         rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1170         rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1171         rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1172         rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1173     }
1174 
1175     /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1176        swapped, in order to match the BPF header layout.
1177 
1178        Unfortunately, some files were, according to a comment in the "libpcap"
1179        source, written with version 2.3 in their headers but without the
1180        interchanged fields, so if "incl_len" is greater than "orig_len" - which
1181        would make no sense - we assume that we need to swap them.  */
1182     if (hdr->version_major == 2 &&
1183         (hdr->version_minor < 3 ||
1184          (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1185         guint32 temp;
1186 
1187         temp = rechdr->orig_len;
1188         rechdr->orig_len = rechdr->incl_len;
1189         rechdr->incl_len = temp;
1190     }
1191 }
1192 
1193 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1194  * or just read().
1195  */
1196 static ssize_t
cap_pipe_read(int pipe_fd,char * buf,size_t sz,gboolean from_socket _U_)1197 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1198 {
1199 #ifdef _WIN32
1200     if (from_socket) {
1201         return recv(pipe_fd, buf, (int)sz, 0);
1202     } else {
1203         return -1;
1204     }
1205 #else
1206     return ws_read(pipe_fd, buf, sz);
1207 #endif
1208 }
1209 
1210 #if defined(_WIN32)
1211 /*
1212  * Thread function that reads from a pipe and pushes the data
1213  * to the main application thread.
1214  */
1215 /*
1216  * XXX Right now we use async queues for basic signaling. The main thread
1217  * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1218  * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1219  * Iff the read is successful cap_pipe_read pushes an item onto
1220  * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1221  * the queues themselves (yet).
1222  *
1223  * We might want to move some of the cap_pipe_dispatch logic here so that
1224  * we can let cap_thread_read run independently, queuing up multiple reads
1225  * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1226  */
cap_thread_read(void * arg)1227 static void *cap_thread_read(void *arg)
1228 {
1229     capture_src *pcap_src;
1230 #ifdef _WIN32
1231     BOOL res;
1232     DWORD last_err, bytes_read;
1233 #else /* _WIN32 */
1234     size_t bytes_read;
1235 #endif /* _WIN32 */
1236 
1237     pcap_src = (capture_src *)arg;
1238     while (pcap_src->cap_pipe_err == PIPOK) {
1239         g_async_queue_pop(pcap_src->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1240         g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1241         bytes_read = 0;
1242         while (bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1243            if ((pcap_src->from_cap_socket)
1244 #ifndef _WIN32
1245               || 1
1246 #endif
1247               )
1248            {
1249                ssize_t b;
1250                b = cap_pipe_read(pcap_src->cap_pipe_fd, pcap_src->cap_pipe_buf+bytes_read,
1251                         pcap_src->cap_pipe_bytes_to_read - bytes_read, pcap_src->from_cap_socket);
1252                if (b <= 0) {
1253                    if (b == 0) {
1254                        pcap_src->cap_pipe_err = PIPEOF;
1255                        bytes_read = 0;
1256                        break;
1257                    } else {
1258                        pcap_src->cap_pipe_err = PIPERR;
1259                        bytes_read = -1;
1260                        break;
1261                    }
1262                } else {
1263                    bytes_read += b;
1264                }
1265            }
1266 #ifdef _WIN32
1267            else
1268            {
1269                /* If we try to use read() on a named pipe on Windows with partial
1270                 * data it appears to return EOF.
1271                 */
1272                DWORD b;
1273                res = ReadFile(pcap_src->cap_pipe_h, pcap_src->cap_pipe_buf+bytes_read,
1274                               pcap_src->cap_pipe_bytes_to_read - bytes_read,
1275                               &b, NULL);
1276 
1277                bytes_read += b;
1278                if (!res) {
1279                    last_err = GetLastError();
1280                    if (last_err == ERROR_MORE_DATA) {
1281                        continue;
1282                    } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1283                        pcap_src->cap_pipe_err = PIPEOF;
1284                        bytes_read = 0;
1285                        break;
1286                    }
1287                    pcap_src->cap_pipe_err = PIPERR;
1288                    bytes_read = -1;
1289                    break;
1290                } else if (b == 0 && pcap_src->cap_pipe_bytes_to_read > 0) {
1291                    pcap_src->cap_pipe_err = PIPEOF;
1292                    bytes_read = 0;
1293                    break;
1294                }
1295            }
1296 #endif /*_WIN32 */
1297         }
1298         pcap_src->cap_pipe_bytes_read = bytes_read;
1299         if (pcap_src->cap_pipe_bytes_read >= pcap_src->cap_pipe_bytes_to_read) {
1300             g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1301         }
1302         g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1303     }
1304     /* Post to queue if we didn't read enough data as the main thread waits for the message */
1305     g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1306     if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1307         /* There's still more of the record to read. */
1308         g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1309     }
1310     g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1311     return NULL;
1312 }
1313 
1314 /*
1315  * Do a blocking read from a pipe within the main thread, by pushing
1316  * the read onto the pipe queue and then popping it off that queue;
1317  * the pipe will block until the pushed read completes.
1318  *
1319  * We do it with another thread because we can't use select() on
1320  * pipes on Windows, as we can on UN*Xes, we can only use it on
1321  * sockets.
1322  */
1323 void
pipe_read_sync(capture_src * pcap_src,void * buf,DWORD nbytes)1324 pipe_read_sync(capture_src *pcap_src, void *buf, DWORD nbytes)
1325 {
1326     pcap_src->cap_pipe_buf = (char *) buf;
1327     pcap_src->cap_pipe_bytes_read = 0;
1328     pcap_src->cap_pipe_bytes_to_read = nbytes;
1329     /* We don't have to worry about cap_pipe_read_mtx here */
1330     g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1331     g_async_queue_pop(pcap_src->cap_pipe_done_q);
1332 }
1333 #endif
1334 
1335 /* Provide select() functionality for a single file descriptor
1336  * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1337  *
1338  * Returns the same values as select.
1339  */
1340 static int
cap_pipe_select(int pipe_fd)1341 cap_pipe_select(int pipe_fd)
1342 {
1343     fd_set      rfds;
1344     struct timeval timeout;
1345 
1346     FD_ZERO(&rfds);
1347     FD_SET(pipe_fd, &rfds);
1348 
1349     timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1350     timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1351 
1352     return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1353 }
1354 
1355 #define DEF_TCP_PORT 19000
1356 
1357 static int
cap_open_socket(char * pipename,capture_src * pcap_src,char * errmsg,size_t errmsgl)1358 cap_open_socket(char *pipename, capture_src *pcap_src, char *errmsg, size_t errmsgl)
1359 {
1360     struct sockaddr_storage sa;
1361     socklen_t sa_len;
1362     int fd;
1363 
1364     /* Skip the initial "TCP@" in the pipename. */
1365     if (ws_socket_ptoa(&sa, pipename + 4, DEF_TCP_PORT) < 0) {
1366         g_snprintf(errmsg, (gulong)errmsgl,
1367                 "The capture session could not be initiated because"
1368                 "\"%s\" is not a valid socket specification", pipename);
1369         pcap_src->cap_pipe_err = PIPERR;
1370         return -1;
1371     }
1372 
1373     if ((fd = (int)socket(sa.ss_family, SOCK_STREAM, 0)) < 0) {
1374         g_snprintf(errmsg, (gulong)errmsgl,
1375             "The capture session could not be initiated because"
1376             " the socket couldn't be created due to the socket error: \n"
1377 #ifdef _WIN32
1378             "         %s", win32strerror(WSAGetLastError()));
1379 #else
1380             "         %d: %s", errno, g_strerror(errno));
1381 #endif
1382         pcap_src->cap_pipe_err = PIPERR;
1383         return -1;
1384     }
1385 
1386     if (sa.ss_family == AF_INET6)
1387         sa_len = sizeof(struct sockaddr_in6);
1388     else
1389         sa_len = sizeof(struct sockaddr_in);
1390     if (connect(fd, (struct sockaddr *)&sa, sa_len) < 0) {
1391         g_snprintf(errmsg, (gulong)errmsgl,
1392             "The capture session could not be initiated because"
1393             " the socket couldn't be connected due to the socket error: \n"
1394 #ifdef _WIN32
1395             "         %s", win32strerror(WSAGetLastError()));
1396 #else
1397             "         %d: %s", errno, g_strerror(errno));
1398 #endif
1399         pcap_src->cap_pipe_err = PIPERR;
1400 
1401         cap_pipe_close(fd, TRUE);
1402         return -1;
1403     }
1404 
1405     pcap_src->from_cap_socket = TRUE;
1406     return fd;
1407 }
1408 
1409 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1410  * otherwise.
1411  */
1412 static void
cap_pipe_close(int pipe_fd,gboolean from_socket)1413 cap_pipe_close(int pipe_fd, gboolean from_socket)
1414 {
1415 #ifdef _WIN32
1416     if (from_socket) {
1417         closesocket(pipe_fd);
1418     }
1419 #else
1420     (void) from_socket; /* Mark unused, similar to Q_UNUSED */
1421     ws_close(pipe_fd);
1422 #endif
1423 }
1424 
1425 /** Read bytes from a capture source, which is assumed to be a pipe or
1426  * socket.
1427  *
1428  * Returns -1, or the number of bytes read similar to read(2).
1429  * Sets pcap_src->cap_pipe_err on error or EOF.
1430  */
1431 static ssize_t
cap_pipe_read_data_bytes(capture_src * pcap_src,char * errmsg,size_t errmsgl)1432 cap_pipe_read_data_bytes(capture_src *pcap_src, char *errmsg, size_t errmsgl)
1433 {
1434     int sel_ret;
1435     int fd = pcap_src->cap_pipe_fd;
1436 #ifdef _WIN32
1437     DWORD sz, bytes_read = 0;
1438 #else /* _WIN32 */
1439     ssize_t sz, bytes_read = 0;
1440 #endif /* _WIN32 */
1441     ssize_t b;
1442 
1443 #ifdef LOG_CAPTURE_VERBOSE
1444     ws_debug("cap_pipe_read_data_bytes read %lu of %lu",
1445           pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1446 #endif
1447     sz = pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read;
1448     while (bytes_read < sz) {
1449         if (fd == -1) {
1450             g_snprintf(errmsg, (gulong)errmsgl, "Invalid file descriptor.");
1451             pcap_src->cap_pipe_err = PIPNEXIST;
1452             return -1;
1453         }
1454 
1455         sel_ret = cap_pipe_select(fd);
1456         if (sel_ret < 0) {
1457             g_snprintf(errmsg, (gulong)errmsgl,
1458                        "Unexpected error from select: %s.", g_strerror(errno));
1459             pcap_src->cap_pipe_err = PIPERR;
1460             return -1;
1461         } else if (sel_ret > 0) {
1462             b = cap_pipe_read(fd, pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read+bytes_read,
1463                               sz-bytes_read, pcap_src->from_cap_socket);
1464             if (b <= 0) {
1465                 if (b == 0) {
1466                     g_snprintf(errmsg, (gulong)errmsgl,
1467                                "End of file reading from pipe or socket.");
1468                     pcap_src->cap_pipe_err = PIPEOF;
1469                 } else {
1470 #ifdef _WIN32
1471                     /*
1472                      * On Windows, we only do this for sockets.
1473                      */
1474                     DWORD lastError = WSAGetLastError();
1475                     errno = lastError;
1476                     g_snprintf(errmsg, (gulong)errmsgl,
1477                                "Error reading from pipe or socket: %s.",
1478                                win32strerror(lastError));
1479 #else
1480                     g_snprintf(errmsg, (gulong)errmsgl,
1481                                "Error reading from pipe or socket: %s.",
1482                                g_strerror(errno));
1483 #endif
1484                     pcap_src->cap_pipe_err = PIPERR;
1485                 }
1486                 return -1;
1487             }
1488             bytes_read += b;
1489         }
1490     }
1491     pcap_src->cap_pipe_bytes_read += bytes_read;
1492 #ifdef LOG_CAPTURE_VERBOSE
1493     ws_debug("cap_pipe_read_data_bytes read %lu of %lu",
1494           pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1495 #endif
1496     return bytes_read;
1497 }
1498 
1499 /* Some forward declarations for breaking up cap_pipe_open_live for pcap and pcapng formats */
1500 static void pcap_pipe_open_live(int fd, capture_src *pcap_src,
1501                                 struct pcap_hdr *hdr,
1502                                 char *errmsg, size_t errmsgl,
1503                                 char *secondary_errmsg, size_t secondary_errmsgl);
1504 static void pcapng_pipe_open_live(int fd, capture_src *pcap_src,
1505                                   char *errmsg, size_t errmsgl);
1506 static int pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src,
1507                                 char *errmsg, size_t errmsgl);
1508 
1509 /* For problems that are probably Not Our Fault. */
1510 static char not_our_bug[] =
1511     "Please report this to the developers of the program writing to the pipe.";
1512 
1513 /* Mimic pcap_open_live() for pipe captures
1514 
1515  * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1516  * open it, and read the header.
1517  *
1518  * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1519  * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1520 static void
cap_pipe_open_live(char * pipename,capture_src * pcap_src,void * hdr,char * errmsg,size_t errmsgl,char * secondary_errmsg,size_t secondary_errmsgl)1521 cap_pipe_open_live(char *pipename,
1522                    capture_src *pcap_src,
1523                    void *hdr,
1524                    char *errmsg, size_t errmsgl,
1525                    char *secondary_errmsg, size_t secondary_errmsgl)
1526 {
1527 #ifndef _WIN32
1528     ws_statb64         pipe_stat;
1529     struct sockaddr_un sa;
1530 #else /* _WIN32 */
1531     char    *pncopy, *pos;
1532     guintptr extcap_pipe_handle;
1533 #endif
1534     gboolean extcap_pipe = FALSE;
1535     ssize_t  b;
1536     int      fd = -1, sel_ret;
1537     size_t   bytes_read;
1538     guint32  magic = 0;
1539     pcap_src->cap_pipe_fd = -1;
1540 #ifdef _WIN32
1541     pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1542 #endif
1543 
1544     ws_debug("cap_pipe_open_live: %s", pipename);
1545 
1546     /*
1547      * XXX - this blocks until a pcap per-file header has been written to
1548      * the pipe, so it could block indefinitely.
1549      */
1550     if (strcmp(pipename, "-") == 0) {
1551 #ifndef _WIN32
1552         fd = 0; /* read from stdin */
1553 #else /* _WIN32 */
1554         pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1555 #endif  /* _WIN32 */
1556     } else if (!strncmp(pipename, "TCP@", 4)) {
1557        if ((fd = cap_open_socket(pipename, pcap_src, errmsg, errmsgl)) < 0) {
1558           return;
1559        }
1560     } else {
1561 #ifndef _WIN32
1562         if ( g_strrstr(pipename, EXTCAP_PIPE_PREFIX) != NULL )
1563             extcap_pipe = TRUE;
1564 
1565         if (ws_stat64(pipename, &pipe_stat) < 0) {
1566             if (errno == ENOENT || errno == ENOTDIR)
1567                 pcap_src->cap_pipe_err = PIPNEXIST;
1568             else {
1569                 g_snprintf(errmsg, (gulong)errmsgl,
1570                            "The capture session could not be initiated "
1571                            "due to error getting information on pipe or socket: %s.", g_strerror(errno));
1572                 pcap_src->cap_pipe_err = PIPERR;
1573             }
1574             return;
1575         }
1576         if (S_ISFIFO(pipe_stat.st_mode)) {
1577             fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1578             if (fd == -1) {
1579                 g_snprintf(errmsg, (gulong)errmsgl,
1580                            "The capture session could not be initiated "
1581                            "due to error on pipe open: %s.", g_strerror(errno));
1582                 pcap_src->cap_pipe_err = PIPERR;
1583                 return;
1584             }
1585         } else if (S_ISSOCK(pipe_stat.st_mode)) {
1586             fd = socket(AF_UNIX, SOCK_STREAM, 0);
1587             if (fd == -1) {
1588                 g_snprintf(errmsg, (gulong)errmsgl,
1589                            "The capture session could not be initiated "
1590                            "due to error on socket create: %s.", g_strerror(errno));
1591                 pcap_src->cap_pipe_err = PIPERR;
1592                 return;
1593             }
1594             sa.sun_family = AF_UNIX;
1595             /*
1596              * The Single UNIX Specification says:
1597              *
1598              *   The size of sun_path has intentionally been left undefined.
1599              *   This is because different implementations use different sizes.
1600              *   For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1601              *   of 104. Since most implementations originate from BSD versions,
1602              *   the size is typically in the range 92 to 108.
1603              *
1604              *   Applications should not assume a particular length for sun_path
1605              *   or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1606              *
1607              * It also says
1608              *
1609              *   The <sys/un.h> header shall define the sockaddr_un structure,
1610              *   which shall include at least the following members:
1611              *
1612              *   sa_family_t  sun_family  Address family.
1613              *   char         sun_path[]  Socket pathname.
1614              *
1615              * so we assume that it's an array, with a specified size,
1616              * and that the size reflects the maximum path length.
1617              */
1618             if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1619                 /* Path name too long */
1620                 g_snprintf(errmsg, (gulong)errmsgl,
1621                            "The capture session coud not be initiated "
1622                            "due to error on socket connect: Path name too long.");
1623                 pcap_src->cap_pipe_err = PIPERR;
1624                 ws_close(fd);
1625                 return;
1626             }
1627             b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1628             if (b == -1) {
1629                 g_snprintf(errmsg, (gulong)errmsgl,
1630                            "The capture session coud not be initiated "
1631                            "due to error on socket connect: %s.", g_strerror(errno));
1632                 pcap_src->cap_pipe_err = PIPERR;
1633                 ws_close(fd);
1634                 return;
1635             }
1636         } else {
1637             if (S_ISCHR(pipe_stat.st_mode)) {
1638                 /*
1639                  * Assume the user specified an interface on a system where
1640                  * interfaces are in /dev.  Pretend we haven't seen it.
1641                  */
1642                 pcap_src->cap_pipe_err = PIPNEXIST;
1643             } else {
1644                 g_snprintf(errmsg, (gulong)errmsgl,
1645                            "The capture session could not be initiated because\n"
1646                            "\"%s\" is neither an interface nor a socket nor a pipe.", pipename);
1647                 pcap_src->cap_pipe_err = PIPERR;
1648             }
1649             return;
1650         }
1651 
1652 #else /* _WIN32 */
1653         if (sscanf(pipename, EXTCAP_PIPE_PREFIX "%" G_GUINTPTR_FORMAT, &extcap_pipe_handle) == 1)
1654         {
1655             /* The client is already connected to extcap pipe.
1656              * We have inherited the handle from parent process.
1657              */
1658             extcap_pipe = TRUE;
1659             pcap_src->cap_pipe_h = (HANDLE)extcap_pipe_handle;
1660         }
1661         else
1662         {
1663 #define PIPE_STR "\\pipe\\"
1664             /* Under Windows, named pipes _must_ have the form
1665              * "\\<server>\pipe\<pipename>".  <server> may be "." for localhost.
1666              */
1667             pncopy = g_strdup(pipename);
1668             if ((pos = strstr(pncopy, "\\\\")) == pncopy) {
1669                 pos = strchr(pncopy + 3, '\\');
1670                 if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1671                     pos = NULL;
1672             }
1673 
1674             g_free(pncopy);
1675 
1676             if (!pos) {
1677                 g_snprintf(errmsg, (gulong)errmsgl,
1678                     "The capture session could not be initiated because\n"
1679                     "\"%s\" is neither an interface nor a pipe.", pipename);
1680                 pcap_src->cap_pipe_err = PIPNEXIST;
1681                 return;
1682             }
1683 
1684 
1685             /* Wait for the pipe to appear */
1686             while (1) {
1687                 pcap_src->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1688                         OPEN_EXISTING, 0, NULL);
1689 
1690                 if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE)
1691                     break;
1692 
1693                 if (GetLastError() != ERROR_PIPE_BUSY) {
1694                     g_snprintf(errmsg, (gulong)errmsgl,
1695                         "The capture session on \"%s\" could not be started "
1696                         "due to error on pipe open: %s.",
1697                         pipename, win32strerror(GetLastError()));
1698                     pcap_src->cap_pipe_err = PIPERR;
1699                     return;
1700                 }
1701 
1702                 if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1703                     g_snprintf(errmsg, (gulong)errmsgl,
1704                         "The capture session on \"%s\" timed out during "
1705                         "pipe open: %s.",
1706                         pipename, win32strerror(GetLastError()));
1707                     pcap_src->cap_pipe_err = PIPERR;
1708                     return;
1709                 }
1710             }
1711         }
1712 #endif /* _WIN32 */
1713     }
1714 
1715     pcap_src->from_cap_pipe = TRUE;
1716 
1717     /*
1718      * We start with a 2KB buffer for packet data, which should be
1719      * large enough for most regular network packets.  We increase it,
1720      * up to the maximum size we allow, as necessary.
1721      */
1722     pcap_src->cap_pipe_databuf = (char*)g_malloc(2048);
1723     pcap_src->cap_pipe_databuf_size = 2048;
1724 
1725     /*
1726      * Read the first 4 bytes of data from the pipe.
1727      *
1728      * If a pcap file is being written to it, that will be
1729      * the pcap magic number.
1730      *
1731      * If a pcapng file is being written to it, that will be
1732      * the block type of the initial SHB.
1733      */
1734 #ifdef _WIN32
1735     /*
1736      * On UN*X, we can use select() on pipes or sockets.
1737      *
1738      * On Windows, we can only use it on sockets; to do non-blocking
1739      * reads from pipes, we currently do reads in a separate thread
1740      * and use GLib asynchronous queues from the main thread to start
1741      * read operations and to wait for them to complete.
1742      */
1743     if (pcap_src->from_cap_socket)
1744 #endif
1745     {
1746         bytes_read = 0;
1747         while (bytes_read < sizeof magic) {
1748             sel_ret = cap_pipe_select(fd);
1749             if (sel_ret < 0) {
1750                 g_snprintf(errmsg, (gulong)errmsgl,
1751                            "Unexpected error from select: %s.",
1752                            g_strerror(errno));
1753                 goto error;
1754             } else if (sel_ret > 0) {
1755                 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
1756                                   sizeof magic-bytes_read,
1757                                   pcap_src->from_cap_socket);
1758                 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1759                 if (extcap_pipe && b <= 0)
1760                     goto error;
1761 
1762                 if (b <= 0) {
1763                     if (b == 0)
1764                         g_snprintf(errmsg, (gulong)errmsgl,
1765                                    "End of file on pipe magic during open.");
1766                     else
1767                         g_snprintf(errmsg, (gulong)errmsgl,
1768                                    "Error on pipe magic during open: %s.",
1769                                    g_strerror(errno));
1770                     goto error;
1771                 }
1772                 bytes_read += b;
1773             }
1774         }
1775     }
1776 #ifdef _WIN32
1777     else {
1778         /* Create a thread to read from this pipe */
1779         g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
1780 
1781         pipe_read_sync(pcap_src, &magic, sizeof(magic));
1782         /* jump messaging, if extcap had an error, stderr will provide the correct message */
1783         if (pcap_src->cap_pipe_bytes_read <= 0 && extcap_pipe)
1784             goto error;
1785 
1786         if (pcap_src->cap_pipe_bytes_read <= 0) {
1787             if (pcap_src->cap_pipe_bytes_read == 0)
1788                 g_snprintf(errmsg, (gulong)errmsgl,
1789                            "End of file on pipe magic during open.");
1790             else
1791                 g_snprintf(errmsg, (gulong)errmsgl,
1792                            "Error on pipe magic during open: %s.",
1793                            g_strerror(errno));
1794             goto error;
1795         }
1796     }
1797 #endif
1798 
1799     switch (magic) {
1800     case PCAP_MAGIC:
1801     case PCAP_NSEC_MAGIC:
1802         /* This is a pcap file.
1803            The host that wrote it has our byte order, and was running
1804            a program using either standard or ss990417 libpcap. */
1805         pcap_src->cap_pipe_info.pcap.byte_swapped = FALSE;
1806         pcap_src->cap_pipe_modified = FALSE;
1807         pcap_src->ts_nsec = magic == PCAP_NSEC_MAGIC;
1808         break;
1809     case PCAP_MODIFIED_MAGIC:
1810         /* This is a pcap file.
1811            The host that wrote it has our byte order, but was running
1812            a program using either ss990915 or ss991029 libpcap. */
1813         pcap_src->cap_pipe_info.pcap.byte_swapped = FALSE;
1814         pcap_src->cap_pipe_modified = TRUE;
1815         break;
1816     case PCAP_SWAPPED_MAGIC:
1817     case PCAP_SWAPPED_NSEC_MAGIC:
1818         /* This is a pcap file.
1819            The host that wrote it has a byte order opposite to ours,
1820            and was running a program using either standard or
1821            ss990417 libpcap. */
1822         pcap_src->cap_pipe_info.pcap.byte_swapped = TRUE;
1823         pcap_src->cap_pipe_modified = FALSE;
1824         pcap_src->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
1825         break;
1826     case PCAP_SWAPPED_MODIFIED_MAGIC:
1827         /* This is a pcap file.
1828            The host that wrote it out has a byte order opposite to
1829            ours, and was running a program using either ss990915
1830            or ss991029 libpcap. */
1831         pcap_src->cap_pipe_info.pcap.byte_swapped = TRUE;
1832         pcap_src->cap_pipe_modified = TRUE;
1833         break;
1834     case BLOCK_TYPE_SHB:
1835         /* This is a pcapng file. */
1836         pcap_src->from_pcapng = TRUE;
1837         pcap_src->cap_pipe_dispatch = pcapng_pipe_dispatch;
1838         pcap_src->cap_pipe_info.pcapng.src_iface_to_global = g_array_new(FALSE, FALSE, sizeof(guint32));
1839         global_capture_opts.use_pcapng = TRUE;      /* we can only output in pcapng format */
1840         break;
1841     default:
1842         /* Not a pcapng file, and either not a pcap type we know about
1843            or not a pcap file, either. */
1844         g_snprintf(errmsg, (gulong)errmsgl,
1845                    "Data written to the pipe is neither in a supported pcap format nor in pcapng format.");
1846         g_snprintf(secondary_errmsg, (gulong)secondary_errmsgl, "%s",
1847                    not_our_bug);
1848         goto error;
1849     }
1850 
1851     if (pcap_src->from_pcapng)
1852         pcapng_pipe_open_live(fd, pcap_src, errmsg, errmsgl);
1853     else
1854         pcap_pipe_open_live(fd, pcap_src, (struct pcap_hdr *) hdr, errmsg, errmsgl,
1855                             secondary_errmsg, secondary_errmsgl);
1856 
1857     return;
1858 
1859 error:
1860     ws_debug("cap_pipe_open_live: error %s", errmsg);
1861     pcap_src->cap_pipe_err = PIPERR;
1862     cap_pipe_close(fd, pcap_src->from_cap_socket);
1863     pcap_src->cap_pipe_fd = -1;
1864 #ifdef _WIN32
1865     pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1866 #endif
1867 }
1868 
1869 /*
1870  * Read the part of the pcap file header that follows the magic
1871  * number (we've already read the magic number).
1872  */
1873 static void
pcap_pipe_open_live(int fd,capture_src * pcap_src,struct pcap_hdr * hdr,char * errmsg,size_t errmsgl,char * secondary_errmsg,size_t secondary_errmsgl)1874 pcap_pipe_open_live(int fd,
1875                     capture_src *pcap_src,
1876                     struct pcap_hdr *hdr,
1877                     char *errmsg, size_t errmsgl,
1878                     char *secondary_errmsg, size_t secondary_errmsgl)
1879 {
1880     size_t   bytes_read;
1881     ssize_t  b;
1882     int      sel_ret;
1883 
1884     /*
1885      * We're reading from a pcap file.  We've already read the magic
1886      * number; read the rest of the header.
1887      *
1888      * (Note that struct pcap_hdr is a structure for the part of a
1889      * pcap file header *following the magic number*; it does not
1890      * include the magic number itself.)
1891      */
1892 #ifdef _WIN32
1893     if (pcap_src->from_cap_socket)
1894 #endif
1895     {
1896         /* Keep reading until we get the rest of the header. */
1897         bytes_read = 0;
1898         while (bytes_read < sizeof(struct pcap_hdr)) {
1899             sel_ret = cap_pipe_select(fd);
1900             if (sel_ret < 0) {
1901                 g_snprintf(errmsg, (gulong)errmsgl,
1902                            "Unexpected error from select: %s.",
1903                            g_strerror(errno));
1904                 goto error;
1905             } else if (sel_ret > 0) {
1906                 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
1907                                   sizeof(struct pcap_hdr) - bytes_read,
1908                                   pcap_src->from_cap_socket);
1909                 if (b <= 0) {
1910                     if (b == 0)
1911                         g_snprintf(errmsg, (gulong)errmsgl,
1912                                    "End of file on pipe header during open.");
1913                     else
1914                         g_snprintf(errmsg, (gulong)errmsgl,
1915                                    "Error on pipe header during open: %s.",
1916                                    g_strerror(errno));
1917                     g_snprintf(secondary_errmsg, (gulong)secondary_errmsgl,
1918                                "%s", not_our_bug);
1919                     goto error;
1920                 }
1921                 bytes_read += b;
1922             }
1923         }
1924     }
1925 #ifdef _WIN32
1926     else {
1927         pipe_read_sync(pcap_src, hdr, sizeof(struct pcap_hdr));
1928         if (pcap_src->cap_pipe_bytes_read <= 0) {
1929             if (pcap_src->cap_pipe_bytes_read == 0)
1930                 g_snprintf(errmsg, (gulong)errmsgl,
1931                            "End of file on pipe header during open.");
1932             else
1933                 g_snprintf(errmsg, (gulong)errmsgl,
1934                            "Error on pipe header header during open: %s.",
1935                            g_strerror(errno));
1936             g_snprintf(secondary_errmsg, (gulong)secondary_errmsgl, "%s",
1937                        not_our_bug);
1938             goto error;
1939         }
1940     }
1941 #endif
1942 
1943     if (pcap_src->cap_pipe_info.pcap.byte_swapped) {
1944         /* Byte-swap the header fields about which we care. */
1945         hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
1946         hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
1947         hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
1948         hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
1949     }
1950     pcap_src->linktype = hdr->network;
1951     /* Pick the appropriate maximum packet size for the link type */
1952     switch (pcap_src->linktype) {
1953 
1954     case 231: /* DLT_DBUS */
1955         pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_DBUS;
1956         break;
1957 
1958     case 279: /* DLT_EBHSCR */
1959         pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_EBHSCR;
1960         break;
1961 
1962     case 249: /* DLT_USBPCAP */
1963         pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_USBPCAP;
1964         break;
1965 
1966     default:
1967         pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
1968         break;
1969     }
1970 
1971     if (hdr->version_major < 2) {
1972         g_snprintf(errmsg, (gulong)errmsgl,
1973                    "The old pcap format version %d.%d is not supported.",
1974                    hdr->version_major, hdr->version_minor);
1975         g_snprintf(secondary_errmsg, (gulong)secondary_errmsgl, "%s",
1976                    not_our_bug);
1977         goto error;
1978     }
1979 
1980     pcap_src->cap_pipe_fd = fd;
1981     return;
1982 
1983 error:
1984     ws_debug("pcap_pipe_open_live: error %s", errmsg);
1985     pcap_src->cap_pipe_err = PIPERR;
1986     cap_pipe_close(fd, pcap_src->from_cap_socket);
1987     pcap_src->cap_pipe_fd = -1;
1988 #ifdef _WIN32
1989     pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1990 #endif
1991 }
1992 
1993 /*
1994  * Synchronously read the fixed portion of the pcapng section header block
1995  * (we've already read the pcapng block header).
1996  */
1997 static int
pcapng_read_shb(capture_src * pcap_src,char * errmsg,size_t errmsgl)1998 pcapng_read_shb(capture_src *pcap_src,
1999                 char *errmsg,
2000                 size_t errmsgl)
2001 {
2002     pcapng_section_header_block_t shb;
2003 
2004 #ifdef _WIN32
2005     if (pcap_src->from_cap_socket)
2006 #endif
2007     {
2008         pcap_src->cap_pipe_bytes_to_read = sizeof(pcapng_block_header_t) + sizeof(pcapng_section_header_block_t);
2009         if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2010             return -1;
2011         }
2012     }
2013 #ifdef _WIN32
2014     else {
2015         pipe_read_sync(pcap_src, pcap_src->cap_pipe_databuf + sizeof(pcapng_block_header_t),
2016             sizeof(pcapng_section_header_block_t));
2017         if (pcap_src->cap_pipe_bytes_read <= 0) {
2018             if (pcap_src->cap_pipe_bytes_read == 0)
2019                 g_snprintf(errmsg, (gulong)errmsgl,
2020                            "End of file reading from pipe or socket.");
2021             else
2022                 g_snprintf(errmsg, (gulong)errmsgl,
2023                            "Error reading from pipe or socket: %s.",
2024                            g_strerror(errno));
2025             return -1;
2026         }
2027         /* Continuing with STATE_EXPECT_DATA requires reading into cap_pipe_databuf at offset cap_pipe_bytes_read */
2028         pcap_src->cap_pipe_bytes_read = sizeof(pcapng_block_header_t) + sizeof(pcapng_section_header_block_t);
2029     }
2030 #endif
2031     memcpy(&shb, pcap_src->cap_pipe_databuf + sizeof(pcapng_block_header_t), sizeof(pcapng_section_header_block_t));
2032     switch (shb.magic)
2033     {
2034     case PCAPNG_MAGIC:
2035         ws_debug("pcapng SHB MAGIC");
2036         break;
2037     case PCAPNG_SWAPPED_MAGIC:
2038         ws_debug("pcapng SHB SWAPPED MAGIC");
2039         /*
2040          * pcapng sources can contain all sorts of block types.
2041          * Rather than add a bunch of complexity to this code (which is
2042          * often privileged), punt and tell the user to swap bytes
2043          * elsewhere.
2044          *
2045          * XXX - punting means that the Wireshark test suite must be
2046          * modified to:
2047          *
2048          *  1) have both little-endian and big-endian versions of
2049          *     all pcapng files piped to dumpcap;
2050          *
2051          *  2) pipe the appropriate file to dumpcap, depending on
2052          *     the byte order of the host on which the tests are
2053          *     being run;
2054          *
2055          * as per comments in bug 15772 and 15754.
2056          *
2057          * Are we *really* certain that the complexity added would be
2058          * significant enough to make adding it a security risk?  And
2059          * why would this code even be running with any elevated
2060          * privileges if you're capturing from a pipe?  We should not
2061          * only have given up all additional privileges if we're reading
2062          * from a pipe, we should give them up in such a fashion that
2063          * we can't reclaim them.
2064          */
2065 #if G_BYTE_ORDER == G_BIG_ENDIAN
2066 #define OUR_ENDIAN "big"
2067 #define IFACE_ENDIAN "little"
2068 #else
2069 #define OUR_ENDIAN "little"
2070 #define IFACE_ENDIAN "big"
2071 #endif
2072         g_snprintf(errmsg, (gulong)errmsgl,
2073                    "Interface %u is " IFACE_ENDIAN " endian but we're " OUR_ENDIAN " endian.",
2074                    pcap_src->interface_id);
2075         return -1;
2076     default:
2077         /* Not a pcapng type we know about, or not pcapng at all. */
2078         g_snprintf(errmsg, (gulong)errmsgl,
2079                    "Unrecognized pcapng format or not pcapng data.");
2080         return -1;
2081     }
2082 
2083     pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
2084 
2085     /* Setup state to capture any options following the section header block */
2086     pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2087 
2088     return 0;
2089 }
2090 
2091 /*
2092  * Save IDB blocks for playback whenever we change output files.
2093  * Rewrite EPB and ISB interface IDs.
2094  */
2095 static gboolean
pcapng_adjust_block(capture_src * pcap_src,const pcapng_block_header_t * bh,u_char * pd)2096 pcapng_adjust_block(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd)
2097 {
2098     switch(bh->block_type) {
2099     case BLOCK_TYPE_SHB:
2100     {
2101         if (global_ld.pcapng_passthrough) {
2102             /*
2103              * We have a single pcapng input. We pass the SHB through when
2104              * writing a single output file and for the first ring buffer
2105              * file. We need to save it for the second and subsequent ring
2106              * buffer files.
2107              */
2108             g_free(global_ld.saved_shb);
2109             global_ld.saved_shb = (guint8 *) g_memdup2(pd, bh->block_total_length);
2110 
2111             /*
2112              * We're dealing with one section at a time, so we can (and must)
2113              * get rid of our old IDBs.
2114              */
2115             for (unsigned i = 0; i < global_ld.saved_idbs->len; i++) {
2116                 saved_idb_t *idb_source = &g_array_index(global_ld.saved_idbs, saved_idb_t, i);
2117                 g_free(idb_source->idb);
2118             }
2119             g_array_set_size(global_ld.saved_idbs, 0);
2120         } else {
2121             /*
2122              * We have a new SHB from this capture source. We need to keep
2123              * global_ld.saved_idbs intact, so we mark IDBs we previously
2124              * collected from this source as deleted.
2125              */
2126             for (unsigned i = 0; i < pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len; i++) {
2127                 guint32 iface_id = g_array_index(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, guint32, i);
2128                 saved_idb_t *idb_source = &g_array_index(global_ld.saved_idbs, saved_idb_t, iface_id);
2129                 ws_assert(idb_source->interface_id == pcap_src->interface_id);
2130                 g_free(idb_source->idb);
2131                 memset(idb_source, 0, sizeof(saved_idb_t));
2132                 idb_source->deleted = TRUE;
2133                 ws_debug("%s: deleted pcapng IDB %u", G_STRFUNC, iface_id);
2134             }
2135         }
2136         g_array_set_size(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, 0);
2137     }
2138         break;
2139     case BLOCK_TYPE_IDB:
2140     {
2141         /*
2142          * Always gather IDBs. We can remove them or mark them as deleted
2143          * when we get a new SHB.
2144          */
2145         saved_idb_t idb_source = { 0 };
2146         idb_source.interface_id = pcap_src->interface_id;
2147         idb_source.idb_len = bh->block_total_length;
2148         idb_source.idb = (guint8 *) g_memdup2(pd, idb_source.idb_len);
2149         g_array_append_val(global_ld.saved_idbs, idb_source);
2150         guint32 iface_id = global_ld.saved_idbs->len - 1;
2151         g_array_append_val(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, iface_id);
2152         ws_debug("%s: mapped pcapng IDB %u -> %u from source %u",
2153               G_STRFUNC, pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len - 1, iface_id, pcap_src->interface_id);
2154     }
2155         break;
2156     case BLOCK_TYPE_EPB:
2157     case BLOCK_TYPE_ISB:
2158     {
2159         if (global_ld.pcapng_passthrough) {
2160             /* Our input and output interface IDs are the same. */
2161             break;
2162         }
2163         /* The interface ID is the first 32-bit field after the BH for both EPBs and ISBs. */
2164         guint32 iface_id;
2165         memcpy(&iface_id, pd + sizeof(pcapng_block_header_t), 4);
2166         if (iface_id < pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len) {
2167             memcpy(pd + sizeof(pcapng_block_header_t),
2168                    &g_array_index(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, guint32, iface_id), 4);
2169         } else {
2170             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);
2171             return FALSE;
2172         }
2173     }
2174         break;
2175     default:
2176         break;
2177     }
2178 
2179     return TRUE;
2180 }
2181 
2182 /*
2183  * Read the part of the initial pcapng SHB following the block type
2184  * (we've already read the block type).
2185  */
2186 static void
pcapng_pipe_open_live(int fd,capture_src * pcap_src,char * errmsg,size_t errmsgl)2187 pcapng_pipe_open_live(int fd,
2188                       capture_src *pcap_src,
2189                       char *errmsg,
2190                       size_t errmsgl)
2191 {
2192     guint32 type = BLOCK_TYPE_SHB;
2193     pcapng_block_header_t *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2194 
2195     ws_debug("pcapng_pipe_open_live: fd %d", fd);
2196 
2197     /*
2198      * A pcapng block begins with the block type followed by the block
2199      * total length; we've already read the block type, now read the
2200      * block length.
2201      */
2202 #ifdef _WIN32
2203     /*
2204      * On UN*X, we can use select() on pipes or sockets.
2205      *
2206      * On Windows, we can only use it on sockets; to do non-blocking
2207      * reads from pipes, we currently do reads in a separate thread
2208      * and use GLib asynchronous queues from the main thread to start
2209      * read operations and to wait for them to complete.
2210      */
2211     if (pcap_src->from_cap_socket)
2212 #endif
2213     {
2214         memcpy(pcap_src->cap_pipe_databuf, &type, sizeof(guint32));
2215         pcap_src->cap_pipe_bytes_read = sizeof(guint32);
2216         pcap_src->cap_pipe_bytes_to_read = sizeof(pcapng_block_header_t);
2217         pcap_src->cap_pipe_fd = fd;
2218         if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2219             goto error;
2220         }
2221         memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(pcapng_block_header_t));
2222     }
2223 #ifdef _WIN32
2224     else {
2225         g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
2226 
2227         bh->block_type = type;
2228         pipe_read_sync(pcap_src, &bh->block_total_length,
2229             sizeof(bh->block_total_length));
2230         if (pcap_src->cap_pipe_bytes_read <= 0) {
2231             if (pcap_src->cap_pipe_bytes_read == 0)
2232                 g_snprintf(errmsg, (gulong)errmsgl,
2233                            "End of file reading from pipe or socket.");
2234             else
2235                 g_snprintf(errmsg, (gulong)errmsgl,
2236                            "Error reading from pipe or socket: %s.",
2237                            g_strerror(errno));
2238             goto error;
2239         }
2240         pcap_src->cap_pipe_bytes_read = sizeof(pcapng_block_header_t);
2241         memcpy(pcap_src->cap_pipe_databuf, bh, sizeof(pcapng_block_header_t));
2242         pcap_src->cap_pipe_fd = fd;
2243     }
2244 #endif
2245     if ((bh->block_total_length & 0x03) != 0) {
2246         g_snprintf(errmsg, (gulong)errmsgl,
2247                    "block_total_length read from pipe is %u, which is not a multiple of 4.",
2248                    bh->block_total_length);
2249         goto error;
2250     }
2251     if (pcapng_read_shb(pcap_src, errmsg, errmsgl)) {
2252         goto error;
2253     }
2254 
2255     return;
2256 
2257 error:
2258     ws_debug("pcapng_pipe_open_live: error %s", errmsg);
2259     pcap_src->cap_pipe_err = PIPERR;
2260     cap_pipe_close(fd, pcap_src->from_cap_socket);
2261     pcap_src->cap_pipe_fd = -1;
2262 #ifdef _WIN32
2263     pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2264 #endif
2265 }
2266 
2267 /* We read one record from the pipe, take care of byte order in the record
2268  * header, write the record to the capture file, and update capture statistics. */
2269 static int
pcap_pipe_dispatch(loop_data * ld,capture_src * pcap_src,char * errmsg,size_t errmsgl)2270 pcap_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, size_t errmsgl)
2271 {
2272     struct pcap_pkthdr  phdr;
2273     enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2274            PD_ERR } result;
2275 #ifdef _WIN32
2276     gpointer  q_status;
2277 #endif
2278     ssize_t   b;
2279     guint new_bufsize;
2280     pcap_pipe_info_t *pcap_info = &pcap_src->cap_pipe_info.pcap;
2281 
2282 #ifdef LOG_CAPTURE_VERBOSE
2283     ws_debug("pcap_pipe_dispatch");
2284 #endif
2285 
2286     switch (pcap_src->cap_pipe_state) {
2287 
2288     case STATE_EXPECT_REC_HDR:
2289 #ifdef _WIN32
2290         if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2291 #endif
2292 
2293             pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2294             pcap_src->cap_pipe_bytes_to_read = pcap_src->cap_pipe_modified ?
2295                 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2296             pcap_src->cap_pipe_bytes_read = 0;
2297 
2298 #ifdef _WIN32
2299             pcap_src->cap_pipe_buf = (char *) &pcap_info->rechdr;
2300             g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2301             g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2302         }
2303 #endif
2304         /* Fall through */
2305 
2306     case STATE_READ_REC_HDR:
2307 #ifdef _WIN32
2308         if (pcap_src->from_cap_socket)
2309 #endif
2310         {
2311             b = cap_pipe_read(pcap_src->cap_pipe_fd, ((char *)&pcap_info->rechdr)+pcap_src->cap_pipe_bytes_read,
2312                  pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read, pcap_src->from_cap_socket);
2313             if (b <= 0) {
2314                 if (b == 0)
2315                     result = PD_PIPE_EOF;
2316                 else
2317                     result = PD_PIPE_ERR;
2318                 break;
2319             }
2320             pcap_src->cap_pipe_bytes_read += b;
2321         }
2322 #ifdef _WIN32
2323         else {
2324             q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2325             if (pcap_src->cap_pipe_err == PIPEOF) {
2326                 result = PD_PIPE_EOF;
2327                 break;
2328             } else if (pcap_src->cap_pipe_err == PIPERR) {
2329                 result = PD_PIPE_ERR;
2330                 break;
2331             }
2332             if (!q_status) {
2333                 return 0;
2334             }
2335         }
2336 #endif
2337         if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2338             /* There's still more of the pcap packet header to read. */
2339             return 0;
2340         }
2341         result = PD_REC_HDR_READ;
2342         break;
2343 
2344     case STATE_EXPECT_DATA:
2345 #ifdef _WIN32
2346         if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2347 #endif
2348 
2349             pcap_src->cap_pipe_state = STATE_READ_DATA;
2350             pcap_src->cap_pipe_bytes_to_read = pcap_info->rechdr.hdr.incl_len;
2351             pcap_src->cap_pipe_bytes_read = 0;
2352 
2353 #ifdef _WIN32
2354             pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2355             g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2356             g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2357         }
2358 #endif
2359         /* Fall through */
2360 
2361     case STATE_READ_DATA:
2362 #ifdef _WIN32
2363         if (pcap_src->from_cap_socket)
2364 #endif
2365         {
2366             b = cap_pipe_read(pcap_src->cap_pipe_fd,
2367                               pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read,
2368                               pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read,
2369                               pcap_src->from_cap_socket);
2370             if (b <= 0) {
2371                 if (b == 0)
2372                     result = PD_PIPE_EOF;
2373                 else
2374                     result = PD_PIPE_ERR;
2375                 break;
2376             }
2377             pcap_src->cap_pipe_bytes_read += b;
2378         }
2379 #ifdef _WIN32
2380         else {
2381 
2382             q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2383             if (pcap_src->cap_pipe_err == PIPEOF) {
2384                 result = PD_PIPE_EOF;
2385                 break;
2386             } else if (pcap_src->cap_pipe_err == PIPERR) {
2387                 result = PD_PIPE_ERR;
2388                 break;
2389             }
2390             if (!q_status) {
2391                 return 0;
2392             }
2393         }
2394 #endif /* _WIN32 */
2395         if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2396             /* There's still more of the pcap packet data to read. */
2397             return 0;
2398         }
2399         result = PD_DATA_READ;
2400         break;
2401 
2402     default:
2403         g_snprintf(errmsg, (gulong)errmsgl,
2404                    "pcap_pipe_dispatch: invalid state");
2405         result = PD_ERR;
2406 
2407     } /* switch (pcap_src->cap_pipe_state) */
2408 
2409     /*
2410      * We've now read as much data as we were expecting, so process it.
2411      */
2412     switch (result) {
2413 
2414     case PD_REC_HDR_READ:
2415         /*
2416          * We've read the packet header, so we know the captured length,
2417          * and thus the number of packet data bytes. Take care of byte order.
2418          */
2419         cap_pipe_adjust_pcap_header(pcap_src->cap_pipe_info.pcap.byte_swapped, &pcap_info->hdr,
2420                                &pcap_info->rechdr.hdr);
2421         if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_max_pkt_size) {
2422             /*
2423              * The record contains more data than the advertised/allowed in the
2424              * pcap header, do not try to read more data (do not change to
2425              * STATE_EXPECT_DATA) as that would not fit in the buffer and
2426              * instead stop with an error.
2427              */
2428             g_snprintf(errmsg, (gulong)errmsgl, "Frame %u too long (%d bytes)",
2429                        ld->packets_captured+1, pcap_info->rechdr.hdr.incl_len);
2430             break;
2431         }
2432 
2433         if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_databuf_size) {
2434             /*
2435              * Grow the buffer to the packet size, rounded up to a power of
2436              * 2.
2437              */
2438             new_bufsize = pcap_info->rechdr.hdr.incl_len;
2439             /*
2440              * https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2441              */
2442             new_bufsize--;
2443             new_bufsize |= new_bufsize >> 1;
2444             new_bufsize |= new_bufsize >> 2;
2445             new_bufsize |= new_bufsize >> 4;
2446             new_bufsize |= new_bufsize >> 8;
2447             new_bufsize |= new_bufsize >> 16;
2448             new_bufsize++;
2449             pcap_src->cap_pipe_databuf = (char*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2450             pcap_src->cap_pipe_databuf_size = new_bufsize;
2451         }
2452 
2453         if (pcap_info->rechdr.hdr.incl_len) {
2454             /*
2455              * The record has some data following the header, try
2456              * to read it next time.
2457              */
2458             pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2459             return 0;
2460         }
2461 
2462         /*
2463          * No data following the record header? Then no more data needs to be
2464          * read and we will fallthrough and emit an empty packet.
2465          */
2466         /* FALLTHROUGH */
2467 
2468     case PD_DATA_READ:
2469         /*
2470          * We've read the full contents of the packet record.
2471          * Fill in a "struct pcap_pkthdr", and process the packet.
2472          */
2473         phdr.ts.tv_sec = pcap_info->rechdr.hdr.ts_sec;
2474         phdr.ts.tv_usec = pcap_info->rechdr.hdr.ts_usec;
2475         phdr.caplen = pcap_info->rechdr.hdr.incl_len;
2476         phdr.len = pcap_info->rechdr.hdr.orig_len;
2477 
2478         if (use_threads) {
2479             capture_loop_queue_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2480         } else {
2481             capture_loop_write_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2482         }
2483 
2484         /*
2485          * Now we want to read the next packet's header.
2486          */
2487         pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2488         return 1;
2489 
2490     case PD_PIPE_EOF:
2491         pcap_src->cap_pipe_err = PIPEOF;
2492         return -1;
2493 
2494     case PD_PIPE_ERR:
2495         g_snprintf(errmsg, (gulong)errmsgl, "Error reading from pipe: %s",
2496 #ifdef _WIN32
2497                    win32strerror(GetLastError()));
2498 #else
2499                    g_strerror(errno));
2500 #endif
2501         /* Fall through */
2502     case PD_ERR:
2503         break;
2504     }
2505 
2506     pcap_src->cap_pipe_err = PIPERR;
2507     /* Return here rather than inside the switch to prevent GCC warning */
2508     return -1;
2509 }
2510 
2511 static int
pcapng_pipe_dispatch(loop_data * ld,capture_src * pcap_src,char * errmsg,size_t errmsgl)2512 pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, size_t errmsgl)
2513 {
2514     enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2515            PD_ERR } result;
2516 #ifdef _WIN32
2517     gpointer  q_status;
2518 #endif
2519     guint new_bufsize;
2520     pcapng_block_header_t *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2521 
2522 #ifdef LOG_CAPTURE_VERBOSE
2523     ws_debug("pcapng_pipe_dispatch");
2524 #endif
2525 
2526     switch (pcap_src->cap_pipe_state) {
2527 
2528     case STATE_EXPECT_REC_HDR:
2529 #ifdef LOG_CAPTURE_VERBOSE
2530         ws_debug("pcapng_pipe_dispatch STATE_EXPECT_REC_HDR");
2531 #endif
2532 #ifdef _WIN32
2533         if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2534 #endif
2535 
2536             pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2537             pcap_src->cap_pipe_bytes_to_read = sizeof(pcapng_block_header_t);
2538             pcap_src->cap_pipe_bytes_read = 0;
2539 
2540 #ifdef _WIN32
2541             if (!pcap_src->from_cap_socket) {
2542                 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2543                 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2544             }
2545             g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2546         }
2547 #endif
2548         /* Fall through */
2549 
2550     case STATE_READ_REC_HDR:
2551 #ifdef LOG_CAPTURE_VERBOSE
2552         ws_debug("pcapng_pipe_dispatch STATE_READ_REC_HDR");
2553 #endif
2554 #ifdef _WIN32
2555         if (pcap_src->from_cap_socket) {
2556 #endif
2557             if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2558                 return -1;
2559             }
2560 #ifdef _WIN32
2561         } else {
2562             q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2563             if (pcap_src->cap_pipe_err == PIPEOF) {
2564                 result = PD_PIPE_EOF;
2565                 break;
2566             } else if (pcap_src->cap_pipe_err == PIPERR) {
2567                 result = PD_PIPE_ERR;
2568                 break;
2569             }
2570             if (!q_status) {
2571                 return 0;
2572             }
2573         }
2574 #endif
2575         if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2576             /* There's still more of the pcapng block header to read. */
2577             return 0;
2578         }
2579         memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(pcapng_block_header_t));
2580         result = PD_REC_HDR_READ;
2581         break;
2582 
2583     case STATE_EXPECT_DATA:
2584 #ifdef LOG_CAPTURE_VERBOSE
2585         ws_debug("pcapng_pipe_dispatch STATE_EXPECT_DATA");
2586 #endif
2587 #ifdef _WIN32
2588         if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2589 #endif
2590             pcap_src->cap_pipe_state = STATE_READ_DATA;
2591             pcap_src->cap_pipe_bytes_to_read = bh->block_total_length;
2592 
2593 #ifdef _WIN32
2594             if (!pcap_src->from_cap_socket) {
2595                 pcap_src->cap_pipe_bytes_to_read -= pcap_src->cap_pipe_bytes_read;
2596                 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf + pcap_src->cap_pipe_bytes_read;
2597                 pcap_src->cap_pipe_bytes_read = 0;
2598                 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2599             }
2600             g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2601         }
2602 #endif
2603         /* Fall through */
2604 
2605     case STATE_READ_DATA:
2606 #ifdef LOG_CAPTURE_VERBOSE
2607         ws_debug("pcapng_pipe_dispatch STATE_READ_DATA");
2608 #endif
2609 #ifdef _WIN32
2610         if (pcap_src->from_cap_socket) {
2611 #endif
2612             if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2613                 return -1;
2614             }
2615 #ifdef _WIN32
2616         } else {
2617 
2618             q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2619             if (pcap_src->cap_pipe_err == PIPEOF) {
2620                 result = PD_PIPE_EOF;
2621                 break;
2622             } else if (pcap_src->cap_pipe_err == PIPERR) {
2623                 result = PD_PIPE_ERR;
2624                 break;
2625             }
2626             if (!q_status) {
2627                 return 0;
2628             }
2629         }
2630 #endif /* _WIN32 */
2631         if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2632             /* There's still more of the pcap block contents to read. */
2633             return 0;
2634         }
2635         result = PD_DATA_READ;
2636         break;
2637 
2638     default:
2639         g_snprintf(errmsg, (gulong)errmsgl,
2640                    "pcapng_pipe_dispatch: invalid state");
2641         result = PD_ERR;
2642 
2643     } /* switch (pcap_src->cap_pipe_state) */
2644 
2645     /*
2646      * We've now read as much data as we were expecting, so process it.
2647      */
2648     switch (result) {
2649 
2650     case PD_REC_HDR_READ:
2651         /*
2652          * We've read the pcapng block header, so we know the block type
2653          * and length.
2654          */
2655         if (bh->block_type == BLOCK_TYPE_SHB) {
2656             /*
2657              * We need to read the fixed portion of the SHB before to
2658              * get the endianness before we can interpret the block length.
2659              * (The block type of the SHB is byte-order-independent, so that
2660              * an SHB can be recognized before we know the endianness of
2661              * the section.)
2662              *
2663              * Continue the read process.
2664              */
2665             pcapng_read_shb(pcap_src, errmsg, errmsgl);
2666             return 1;
2667         }
2668 
2669         if ((bh->block_total_length & 0x03) != 0) {
2670             g_snprintf(errmsg, (gulong)errmsgl,
2671                        "Total length of pcapng block read from pipe is %u, which is not a multiple of 4.",
2672                        bh->block_total_length);
2673             break;
2674         }
2675         if (bh->block_total_length > pcap_src->cap_pipe_max_pkt_size) {
2676             /*
2677             * The record contains more data than the advertised/allowed in the
2678             * pcapng header, do not try to read more data (do not change to
2679             * STATE_EXPECT_DATA) as that would not fit in the buffer and
2680             * instead stop with an error.
2681             */
2682             g_snprintf(errmsg, (gulong)errmsgl, "Frame %u too long (%d bytes)",
2683                     ld->packets_captured+1, bh->block_total_length);
2684             break;
2685         }
2686 
2687         if (bh->block_total_length > pcap_src->cap_pipe_databuf_size) {
2688             /*
2689             * Grow the buffer to the packet size, rounded up to a power of
2690             * 2.
2691             */
2692             new_bufsize = bh->block_total_length;
2693             /*
2694             * https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2695             */
2696             new_bufsize--;
2697             new_bufsize |= new_bufsize >> 1;
2698             new_bufsize |= new_bufsize >> 2;
2699             new_bufsize |= new_bufsize >> 4;
2700             new_bufsize |= new_bufsize >> 8;
2701             new_bufsize |= new_bufsize >> 16;
2702             new_bufsize++;
2703             pcap_src->cap_pipe_databuf = (guchar*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2704             pcap_src->cap_pipe_databuf_size = new_bufsize;
2705         }
2706 
2707         /* The record always has at least the block total length following the header */
2708         if (bh->block_total_length < sizeof(pcapng_block_header_t)+sizeof(guint32)) {
2709             g_snprintf(errmsg, (gulong)errmsgl,
2710                        "malformed pcapng block_total_length < minimum");
2711             pcap_src->cap_pipe_err = PIPEOF;
2712             return -1;
2713         }
2714 
2715         /*
2716          * Now we want to read the block contents.
2717          */
2718         pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2719         return 0;
2720 
2721     case PD_DATA_READ:
2722         /*
2723          * We've read the full contents of the block.
2724          * Process the block.
2725          */
2726         if (use_threads) {
2727             capture_loop_queue_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
2728         } else {
2729             capture_loop_write_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
2730         }
2731 
2732         /*
2733          * Now we want to read the next block's header.
2734          */
2735         pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2736         return 1;
2737 
2738     case PD_PIPE_EOF:
2739         pcap_src->cap_pipe_err = PIPEOF;
2740         return -1;
2741 
2742     case PD_PIPE_ERR:
2743         g_snprintf(errmsg, (gulong)errmsgl, "Error reading from pipe: %s",
2744 #ifdef _WIN32
2745                    win32strerror(GetLastError()));
2746 #else
2747                    g_strerror(errno));
2748 #endif
2749         /* Fall through */
2750     case PD_ERR:
2751         break;
2752     }
2753 
2754     pcap_src->cap_pipe_err = PIPERR;
2755     /* Return here rather than inside the switch to prevent GCC warning */
2756     return -1;
2757 }
2758 
2759 /** Open the capture input sources; each one is either a pcap device,
2760  *  a capture pipe, or a capture socket.
2761  *  Returns TRUE if it succeeds, FALSE otherwise. */
2762 static gboolean
capture_loop_open_input(capture_options * capture_opts,loop_data * ld,char * errmsg,size_t errmsg_len,char * secondary_errmsg,size_t secondary_errmsg_len)2763 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2764                         char *errmsg, size_t errmsg_len,
2765                         char *secondary_errmsg, size_t secondary_errmsg_len)
2766 {
2767     cap_device_open_status open_status;
2768     gchar               open_status_str[PCAP_ERRBUF_SIZE];
2769     gchar              *sync_msg_str;
2770     interface_options  *interface_opts;
2771     capture_src        *pcap_src;
2772     guint               i;
2773 
2774     if ((use_threads == FALSE) &&
2775         (capture_opts->ifaces->len > 1)) {
2776         g_snprintf(errmsg, (gulong) errmsg_len,
2777                    "Using threads is required for capturing on multiple interfaces.");
2778         return FALSE;
2779     }
2780 
2781     int pcapng_src_count = 0;
2782     for (i = 0; i < capture_opts->ifaces->len; i++) {
2783         interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
2784         pcap_src = g_new0(capture_src, 1);
2785         if (pcap_src == NULL) {
2786             g_snprintf(errmsg, (gulong) errmsg_len,
2787                    "Could not allocate memory.");
2788             return FALSE;
2789         }
2790 
2791         /*
2792          * Add our pcapng interface entry. This will be deleted further
2793          * down if pcapng_passthrough == TRUE.
2794          */
2795         saved_idb_t idb_source = { 0 };
2796         idb_source.interface_id = i;
2797         g_rw_lock_writer_lock (&ld->saved_shb_idb_lock);
2798         g_array_append_val(global_ld.saved_idbs, idb_source);
2799         g_rw_lock_writer_unlock (&ld->saved_shb_idb_lock);
2800         ws_debug("%s: saved capture_opts IDB %u",
2801               G_STRFUNC, i);
2802 
2803 #ifdef MUST_DO_SELECT
2804         pcap_src->pcap_fd = -1;
2805 #endif
2806         pcap_src->interface_id = i;
2807         pcap_src->linktype = -1;
2808 #ifdef _WIN32
2809         pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2810 #endif
2811         pcap_src->cap_pipe_fd = -1;
2812         pcap_src->cap_pipe_dispatch = pcap_pipe_dispatch;
2813         pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2814         pcap_src->cap_pipe_err = PIPOK;
2815 #ifdef _WIN32
2816         pcap_src->cap_pipe_read_mtx = g_new(GMutex, 1);
2817         g_mutex_init(pcap_src->cap_pipe_read_mtx);
2818         pcap_src->cap_pipe_pending_q = g_async_queue_new();
2819         pcap_src->cap_pipe_done_q = g_async_queue_new();
2820 #endif
2821         g_array_append_val(ld->pcaps, pcap_src);
2822 
2823         ws_debug("capture_loop_open_input : %s", interface_opts->name);
2824         pcap_src->pcap_h = open_capture_device(capture_opts, interface_opts,
2825             CAP_READ_TIMEOUT, &open_status, &open_status_str);
2826 
2827         if (pcap_src->pcap_h != NULL) {
2828             /* we've opened "iface" as a network device */
2829 
2830 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2831             /* Find out if we're getting nanosecond-precision time stamps */
2832             pcap_src->ts_nsec = have_high_resolution_timestamp(pcap_src->pcap_h);
2833 #endif
2834 
2835 #if defined(HAVE_PCAP_SETSAMPLING)
2836             if (interface_opts->sampling_method != CAPTURE_SAMP_NONE) {
2837                 struct pcap_samp *samp;
2838 
2839                 if ((samp = pcap_setsampling(pcap_src->pcap_h)) != NULL) {
2840                     switch (interface_opts->sampling_method) {
2841                     case CAPTURE_SAMP_BY_COUNT:
2842                         samp->method = PCAP_SAMP_1_EVERY_N;
2843                         break;
2844 
2845                     case CAPTURE_SAMP_BY_TIMER:
2846                         samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2847                         break;
2848 
2849                     default:
2850                         sync_msg_str = g_strdup_printf(
2851                             "Unknown sampling method %d specified,\n"
2852                             "continue without packet sampling",
2853                             interface_opts->sampling_method);
2854                         report_capture_error("Couldn't set the capture "
2855                                              "sampling", sync_msg_str);
2856                         g_free(sync_msg_str);
2857                     }
2858                     samp->value = interface_opts->sampling_param;
2859                 } else {
2860                     report_capture_error("Couldn't set the capture sampling",
2861                                          "Cannot get packet sampling data structure");
2862                 }
2863             }
2864 #endif
2865 
2866             /* setting the data link type only works on real interfaces */
2867             if (!set_pcap_datalink(pcap_src->pcap_h, interface_opts->linktype,
2868                                    interface_opts->name,
2869                                    errmsg, errmsg_len,
2870                                    secondary_errmsg, secondary_errmsg_len)) {
2871                 return FALSE;
2872             }
2873             pcap_src->linktype = get_pcap_datalink(pcap_src->pcap_h, interface_opts->name);
2874         } else {
2875             /* We couldn't open "iface" as a network device. */
2876             /* Try to open it as a pipe */
2877             gboolean pipe_err = FALSE;
2878             cap_pipe_open_live(interface_opts->name, pcap_src,
2879                                &pcap_src->cap_pipe_info.pcap.hdr,
2880                                errmsg, errmsg_len,
2881                                secondary_errmsg, secondary_errmsg_len);
2882 
2883 #ifdef _WIN32
2884             if (pcap_src->from_cap_socket) {
2885 #endif
2886                 if (pcap_src->cap_pipe_fd == -1) {
2887                     pipe_err = TRUE;
2888                 }
2889 #ifdef _WIN32
2890             } else {
2891                 if (pcap_src->cap_pipe_h == INVALID_HANDLE_VALUE) {
2892                     pipe_err = TRUE;
2893                 }
2894             }
2895 #endif
2896 
2897             if (pipe_err) {
2898                 if (pcap_src->cap_pipe_err == PIPNEXIST) {
2899                     /*
2900                      * We tried opening as an interface, and that failed,
2901                      * so we tried to open it as a pipe, but the pipe
2902                      * doesn't exist.  Report the error message for
2903                      * the interface.
2904                      */
2905                     get_capture_device_open_failure_messages(open_status,
2906                                                              open_status_str,
2907                                                              interface_opts->name,
2908                                                              errmsg,
2909                                                              errmsg_len,
2910                                                              secondary_errmsg,
2911                                                              secondary_errmsg_len);
2912                 }
2913                 /*
2914                  * Else pipe (or file) does exist and cap_pipe_open_live() has
2915                  * filled in errmsg
2916                  */
2917                 return FALSE;
2918             } else {
2919                 /*
2920                  * We tried opening as an interface, and that failed,
2921                  * so we tried to open it as a pipe, and that succeeded.
2922                  */
2923                 open_status = CAP_DEVICE_OPEN_NO_ERR;
2924             }
2925         }
2926 
2927 /* XXX - will this work for tshark? */
2928 #ifdef MUST_DO_SELECT
2929         if (!pcap_src->from_cap_pipe) {
2930             pcap_src->pcap_fd = pcap_get_selectable_fd(pcap_src->pcap_h);
2931         }
2932 #endif
2933 
2934         /* Is "open_status" something other than CAP_DEVICE_OPEN_NO_ERR?
2935            If so, "open_capture_device()" returned a warning; print it,
2936            but keep capturing. */
2937         if (open_status != CAP_DEVICE_OPEN_NO_ERR) {
2938             sync_msg_str = g_strdup_printf("%s.", open_status_str);
2939             report_capture_error(sync_msg_str, "");
2940             g_free(sync_msg_str);
2941         }
2942         if (pcap_src->from_pcapng) {
2943             pcapng_src_count++;
2944         }
2945     }
2946 
2947     /*
2948      * Are we capturing from one source that is providing pcapng
2949      * information?
2950      */
2951     if (capture_opts->ifaces->len == 1 && pcapng_src_count == 1) {
2952         /*
2953          * Yes; pass through SHBs and IDBs from the source, rather
2954          * than generating our own.
2955          */
2956         ld->pcapng_passthrough = TRUE;
2957         g_rw_lock_writer_lock (&ld->saved_shb_idb_lock);
2958         ws_debug("%s: Clearing %u interfaces for passthrough",
2959               G_STRFUNC, global_ld.saved_idbs->len);
2960         g_array_set_size(global_ld.saved_idbs, 0);
2961         g_rw_lock_writer_unlock (&ld->saved_shb_idb_lock);
2962     }
2963 
2964     /* If not using libcap: we now can now set euid/egid to ruid/rgid         */
2965     /*  to remove any suid privileges.                                        */
2966     /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities  */
2967     /*  (euid/egid have already previously been set to ruid/rgid.             */
2968     /* (See comment in main() for details)                                    */
2969 #ifndef HAVE_LIBCAP
2970     relinquish_special_privs_perm();
2971 #else
2972     relinquish_all_capabilities();
2973 #endif
2974     return TRUE;
2975 }
2976 
2977 /* close the capture input file (pcap or capture pipe) */
capture_loop_close_input(loop_data * ld)2978 static void capture_loop_close_input(loop_data *ld)
2979 {
2980     guint        i;
2981     capture_src *pcap_src;
2982 
2983     ws_debug("capture_loop_close_input");
2984 
2985     for (i = 0; i < ld->pcaps->len; i++) {
2986         pcap_src = g_array_index(ld->pcaps, capture_src *, i);
2987         /* Pipe, or capture device? */
2988         if (pcap_src->from_cap_pipe) {
2989             /* Pipe. If open, close the capture pipe "input file". */
2990             if (pcap_src->cap_pipe_fd >= 0) {
2991                 cap_pipe_close(pcap_src->cap_pipe_fd, pcap_src->from_cap_socket);
2992                 pcap_src->cap_pipe_fd = -1;
2993             }
2994 #ifdef _WIN32
2995             if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE) {
2996                 CloseHandle(pcap_src->cap_pipe_h);
2997                 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2998             }
2999 #endif
3000             if (pcap_src->cap_pipe_databuf != NULL) {
3001                 /* Free the buffer. */
3002                 g_free(pcap_src->cap_pipe_databuf);
3003                 pcap_src->cap_pipe_databuf = NULL;
3004             }
3005             if (pcap_src->from_pcapng) {
3006                 g_array_free(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, TRUE);
3007                 pcap_src->cap_pipe_info.pcapng.src_iface_to_global = NULL;
3008             }
3009         } else {
3010             /* Capture device.  If open, close the pcap_t. */
3011             if (pcap_src->pcap_h != NULL) {
3012                 ws_debug("capture_loop_close_input: closing %p", (void *)pcap_src->pcap_h);
3013                 pcap_close(pcap_src->pcap_h);
3014                 pcap_src->pcap_h = NULL;
3015             }
3016         }
3017     }
3018 
3019     ld->go = FALSE;
3020 }
3021 
3022 
3023 /* init the capture filter */
3024 static initfilter_status_t
capture_loop_init_filter(pcap_t * pcap_h,gboolean from_cap_pipe,const gchar * name,const gchar * cfilter)3025 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
3026                          const gchar * name, const gchar * cfilter)
3027 {
3028     struct bpf_program fcode;
3029 
3030     ws_debug("capture_loop_init_filter: %s", cfilter);
3031 
3032     /* capture filters only work on real interfaces */
3033     if (cfilter && !from_cap_pipe) {
3034         /* A capture filter was specified; set it up. */
3035         if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
3036             /* Treat this specially - our caller might try to compile this
3037                as a display filter and, if that succeeds, warn the user that
3038                the display and capture filter syntaxes are different. */
3039             return INITFILTER_BAD_FILTER;
3040         }
3041         if (pcap_setfilter(pcap_h, &fcode) < 0) {
3042 #ifdef HAVE_PCAP_FREECODE
3043             pcap_freecode(&fcode);
3044 #endif
3045             return INITFILTER_OTHER_ERROR;
3046         }
3047 #ifdef HAVE_PCAP_FREECODE
3048         pcap_freecode(&fcode);
3049 #endif
3050     }
3051 
3052     return INITFILTER_NO_ERROR;
3053 }
3054 
3055 /*
3056  * Write the dumpcap pcapng SHB and IDBs if needed.
3057  * Called from capture_loop_init_output and do_file_switch_or_stop.
3058  */
3059 static gboolean
capture_loop_init_pcapng_output(capture_options * capture_opts,loop_data * ld,int * err)3060 capture_loop_init_pcapng_output(capture_options *capture_opts, loop_data *ld,
3061                                 int *err)
3062 {
3063     g_rw_lock_reader_lock (&ld->saved_shb_idb_lock);
3064 
3065     if (ld->pcapng_passthrough && !ld->saved_shb) {
3066         /* We have a single pcapng capture interface and this is the first or only output file. */
3067         ws_debug("%s: skipping dumpcap SHB and IDBs in favor of source", G_STRFUNC);
3068         g_rw_lock_reader_unlock (&ld->saved_shb_idb_lock);
3069         return TRUE;
3070     }
3071 
3072     gboolean successful = TRUE;
3073     GString *os_info_str = g_string_new("");
3074 
3075     *err = 0;
3076     get_os_version_info(os_info_str);
3077 
3078     if (ld->saved_shb) {
3079         /* We have a single pcapng capture interface and multiple output files. */
3080 
3081         pcapng_block_header_t bh;
3082 
3083         memcpy(&bh, ld->saved_shb, sizeof(pcapng_block_header_t));
3084 
3085         successful = pcapng_write_block(ld->pdh, ld->saved_shb, bh.block_total_length, &ld->bytes_written, err);
3086 
3087         ws_debug("%s: wrote saved passthrough SHB %d", G_STRFUNC, successful);
3088     } else {
3089         GString *cpu_info_str = g_string_new("");
3090         get_cpu_info(cpu_info_str);
3091 
3092         successful = pcapng_write_section_header_block(ld->pdh,
3093                                                        capture_comments,   /* Comments */
3094                                                        cpu_info_str->str,           /* HW */
3095                                                        os_info_str->str,            /* OS */
3096                                                        get_appname_and_version(),
3097                                                        -1,                          /* section_length */
3098                                                        &ld->bytes_written,
3099                                                        err);
3100         ws_debug("%s: wrote dumpcap SHB %d", G_STRFUNC, successful);
3101         g_string_free(cpu_info_str, TRUE);
3102     }
3103 
3104     for (unsigned i = 0; successful && (i < ld->saved_idbs->len); i++) {
3105         saved_idb_t idb_source = g_array_index(ld->saved_idbs, saved_idb_t, i);
3106         if (idb_source.deleted) {
3107             /*
3108              * Our interface is out of scope. Suppose we're writing multiple
3109              * files and a source switches sections. We currently write dummy
3110              * IDBs like so:
3111              *
3112              * File 1: IDB0, IDB1, IDB2
3113              * [ The source of IDBs 1 and 2 writes an SHB with two new IDBs ]
3114              * [ We switch output files ]
3115              * File 2: IDB0, dummy IDB, dummy IDB, IDB3, IDB4
3116              *
3117              * It might make more sense to write the original data so that
3118              * so that our IDB lists are more consistent across files.
3119              */
3120             successful = pcapng_write_interface_description_block(global_ld.pdh,
3121                                                                   "Interface went out of scope",    /* OPT_COMMENT       1 */
3122                                                                   "dummy",                          /* IDB_NAME          2 */
3123                                                                   "Dumpcap dummy interface",        /* IDB_DESCRIPTION   3 */
3124                                                                   NULL,                             /* IDB_FILTER       11 */
3125                                                                   os_info_str->str,                 /* IDB_OS           12 */
3126                                                                   NULL,                             /* IDB_HARDWARE     15 */
3127                                                                   -1,
3128                                                                   0,
3129                                                                   &(global_ld.bytes_written),
3130                                                                   0,                                /* IDB_IF_SPEED      8 */
3131                                                                   6,                                /* IDB_TSRESOL       9 */
3132                                                                   &global_ld.err);
3133             ws_debug("%s: skipping deleted pcapng IDB %u", G_STRFUNC, i);
3134         } else if (idb_source.idb && idb_source.idb_len) {
3135             successful = pcapng_write_block(global_ld.pdh, idb_source.idb, idb_source.idb_len, &ld->bytes_written, err);
3136             ws_debug("%s: wrote pcapng IDB %d", G_STRFUNC, successful);
3137         } else if (idb_source.interface_id < capture_opts->ifaces->len) {
3138             unsigned if_id = idb_source.interface_id;
3139             interface_options *interface_opts = &g_array_index(capture_opts->ifaces, interface_options, if_id);
3140             capture_src *pcap_src = g_array_index(ld->pcaps, capture_src *, if_id);
3141             if (pcap_src->from_cap_pipe) {
3142                 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
3143             } else {
3144                 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
3145             }
3146             successful = pcapng_write_interface_description_block(global_ld.pdh,
3147                                                                    NULL,                       /* OPT_COMMENT       1 */
3148                                                                   (interface_opts->ifname != NULL) ? interface_opts->ifname : interface_opts->name, /* IDB_NAME          2 */
3149                                                                   interface_opts->descr,      /* IDB_DESCRIPTION   3 */
3150                                                                   interface_opts->cfilter,    /* IDB_FILTER       11 */
3151                                                                   os_info_str->str,           /* IDB_OS           12 */
3152                                                                   interface_opts->hardware,   /* IDB_HARDWARE     15 */
3153                                                                   pcap_src->linktype,
3154                                                                   pcap_src->snaplen,
3155                                                                   &(global_ld.bytes_written),
3156                                                                   0,                          /* IDB_IF_SPEED      8 */
3157                                                                   pcap_src->ts_nsec ? 9 : 6,  /* IDB_TSRESOL       9 */
3158                                                                   &global_ld.err);
3159             ws_debug("%s: wrote capture_opts IDB %d: %d", G_STRFUNC, if_id, successful);
3160         }
3161     }
3162     g_rw_lock_reader_unlock (&ld->saved_shb_idb_lock);
3163 
3164     g_string_free(os_info_str, TRUE);
3165 
3166     return successful;
3167 }
3168 
3169 /* set up to write to the already-opened capture output file/files */
3170 static gboolean
capture_loop_init_output(capture_options * capture_opts,loop_data * ld,char * errmsg,int errmsg_len)3171 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
3172 {
3173     int err = 0;
3174 
3175     ws_debug("capture_loop_init_output");
3176 
3177     if ((capture_opts->use_pcapng == FALSE) &&
3178         (capture_opts->ifaces->len > 1)) {
3179         g_snprintf(errmsg, errmsg_len,
3180                    "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
3181         return FALSE;
3182     }
3183 
3184     /* Set up to write to the capture file. */
3185     if (capture_opts->multi_files_on) {
3186         ld->pdh = ringbuf_init_libpcap_fdopen(&err);
3187     } else {
3188         ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
3189         if (ld->pdh == NULL) {
3190             err = errno;
3191         } else {
3192             size_t buffsize = IO_BUF_SIZE;
3193 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
3194             ws_statb64 statb;
3195 
3196             if (ws_fstat64(ld->save_file_fd, &statb) == 0) {
3197                 if (statb.st_blksize > IO_BUF_SIZE) {
3198                     buffsize = statb.st_blksize;
3199                 }
3200             }
3201 #endif
3202             /* Increase the size of the IO buffer */
3203             ld->io_buffer = (char *)g_malloc(buffsize);
3204             setvbuf(ld->pdh, ld->io_buffer, _IOFBF, buffsize);
3205             ws_debug("capture_loop_init_output: buffsize %zu", buffsize);
3206         }
3207     }
3208     if (ld->pdh) {
3209         gboolean successful;
3210         if (capture_opts->use_pcapng) {
3211             successful = capture_loop_init_pcapng_output(capture_opts, ld, &err);
3212         } else {
3213             capture_src *pcap_src;
3214             pcap_src = g_array_index(ld->pcaps, capture_src *, 0);
3215             if (pcap_src->from_cap_pipe) {
3216                 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
3217             } else {
3218                 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
3219             }
3220             successful = libpcap_write_file_header(ld->pdh, pcap_src->linktype, pcap_src->snaplen,
3221                                                 pcap_src->ts_nsec, &ld->bytes_written, &err);
3222         }
3223         if (!successful) {
3224             fclose(ld->pdh);
3225             ld->pdh = NULL;
3226             g_free(ld->io_buffer);
3227             ld->io_buffer = NULL;
3228         }
3229     }
3230 
3231     if (ld->pdh == NULL) {
3232         /* We couldn't set up to write to the capture file. */
3233         /* XXX - use cf_open_error_message from tshark instead? */
3234         if (err < 0) {
3235             g_snprintf(errmsg, errmsg_len,
3236                        "The file to which the capture would be"
3237                        " saved (\"%s\") could not be opened: Error %d.",
3238                        capture_opts->save_file, err);
3239         } else {
3240             g_snprintf(errmsg, errmsg_len,
3241                        "The file to which the capture would be"
3242                        " saved (\"%s\") could not be opened: %s.",
3243                        capture_opts->save_file, g_strerror(err));
3244         }
3245         return FALSE;
3246     }
3247 
3248     return TRUE;
3249 }
3250 
3251 static gboolean
capture_loop_close_output(capture_options * capture_opts,loop_data * ld,int * err_close)3252 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
3253 {
3254 
3255     unsigned int i;
3256     capture_src *pcap_src;
3257     guint64      end_time = create_timestamp();
3258     gboolean success;
3259 
3260     ws_debug("capture_loop_close_output");
3261 
3262     if (capture_opts->multi_files_on) {
3263         return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
3264     } else {
3265         if (capture_opts->use_pcapng) {
3266             for (i = 0; i < global_ld.pcaps->len; i++) {
3267                 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3268                 if (!pcap_src->from_cap_pipe) {
3269                     guint64 isb_ifrecv, isb_ifdrop;
3270                     struct pcap_stat stats;
3271 
3272                     if (pcap_stats(pcap_src->pcap_h, &stats) >= 0) {
3273                         isb_ifrecv = pcap_src->received;
3274                         isb_ifdrop = stats.ps_drop + pcap_src->dropped + pcap_src->flushed;
3275                    } else {
3276                         isb_ifrecv = G_MAXUINT64;
3277                         isb_ifdrop = G_MAXUINT64;
3278                     }
3279                     pcapng_write_interface_statistics_block(ld->pdh,
3280                                                             i,
3281                                                             &ld->bytes_written,
3282                                                             "Counters provided by dumpcap",
3283                                                             start_time,
3284                                                             end_time,
3285                                                             isb_ifrecv,
3286                                                             isb_ifdrop,
3287                                                             err_close);
3288                 }
3289             }
3290         }
3291         if (fclose(ld->pdh) == EOF) {
3292             if (err_close != NULL) {
3293                 *err_close = errno;
3294             }
3295             success = FALSE;
3296         } else {
3297             success = TRUE;
3298         }
3299         g_free(ld->io_buffer);
3300         ld->io_buffer = NULL;
3301         return success;
3302     }
3303 }
3304 
3305 /* dispatch incoming packets (pcap or capture pipe)
3306  *
3307  * Waits for incoming packets to be available, and calls pcap_dispatch()
3308  * to cause them to be processed.
3309  *
3310  * Returns the number of packets which were processed.
3311  *
3312  * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3313  * packet-batching behaviour does not cause packets to get held back
3314  * indefinitely.
3315  */
3316 static int
capture_loop_dispatch(loop_data * ld,char * errmsg,int errmsg_len,capture_src * pcap_src)3317 capture_loop_dispatch(loop_data *ld,
3318                       char *errmsg, int errmsg_len, capture_src *pcap_src)
3319 {
3320     int    inpkts = 0;
3321     gint   packet_count_before;
3322     int    sel_ret;
3323 
3324     packet_count_before = ld->packets_captured;
3325     if (pcap_src->from_cap_pipe) {
3326         /* dispatch from capture pipe */
3327 #ifdef LOG_CAPTURE_VERBOSE
3328         ws_debug("capture_loop_dispatch: from capture pipe");
3329 #endif
3330 #ifdef _WIN32
3331         if (pcap_src->from_cap_socket) {
3332 #endif
3333             sel_ret = cap_pipe_select(pcap_src->cap_pipe_fd);
3334             if (sel_ret <= 0) {
3335                 if (sel_ret < 0 && errno != EINTR) {
3336                     g_snprintf(errmsg, errmsg_len,
3337                             "Unexpected error from select: %s", g_strerror(errno));
3338                     report_capture_error(errmsg, please_report_bug());
3339                     ld->go = FALSE;
3340                 }
3341             }
3342 #ifdef _WIN32
3343         } else {
3344             /* Windows does not have select() for pipes. */
3345             /* Proceed with _dispatch() which waits for cap_pipe_done_q
3346              * notification from cap_thread_read() when ReadFile() on
3347              * the pipe has read enough bytes. */
3348             sel_ret = 1;
3349         }
3350 #endif
3351         if (sel_ret > 0) {
3352             /*
3353              * "select()" says we can read from the pipe without blocking
3354              */
3355             inpkts = pcap_src->cap_pipe_dispatch(ld, pcap_src, errmsg, errmsg_len);
3356             if (inpkts < 0) {
3357                 ws_debug("%s: src %u pipe reached EOF or err, rcv: %u drop: %u flush: %u",
3358                       G_STRFUNC, pcap_src->interface_id, pcap_src->received, pcap_src->dropped, pcap_src->flushed);
3359                 ws_assert(pcap_src->cap_pipe_err != PIPOK);
3360             }
3361         }
3362     }
3363     else
3364     {
3365         /* dispatch from pcap */
3366 #ifdef MUST_DO_SELECT
3367         /*
3368          * If we have "pcap_get_selectable_fd()", we use it to get the
3369          * descriptor on which to select; if that's -1, it means there
3370          * is no descriptor on which you can do a "select()" (perhaps
3371          * because you're capturing on a special device, and that device's
3372          * driver unfortunately doesn't support "select()", in which case
3373          * we don't do the select - which means it might not be possible
3374          * to stop a capture until a packet arrives.  If that's unacceptable,
3375          * plead with whoever supplies the software for that device to add
3376          * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3377          * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3378          * later, so it can use pcap_breakloop().
3379          */
3380 #ifdef LOG_CAPTURE_VERBOSE
3381         ws_debug("capture_loop_dispatch: from pcap_dispatch with select");
3382 #endif
3383         if (pcap_src->pcap_fd != -1) {
3384             sel_ret = cap_pipe_select(pcap_src->pcap_fd);
3385             if (sel_ret > 0) {
3386                 /*
3387                  * "select()" says we can read from it without blocking; go for
3388                  * it.
3389                  *
3390                  * We don't have pcap_breakloop(), so we only process one packet
3391                  * per pcap_dispatch() call, to allow a signal to stop the
3392                  * processing immediately, rather than processing all packets
3393                  * in a batch before quitting.
3394                  */
3395                 if (use_threads) {
3396                     inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3397                 } else {
3398                     inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3399                 }
3400                 if (inpkts < 0) {
3401                     if (inpkts == -1) {
3402                         /* Error, rather than pcap_breakloop(). */
3403                         pcap_src->pcap_err = TRUE;
3404                     }
3405                     ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3406                 }
3407             } else {
3408                 if (sel_ret < 0 && errno != EINTR) {
3409                     g_snprintf(errmsg, errmsg_len,
3410                                "Unexpected error from select: %s", g_strerror(errno));
3411                     report_capture_error(errmsg, please_report_bug());
3412                     ld->go = FALSE;
3413                 }
3414             }
3415         }
3416         else
3417 #endif /* MUST_DO_SELECT */
3418         {
3419             /* dispatch from pcap without select */
3420 #if 1
3421 #ifdef LOG_CAPTURE_VERBOSE
3422             ws_debug("capture_loop_dispatch: from pcap_dispatch");
3423 #endif
3424 #ifdef _WIN32
3425             /*
3426              * On Windows, we don't support asynchronously telling a process to
3427              * stop capturing; instead, we check for an indication on a pipe
3428              * after processing packets.  We therefore process only one packet
3429              * at a time, so that we can check the pipe after every packet.
3430              */
3431             if (use_threads) {
3432                 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3433             } else {
3434                 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3435             }
3436 #else
3437             if (use_threads) {
3438                 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3439             } else {
3440                 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3441             }
3442 #endif
3443             if (inpkts < 0) {
3444                 if (inpkts == -1) {
3445                     /* Error, rather than pcap_breakloop(). */
3446                     pcap_src->pcap_err = TRUE;
3447                 }
3448                 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3449             }
3450 #else /* pcap_next_ex */
3451 #ifdef LOG_CAPTURE_VERBOSE
3452             ws_debug("capture_loop_dispatch: from pcap_next_ex");
3453 #endif
3454             /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3455 
3456             /*
3457              * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3458              * see https://gitlab.com/wireshark/wireshark/-/wikis/CaptureSetup/WinPcapRemote
3459              * This should be fixed in the WinPcap 4.0 alpha release.
3460              *
3461              * For reference, an example remote interface:
3462              * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3463              */
3464 
3465             /* emulate dispatch from pcap */
3466             {
3467                 int in;
3468                 struct pcap_pkthdr *pkt_header;
3469                 u_char *pkt_data;
3470 
3471                 in = 0;
3472                 while(ld->go &&
3473                       (in = pcap_next_ex(pcap_src->pcap_h, &pkt_header, &pkt_data)) == 1) {
3474                     if (use_threads) {
3475                         capture_loop_queue_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
3476                     } else {
3477                         capture_loop_write_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
3478                     }
3479                 }
3480 
3481                 if (in < 0) {
3482                     pcap_src->pcap_err = TRUE;
3483                     ld->go = FALSE;
3484                 }
3485             }
3486 #endif /* pcap_next_ex */
3487         }
3488     }
3489 
3490 #ifdef LOG_CAPTURE_VERBOSE
3491     ws_debug("capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3492 #endif
3493 
3494     return ld->packets_captured - packet_count_before;
3495 }
3496 
3497 #ifdef _WIN32
3498 /* Isolate the Universally Unique Identifier from the interface.  Basically, we
3499  * want to grab only the characters between the '{' and '}' delimiters.
3500  *
3501  * Returns a GString that must be freed with g_string_free(). */
3502 static GString *
isolate_uuid(const char * iface)3503 isolate_uuid(const char *iface)
3504 {
3505     gchar   *ptr;
3506     GString *gstr;
3507 
3508     ptr = strchr(iface, '{');
3509     if (ptr == NULL)
3510         return g_string_new(iface);
3511     gstr = g_string_new(ptr + 1);
3512 
3513     ptr = strchr(gstr->str, '}');
3514     if (ptr == NULL)
3515         return gstr;
3516 
3517     gstr = g_string_truncate(gstr, ptr - gstr->str);
3518     return gstr;
3519 }
3520 #endif
3521 
3522 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3523 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3524 static gboolean
capture_loop_open_output(capture_options * capture_opts,int * save_file_fd,char * errmsg,int errmsg_len)3525 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3526                          char *errmsg, int errmsg_len)
3527 {
3528     gchar    *capfile_name;
3529     gchar    *prefix, *suffix;
3530     gboolean  is_tempfile;
3531     GError   *err_tempfile = NULL;
3532 
3533     ws_debug("capture_loop_open_output: %s",
3534           (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3535 
3536     if (capture_opts->save_file != NULL) {
3537         /* We return to the caller while the capture is in progress.
3538          * Therefore we need to take a copy of save_file in
3539          * case the caller destroys it after we return.
3540          */
3541         capfile_name = g_strdup(capture_opts->save_file);
3542 
3543         if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3544             if (capture_opts->multi_files_on) {
3545                 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3546                 g_snprintf(errmsg, errmsg_len,
3547                            "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3548                 g_free(capfile_name);
3549                 return FALSE;
3550             }
3551             if (strcmp(capfile_name, "-") == 0) {
3552                 /* write to stdout */
3553                 *save_file_fd = 1;
3554 #ifdef _WIN32
3555                 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF)  */
3556                 _setmode(1, O_BINARY);
3557 #endif
3558             } else {
3559                 /* Try to open the specified FIFO for use as a capture buffer.
3560                    Do *not* create it if it doesn't exist.  There's nothing
3561                    to truncate. If we need to read it, We Have A Problem. */
3562                 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY, 0);
3563             }
3564         } /* if (...output_to_pipe ... */
3565 
3566         else {
3567             if (capture_opts->multi_files_on) {
3568                 /* ringbuffer is enabled */
3569                 *save_file_fd = ringbuf_init(capfile_name,
3570                                              (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3571                                              capture_opts->group_read_access,
3572                                              capture_opts->compress_type,
3573                                              capture_opts->has_nametimenum);
3574 
3575                 /* capfile_name is unused as the ringbuffer provides its own filename. */
3576                 if (*save_file_fd != -1) {
3577                     g_free(capfile_name);
3578                     capfile_name = NULL;
3579                 }
3580                 if (capture_opts->print_file_names) {
3581                     if (!ringbuf_set_print_name(capture_opts->print_name_to, NULL)) {
3582                         g_snprintf(errmsg, errmsg_len, "Could not write filenames to %s: %s.\n",
3583                                    capture_opts->print_name_to,
3584                                    g_strerror(errno));
3585                         g_free(capfile_name);
3586                         ringbuf_error_cleanup();
3587                         return FALSE;
3588                     }
3589                 }
3590             } else {
3591                 /* Try to open/create the specified file for use as a capture buffer. */
3592                 *save_file_fd = ws_open(capfile_name, O_WRONLY|O_BINARY|O_TRUNC|O_CREAT,
3593                                         (capture_opts->group_read_access) ? 0640 : 0600);
3594             }
3595         }
3596         is_tempfile = FALSE;
3597     } else {
3598         /* Choose a random name for the temporary capture buffer */
3599         if (global_capture_opts.ifaces->len > 1) {
3600             /*
3601              * More than one interface; just use the number of interfaces
3602              * to generate the temporary file name prefix.
3603              */
3604             prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3605         } else {
3606             /*
3607              * One interface; use its description, if it has one, to generate
3608              * the temporary file name, otherwise use its name.
3609              */
3610             gchar *basename;
3611             const interface_options *interface_opts;
3612 
3613             interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
3614 
3615             /*
3616              * Do we have a description?
3617              */
3618             if (interface_opts->descr) {
3619                 /*
3620                  * Yes - use it.
3621                  *
3622                  * Strip off any stuff we shouldn't use in the file name,
3623                  * by getting the last component of what would be a file
3624                  * name.
3625                  */
3626                 basename = g_path_get_basename(interface_opts->descr);
3627             } else {
3628                 /*
3629                  * No - use the name.
3630                  *
3631                  * Strip off any stuff we shouldn't use in the file name,
3632                  * by getting the last component of what would be a file
3633                  * name.
3634                  */
3635                 basename = g_path_get_basename(interface_opts->name);
3636 #ifdef _WIN32
3637                 /*
3638                  * This is Windows, where we might have an ugly GUID-based
3639                  * interface name.
3640                  *
3641                  * If it's an ugly GUID-based name, use the generic portion
3642                  * of the interface GUID to form the basis of the filename.
3643                  */
3644                 if (strncmp("NPF_{", basename, 5) == 0) {
3645                     /*
3646                      * We have a GUID-based name; extract the GUID digits
3647                      * as the basis of the filename.
3648                      */
3649                     GString *iface;
3650                     iface = isolate_uuid(basename);
3651                     g_free(basename);
3652                     basename = g_strdup(iface->str);
3653                     g_string_free(iface, TRUE);
3654                 }
3655 #endif
3656             }
3657             /* generate the temp file name prefix */
3658             prefix = g_strconcat("wireshark_", basename, NULL);
3659             g_free(basename);
3660         }
3661 
3662         /* Generate the appropriate suffix. */
3663         if (capture_opts->use_pcapng) {
3664             suffix = ".pcapng";
3665         } else {
3666             suffix = ".pcap";
3667         }
3668         *save_file_fd = create_tempfile(&capfile_name, prefix, suffix, &err_tempfile);
3669         g_free(prefix);
3670         is_tempfile = TRUE;
3671     }
3672 
3673     /* did we fail to open the output file? */
3674     if (*save_file_fd == -1) {
3675         if (is_tempfile) {
3676             g_snprintf(errmsg, errmsg_len,
3677                        "The temporary file to which the capture would be saved (\"%s\") "
3678                        "could not be opened: %s.", capfile_name, err_tempfile->message);
3679             g_error_free(err_tempfile);
3680         } else {
3681             if (capture_opts->multi_files_on) {
3682                 /* Ensures that the ringbuffer is not used. This ensures that
3683                  * !ringbuf_is_initialized() is equivalent to
3684                  * capture_opts->save_file not being part of ringbuffer. */
3685                 ringbuf_error_cleanup();
3686             }
3687 
3688             g_snprintf(errmsg, errmsg_len,
3689                        "The file to which the capture would be saved (\"%s\") "
3690                        "could not be opened: %s.", capfile_name,
3691                        g_strerror(errno));
3692         }
3693         g_free(capfile_name);
3694         return FALSE;
3695     }
3696 
3697     g_free(capture_opts->save_file);
3698     if (!is_tempfile && capture_opts->multi_files_on) {
3699         /* In ringbuffer mode, save_file points to a filename from ringbuffer.c.
3700          * capfile_name was already freed before. */
3701         capture_opts->save_file = (char *)ringbuf_current_filename();
3702     } else {
3703         /* capture_opts_cleanup will g_free(capture_opts->save_file). */
3704         capture_opts->save_file = capfile_name;
3705     }
3706 
3707     return TRUE;
3708 }
3709 
get_next_time_interval(int interval_s)3710 static time_t get_next_time_interval(int interval_s) {
3711     time_t next_time = time(NULL);
3712     next_time -= next_time % interval_s;
3713     next_time += interval_s;
3714     return next_time;
3715 }
3716 
3717 /* Do the work of handling either the file size or file duration capture
3718    conditions being reached, and switching files or stopping. */
3719 static gboolean
do_file_switch_or_stop(capture_options * capture_opts)3720 do_file_switch_or_stop(capture_options *capture_opts)
3721 {
3722     gboolean          successful;
3723 
3724     if (capture_opts->multi_files_on) {
3725         if (capture_opts->has_autostop_files &&
3726             ++global_ld.file_count >= capture_opts->autostop_files) {
3727             /* no files left: stop here */
3728             global_ld.go = FALSE;
3729             return FALSE;
3730         }
3731 
3732         /* Switch to the next ringbuffer file */
3733         if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3734                                 &global_ld.save_file_fd, &global_ld.err)) {
3735 
3736             /* File switch succeeded: reset the conditions */
3737             global_ld.bytes_written = 0;
3738             global_ld.packets_written = 0;
3739             if (capture_opts->use_pcapng) {
3740                 successful = capture_loop_init_pcapng_output(capture_opts, &global_ld, &global_ld.err);
3741             } else {
3742                 capture_src *pcap_src;
3743                 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3744                 successful = libpcap_write_file_header(global_ld.pdh, pcap_src->linktype, pcap_src->snaplen,
3745                                                        pcap_src->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3746             }
3747 
3748             if (!successful) {
3749                 fclose(global_ld.pdh);
3750                 global_ld.pdh = NULL;
3751                 global_ld.go = FALSE;
3752                 g_free(global_ld.io_buffer);
3753                 global_ld.io_buffer = NULL;
3754                 return FALSE;
3755             }
3756             if (global_ld.file_duration_timer) {
3757                 g_timer_reset(global_ld.file_duration_timer);
3758             }
3759             if (global_ld.next_interval_time) {
3760                 global_ld.next_interval_time = get_next_time_interval(global_ld.interval_s);
3761             }
3762             fflush(global_ld.pdh);
3763             if (global_ld.inpkts_to_sync_pipe) {
3764                 if (!quiet)
3765                     report_packet_count(global_ld.inpkts_to_sync_pipe);
3766                 global_ld.inpkts_to_sync_pipe = 0;
3767             }
3768             report_new_capture_file(capture_opts->save_file);
3769         } else {
3770             /* File switch failed: stop here */
3771             global_ld.go = FALSE;
3772             return FALSE;
3773         }
3774     } else {
3775         /* single file, stop now */
3776         global_ld.go = FALSE;
3777         return FALSE;
3778     }
3779     return TRUE;
3780 }
3781 
3782 static void *
pcap_read_handler(void * arg)3783 pcap_read_handler(void* arg)
3784 {
3785     capture_src *pcap_src = (capture_src *)arg;
3786     char         errmsg[MSG_MAX_LENGTH+1];
3787 
3788     ws_info("Started thread for interface %d.", pcap_src->interface_id);
3789 
3790     /* If this is a pipe input it might finish early. */
3791     while (global_ld.go && pcap_src->cap_pipe_err == PIPOK) {
3792         /* dispatch incoming packets */
3793         capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_src);
3794     }
3795 
3796     ws_info("Stopped thread for interface %d.", pcap_src->interface_id);
3797     g_thread_exit(NULL);
3798     return (NULL);
3799 }
3800 
3801 /* Try to pop an item off the packet queue and if it exists, write it */
3802 static gboolean
capture_loop_dequeue_packet(void)3803 capture_loop_dequeue_packet(void) {
3804     pcap_queue_element *queue_element;
3805 
3806     g_async_queue_lock(pcap_queue);
3807     queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3808     if (queue_element) {
3809         if (queue_element->pcap_src->from_pcapng) {
3810             pcap_queue_bytes -= queue_element->u.bh.block_total_length;
3811         } else {
3812             pcap_queue_bytes -= queue_element->u.phdr.caplen;
3813         }
3814         pcap_queue_packets -= 1;
3815     }
3816     g_async_queue_unlock(pcap_queue);
3817     if (queue_element) {
3818         if (queue_element->pcap_src->from_pcapng) {
3819             ws_info("Dequeued a block of type 0x%08x of length %d captured on interface %d.",
3820                   queue_element->u.bh.block_type, queue_element->u.bh.block_total_length,
3821                   queue_element->pcap_src->interface_id);
3822 
3823             capture_loop_write_pcapng_cb(queue_element->pcap_src,
3824                                         &queue_element->u.bh,
3825                                         queue_element->pd);
3826         } else {
3827             ws_info("Dequeued a packet of length %d captured on interface %d.",
3828                 queue_element->u.phdr.caplen, queue_element->pcap_src->interface_id);
3829 
3830             capture_loop_write_packet_cb((u_char *) queue_element->pcap_src,
3831                                         &queue_element->u.phdr,
3832                                         queue_element->pd);
3833         }
3834         g_free(queue_element->pd);
3835         g_free(queue_element);
3836         return TRUE;
3837     }
3838     return FALSE;
3839 }
3840 
3841 /*
3842  * Note: this code will never be run on any OS other than Windows.
3843  *
3844  * We keep the arguments in case there's something in the future
3845  * that needs to be reported as an NPCAP bug.
3846  */
3847 static char *
handle_npcap_bug(char * adapter_name _U_,char * cap_err_str _U_)3848 handle_npcap_bug(char *adapter_name _U_, char *cap_err_str _U_)
3849 {
3850     GString *pcap_info_str;
3851     GString *windows_info_str;
3852     char *msg;
3853 
3854     pcap_info_str = g_string_new("");
3855     get_runtime_caplibs_version(pcap_info_str);
3856     if (!g_str_has_prefix(pcap_info_str->str, "with Npcap")) {
3857         /*
3858          * We're not using Npcap, so don't recomment a user
3859          * file a bug against Npcap.
3860          */
3861         g_string_free(pcap_info_str, TRUE);
3862         return g_strdup("");
3863     }
3864     windows_info_str = g_string_new("");
3865     get_os_version_info(windows_info_str);
3866     msg = g_strdup_printf("If you have not removed that adapter, this "
3867                           "is probably a known issue in Npcap resulting from "
3868                           "the behavior of the Windows networking stack. "
3869                           "Work is being done in Npcap to improve the "
3870                           "handling of this issue; it does not need to "
3871                           "be reported as a Wireshark or Npcap bug.");
3872     g_string_free(windows_info_str, TRUE);
3873     g_string_free(pcap_info_str, TRUE);
3874     return msg;
3875 }
3876 
3877 /* Do the low-level work of a capture.
3878    Returns TRUE if it succeeds, FALSE otherwise. */
3879 static gboolean
capture_loop_start(capture_options * capture_opts,gboolean * stats_known,struct pcap_stat * stats)3880 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3881 {
3882 #ifdef _WIN32
3883     DWORD             upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3884 #else
3885     struct timeval    upd_time, cur_time;
3886 #endif
3887     int               err_close;
3888     int               inpkts;
3889     GTimer           *autostop_duration_timer = NULL;
3890     gboolean          write_ok;
3891     gboolean          close_ok;
3892     gboolean          cfilter_error         = FALSE;
3893     char              errmsg[MSG_MAX_LENGTH+1];
3894     char              secondary_errmsg[MSG_MAX_LENGTH+1];
3895     capture_src      *pcap_src;
3896     interface_options *interface_opts;
3897     guint             i, error_index        = 0;
3898 
3899     *errmsg           = '\0';
3900     *secondary_errmsg = '\0';
3901 
3902     /* init the loop data */
3903     global_ld.go                  = TRUE;
3904     global_ld.packets_captured    = 0;
3905 #ifdef SIGINFO
3906     global_ld.report_packet_count = FALSE;
3907 #endif
3908     global_ld.inpkts_to_sync_pipe = 0;
3909     global_ld.err                 = 0;  /* no error seen yet */
3910     global_ld.pdh                 = NULL;
3911     global_ld.save_file_fd        = -1;
3912     global_ld.io_buffer           = NULL;
3913     global_ld.file_count          = 0;
3914     global_ld.file_duration_timer = NULL;
3915     global_ld.next_interval_time  = 0;
3916     global_ld.interval_s          = 0;
3917 
3918     /* We haven't yet gotten the capture statistics. */
3919     *stats_known      = FALSE;
3920 
3921     ws_info("Capture loop starting ...");
3922     capture_opts_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_DEBUG, capture_opts);
3923 
3924     /* open the "input file" from network interface or capture pipe */
3925     if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3926                                  secondary_errmsg, sizeof(secondary_errmsg))) {
3927         goto error;
3928     }
3929     for (i = 0; i < capture_opts->ifaces->len; i++) {
3930         pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3931         interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
3932         /* init the input filter from the network interface (capture pipe will do nothing) */
3933         /*
3934          * When remote capturing WinPCap crashes when the capture filter
3935          * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3936          * string.
3937          */
3938         switch (capture_loop_init_filter(pcap_src->pcap_h, pcap_src->from_cap_pipe,
3939                                          interface_opts->name,
3940                                          interface_opts->cfilter?interface_opts->cfilter:"")) {
3941 
3942         case INITFILTER_NO_ERROR:
3943             break;
3944 
3945         case INITFILTER_BAD_FILTER:
3946             cfilter_error = TRUE;
3947             error_index = i;
3948             g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_src->pcap_h));
3949             goto error;
3950 
3951         case INITFILTER_OTHER_ERROR:
3952             g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3953                        pcap_geterr(pcap_src->pcap_h));
3954             g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report_bug());
3955             goto error;
3956         }
3957     }
3958 
3959     /* If we're supposed to write to a capture file, open it for output
3960        (temporary/specified name/ringbuffer) */
3961     if (capture_opts->saving_to_file) {
3962         if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3963                                       errmsg, sizeof(errmsg))) {
3964             goto error;
3965         }
3966 
3967         /* set up to write to the already-opened capture output file/files */
3968         if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3969                                       sizeof(errmsg))) {
3970             goto error;
3971         }
3972 
3973         /* XXX - capture SIGTERM and close the capture, in case we're on a
3974            Linux 2.0[.x] system and you have to explicitly close the capture
3975            stream in order to turn promiscuous mode off?  We need to do that
3976            in other places as well - and I don't think that works all the
3977            time in any case, due to libpcap bugs. */
3978 
3979         /* Well, we should be able to start capturing.
3980 
3981            Sync out the capture file, so the header makes it to the file system,
3982            and send a "capture started successfully and capture file created"
3983            message to our parent so that they'll open the capture file and
3984            update its windows to indicate that we have a live capture in
3985            progress. */
3986         fflush(global_ld.pdh);
3987         report_new_capture_file(capture_opts->save_file);
3988     }
3989 
3990     if (capture_opts->has_file_interval) {
3991         global_ld.interval_s = capture_opts->file_interval;
3992         global_ld.next_interval_time = get_next_time_interval(global_ld.interval_s);
3993     }
3994     /* create stop conditions */
3995     if (capture_opts->has_autostop_filesize) {
3996         if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3997             capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3998         }
3999     }
4000     if (capture_opts->has_autostop_duration) {
4001         autostop_duration_timer = g_timer_new();
4002     }
4003 
4004     if (capture_opts->multi_files_on) {
4005         if (capture_opts->has_file_duration) {
4006             global_ld.file_duration_timer = g_timer_new();
4007         }
4008     }
4009 
4010     /* init the time values */
4011 #ifdef _WIN32
4012     upd_time = GetTickCount();
4013 #else
4014     gettimeofday(&upd_time, NULL);
4015 #endif
4016     start_time = create_timestamp();
4017     ws_info("Capture loop running.");
4018     capture_opts_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_DEBUG, capture_opts);
4019 
4020     /* WOW, everything is prepared! */
4021     /* please fasten your seat belts, we will enter now the actual capture loop */
4022     if (use_threads) {
4023         pcap_queue = g_async_queue_new();
4024         pcap_queue_bytes = 0;
4025         pcap_queue_packets = 0;
4026         for (i = 0; i < global_ld.pcaps->len; i++) {
4027             pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4028             /* XXX - Add an interface name here? */
4029             pcap_src->tid = g_thread_new("Capture read", pcap_read_handler, pcap_src);
4030         }
4031     }
4032     while (global_ld.go) {
4033         /* dispatch incoming packets */
4034         if (use_threads) {
4035             gboolean dequeued = capture_loop_dequeue_packet();
4036 
4037             if (dequeued) {
4038                 inpkts = 1;
4039             } else {
4040                 inpkts = 0;
4041             }
4042         } else {
4043             pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
4044             inpkts = capture_loop_dispatch(&global_ld, errmsg,
4045                                            sizeof(errmsg), pcap_src);
4046         }
4047         if (inpkts == 0) {
4048             /* Stop capturing if all of our sources are pipes and none of them are open. */
4049             gboolean open_interfaces = FALSE;
4050             for (i = 0; i < global_ld.pcaps->len; i++) {
4051                 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4052                 if (pcap_src->cap_pipe_err == PIPOK) {
4053                     /* True for both non-pipes and open pipes. */
4054                     open_interfaces = TRUE;
4055                 }
4056             }
4057             if (!open_interfaces) {
4058                 global_ld.go = FALSE;
4059             }
4060         }
4061 #ifdef SIGINFO
4062         /* Were we asked to print packet counts by the SIGINFO handler? */
4063         if (global_ld.report_packet_count) {
4064             fprintf(stderr, "%u packet%s captured\n", global_ld.packets_captured,
4065                     plurality(global_ld.packets_captured, "", "s"));
4066             global_ld.report_packet_count = FALSE;
4067         }
4068 #endif
4069 
4070 #ifdef _WIN32
4071         /* any news from our parent (signal pipe)? -> just stop the capture */
4072         if (!signal_pipe_check_running()) {
4073             global_ld.go = FALSE;
4074         }
4075 #endif
4076 
4077         if (inpkts > 0) {
4078             if (capture_opts->output_to_pipe) {
4079                 fflush(global_ld.pdh);
4080             }
4081         } /* inpkts */
4082 
4083         /* Only update once every 500ms so as not to overload slow displays.
4084          * This also prevents too much context-switching between the dumpcap
4085          * and wireshark processes.
4086          */
4087 #define DUMPCAP_UPD_TIME 500
4088 
4089 #ifdef _WIN32
4090         cur_time = GetTickCount();  /* Note: wraps to 0 if sys runs for 49.7 days */
4091         if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) /* wrap just causes an extra update */
4092 #else
4093         gettimeofday(&cur_time, NULL);
4094         if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
4095             ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000))
4096 #endif
4097         {
4098 
4099             upd_time = cur_time;
4100 
4101 #if 0
4102             if (pcap_stats(pch, stats) >= 0) {
4103                 *stats_known = TRUE;
4104             }
4105 #endif
4106             /* Let the parent process know. */
4107             if (global_ld.inpkts_to_sync_pipe) {
4108                 /* do sync here */
4109                 fflush(global_ld.pdh);
4110 
4111                 /* Send our parent a message saying we've written out
4112                    "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
4113                 if (!quiet)
4114                     report_packet_count(global_ld.inpkts_to_sync_pipe);
4115 
4116                 global_ld.inpkts_to_sync_pipe = 0;
4117             }
4118 
4119             /* check capture duration condition */
4120             if (autostop_duration_timer != NULL && g_timer_elapsed(autostop_duration_timer, NULL) >= capture_opts->autostop_duration) {
4121                 /* The maximum capture time has elapsed; stop the capture. */
4122                 global_ld.go = FALSE;
4123                 continue;
4124             }
4125 
4126             /* check capture file duration condition */
4127             if (global_ld.file_duration_timer != NULL && g_timer_elapsed(global_ld.file_duration_timer, NULL) >= capture_opts->file_duration) {
4128                 /* duration limit reached, do we have another file? */
4129                 if (!do_file_switch_or_stop(capture_opts))
4130                     continue;
4131             } /* cnd_file_duration */
4132 
4133             /* check capture file interval condition */
4134             if (global_ld.interval_s && time(NULL) >= global_ld.next_interval_time) {
4135                 /* end of interval reached, do we have another file? */
4136                 if (!do_file_switch_or_stop(capture_opts))
4137                     continue;
4138             } /* cnd_file_interval */
4139         }
4140     }
4141 
4142     ws_info("Capture loop stopping ...");
4143     if (use_threads) {
4144 
4145         for (i = 0; i < global_ld.pcaps->len; i++) {
4146             pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4147             ws_info("Waiting for thread of interface %u...", pcap_src->interface_id);
4148             g_thread_join(pcap_src->tid);
4149             ws_info("Thread of interface %u terminated.", pcap_src->interface_id);
4150         }
4151         while (1) {
4152             gboolean dequeued = capture_loop_dequeue_packet();
4153             if (!dequeued) {
4154                 break;
4155             }
4156             if (capture_opts->output_to_pipe) {
4157                 fflush(global_ld.pdh);
4158             }
4159         }
4160     }
4161 
4162 
4163     /* delete stop conditions */
4164     if (global_ld.file_duration_timer != NULL)
4165         g_timer_destroy(global_ld.file_duration_timer);
4166     if (autostop_duration_timer != NULL)
4167         g_timer_destroy(autostop_duration_timer);
4168 
4169     /* did we have a pcap (input) error? */
4170     for (i = 0; i < capture_opts->ifaces->len; i++) {
4171         pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4172         if (pcap_src->pcap_err) {
4173             /* On Linux, if an interface goes down while you're capturing on it,
4174                you'll get "recvfrom: Network is down".
4175                (At least you will if g_strerror() doesn't show a local translation
4176                of the error.)
4177 
4178                Newer versions of libpcap maps that to just
4179                "The interface went down".
4180 
4181                On FreeBSD, DragonFly BSD, and macOS, if a network adapter
4182                disappears while you're capturing on it, you'll get
4183                "read: Device not configured" error (ENXIO).  (See previous
4184                parenthetical note.)
4185 
4186                On OpenBSD, you get "read: I/O error" (EIO) in the same case.
4187 
4188                With WinPcap and Npcap, you'll get
4189                "read error: PacketReceivePacket failed" or
4190                "PacketReceivePacket error: The device has been removed. (1617)".
4191 
4192                Newer versions of libpcap map some or all of those to just
4193                "The interface disappeared" or something beginning with
4194                "The interface disappeared".
4195 
4196                These should *not* be reported to the Wireshark developers,
4197                although, with Npcap, "The interface disappeared" messages
4198                should perhaps be reported to the Npcap developers, at least
4199                until errors of that sort that shouldn't happen are fixed,
4200                if that's possible. */
4201             char *cap_err_str;
4202             char *primary_msg;
4203             char *secondary_msg;
4204 
4205             interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
4206             cap_err_str = pcap_geterr(pcap_src->pcap_h);
4207             if (strcmp(cap_err_str, "The interface went down") == 0 ||
4208                 strcmp(cap_err_str, "recvfrom: Network is down") == 0) {
4209                 primary_msg = g_strdup_printf("The network adapter \"%s\" "
4210                                               "is no longer running; the "
4211                                               "capture has stopped.",
4212                                               interface_opts->display_name);
4213                 secondary_msg = g_strdup("");
4214             } else if (strcmp(cap_err_str, "The interface disappeared") == 0 ||
4215                        strcmp(cap_err_str, "read: Device not configured") == 0 ||
4216                        strcmp(cap_err_str, "read: I/O error") == 0 ||
4217                        strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
4218                 primary_msg = g_strdup_printf("The network adapter \"%s\" "
4219                                               "is no longer attached; the "
4220                                               "capture has stopped.",
4221                                               interface_opts->display_name);
4222                 secondary_msg = g_strdup("");
4223             } else if (g_str_has_prefix(cap_err_str, "The interface disappeared ")) {
4224                 /*
4225                  * Npcap, if it picks up a recent commit to libpcap, will
4226                  * report an error *beginning* with "The interface
4227                  * disappeared", with the name of the Windows status code,
4228                  * and the corresponding NT status code, after it.
4229                  *
4230                  * Those should be reported as Npcap issues.
4231                  */
4232                 primary_msg = g_strdup_printf("The network adapter \"%s\" "
4233                                               "is no longer attached; the "
4234                                               "capture has stopped.",
4235                                               interface_opts->display_name);
4236                 secondary_msg = handle_npcap_bug(interface_opts->display_name,
4237                                                  cap_err_str);
4238             } else if (g_str_has_prefix(cap_err_str, "PacketReceivePacket error:") &&
4239                        g_str_has_suffix(cap_err_str, "(1617)")) {
4240                 /*
4241                  * "PacketReceivePacket error: {message in arbitrary language} (1617)",
4242                  * which is ERROR_DEVICE_REMOVED.
4243                  *
4244                  * Current libpcap/Npcap treat ERROR_GEN_FAILURE as
4245                  * "the device is no longer attached"; users are also
4246                  * getting ERROR_DEVICE_REMOVED.
4247                  *
4248                  * For now, some users appear to be getg ERROR_DEVICE_REMOVED
4249                  * in cases where the device *wasn't* removed, so tell
4250                  * them to report this as an Npcap issue; I seem to
4251                  * remember some discussion between Daniel and somebody
4252                  * at Microsoft about the Windows 10 network stack setup/
4253                  * teardown code being modified to try to prevent those
4254                  * sort of problems popping up, but I can't find that
4255                  * discussion.
4256                  */
4257                 primary_msg = g_strdup_printf("The network adapter \"%s\" "
4258                                               "is no longer attached; the "
4259                                               "capture has stopped.",
4260                                               interface_opts->display_name);
4261                 secondary_msg = handle_npcap_bug(interface_opts->display_name,
4262                                                  "The interface disappeared (error code ERROR_DEVICE_REMOVED/STATUS_DEVICE_REMOVED)");
4263             } else if (strcmp(cap_err_str, "The other host terminated the connection") == 0) {
4264                 primary_msg = g_strdup(cap_err_str);
4265                 secondary_msg = g_strdup("This may be a problem with the "
4266                                          "remote host on which you are "
4267                                          "capturing packets.");
4268             } else {
4269                 primary_msg = g_strdup_printf("Error while capturing packets: %s",
4270                                               cap_err_str);
4271                 secondary_msg = g_strdup(please_report_bug());
4272             }
4273             report_capture_error(primary_msg, secondary_msg);
4274             g_free(primary_msg);
4275             g_free(secondary_msg);
4276             break;
4277         } else if (pcap_src->from_cap_pipe && pcap_src->cap_pipe_err == PIPERR) {
4278             report_capture_error(errmsg, "");
4279             break;
4280         }
4281     }
4282     /* did we have an output error while capturing? */
4283     if (global_ld.err == 0) {
4284         write_ok = TRUE;
4285     } else {
4286         capture_loop_get_errmsg(errmsg, sizeof(errmsg), secondary_errmsg,
4287                                 sizeof(secondary_errmsg),
4288                                 capture_opts->save_file, global_ld.err, FALSE);
4289         report_capture_error(errmsg, secondary_errmsg);
4290         write_ok = FALSE;
4291     }
4292 
4293     if (capture_opts->saving_to_file) {
4294         /* close the output file */
4295         close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
4296     } else
4297         close_ok = TRUE;
4298 
4299     /* there might be packets not yet notified to the parent */
4300     /* (do this after closing the file, so all packets are already flushed) */
4301     if (global_ld.inpkts_to_sync_pipe) {
4302         if (!quiet)
4303             report_packet_count(global_ld.inpkts_to_sync_pipe);
4304         global_ld.inpkts_to_sync_pipe = 0;
4305     }
4306 
4307     /* If we've displayed a message about a write error, there's no point
4308        in displaying another message about an error on close. */
4309     if (!close_ok && write_ok) {
4310         capture_loop_get_errmsg(errmsg, sizeof(errmsg), secondary_errmsg,
4311                                 sizeof(secondary_errmsg),
4312                                 capture_opts->save_file, err_close, TRUE);
4313         report_capture_error(errmsg, secondary_errmsg);
4314     }
4315 
4316     /*
4317      * XXX We exhibit different behaviour between normal mode and sync mode
4318      * when the pipe is stdin and not already at EOF.  If we're a child, the
4319      * parent's stdin isn't closed, so if the user starts another capture,
4320      * cap_pipe_open_live() will very likely not see the expected magic bytes and
4321      * will say "Unrecognized libpcap format".  On the other hand, in normal
4322      * mode, cap_pipe_open_live() will say "End of file on pipe during open".
4323      */
4324 
4325     report_capture_count(TRUE);
4326 
4327     /* get packet drop statistics from pcap */
4328     for (i = 0; i < capture_opts->ifaces->len; i++) {
4329         guint32 received;
4330         guint32 pcap_dropped = 0;
4331 
4332         pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4333         interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
4334         received = pcap_src->received;
4335         if (pcap_src->pcap_h != NULL) {
4336             ws_assert(!pcap_src->from_cap_pipe);
4337             /* Get the capture statistics, so we know how many packets were dropped. */
4338             if (pcap_stats(pcap_src->pcap_h, stats) >= 0) {
4339                 *stats_known = TRUE;
4340                 /* Let the parent process know. */
4341                 pcap_dropped += stats->ps_drop;
4342             } else {
4343                 g_snprintf(errmsg, sizeof(errmsg),
4344                            "Can't get packet-drop statistics: %s",
4345                            pcap_geterr(pcap_src->pcap_h));
4346                 report_capture_error(errmsg, please_report_bug());
4347             }
4348         }
4349         report_packet_drops(received, pcap_dropped, pcap_src->dropped, pcap_src->flushed, stats->ps_ifdrop, interface_opts->display_name);
4350     }
4351 
4352     /* close the input file (pcap or capture pipe) */
4353     capture_loop_close_input(&global_ld);
4354 
4355     ws_info("Capture loop stopped.");
4356 
4357     /* ok, if the write and the close were successful. */
4358     return write_ok && close_ok;
4359 
4360 error:
4361     if (capture_opts->multi_files_on) {
4362         /* cleanup ringbuffer */
4363         ringbuf_error_cleanup();
4364     } else {
4365         /* We can't use the save file, and we have no FILE * for the stream
4366            to close in order to close it, so close the FD directly. */
4367         if (global_ld.save_file_fd != -1) {
4368             ws_close(global_ld.save_file_fd);
4369         }
4370 
4371         /* We couldn't even start the capture, so get rid of the capture
4372            file. */
4373         if (capture_opts->save_file != NULL) {
4374             ws_unlink(capture_opts->save_file);
4375         }
4376     }
4377     if (cfilter_error)
4378         report_cfilter_error(capture_opts, error_index, errmsg);
4379     else
4380         report_capture_error(errmsg, secondary_errmsg);
4381 
4382     /* close the input file (pcap or cap_pipe) */
4383     capture_loop_close_input(&global_ld);
4384 
4385     ws_info("Capture loop stopped with error");
4386 
4387     return FALSE;
4388 }
4389 
4390 
4391 static void
capture_loop_stop(void)4392 capture_loop_stop(void)
4393 {
4394     guint        i;
4395     capture_src *pcap_src;
4396 
4397     for (i = 0; i < global_ld.pcaps->len; i++) {
4398         pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
4399         if (pcap_src->pcap_h != NULL)
4400             pcap_breakloop(pcap_src->pcap_h);
4401     }
4402     global_ld.go = FALSE;
4403 }
4404 
4405 
4406 static void
capture_loop_get_errmsg(char * errmsg,size_t errmsglen,char * secondary_errmsg,size_t secondary_errmsglen,const char * fname,int err,gboolean is_close)4407 capture_loop_get_errmsg(char *errmsg, size_t errmsglen, char *secondary_errmsg,
4408                         size_t secondary_errmsglen, const char *fname,
4409                         int err, gboolean is_close)
4410 {
4411     static const char find_space[] =
4412         "You will need to free up space on that file system"
4413         " or put the capture file on a different file system.";
4414 
4415     switch (err) {
4416 
4417     case ENOSPC:
4418         g_snprintf(errmsg, (gulong)errmsglen,
4419                    "Not all the packets could be written to the file"
4420                    " to which the capture was being saved\n"
4421                    "(\"%s\") because there is no space left on the file system\n"
4422                    "on which that file resides.",
4423                    fname);
4424         g_snprintf(secondary_errmsg, (gulong)secondary_errmsglen, "%s",
4425                    find_space);
4426         break;
4427 
4428 #ifdef EDQUOT
4429     case EDQUOT:
4430         g_snprintf(errmsg, (gulong)errmsglen,
4431                    "Not all the packets could be written to the file"
4432                    " to which the capture was being saved\n"
4433                    "(\"%s\") because you are too close to, or over,"
4434                    " your disk quota\n"
4435                    "on the file system on which that file resides.",
4436                    fname);
4437         g_snprintf(secondary_errmsg, (gulong)secondary_errmsglen, "%s",
4438                    find_space);
4439         break;
4440 #endif
4441 
4442     default:
4443         if (is_close) {
4444             g_snprintf(errmsg, (gulong)errmsglen,
4445                        "The file to which the capture was being saved\n"
4446                        "(\"%s\") could not be closed: %s.",
4447                        fname, g_strerror(err));
4448         } else {
4449             g_snprintf(errmsg, (gulong)errmsglen,
4450                        "An error occurred while writing to the file"
4451                        " to which the capture was being saved\n"
4452                        "(\"%s\"): %s.",
4453                        fname, g_strerror(err));
4454         }
4455         g_snprintf(secondary_errmsg, (gulong)secondary_errmsglen,
4456                    "%s", please_report_bug());
4457         break;
4458     }
4459 }
4460 
4461 /*
4462  * We wrote one packet. Update some statistics and check if we've met any
4463  * autostop or ring buffer conditions.
4464  */
4465 static void
capture_loop_wrote_one_packet(capture_src * pcap_src)4466 capture_loop_wrote_one_packet(capture_src *pcap_src) {
4467     global_ld.packets_captured++;
4468     global_ld.packets_written++;
4469     global_ld.inpkts_to_sync_pipe++;
4470 
4471     if (!use_threads) {
4472         pcap_src->received++;
4473     }
4474 
4475     /* check -c NUM / -a packets:NUM */
4476     if (global_capture_opts.has_autostop_packets && global_ld.packets_captured >= global_capture_opts.autostop_packets) {
4477         fflush(global_ld.pdh);
4478         global_ld.go = FALSE;
4479         return;
4480     }
4481     /* check -b packets:NUM */
4482     if (global_capture_opts.has_file_packets && global_ld.packets_written >= global_capture_opts.file_packets) {
4483         do_file_switch_or_stop(&global_capture_opts);
4484         return;
4485     }
4486     /* check -a filesize:NUM */
4487     if (global_capture_opts.has_autostop_filesize &&
4488         global_capture_opts.autostop_filesize > 0 &&
4489         global_ld.bytes_written / 1000 >= global_capture_opts.autostop_filesize) {
4490         /* Capture size limit reached, do we have another file? */
4491         do_file_switch_or_stop(&global_capture_opts);
4492         return;
4493     }
4494 }
4495 
4496 /* one pcapng block was captured, process it */
4497 static void
capture_loop_write_pcapng_cb(capture_src * pcap_src,const pcapng_block_header_t * bh,u_char * pd)4498 capture_loop_write_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd)
4499 {
4500     int          err;
4501 
4502     /*
4503      * This should never be called if we're not writing pcapng.
4504      */
4505     ws_assert(global_capture_opts.use_pcapng);
4506 
4507     /* We may be called multiple times from pcap_dispatch(); if we've set
4508        the "stop capturing" flag, ignore this packet, as we're not
4509        supposed to be saving any more packets. */
4510     if (!global_ld.go) {
4511         pcap_src->flushed++;
4512         return;
4513     }
4514 
4515     if (!pcapng_adjust_block(pcap_src, bh, pd)) {
4516         ws_info("%s failed to adjust pcapng block.", G_STRFUNC);
4517         ws_assert_not_reached();
4518         return;
4519     }
4520 
4521     if (bh->block_type == BLOCK_TYPE_SHB && !global_ld.pcapng_passthrough) {
4522         /*
4523          * capture_loop_init_pcapng_output should've handled this. We need
4524          * to write ISBs when they're initially read so we shouldn't skip
4525          * them here.
4526          */
4527         return;
4528     }
4529 
4530     if (global_ld.pdh) {
4531         gboolean successful;
4532 
4533         /* We're supposed to write the packet to a file; do so.
4534            If this fails, set "ld->go" to FALSE, to stop the capture, and set
4535            "ld->err" to the error. */
4536         successful = pcapng_write_block(global_ld.pdh,
4537                                        pd,
4538                                        bh->block_total_length,
4539                                        &global_ld.bytes_written, &err);
4540 
4541         fflush(global_ld.pdh);
4542         if (!successful) {
4543             global_ld.go = FALSE;
4544             global_ld.err = err;
4545             pcap_src->dropped++;
4546         } else if (bh->block_type == BLOCK_TYPE_EPB || bh->block_type == BLOCK_TYPE_SPB || bh->block_type == BLOCK_TYPE_SYSTEMD_JOURNAL_EXPORT) {
4547             /* count packet only if we actually have an EPB or SPB */
4548 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4549             ws_info("Wrote a pcapng block type %u of length %d captured on interface %u.",
4550                    bh->block_type, bh->block_total_length, pcap_src->interface_id);
4551 #endif
4552             capture_loop_wrote_one_packet(pcap_src);
4553         } else if (bh->block_type == BLOCK_TYPE_SHB && report_capture_filename) {
4554 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4555             ws_info("Sending SP_FILE on first SHB");
4556 #endif
4557             /* SHB is now ready for capture parent to read on SP_FILE message */
4558             pipe_write_block(2, SP_FILE, report_capture_filename);
4559             report_capture_filename = NULL;
4560         }
4561     }
4562 }
4563 
4564 /* one pcap packet was captured, process it */
4565 static void
capture_loop_write_packet_cb(u_char * pcap_src_p,const struct pcap_pkthdr * phdr,const u_char * pd)4566 capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
4567                              const u_char *pd)
4568 {
4569     capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
4570     int          err;
4571     guint        ts_mul    = pcap_src->ts_nsec ? 1000000000 : 1000000;
4572 
4573     ws_debug("capture_loop_write_packet_cb");
4574 
4575     /* We may be called multiple times from pcap_dispatch(); if we've set
4576        the "stop capturing" flag, ignore this packet, as we're not
4577        supposed to be saving any more packets. */
4578     if (!global_ld.go) {
4579         pcap_src->flushed++;
4580         return;
4581     }
4582 
4583     if (global_ld.pdh) {
4584         gboolean successful;
4585 
4586         /* We're supposed to write the packet to a file; do so.
4587            If this fails, set "ld->go" to FALSE, to stop the capture, and set
4588            "ld->err" to the error. */
4589         if (global_capture_opts.use_pcapng) {
4590             successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
4591                                                             NULL,
4592                                                             phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4593                                                             phdr->caplen, phdr->len,
4594                                                             pcap_src->interface_id,
4595                                                             ts_mul,
4596                                                             pd, 0,
4597                                                             &global_ld.bytes_written, &err);
4598         } else {
4599             successful = libpcap_write_packet(global_ld.pdh,
4600                                               phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4601                                               phdr->caplen, phdr->len,
4602                                               pd,
4603                                               &global_ld.bytes_written, &err);
4604         }
4605         if (!successful) {
4606             global_ld.go = FALSE;
4607             global_ld.err = err;
4608             pcap_src->dropped++;
4609         } else {
4610 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4611             ws_info("Wrote a pcap packet of length %d captured on interface %u.",
4612                    phdr->caplen, pcap_src->interface_id);
4613 #endif
4614             capture_loop_wrote_one_packet(pcap_src);
4615         }
4616     }
4617 }
4618 
4619 /* one packet was captured, queue it */
4620 static void
capture_loop_queue_packet_cb(u_char * pcap_src_p,const struct pcap_pkthdr * phdr,const u_char * pd)4621 capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
4622                              const u_char *pd)
4623 {
4624     capture_src        *pcap_src = (capture_src *) (void *) pcap_src_p;
4625     pcap_queue_element *queue_element;
4626     gboolean            limit_reached;
4627 
4628     /* We may be called multiple times from pcap_dispatch(); if we've set
4629        the "stop capturing" flag, ignore this packet, as we're not
4630        supposed to be saving any more packets. */
4631     if (!global_ld.go) {
4632         pcap_src->flushed++;
4633         return;
4634     }
4635 
4636     queue_element = g_new(pcap_queue_element, 1);
4637     if (queue_element == NULL) {
4638        pcap_src->dropped++;
4639        return;
4640     }
4641     queue_element->pcap_src = pcap_src;
4642     queue_element->u.phdr = *phdr;
4643     queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4644     if (queue_element->pd == NULL) {
4645         pcap_src->dropped++;
4646         g_free(queue_element);
4647         return;
4648     }
4649     memcpy(queue_element->pd, pd, phdr->caplen);
4650     g_async_queue_lock(pcap_queue);
4651     if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4652         ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4653         limit_reached = FALSE;
4654         g_async_queue_push_unlocked(pcap_queue, queue_element);
4655         pcap_queue_bytes += phdr->caplen;
4656         pcap_queue_packets += 1;
4657     } else {
4658         limit_reached = TRUE;
4659     }
4660     g_async_queue_unlock(pcap_queue);
4661     if (limit_reached) {
4662         pcap_src->dropped++;
4663         g_free(queue_element->pd);
4664         g_free(queue_element);
4665         ws_info("Dropped a packet of length %d captured on interface %u.",
4666               phdr->caplen, pcap_src->interface_id);
4667     } else {
4668         pcap_src->received++;
4669         ws_info("Queued a packet of length %d captured on interface %u.",
4670               phdr->caplen, pcap_src->interface_id);
4671     }
4672     /* I don't want to hold the mutex over the debug output. So the
4673        output may be wrong */
4674     ws_info("Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4675           pcap_queue_bytes, pcap_queue_packets);
4676 }
4677 
4678 /* one pcapng block was captured, queue it */
4679 static void
capture_loop_queue_pcapng_cb(capture_src * pcap_src,const pcapng_block_header_t * bh,u_char * pd)4680 capture_loop_queue_pcapng_cb(capture_src *pcap_src, const pcapng_block_header_t *bh, u_char *pd)
4681 {
4682     pcap_queue_element *queue_element;
4683     gboolean            limit_reached;
4684 
4685     /* We may be called multiple times from pcap_dispatch(); if we've set
4686        the "stop capturing" flag, ignore this packet, as we're not
4687        supposed to be saving any more packets. */
4688     if (!global_ld.go) {
4689         pcap_src->flushed++;
4690         return;
4691     }
4692 
4693     queue_element = g_new(pcap_queue_element, 1);
4694     if (queue_element == NULL) {
4695        pcap_src->dropped++;
4696        return;
4697     }
4698     queue_element->pcap_src = pcap_src;
4699     queue_element->u.bh = *bh;
4700     queue_element->pd = (u_char *)g_malloc(bh->block_total_length);
4701     if (queue_element->pd == NULL) {
4702         pcap_src->dropped++;
4703         g_free(queue_element);
4704         return;
4705     }
4706     memcpy(queue_element->pd, pd, bh->block_total_length);
4707     g_async_queue_lock(pcap_queue);
4708     if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4709         ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4710         limit_reached = FALSE;
4711         g_async_queue_push_unlocked(pcap_queue, queue_element);
4712         pcap_queue_bytes += bh->block_total_length;
4713         pcap_queue_packets += 1;
4714     } else {
4715         limit_reached = TRUE;
4716     }
4717     g_async_queue_unlock(pcap_queue);
4718     if (limit_reached) {
4719         pcap_src->dropped++;
4720         g_free(queue_element->pd);
4721         g_free(queue_element);
4722         ws_info("Dropped a packet of length %d captured on interface %u.",
4723               bh->block_total_length, pcap_src->interface_id);
4724     } else {
4725         pcap_src->received++;
4726         ws_info("Queued a block of type 0x%08x of length %d captured on interface %u.",
4727               bh->block_type, bh->block_total_length, pcap_src->interface_id);
4728     }
4729     /* I don't want to hold the mutex over the debug output. So the
4730        output may be wrong */
4731     ws_info("Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4732           pcap_queue_bytes, pcap_queue_packets);
4733 }
4734 
4735 static int
set_80211_channel(const char * iface,const char * opt)4736 set_80211_channel(const char *iface, const char *opt)
4737 {
4738     guint32 freq = 0;
4739     int type = -1;
4740     guint32 center_freq1 = 0;
4741     guint32 center_freq2 = 0;
4742     int args;
4743     int ret = 0;
4744     gchar **options = NULL;
4745 
4746     options = g_strsplit_set(opt, ",", 4);
4747     for (args = 0; options[args]; args++)
4748         ;
4749 
4750     ret = ws80211_init();
4751     if (ret != WS80211_INIT_OK) {
4752         if (ret == WS80211_INIT_NOT_SUPPORTED)
4753             cmdarg_err("Setting 802.11 channels is not supported on this platform");
4754         else
4755             cmdarg_err("Failed to init ws80211: %s", g_strerror(abs(ret)));
4756         ret = 2;
4757         goto out;
4758     }
4759 
4760     if (options[0])
4761         freq = get_nonzero_guint32(options[0], "802.11 channel frequency");
4762 
4763     if (args >= 1 && options[1]) {
4764         type = ws80211_str_to_chan_type(options[1]);
4765         if (type == -1) {
4766             cmdarg_err("\"%s\" is not a valid 802.11 channel type", options[1]);
4767             ret = EINVAL;
4768             goto out;
4769         }
4770     }
4771 
4772     if (args >= 2 && options[2])
4773         center_freq1 = get_nonzero_guint32(options[2], "VHT center frequency");
4774 
4775     if (args >= 3 && options[3])
4776         center_freq2 = get_nonzero_guint32(options[3], "VHT center frequency 2");
4777 
4778     ret = ws80211_set_freq(iface, freq, type, center_freq1, center_freq2);
4779 
4780     if (ret) {
4781         cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4782         ret = 2;
4783         goto out;
4784     }
4785 
4786     if (capture_child)
4787         pipe_write_block(2, SP_SUCCESS, NULL);
4788 
4789 out:
4790     g_strfreev(options);
4791     return ret;
4792 }
4793 
4794 static void
get_dumpcap_compiled_info(GString * str)4795 get_dumpcap_compiled_info(GString *str)
4796 {
4797     /* Capture libraries */
4798     g_string_append(str, ", ");
4799     get_compiled_caplibs_version(str);
4800 }
4801 
4802 static void
get_dumpcap_runtime_info(GString * str)4803 get_dumpcap_runtime_info(GString *str)
4804 {
4805     /* Capture libraries */
4806     g_string_append(str, ", ");
4807     get_runtime_caplibs_version(str);
4808 }
4809 
4810 #define LONGOPT_IFNAME             LONGOPT_BASE_APPLICATION+1
4811 #define LONGOPT_IFDESCR            LONGOPT_BASE_APPLICATION+2
4812 #define LONGOPT_CAPTURE_COMMENT    LONGOPT_BASE_APPLICATION+3
4813 
4814 /* And now our feature presentation... [ fade to music ] */
4815 int
main(int argc,char * argv[])4816 main(int argc, char *argv[])
4817 {
4818     char             *err_msg;
4819     int               opt;
4820     static const struct ws_option long_options[] = {
4821         {"help", ws_no_argument, NULL, 'h'},
4822         {"version", ws_no_argument, NULL, 'v'},
4823         LONGOPT_CAPTURE_COMMON
4824         {"ifname", ws_required_argument, NULL, LONGOPT_IFNAME},
4825         {"ifdescr", ws_required_argument, NULL, LONGOPT_IFDESCR},
4826         {"capture-comment", ws_required_argument, NULL, LONGOPT_CAPTURE_COMMENT},
4827         {0, 0, 0, 0 }
4828     };
4829 
4830     gboolean          arg_error             = FALSE;
4831 
4832 #ifndef _WIN32
4833     struct sigaction  action, oldaction;
4834 #endif
4835 
4836     gboolean          stats_known;
4837     struct pcap_stat  stats = {0};
4838     gboolean          list_interfaces       = FALSE;
4839     int               caps_queries          = 0;
4840     gboolean          print_bpf_code        = FALSE;
4841     gboolean          set_chan              = FALSE;
4842     gchar            *set_chan_arg          = NULL;
4843     gboolean          machine_readable      = FALSE;
4844     gboolean          print_statistics      = FALSE;
4845     int               status, run_once_args = 0;
4846     gint              i;
4847     guint             j;
4848 #if defined(__APPLE__) && defined(__LP64__)
4849     struct utsname    osinfo;
4850 #endif
4851     GString          *str;
4852 
4853     /*
4854      * Determine if dumpcap is being requested to run in a special
4855      * capture_child mode by going thru the command line args to see if
4856      * a -Z is present. (-Z is a hidden option).
4857      *
4858      * The primary result of running in capture_child mode is that
4859      * all messages sent out on stderr are in a special type/len/string
4860      * format to allow message processing by type.  These messages include
4861      * error messages if dumpcap fails to start the operation it was
4862      * requested to do, as well as various "status" messages which are sent
4863      * when an actual capture is in progress, and a "success" message sent
4864      * if dumpcap was requested to perform an operation other than a
4865      * capture.
4866      *
4867      * Capture_child mode would normally be requested by a parent process
4868      * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4869      * to which dumpcap stderr has been redirected.  It might also have
4870      * another pipe to obtain dumpcap stdout output; for operations other
4871      * than a capture, that information is formatted specially for easier
4872      * parsing by the parent process.
4873      *
4874      * Capture_child mode needs to be determined immediately upon
4875      * startup so that any messages generated by dumpcap in this mode
4876      * (eg: during initialization) will be formatted properly.
4877      */
4878 
4879     for (i=1; i<argc; i++) {
4880         if (strcmp("-Z", argv[i]) == 0) {
4881             capture_child    = TRUE;
4882             machine_readable = TRUE;  /* request machine-readable output */
4883 #ifdef _WIN32
4884             /* set output pipe to binary mode, to avoid ugly text conversions */
4885             _setmode(2, O_BINARY);
4886 #endif
4887         }
4888     }
4889 
4890     cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
4891 
4892     /* Initialize log handler early so we can have proper logging during startup. */
4893     ws_log_init_with_writer("dumpcap", dumpcap_log_writer, vcmdarg_err);
4894 
4895     /* Early logging command-line initialization. */
4896     ws_log_parse_args(&argc, argv, vcmdarg_err, 1);
4897 
4898 #ifdef _WIN32
4899     create_app_running_mutex();
4900 
4901     /*
4902      * Initialize our DLL search path. MUST be called before LoadLibrary
4903      * or g_module_open.
4904      */
4905     ws_init_dll_search_path();
4906 
4907     /* Load wpcap if possible. Do this before collecting the run-time version information */
4908     load_wpcap();
4909 #endif
4910 
4911     /* Initialize the version information. */
4912     ws_init_version_info("Dumpcap (Wireshark)", NULL, get_dumpcap_compiled_info,
4913                          get_dumpcap_runtime_info);
4914 
4915 #ifdef HAVE_PCAP_REMOTE
4916 #define OPTSTRING_r "r"
4917 #define OPTSTRING_u "u"
4918 #else
4919 #define OPTSTRING_r
4920 #define OPTSTRING_u
4921 #endif
4922 
4923 #ifdef HAVE_PCAP_SETSAMPLING
4924 #define OPTSTRING_m "m:"
4925 #else
4926 #define OPTSTRING_m
4927 #endif
4928 
4929 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:dghk:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
4930 
4931 #ifdef DEBUG_CHILD_DUMPCAP
4932     if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4933         fprintf (stderr, "Unable to open debug log file .\n");
4934         exit (1);
4935     }
4936 #endif
4937 
4938 #if defined(__APPLE__) && defined(__LP64__)
4939     /*
4940      * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4?  If so, we need
4941      * a bug workaround - timeouts less than 1 second don't work with libpcap
4942      * in 64-bit code.  (The bug was introduced in 10.6, fixed in 10.6.2,
4943      * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4944      * The problem is extremely unlikely to be reintroduced in a future
4945      * release.)
4946      */
4947     if (uname(&osinfo) == 0) {
4948         /*
4949          * {Mac} OS X/macOS 10.x uses Darwin {x+4}.0.0; 10.x.y uses Darwin
4950          * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4951          * number of 10.0.0, not 10.1.0 - go figure).
4952          */
4953         if (strcmp(osinfo.release, "10.0.0") == 0 ||    /* 10.6, 10.6.1 */
4954             strcmp(osinfo.release, "10.3.0") == 0 ||    /* 10.6.3 */
4955             strcmp(osinfo.release, "10.4.0") == 0)              /* 10.6.4 */
4956             need_timeout_workaround = TRUE;
4957     }
4958 #endif
4959 
4960     /* Initialize the pcaps list and IDBs */
4961     global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(capture_src *));
4962     global_ld.pcapng_passthrough = FALSE;
4963     global_ld.saved_shb = NULL;
4964     global_ld.saved_idbs = g_array_new(FALSE, TRUE, sizeof(saved_idb_t));
4965 
4966     err_msg = ws_init_sockets();
4967     if (err_msg != NULL)
4968     {
4969         ws_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_ERROR,
4970                           "ERROR: %s", err_msg);
4971         g_free(err_msg);
4972         ws_log(LOG_DOMAIN_CAPCHILD, LOG_LEVEL_ERROR,
4973                           "%s", please_report_bug());
4974         exit_main(1);
4975     }
4976 
4977 #ifdef _WIN32
4978     /* Set handler for Ctrl+C key */
4979     SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4980 #else
4981     /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4982        and exit.  Do the same with SIGPIPE, in case, for example,
4983        we're writing to our standard output and it's a pipe.
4984        Do the same with SIGHUP if it's not being ignored (if we're
4985        being run under nohup, it might be ignored, in which case we
4986        should leave it ignored).
4987 
4988        XXX - apparently, Coverity complained that part of action
4989        wasn't initialized.  Perhaps it's running on Linux, where
4990        struct sigaction has an ignored "sa_restorer" element and
4991        where "sa_handler" and "sa_sigaction" might not be two
4992        members of a union. */
4993     memset(&action, 0, sizeof(action));
4994     action.sa_handler = capture_cleanup_handler;
4995     /*
4996      * Arrange that system calls not get restarted, because when
4997      * our signal handler returns we don't want to restart
4998      * a call that was waiting for packets to arrive.
4999      */
5000     action.sa_flags = 0;
5001     sigemptyset(&action.sa_mask);
5002     sigaction(SIGTERM, &action, NULL);
5003     sigaction(SIGINT, &action, NULL);
5004     sigaction(SIGPIPE, &action, NULL);
5005     sigaction(SIGHUP, NULL, &oldaction);
5006     if (oldaction.sa_handler == SIG_DFL)
5007         sigaction(SIGHUP, &action, NULL);
5008 
5009 #ifdef SIGINFO
5010     /* Catch SIGINFO and, if we get it and we're capturing in
5011        quiet mode, report the number of packets we've captured. */
5012     action.sa_handler = report_counts_siginfo;
5013     action.sa_flags = SA_RESTART;
5014     sigemptyset(&action.sa_mask);
5015     sigaction(SIGINFO, &action, NULL);
5016 #endif /* SIGINFO */
5017 #endif  /* _WIN32 */
5018 
5019     /* ----------------------------------------------------------------- */
5020     /* Privilege and capability handling                                 */
5021     /* Cases:                                                            */
5022     /* 1. Running not as root or suid root; no special capabilities.     */
5023     /*    Action: none                                                   */
5024     /*                                                                   */
5025     /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap.  */
5026     /*    Action: none                                                   */
5027     /*                                                                   */
5028     /* 3. Running logged in as root (euid=0; ruid=0). Using libcap.      */
5029     /*    Action:                                                        */
5030     /*      - Near start of program: Enable NET_RAW and NET_ADMIN        */
5031     /*        capabilities; Drop all other capabilities;                 */
5032     /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
5033     /*        else: after  pcap_open_live() in capture_loop_open_input() */
5034     /*         drop all capabilities (NET_RAW and NET_ADMIN);            */
5035     /*         (Note: this means that the process, although logged in    */
5036     /*          as root, does not have various permissions such as the   */
5037     /*          ability to bypass file access permissions).              */
5038     /*      XXX: Should we just leave capabilities alone in this case    */
5039     /*          so that user gets expected effect that root can do       */
5040     /*          anything ??                                              */
5041     /*                                                                   */
5042     /* 4. Running as suid root (euid=0, ruid=n); Not using libcap.       */
5043     /*    Action:                                                        */
5044     /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
5045     /*        else: after  pcap_open_live() in capture_loop_open_input() */
5046     /*         drop suid root (set euid=ruid).(ie: keep suid until after */
5047     /*         pcap_open_live).                                          */
5048     /*                                                                   */
5049     /* 5. Running as suid root (euid=0, ruid=n); Using libcap.           */
5050     /*    Action:                                                        */
5051     /*      - Near start of program: Enable NET_RAW and NET_ADMIN        */
5052     /*        capabilities; Drop all other capabilities;                 */
5053     /*        Drop suid privileges (euid=ruid);                          */
5054     /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
5055     /*        else: after  pcap_open_live() in capture_loop_open_input() */
5056     /*         drop all capabilities (NET_RAW and NET_ADMIN).            */
5057     /*                                                                   */
5058     /*      XXX: For some Linux versions/distros with capabilities       */
5059     /*        a 'normal' process with any capabilities cannot be         */
5060     /*        'killed' (signaled) from another (same uid) non-privileged */
5061     /*        process.                                                   */
5062     /*        For example: If (non-suid) Wireshark forks a               */
5063     /*        child suid dumpcap which acts as described here (case 5),  */
5064     /*        Wireshark will be unable to kill (signal) the child        */
5065     /*        dumpcap process until the capabilities have been dropped   */
5066     /*        (after pcap_open_live()).                                  */
5067     /*        This behaviour will apparently be changed in the kernel    */
5068     /*        to allow the kill (signal) in this case.                   */
5069     /*        See the following for details:                             */
5070     /*           https://www.mail-archive.com/  [wrapped]                */
5071     /*             linux-security-module@vger.kernel.org/msg02913.html   */
5072     /*                                                                   */
5073     /*        It is therefore conceivable that if dumpcap somehow hangs  */
5074     /*        in pcap_open_live or before that wireshark will not        */
5075     /*        be able to stop dumpcap using a signal (INT, TERM, etc).   */
5076     /*        In this case, exiting wireshark will kill the child        */
5077     /*        dumpcap process.                                           */
5078     /*                                                                   */
5079     /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN        */
5080     /*     capabilities; Using libcap.  Note: capset cmd (which see)     */
5081     /*     used to assign capabilities to file.                          */
5082     /*    Action:                                                        */
5083     /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
5084     /*        else: after  pcap_open_live() in capture_loop_open_input() */
5085     /*         drop all capabilities (NET_RAW and NET_ADMIN)             */
5086     /*                                                                   */
5087     /* ToDo: -S (stats) should drop privileges/capabilities when no      */
5088     /*       longer required (similar to capture).                       */
5089     /*                                                                   */
5090     /* ----------------------------------------------------------------- */
5091 
5092     init_process_policies();
5093 
5094 #ifdef HAVE_LIBCAP
5095     /* If 'started with special privileges' (and using libcap)  */
5096     /*   Set to keep only NET_RAW and NET_ADMIN capabilities;   */
5097     /*   Set euid/egid = ruid/rgid to remove suid privileges    */
5098     relinquish_privs_except_capture();
5099 #endif
5100 
5101     /* Set the initial values in the capture options. This might be overwritten
5102        by the command line parameters. */
5103     capture_opts_init(&global_capture_opts);
5104     /* We always save to a file - if no file was specified, we save to a
5105        temporary file. */
5106     global_capture_opts.saving_to_file      = TRUE;
5107     global_capture_opts.has_ring_num_files  = TRUE;
5108 
5109     /* Pass on capture_child mode for capture_opts */
5110     global_capture_opts.capture_child = capture_child;
5111 
5112     /* Now get our args */
5113     while ((opt = ws_getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
5114         switch (opt) {
5115         case 'h':        /* Print help and exit */
5116             show_help_header("Capture network packets and dump them into a pcapng or pcap file.");
5117             print_usage(stdout);
5118             exit_main(0);
5119             break;
5120         case 'v':        /* Show version and exit */
5121             show_version();
5122             exit_main(0);
5123             break;
5124         /*** capture option specific ***/
5125         case 'a':        /* autostop criteria */
5126         case 'b':        /* Ringbuffer option */
5127         case 'c':        /* Capture x packets */
5128         case 'f':        /* capture filter */
5129         case 'g':        /* enable group read access on file(s) */
5130         case 'i':        /* Use interface x */
5131         case LONGOPT_SET_TSTAMP_TYPE: /* Set capture timestamp type */
5132         case 'n':        /* Use pcapng format */
5133         case 'p':        /* Don't capture in promiscuous mode */
5134         case 'P':        /* Use pcap format */
5135         case 's':        /* Set the snapshot (capture) length */
5136         case 'w':        /* Write to capture file x */
5137         case 'y':        /* Set the pcap data link type */
5138 #ifdef HAVE_PCAP_REMOTE
5139         case 'u':        /* Use UDP for data transfer */
5140         case 'r':        /* Capture own RPCAP traffic too */
5141         case 'A':        /* Authentication */
5142 #endif
5143 #ifdef HAVE_PCAP_SETSAMPLING
5144         case 'm':        /* Sampling */
5145 #endif
5146 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
5147         case 'B':        /* Buffer size */
5148 #endif
5149 #ifdef HAVE_PCAP_CREATE
5150         case 'I':        /* Monitor mode */
5151 #endif
5152         case LONGOPT_COMPRESS_TYPE:        /* compress type */
5153             status = capture_opts_add_opt(&global_capture_opts, opt, ws_optarg);
5154             if (status != 0) {
5155                 exit_main(status);
5156             }
5157             break;
5158             /*** hidden option: Wireshark child mode (using binary output messages) ***/
5159         case LONGOPT_IFNAME:
5160             if (global_capture_opts.ifaces->len > 0) {
5161                 interface_options *interface_opts;
5162 
5163                 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, global_capture_opts.ifaces->len - 1);
5164                 interface_opts->ifname = g_strdup(ws_optarg);
5165             } else {
5166                 cmdarg_err("--ifname must be specified after a -i option");
5167                 exit_main(1);
5168             }
5169             break;
5170         case LONGOPT_IFDESCR:
5171             if (global_capture_opts.ifaces->len > 0) {
5172                 interface_options *interface_opts;
5173 
5174                 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, global_capture_opts.ifaces->len - 1);
5175                 interface_opts->descr = g_strdup(ws_optarg);
5176             } else {
5177                 cmdarg_err("--ifdescr must be specified after a -i option");
5178                 exit_main(1);
5179             }
5180             break;
5181         case LONGOPT_CAPTURE_COMMENT:  /* capture comment */
5182             if (capture_comments == NULL) {
5183                 capture_comments = g_ptr_array_new_with_free_func(g_free);
5184             }
5185             g_ptr_array_add(capture_comments, g_strdup(ws_optarg));
5186             break;
5187         case 'Z':
5188             capture_child = TRUE;
5189 #ifdef _WIN32
5190             /* set output pipe to binary mode, to avoid ugly text conversions */
5191             _setmode(2, O_BINARY);
5192             /*
5193              * ws_optarg = the control ID, aka the PPID, currently used for the
5194              * signal pipe name.
5195              */
5196             if (strcmp(ws_optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
5197                 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, ws_optarg);
5198                 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
5199                                              GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
5200 
5201                 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
5202                     ws_info("Signal pipe: Unable to open %s.  Dead parent?",
5203                           sig_pipe_name);
5204                     exit_main(1);
5205                 }
5206             }
5207 #endif
5208             break;
5209 
5210         case 'q':        /* Quiet */
5211             quiet = TRUE;
5212             break;
5213         case 't':
5214             use_threads = TRUE;
5215             break;
5216             /*** all non capture option specific ***/
5217         case 'D':        /* Print a list of capture devices and exit */
5218             if (!list_interfaces) {
5219                 list_interfaces = TRUE;
5220                 run_once_args++;
5221             }
5222             break;
5223         case 'L':        /* Print list of link-layer types and exit */
5224             if (!(caps_queries & CAPS_QUERY_LINK_TYPES)) {
5225                 caps_queries |= CAPS_QUERY_LINK_TYPES;
5226                 run_once_args++;
5227             }
5228             break;
5229         case LONGOPT_LIST_TSTAMP_TYPES:
5230                 caps_queries |= CAPS_QUERY_TIMESTAMP_TYPES;
5231         break;
5232         case 'd':        /* Print BPF code for capture filter and exit */
5233             if (!print_bpf_code) {
5234                 print_bpf_code = TRUE;
5235                 run_once_args++;
5236             }
5237             break;
5238         case 'S':        /* Print interface statistics once a second */
5239             if (!print_statistics) {
5240                 print_statistics = TRUE;
5241                 run_once_args++;
5242             }
5243             break;
5244         case 'k':        /* Set wireless channel */
5245             if (!set_chan) {
5246                 set_chan = TRUE;
5247                 set_chan_arg = ws_optarg;
5248                 run_once_args++;
5249             } else {
5250                 cmdarg_err("Only one -k flag may be specified");
5251                 arg_error = TRUE;
5252             }
5253             break;
5254         case 'M':        /* For -D, -L, and -S, print machine-readable output */
5255             machine_readable = TRUE;
5256             break;
5257         case 'C':
5258             pcap_queue_byte_limit = get_positive_int(ws_optarg, "byte_limit");
5259             break;
5260         case 'N':
5261             pcap_queue_packet_limit = get_positive_int(ws_optarg, "packet_limit");
5262             break;
5263         default:
5264             cmdarg_err("Invalid Option: %s", argv[ws_optind-1]);
5265             /* FALLTHROUGH */
5266         case '?':        /* Bad flag - print usage message */
5267             arg_error = TRUE;
5268             break;
5269         }
5270     }
5271     if (!arg_error) {
5272         argc -= ws_optind;
5273         argv += ws_optind;
5274         if (argc >= 1) {
5275             /* user specified file name as regular command-line argument */
5276             /* XXX - use it as the capture file name (or something else)? */
5277             argc--;
5278             argv++;
5279         }
5280         if (argc != 0) {
5281             /*
5282              * Extra command line arguments were specified; complain.
5283              * XXX - interpret as capture filter, as tcpdump and tshark do?
5284              */
5285             cmdarg_err("Invalid argument: %s", argv[0]);
5286             arg_error = TRUE;
5287         }
5288     }
5289 
5290     if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
5291         use_threads = TRUE;
5292     }
5293     if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
5294         /* Use some default if the user hasn't specified some */
5295         /* XXX: Are these defaults good enough? */
5296         pcap_queue_byte_limit = 1000 * 1000;
5297         pcap_queue_packet_limit = 1000;
5298     }
5299     if (arg_error) {
5300         print_usage(stderr);
5301         exit_main(1);
5302     }
5303 
5304     if (run_once_args > 1) {
5305         cmdarg_err("Only one of -D, -L, -d, -k or -S may be supplied.");
5306         exit_main(1);
5307     } else if (run_once_args == 1) {
5308         /* We're supposed to print some information, rather than
5309            to capture traffic; did they specify a ring buffer option? */
5310         if (global_capture_opts.multi_files_on) {
5311             cmdarg_err("Ring buffer requested, but a capture isn't being done.");
5312             exit_main(1);
5313         }
5314     } else {
5315         /* We're supposed to capture traffic; */
5316 
5317         /* Are we capturing on multiple interface? If so, use threads and pcapng. */
5318         if (global_capture_opts.ifaces->len > 1) {
5319             use_threads = TRUE;
5320             global_capture_opts.use_pcapng = TRUE;
5321         }
5322 
5323         if (capture_comments &&
5324             (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
5325             /* XXX - for ringbuffer, should we apply the comments to each file? */
5326             cmdarg_err("Capture comments can only be set if we capture into a single pcapng file.");
5327             exit_main(1);
5328         }
5329 
5330         /* Was the ring buffer option specified and, if so, does it make sense? */
5331         if (global_capture_opts.multi_files_on) {
5332             /* Ring buffer works only under certain conditions:
5333                a) ring buffer does not work with temporary files;
5334                b) it makes no sense to enable the ring buffer if the maximum
5335                file size is set to "infinite". */
5336             if (global_capture_opts.save_file == NULL) {
5337                 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
5338                 global_capture_opts.multi_files_on = FALSE;
5339             }
5340             if (!global_capture_opts.has_autostop_filesize &&
5341                 !global_capture_opts.has_file_duration &&
5342                 !global_capture_opts.has_file_interval &&
5343                 !global_capture_opts.has_file_packets) {
5344                 cmdarg_err("Ring buffer requested, but no maximum capture file size, duration "
5345                            "interval, or packets were specified.");
5346 #if 0
5347                 /* XXX - this must be redesigned as the conditions changed */
5348                 global_capture_opts.multi_files_on = FALSE;
5349 #endif
5350             }
5351             if (global_capture_opts.has_file_duration && global_capture_opts.has_file_interval) {
5352                 cmdarg_err("Ring buffer file duration and interval can't be used at the same time.");
5353                 exit_main(1);
5354             }
5355         }
5356     }
5357 
5358     /*
5359      * "-D" requires no interface to be selected; it's supposed to list
5360      * all interfaces.
5361      */
5362     if (list_interfaces) {
5363         /* Get the list of interfaces */
5364         GList *if_list;
5365         int    err;
5366         gchar *err_str;
5367 
5368         if_list = capture_interface_list(&err, &err_str, NULL);
5369         if (if_list == NULL) {
5370             if (err == 0) {
5371                 /*
5372                  * If we're being run by another program, just give them
5373                  * an empty list of interfaces, don't report this as
5374                  * an error; that lets them decide whether to report
5375                  * this as an error or not.
5376                  */
5377                 if (!machine_readable) {
5378                     cmdarg_err("There are no interfaces on which a capture can be done");
5379                     exit_main(2);
5380                 }
5381             } else {
5382                 cmdarg_err("%s", err_str);
5383                 g_free(err_str);
5384                 exit_main(2);
5385             }
5386         }
5387 
5388         if (machine_readable)      /* tab-separated values to stdout */
5389             print_machine_readable_interfaces(if_list);
5390         else
5391             capture_opts_print_interfaces(if_list);
5392         free_interface_list(if_list);
5393         exit_main(0);
5394     }
5395 
5396     /*
5397      * "-S" requires no interface to be selected; it gives statistics
5398      * for all interfaces.
5399      */
5400     if (print_statistics) {
5401         status = print_statistics_loop(machine_readable);
5402         exit_main(status);
5403     }
5404 
5405     if (set_chan) {
5406         interface_options *interface_opts;
5407 
5408         if (global_capture_opts.ifaces->len != 1) {
5409             cmdarg_err("Need one interface");
5410             exit_main(2);
5411         }
5412 
5413         interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, 0);
5414         status = set_80211_channel(interface_opts->name, set_chan_arg);
5415         exit_main(status);
5416     }
5417 
5418     /*
5419      * "-L", "-d", and capturing act on a particular interface, so we have to
5420      * have an interface; if none was specified, pick a default.
5421      */
5422     status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
5423     if (status != 0) {
5424         /* cmdarg_err() already called .... */
5425         exit_main(status);
5426     }
5427 
5428     if (caps_queries) {
5429         /* Get the list of link-layer and/or timestamp types for the capture device. */
5430         if_capabilities_t *caps;
5431         cap_device_open_status open_status;
5432         gchar *open_status_str;
5433         guint  ii;
5434 
5435         for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
5436             interface_options *interface_opts;
5437 
5438             interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, ii);
5439 
5440             caps = get_if_capabilities(interface_opts, &open_status, &open_status_str);
5441             if (caps == NULL) {
5442                 if (capture_child) {
5443                     char *error_msg = g_strdup_printf("The capabilities of the capture device "
5444                                                 "\"%s\" could not be obtained (%s)",
5445                                                 interface_opts->name, open_status_str);
5446                     sync_pipe_errmsg_to_parent(2, error_msg,
5447                             get_pcap_failure_secondary_error_message(open_status, open_status_str));
5448                     g_free(error_msg);
5449                 }
5450                 else {
5451                     cmdarg_err("The capabilities of the capture device "
5452                                 "\"%s\" could not be obtained (%s).\n%s",
5453                                 interface_opts->name, open_status_str,
5454                                 get_pcap_failure_secondary_error_message(open_status, open_status_str));
5455                 }
5456                 g_free(open_status_str);
5457                 exit_main(2);
5458             }
5459 
5460             if (machine_readable) {     /* tab-separated values to stdout */
5461                 /* XXX: We need to change the format and adapt consumers */
5462                 print_machine_readable_if_capabilities(caps, caps_queries);
5463                 status = 0;
5464 	    } else
5465                 /* XXX: We might want to print also the interface name */
5466                 status = capture_opts_print_if_capabilities(caps,
5467                                                             interface_opts,
5468                                                             caps_queries);
5469             free_if_capabilities(caps);
5470             if (status != 0)
5471                 break;
5472         }
5473         exit_main(status);
5474     }
5475 
5476 #ifdef HAVE_PCAP_SET_TSTAMP_TYPE
5477     for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5478         interface_options *interface_opts;
5479 
5480         interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5481         if (interface_opts->timestamp_type) {
5482             interface_opts->timestamp_type_id = pcap_tstamp_type_name_to_val(interface_opts->timestamp_type);
5483             if (interface_opts->timestamp_type_id < 0) {
5484                 cmdarg_err("Invalid argument to option: --time-stamp-type=%s", interface_opts->timestamp_type);
5485                 exit_main(1);
5486             }
5487         }
5488     }
5489 #endif
5490 
5491     /* We're supposed to do a capture, or print the BPF code for a filter. */
5492 
5493     /* Let the user know what interfaces were chosen. */
5494     if (capture_child) {
5495         for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5496             interface_options *interface_opts;
5497 
5498             interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5499             ws_debug("Interface: %s\n", interface_opts->name);
5500         }
5501     } else {
5502         str = g_string_new("");
5503 #ifdef _WIN32
5504         if (global_capture_opts.ifaces->len < 2)
5505 #else
5506         if (global_capture_opts.ifaces->len < 4)
5507 #endif
5508         {
5509             for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5510                 interface_options *interface_opts;
5511 
5512                 interface_opts = &g_array_index(global_capture_opts.ifaces, interface_options, j);
5513                 if (j > 0) {
5514                     if (global_capture_opts.ifaces->len > 2) {
5515                         g_string_append_printf(str, ",");
5516                     }
5517                     g_string_append_printf(str, " ");
5518                     if (j == global_capture_opts.ifaces->len - 1) {
5519                         g_string_append_printf(str, "and ");
5520                     }
5521                 }
5522                 if (interface_opts->ifname != NULL) {
5523                     /*
5524                      * Re-generate the display name based on the strins
5525                      * we were handed.
5526                      */
5527                     g_free(interface_opts->display_name);
5528                     if (interface_opts->descr != NULL) {
5529 #ifdef _WIN32
5530                         interface_opts->display_name = g_strdup_printf("%s",
5531                             interface_opts->descr);
5532 #else
5533                         interface_opts->display_name = g_strdup_printf("%s: %s",
5534                             interface_opts->descr, interface_opts->ifname);
5535 #endif
5536                     } else {
5537                         interface_opts->display_name = g_strdup_printf("%s",
5538                             interface_opts->ifname);
5539                     }
5540                 }
5541                 g_string_append_printf(str, "'%s'", interface_opts->display_name);
5542             }
5543         } else {
5544             g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
5545         }
5546         fprintf(stderr, "Capturing on %s\n", str->str);
5547         g_string_free(str, TRUE);
5548     }
5549 
5550     /* Process the snapshot length, as that affects the generated BPF code. */
5551     capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
5552 
5553     if (print_bpf_code) {
5554         show_filter_code(&global_capture_opts);
5555         exit_main(0);
5556     }
5557 
5558     /* We're supposed to do a capture.  Process the ring buffer arguments. */
5559     capture_opts_trim_ring_num_files(&global_capture_opts);
5560 
5561     /* flush stderr prior to starting the main capture loop */
5562     fflush(stderr);
5563 
5564     /* Now start the capture. */
5565     if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
5566         /* capture ok */
5567         exit_main(0);
5568     } else {
5569         /* capture failed */
5570         exit_main(1);
5571     }
5572     return 0; /* never here, make compiler happy */
5573 }
5574 
5575 static void
dumpcap_log_writer(const char * domain,enum ws_log_level level,ws_log_time_t timestamp,const char * file,int line,const char * func,const char * user_format,va_list user_ap,void * user_data _U_)5576 dumpcap_log_writer(const char *domain, enum ws_log_level level,
5577                                    ws_log_time_t timestamp,
5578                                    const char *file, int line, const char *func,
5579                                    const char *user_format, va_list user_ap,
5580                                    void *user_data _U_)
5581 {
5582     /* ignore log message, if log_level isn't interesting */
5583     if (level <= LOG_LEVEL_INFO) {
5584 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
5585         return;
5586 #endif
5587     }
5588 
5589     /* DEBUG & INFO msgs (if we're debugging today)                 */
5590 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
5591     if (level <= LOG_LEVEL_INFO && ws_log_msg_is_active(domain, level)) {
5592 #ifdef DEBUG_DUMPCAP
5593         ws_log_console_writer(domain, level, timestamp, file, line, func, user_format, user_ap, NULL);
5594 #endif
5595 #ifdef DEBUG_CHILD_DUMPCAP
5596         ws_log_file_writer(debug_log, domain, level, timestamp, file, line, func, user_format, user_ap, NULL);
5597 #endif
5598         return;
5599     }
5600 #endif
5601 
5602     /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or    */
5603     /*  to parent especially formatted if dumpcap running as child. */
5604     if (capture_child) {
5605         gchar *msg = g_strdup_vprintf(user_format, user_ap);
5606         sync_pipe_errmsg_to_parent(2, msg, "");
5607         g_free(msg);
5608     } else if(ws_log_msg_is_active(domain, level)) {
5609         ws_log_console_writer(domain, level, timestamp, file, line, func, user_format, user_ap);
5610     }
5611 }
5612 
5613 
5614 /****************************************************************************************************************/
5615 /* indication report routines */
5616 
5617 
5618 static void
report_packet_count(unsigned int packet_count)5619 report_packet_count(unsigned int packet_count)
5620 {
5621     char count_str[SP_DECISIZE+1+1];
5622     static unsigned int count = 0;
5623 
5624     if (capture_child) {
5625         g_snprintf(count_str, sizeof(count_str), "%u", packet_count);
5626         ws_debug("Packets: %s", count_str);
5627         pipe_write_block(2, SP_PACKET_COUNT, count_str);
5628     } else {
5629         count += packet_count;
5630         fprintf(stderr, "\rPackets: %u ", count);
5631         /* stderr could be line buffered */
5632         fflush(stderr);
5633     }
5634 }
5635 
5636 static void
report_new_capture_file(const char * filename)5637 report_new_capture_file(const char *filename)
5638 {
5639     if (capture_child) {
5640         ws_debug("File: %s", filename);
5641         if (global_ld.pcapng_passthrough) {
5642             /* Save filename for sending SP_FILE to capture parent after SHB is passed-through */
5643 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
5644             ws_info("Delaying SP_FILE until first SHB");
5645 #endif
5646             report_capture_filename = filename;
5647         } else {
5648             pipe_write_block(2, SP_FILE, filename);
5649         }
5650     } else {
5651 #ifdef SIGINFO
5652         /*
5653          * Prevent a SIGINFO handler from writing to the standard error
5654          * while we're doing so; instead, have it just set a flag telling
5655          * us to print that information when we're done.
5656          */
5657         infodelay = TRUE;
5658 #endif /* SIGINFO */
5659         fprintf(stderr, "File: %s\n", filename);
5660         /* stderr could be line buffered */
5661         fflush(stderr);
5662 
5663 #ifdef SIGINFO
5664         /*
5665          * Allow SIGINFO handlers to write.
5666          */
5667         infodelay = FALSE;
5668 
5669         /*
5670          * If a SIGINFO handler asked us to write out capture counts, do so.
5671          */
5672         if (infoprint)
5673           report_counts_for_siginfo();
5674 #endif /* SIGINFO */
5675     }
5676 }
5677 
5678 static void
report_cfilter_error(capture_options * capture_opts,guint i,const char * errmsg)5679 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
5680 {
5681     interface_options *interface_opts;
5682     char tmp[MSG_MAX_LENGTH+1+6];
5683 
5684     if (i < capture_opts->ifaces->len) {
5685         if (capture_child) {
5686             g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
5687             ws_debug("Capture filter error: %s", errmsg);
5688             pipe_write_block(2, SP_BAD_FILTER, tmp);
5689         } else {
5690             /*
5691              * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5692              * the error message below.
5693              */
5694             interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
5695             cmdarg_err(
5696               "Invalid capture filter \"%s\" for interface '%s'.\n"
5697               "\n"
5698               "That string isn't a valid capture filter (%s).\n"
5699               "See the User's Guide for a description of the capture filter syntax.",
5700               interface_opts->cfilter, interface_opts->name, errmsg);
5701         }
5702     }
5703 }
5704 
5705 static void
report_capture_error(const char * error_msg,const char * secondary_error_msg)5706 report_capture_error(const char *error_msg, const char *secondary_error_msg)
5707 {
5708     if (capture_child) {
5709         ws_debug("Primary Error: %s", error_msg);
5710         ws_debug("Secondary Error: %s", secondary_error_msg);
5711         sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5712     } else {
5713         cmdarg_err("%s", error_msg);
5714         if (secondary_error_msg[0] != '\0')
5715           cmdarg_err_cont("%s", secondary_error_msg);
5716     }
5717 }
5718 
5719 static void
report_packet_drops(guint32 received,guint32 pcap_drops,guint32 drops,guint32 flushed,guint32 ps_ifdrop,gchar * name)5720 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
5721 {
5722     guint32 total_drops = pcap_drops + drops + flushed;
5723 
5724     if (capture_child) {
5725         char* tmp = g_strdup_printf("%u:%s", total_drops, name);
5726 
5727         ws_debug("Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
5728             name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
5729         pipe_write_block(2, SP_DROPS, tmp);
5730         g_free(tmp);
5731     } else {
5732         fprintf(stderr,
5733             "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
5734             name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
5735             received ? 100.0 * received / (received + total_drops) : 0.0);
5736         /* stderr could be line buffered */
5737         fflush(stderr);
5738     }
5739 }
5740 
5741 
5742 /************************************************************************************************/
5743 /* signal_pipe handling */
5744 
5745 
5746 #ifdef _WIN32
5747 static gboolean
signal_pipe_check_running(void)5748 signal_pipe_check_running(void)
5749 {
5750     /* any news from our parent? -> just stop the capture */
5751     DWORD    avail = 0;
5752     gboolean result;
5753 
5754     /* if we are running standalone, no check required */
5755     if (!capture_child) {
5756         return TRUE;
5757     }
5758 
5759     if (!sig_pipe_name || !sig_pipe_handle) {
5760         /* This shouldn't happen */
5761         ws_info("Signal pipe: No name or handle");
5762         return FALSE;
5763     }
5764 
5765     /*
5766      * XXX - We should have the process ID of the parent (from the "-Z" flag)
5767      * at this point.  Should we check to see if the parent is still alive,
5768      * e.g. by using OpenProcess?
5769      */
5770 
5771     result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5772 
5773     if (!result || avail > 0) {
5774         /* peek failed or some bytes really available */
5775         /* (if not piping from stdin this would fail) */
5776         ws_info("Signal pipe: Stop capture: %s", sig_pipe_name);
5777         ws_debug("Signal pipe: %s (%p) result: %u avail: %lu", sig_pipe_name,
5778             sig_pipe_handle, result, avail);
5779         return FALSE;
5780     } else {
5781         /* pipe ok and no bytes available */
5782         return TRUE;
5783     }
5784 }
5785 #endif
5786 
5787 /*
5788  * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
5789  *
5790  * Local variables:
5791  * c-basic-offset: 4
5792  * tab-width: 8
5793  * indent-tabs-mode: nil
5794  * End:
5795  *
5796  * vi: set shiftwidth=4 tabstop=8 expandtab:
5797  * :indentSize=4:tabSize=8:noTabs=true:
5798  */
5799