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