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