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