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