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