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