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