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