Fix the description of dissector_try_uint_new().
[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 Mac 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: %u)\n", WTAP_MAX_PACKET_SIZE);
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;
2579 #ifndef _WIN32
2580     int    sel_ret;
2581 #endif
2582
2583     pcap_data = (guchar*)g_malloc(WTAP_MAX_PACKET_SIZE);
2584     packet_count_before = ld->packet_count;
2585     if (pcap_src->from_cap_pipe) {
2586         /* dispatch from capture pipe */
2587 #ifdef LOG_CAPTURE_VERBOSE
2588         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2589 #endif
2590 #ifndef _WIN32
2591         sel_ret = cap_pipe_select(pcap_src->cap_pipe_fd);
2592         if (sel_ret <= 0) {
2593             if (sel_ret < 0 && errno != EINTR) {
2594                 g_snprintf(errmsg, errmsg_len,
2595                            "Unexpected error from select: %s", g_strerror(errno));
2596                 report_capture_error(errmsg, please_report);
2597                 ld->go = FALSE;
2598             }
2599         } else {
2600             /*
2601              * "select()" says we can read from the pipe without blocking
2602              */
2603 #endif
2604             inpkts = cap_pipe_dispatch(ld, pcap_src, pcap_data, errmsg, errmsg_len);
2605             if (inpkts < 0) {
2606                 ld->go = FALSE;
2607             }
2608 #ifndef _WIN32
2609         }
2610 #endif
2611     }
2612     else
2613     {
2614         /* dispatch from pcap */
2615 #ifdef MUST_DO_SELECT
2616         /*
2617          * If we have "pcap_get_selectable_fd()", we use it to get the
2618          * descriptor on which to select; if that's -1, it means there
2619          * is no descriptor on which you can do a "select()" (perhaps
2620          * because you're capturing on a special device, and that device's
2621          * driver unfortunately doesn't support "select()", in which case
2622          * we don't do the select - which means it might not be possible
2623          * to stop a capture until a packet arrives.  If that's unacceptable,
2624          * plead with whoever supplies the software for that device to add
2625          * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2626          * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2627          * later, so it can use pcap_breakloop().
2628          */
2629 #ifdef LOG_CAPTURE_VERBOSE
2630         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2631 #endif
2632         if (pcap_src->pcap_fd != -1) {
2633             sel_ret = cap_pipe_select(pcap_src->pcap_fd);
2634             if (sel_ret > 0) {
2635                 /*
2636                  * "select()" says we can read from it without blocking; go for
2637                  * it.
2638                  *
2639                  * We don't have pcap_breakloop(), so we only process one packet
2640                  * per pcap_dispatch() call, to allow a signal to stop the
2641                  * processing immediately, rather than processing all packets
2642                  * in a batch before quitting.
2643                  */
2644                 if (use_threads) {
2645                     inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
2646                 } else {
2647                     inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
2648                 }
2649                 if (inpkts < 0) {
2650                     if (inpkts == -1) {
2651                         /* Error, rather than pcap_breakloop(). */
2652                         pcap_src->pcap_err = TRUE;
2653                     }
2654                     ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2655                 }
2656             } else {
2657                 if (sel_ret < 0 && errno != EINTR) {
2658                     g_snprintf(errmsg, errmsg_len,
2659                                "Unexpected error from select: %s", g_strerror(errno));
2660                     report_capture_error(errmsg, please_report);
2661                     ld->go = FALSE;
2662                 }
2663             }
2664         }
2665         else
2666 #endif /* MUST_DO_SELECT */
2667         {
2668             /* dispatch from pcap without select */
2669 #if 1
2670 #ifdef LOG_CAPTURE_VERBOSE
2671             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2672 #endif
2673 #ifdef _WIN32
2674             /*
2675              * On Windows, we don't support asynchronously telling a process to
2676              * stop capturing; instead, we check for an indication on a pipe
2677              * after processing packets.  We therefore process only one packet
2678              * at a time, so that we can check the pipe after every packet.
2679              */
2680             if (use_threads) {
2681                 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
2682             } else {
2683                 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
2684             }
2685 #else
2686             if (use_threads) {
2687                 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
2688             } else {
2689                 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_src);
2690             }
2691 #endif
2692             if (inpkts < 0) {
2693                 if (inpkts == -1) {
2694                     /* Error, rather than pcap_breakloop(). */
2695                     pcap_src->pcap_err = TRUE;
2696                 }
2697                 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2698             }
2699 #else /* pcap_next_ex */
2700 #ifdef LOG_CAPTURE_VERBOSE
2701             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2702 #endif
2703             /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2704
2705             /*
2706              * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2707              * see https://wiki.wireshark.org/CaptureSetup/WinPcapRemote
2708              * This should be fixed in the WinPcap 4.0 alpha release.
2709              *
2710              * For reference, an example remote interface:
2711              * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2712              */
2713
2714             /* emulate dispatch from pcap */
2715             {
2716                 int in;
2717                 struct pcap_pkthdr *pkt_header;
2718                 u_char *pkt_data;
2719
2720                 in = 0;
2721                 while(ld->go &&
2722                       (in = pcap_next_ex(pcap_src->pcap_h, &pkt_header, &pkt_data)) == 1) {
2723                     if (use_threads) {
2724                         capture_loop_queue_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
2725                     } else {
2726                         capture_loop_write_packet_cb((u_char *)pcap_src, pkt_header, pkt_data);
2727                     }
2728                 }
2729
2730                 if (in < 0) {
2731                     pcap_src->pcap_err = TRUE;
2732                     ld->go = FALSE;
2733                 }
2734             }
2735 #endif /* pcap_next_ex */
2736         }
2737     }
2738
2739 #ifdef LOG_CAPTURE_VERBOSE
2740     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2741 #endif
2742
2743     g_free(pcap_data);
2744     return ld->packet_count - packet_count_before;
2745 }
2746
2747 #ifdef _WIN32
2748 /* Isolate the Universally Unique Identifier from the interface.  Basically, we
2749  * want to grab only the characters between the '{' and '}' delimiters.
2750  *
2751  * Returns a GString that must be freed with g_string_free(). */
2752 static GString *
2753 isolate_uuid(const char *iface)
2754 {
2755     gchar   *ptr;
2756     GString *gstr;
2757
2758     ptr = strchr(iface, '{');
2759     if (ptr == NULL)
2760         return g_string_new(iface);
2761     gstr = g_string_new(ptr + 1);
2762
2763     ptr = strchr(gstr->str, '}');
2764     if (ptr == NULL)
2765         return gstr;
2766
2767     gstr = g_string_truncate(gstr, ptr - gstr->str);
2768     return gstr;
2769 }
2770 #endif
2771
2772 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2773 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2774 static gboolean
2775 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2776                          char *errmsg, int errmsg_len)
2777 {
2778     char     *tmpname;
2779     gchar    *capfile_name;
2780     gchar    *prefix, *suffix;
2781     gboolean  is_tempfile;
2782
2783     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2784           (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
2785
2786     if (capture_opts->save_file != NULL) {
2787         /* We return to the caller while the capture is in progress.
2788          * Therefore we need to take a copy of save_file in
2789          * case the caller destroys it after we return.
2790          */
2791         capfile_name = g_strdup(capture_opts->save_file);
2792
2793         if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2794             if (capture_opts->multi_files_on) {
2795                 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2796                 g_snprintf(errmsg, errmsg_len,
2797                            "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2798                 g_free(capfile_name);
2799                 return FALSE;
2800             }
2801             if (strcmp(capfile_name, "-") == 0) {
2802                 /* write to stdout */
2803                 *save_file_fd = 1;
2804 #ifdef _WIN32
2805                 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF)  */
2806                 _setmode(1, O_BINARY);
2807 #endif
2808             }
2809         } /* if (...output_to_pipe ... */
2810
2811         else {
2812             if (capture_opts->multi_files_on) {
2813                 /* ringbuffer is enabled */
2814                 *save_file_fd = ringbuf_init(capfile_name,
2815                                              (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
2816                                              capture_opts->group_read_access);
2817
2818                 /* we need the ringbuf name */
2819                 if (*save_file_fd != -1) {
2820                     g_free(capfile_name);
2821                     capfile_name = g_strdup(ringbuf_current_filename());
2822                 }
2823             } else {
2824                 /* Try to open/create the specified file for use as a capture buffer. */
2825                 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
2826                                         (capture_opts->group_read_access) ? 0640 : 0600);
2827             }
2828         }
2829         is_tempfile = FALSE;
2830     } else {
2831         /* Choose a random name for the temporary capture buffer */
2832         if (global_capture_opts.ifaces->len > 1) {
2833             prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
2834             if (capture_opts->use_pcapng) {
2835                 suffix = ".pcapng";
2836             }else{
2837                 suffix = ".pcap";
2838             }
2839         } else {
2840             gchar *basename;
2841             basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
2842 #ifdef _WIN32
2843             /* use the generic portion of the interface guid to form the basis of the filename */
2844             if (strncmp("NPF_{", basename, 5)==0)
2845             {
2846                 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
2847                 GString *iface;
2848                 iface = isolate_uuid(basename);
2849                 g_free(basename);
2850                 basename = g_strdup(iface->str);
2851                 g_string_free(iface, TRUE);
2852             }
2853 #endif
2854             /* generate the temp file name prefix and suffix */
2855             if (capture_opts->use_pcapng) {
2856                 prefix = g_strconcat("wireshark_", basename, NULL);
2857                 suffix = ".pcapng";
2858             }else{
2859                 prefix = g_strconcat("wireshark_", basename, NULL);
2860                 suffix = ".pcap";
2861             }
2862             g_free(basename);
2863         }
2864         *save_file_fd = create_tempfile(&tmpname, prefix, suffix);
2865         g_free(prefix);
2866         capfile_name = g_strdup(tmpname);
2867         is_tempfile = TRUE;
2868     }
2869
2870     /* did we fail to open the output file? */
2871     if (*save_file_fd == -1) {
2872         if (is_tempfile) {
2873             g_snprintf(errmsg, errmsg_len,
2874                        "The temporary file to which the capture would be saved (\"%s\") "
2875                        "could not be opened: %s.", capfile_name, g_strerror(errno));
2876         } else {
2877             if (capture_opts->multi_files_on) {
2878                 ringbuf_error_cleanup();
2879             }
2880
2881             g_snprintf(errmsg, errmsg_len,
2882                        "The file to which the capture would be saved (\"%s\") "
2883                        "could not be opened: %s.", capfile_name,
2884                        g_strerror(errno));
2885         }
2886         g_free(capfile_name);
2887         return FALSE;
2888     }
2889
2890     if (capture_opts->save_file != NULL) {
2891         g_free(capture_opts->save_file);
2892     }
2893     capture_opts->save_file = capfile_name;
2894     /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2895        "g_free(capfile_name)". */
2896
2897     return TRUE;
2898 }
2899
2900
2901 /* Do the work of handling either the file size or file duration capture
2902    conditions being reached, and switching files or stopping. */
2903 static gboolean
2904 do_file_switch_or_stop(capture_options *capture_opts,
2905                        condition *cnd_autostop_files,
2906                        condition *cnd_autostop_size,
2907                        condition *cnd_file_duration)
2908 {
2909     guint             i;
2910     capture_src      *pcap_src;
2911     interface_options interface_opts;
2912     gboolean          successful;
2913
2914     if (capture_opts->multi_files_on) {
2915         if (cnd_autostop_files != NULL &&
2916             cnd_eval(cnd_autostop_files, (guint64)++global_ld.autostop_files)) {
2917             /* no files left: stop here */
2918             global_ld.go = FALSE;
2919             return FALSE;
2920         }
2921
2922         /* Switch to the next ringbuffer file */
2923         if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2924                                 &global_ld.save_file_fd, &global_ld.err)) {
2925
2926             /* File switch succeeded: reset the conditions */
2927             global_ld.bytes_written = 0;
2928             if (capture_opts->use_pcapng) {
2929                 char    *appname;
2930                 GString *cpu_info_str;
2931                 GString *os_info_str;
2932
2933                 cpu_info_str = g_string_new("");
2934                 os_info_str = g_string_new("");
2935                 get_cpu_info(cpu_info_str);
2936                 get_os_version_info(os_info_str);
2937
2938                 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2939                 successful = pcapng_write_session_header_block(global_ld.pdh,
2940                                 (const char *)capture_opts->capture_comment,   /* Comment */
2941                                 cpu_info_str->str,           /* HW */
2942                                 os_info_str->str,            /* OS */
2943                                 appname,
2944                                 -1,                          /* section_length */
2945                                 &(global_ld.bytes_written),
2946                                 &global_ld.err);
2947                 g_free(appname);
2948
2949                 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2950                     interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2951                     pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
2952                     successful = pcapng_write_interface_description_block(global_ld.pdh,
2953                                                                           NULL,                       /* OPT_COMMENT       1 */
2954                                                                           interface_opts.name,        /* IDB_NAME          2 */
2955                                                                           interface_opts.descr,       /* IDB_DESCRIPTION   3 */
2956                                                                           interface_opts.cfilter,     /* IDB_FILTER       11 */
2957                                                                           os_info_str->str,           /* IDB_OS           12 */
2958                                                                           pcap_src->linktype,
2959                                                                           pcap_src->snaplen,
2960                                                                           &(global_ld.bytes_written),
2961                                                                           0,                          /* IDB_IF_SPEED      8 */
2962                                                                           pcap_src->ts_nsec ? 9 : 6, /* IDB_TSRESOL       9 */
2963                                                                           &global_ld.err);
2964                 }
2965
2966                 g_string_free(os_info_str, TRUE);
2967
2968             } else {
2969                 pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
2970                 successful = libpcap_write_file_header(global_ld.pdh, pcap_src->linktype, pcap_src->snaplen,
2971                                                        pcap_src->ts_nsec, &global_ld.bytes_written, &global_ld.err);
2972             }
2973             if (!successful) {
2974                 fclose(global_ld.pdh);
2975                 global_ld.pdh = NULL;
2976                 global_ld.go = FALSE;
2977                 return FALSE;
2978             }
2979             if (cnd_autostop_size)
2980                 cnd_reset(cnd_autostop_size);
2981             if (cnd_file_duration)
2982                 cnd_reset(cnd_file_duration);
2983             fflush(global_ld.pdh);
2984             if (!quiet)
2985                 report_packet_count(global_ld.inpkts_to_sync_pipe);
2986             global_ld.inpkts_to_sync_pipe = 0;
2987             report_new_capture_file(capture_opts->save_file);
2988         } else {
2989             /* File switch failed: stop here */
2990             global_ld.go = FALSE;
2991             return FALSE;
2992         }
2993     } else {
2994         /* single file, stop now */
2995         global_ld.go = FALSE;
2996         return FALSE;
2997     }
2998     return TRUE;
2999 }
3000
3001 static void *
3002 pcap_read_handler(void* arg)
3003 {
3004     capture_src *pcap_src;
3005     char         errmsg[MSG_MAX_LENGTH+1];
3006
3007     pcap_src = (capture_src *)arg;
3008
3009     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3010           pcap_src->interface_id);
3011
3012     while (global_ld.go) {
3013         /* dispatch incoming packets */
3014         capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_src);
3015     }
3016     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3017           pcap_src->interface_id);
3018     g_thread_exit(NULL);
3019     return (NULL);
3020 }
3021
3022 /* Do the low-level work of a capture.
3023    Returns TRUE if it succeeds, FALSE otherwise. */
3024 static gboolean
3025 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3026 {
3027 #ifdef _WIN32
3028     DWORD             upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3029 #else
3030     struct timeval    upd_time, cur_time;
3031 #endif
3032     int               err_close;
3033     int               inpkts;
3034     condition        *cnd_file_duration     = NULL;
3035     condition        *cnd_autostop_files    = NULL;
3036     condition        *cnd_autostop_size     = NULL;
3037     condition        *cnd_autostop_duration = NULL;
3038     gboolean          write_ok;
3039     gboolean          close_ok;
3040     gboolean          cfilter_error         = FALSE;
3041     char              errmsg[MSG_MAX_LENGTH+1];
3042     char              secondary_errmsg[MSG_MAX_LENGTH+1];
3043     capture_src      *pcap_src;
3044     interface_options interface_opts;
3045     guint             i, error_index        = 0;
3046
3047     *errmsg           = '\0';
3048     *secondary_errmsg = '\0';
3049
3050     /* init the loop data */
3051     global_ld.go                  = TRUE;
3052     global_ld.packet_count        = 0;
3053 #ifdef SIGINFO
3054     global_ld.report_packet_count = FALSE;
3055 #endif
3056     if (capture_opts->has_autostop_packets)
3057         global_ld.packet_max      = capture_opts->autostop_packets;
3058     else
3059         global_ld.packet_max      = 0;        /* no limit */
3060     global_ld.inpkts_to_sync_pipe = 0;
3061     global_ld.err                 = 0;  /* no error seen yet */
3062     global_ld.pdh                 = NULL;
3063     global_ld.autostop_files      = 0;
3064     global_ld.save_file_fd        = -1;
3065
3066     /* We haven't yet gotten the capture statistics. */
3067     *stats_known      = FALSE;
3068
3069     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3070     capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3071
3072     /* open the "input file" from network interface or capture pipe */
3073     if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3074                                  secondary_errmsg, sizeof(secondary_errmsg))) {
3075         goto error;
3076     }
3077     for (i = 0; i < capture_opts->ifaces->len; i++) {
3078         pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3079         interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3080         /* init the input filter from the network interface (capture pipe will do nothing) */
3081         /*
3082          * When remote capturing WinPCap crashes when the capture filter
3083          * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3084          * string.
3085          */
3086         switch (capture_loop_init_filter(pcap_src->pcap_h, pcap_src->from_cap_pipe,
3087                                          interface_opts.name,
3088                                          interface_opts.cfilter?interface_opts.cfilter:"")) {
3089
3090         case INITFILTER_NO_ERROR:
3091             break;
3092
3093         case INITFILTER_BAD_FILTER:
3094             cfilter_error = TRUE;
3095             error_index = i;
3096             g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_src->pcap_h));
3097             goto error;
3098
3099         case INITFILTER_OTHER_ERROR:
3100             g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3101                        pcap_geterr(pcap_src->pcap_h));
3102             g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3103             goto error;
3104         }
3105     }
3106
3107     /* If we're supposed to write to a capture file, open it for output
3108        (temporary/specified name/ringbuffer) */
3109     if (capture_opts->saving_to_file) {
3110         if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3111                                       errmsg, sizeof(errmsg))) {
3112             goto error;
3113         }
3114
3115         /* set up to write to the already-opened capture output file/files */
3116         if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3117                                       sizeof(errmsg))) {
3118             goto error;
3119         }
3120
3121         /* XXX - capture SIGTERM and close the capture, in case we're on a
3122            Linux 2.0[.x] system and you have to explicitly close the capture
3123            stream in order to turn promiscuous mode off?  We need to do that
3124            in other places as well - and I don't think that works all the
3125            time in any case, due to libpcap bugs. */
3126
3127         /* Well, we should be able to start capturing.
3128
3129            Sync out the capture file, so the header makes it to the file system,
3130            and send a "capture started successfully and capture file created"
3131            message to our parent so that they'll open the capture file and
3132            update its windows to indicate that we have a live capture in
3133            progress. */
3134         fflush(global_ld.pdh);
3135         report_new_capture_file(capture_opts->save_file);
3136     }
3137
3138     /* initialize capture stop (and alike) conditions */
3139     init_capture_stop_conditions();
3140     /* create stop conditions */
3141     if (capture_opts->has_autostop_filesize) {
3142         if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3143             capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3144         }
3145         cnd_autostop_size =
3146             cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1000);
3147     }
3148     if (capture_opts->has_autostop_duration)
3149         cnd_autostop_duration =
3150             cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3151
3152     if (capture_opts->multi_files_on) {
3153         if (capture_opts->has_file_duration)
3154             cnd_file_duration =
3155                 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3156
3157         if (capture_opts->has_autostop_files)
3158             cnd_autostop_files =
3159                 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_files);
3160     }
3161
3162     /* init the time values */
3163 #ifdef _WIN32
3164     upd_time = GetTickCount();
3165 #else
3166     gettimeofday(&upd_time, NULL);
3167 #endif
3168     start_time = create_timestamp();
3169     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3170     capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3171
3172     /* WOW, everything is prepared! */
3173     /* please fasten your seat belts, we will enter now the actual capture loop */
3174     if (use_threads) {
3175         pcap_queue = g_async_queue_new();
3176         pcap_queue_bytes = 0;
3177         pcap_queue_packets = 0;
3178         for (i = 0; i < global_ld.pcaps->len; i++) {
3179             pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3180 #if GLIB_CHECK_VERSION(2,31,0)
3181             /* XXX - Add an interface name here? */
3182             pcap_src->tid = g_thread_new("Capture read", pcap_read_handler, pcap_src);
3183 #else
3184             pcap_src->tid = g_thread_create(pcap_read_handler, pcap_src, TRUE, NULL);
3185 #endif
3186         }
3187     }
3188     while (global_ld.go) {
3189         /* dispatch incoming packets */
3190         if (use_threads) {
3191             pcap_queue_element *queue_element;
3192 #if GLIB_CHECK_VERSION(2,31,18)
3193
3194             g_async_queue_lock(pcap_queue);
3195             queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3196 #else
3197             GTimeVal write_thread_time;
3198
3199             g_get_current_time(&write_thread_time);
3200             g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3201             g_async_queue_lock(pcap_queue);
3202             queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3203 #endif
3204             if (queue_element) {
3205                 pcap_queue_bytes -= queue_element->phdr.caplen;
3206                 pcap_queue_packets -= 1;
3207             }
3208             g_async_queue_unlock(pcap_queue);
3209             if (queue_element) {
3210                 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3211                       "Dequeued a packet of length %d captured on interface %d.",
3212                       queue_element->phdr.caplen, queue_element->pcap_src->interface_id);
3213
3214                 capture_loop_write_packet_cb((u_char *) queue_element->pcap_src,
3215                                              &queue_element->phdr,
3216                                              queue_element->pd);
3217                 g_free(queue_element->pd);
3218                 g_free(queue_element);
3219                 inpkts = 1;
3220             } else {
3221                 inpkts = 0;
3222             }
3223         } else {
3224             pcap_src = g_array_index(global_ld.pcaps, capture_src *, 0);
3225             inpkts = capture_loop_dispatch(&global_ld, errmsg,
3226                                            sizeof(errmsg), pcap_src);
3227         }
3228 #ifdef SIGINFO
3229         /* Were we asked to print packet counts by the SIGINFO handler? */
3230         if (global_ld.report_packet_count) {
3231             fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3232                     plurality(global_ld.packet_count, "", "s"));
3233             global_ld.report_packet_count = FALSE;
3234         }
3235 #endif
3236
3237 #ifdef _WIN32
3238         /* any news from our parent (signal pipe)? -> just stop the capture */
3239         if (!signal_pipe_check_running()) {
3240             global_ld.go = FALSE;
3241         }
3242 #endif
3243
3244         if (inpkts > 0) {
3245             global_ld.inpkts_to_sync_pipe += inpkts;
3246
3247             /* check capture size condition */
3248             if (cnd_autostop_size != NULL &&
3249                 cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
3250                 /* Capture size limit reached, do we have another file? */
3251                 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3252                                             cnd_autostop_size, cnd_file_duration))
3253                     continue;
3254             } /* cnd_autostop_size */
3255             if (capture_opts->output_to_pipe) {
3256                 fflush(global_ld.pdh);
3257             }
3258         } /* inpkts */
3259
3260         /* Only update once every 500ms so as not to overload slow displays.
3261          * This also prevents too much context-switching between the dumpcap
3262          * and wireshark processes.
3263          */
3264 #define DUMPCAP_UPD_TIME 500
3265
3266 #ifdef _WIN32
3267         cur_time = GetTickCount();  /* Note: wraps to 0 if sys runs for 49.7 days */
3268         if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3269 #else
3270         gettimeofday(&cur_time, NULL);
3271         if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3272             ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3273 #endif
3274
3275             upd_time = cur_time;
3276
3277 #if 0
3278             if (pcap_stats(pch, stats) >= 0) {
3279                 *stats_known = TRUE;
3280             }
3281 #endif
3282             /* Let the parent process know. */
3283             if (global_ld.inpkts_to_sync_pipe) {
3284                 /* do sync here */
3285                 fflush(global_ld.pdh);
3286
3287                 /* Send our parent a message saying we've written out
3288                    "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3289                 if (!quiet)
3290                     report_packet_count(global_ld.inpkts_to_sync_pipe);
3291
3292                 global_ld.inpkts_to_sync_pipe = 0;
3293             }
3294
3295             /* check capture duration condition */
3296             if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3297                 /* The maximum capture time has elapsed; stop the capture. */
3298                 global_ld.go = FALSE;
3299                 continue;
3300             }
3301
3302             /* check capture file duration condition */
3303             if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3304                 /* duration limit reached, do we have another file? */
3305                 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3306                                             cnd_autostop_size, cnd_file_duration))
3307                     continue;
3308             } /* cnd_file_duration */
3309         }
3310     }
3311
3312     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3313     if (use_threads) {
3314         pcap_queue_element *queue_element;
3315
3316         for (i = 0; i < global_ld.pcaps->len; i++) {
3317             pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3318             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3319                   pcap_src->interface_id);
3320             g_thread_join(pcap_src->tid);
3321             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3322                   pcap_src->interface_id);
3323         }
3324         while (1) {
3325             g_async_queue_lock(pcap_queue);
3326             queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3327             if (queue_element) {
3328                 pcap_queue_bytes -= queue_element->phdr.caplen;
3329                 pcap_queue_packets -= 1;
3330             }
3331             g_async_queue_unlock(pcap_queue);
3332             if (queue_element == NULL) {
3333                 break;
3334             }
3335             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3336                   "Dequeued a packet of length %d captured on interface %d.",
3337                   queue_element->phdr.caplen, queue_element->pcap_src->interface_id);
3338             capture_loop_write_packet_cb((u_char *)queue_element->pcap_src,
3339                                          &queue_element->phdr,
3340                                          queue_element->pd);
3341             g_free(queue_element->pd);
3342             g_free(queue_element);
3343             global_ld.inpkts_to_sync_pipe += 1;
3344             if (capture_opts->output_to_pipe) {
3345                 fflush(global_ld.pdh);
3346             }
3347         }
3348     }
3349
3350
3351     /* delete stop conditions */
3352     if (cnd_file_duration != NULL)
3353         cnd_delete(cnd_file_duration);
3354     if (cnd_autostop_files != NULL)
3355         cnd_delete(cnd_autostop_files);
3356     if (cnd_autostop_size != NULL)
3357         cnd_delete(cnd_autostop_size);
3358     if (cnd_autostop_duration != NULL)
3359         cnd_delete(cnd_autostop_duration);
3360
3361     /* did we have a pcap (input) error? */
3362     for (i = 0; i < capture_opts->ifaces->len; i++) {
3363         pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3364         if (pcap_src->pcap_err) {
3365             /* On Linux, if an interface goes down while you're capturing on it,
3366                you'll get a "recvfrom: Network is down" or
3367                "The interface went down" error (ENETDOWN).
3368                (At least you will if g_strerror() doesn't show a local translation
3369                of the error.)
3370
3371                On FreeBSD and macOS, if a network adapter disappears while
3372                you're capturing on it, you'll get a "read: Device not configured"
3373                error (ENXIO).  (See previous parenthetical note.)
3374
3375                On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3376
3377                These should *not* be reported to the Wireshark developers. */
3378             char *cap_err_str;
3379
3380             cap_err_str = pcap_geterr(pcap_src->pcap_h);
3381             if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3382                 strcmp(cap_err_str, "The interface went down") == 0 ||
3383                 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3384                 strcmp(cap_err_str, "read: I/O error") == 0 ||
3385                 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3386                 report_capture_error("The network adapter on which the capture was being done "
3387                                      "is no longer running; the capture has stopped.",
3388                                      "");
3389             } else {
3390                 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3391                            cap_err_str);
3392                 report_capture_error(errmsg, please_report);
3393             }
3394             break;
3395         } else if (pcap_src->from_cap_pipe && pcap_src->cap_pipe_err == PIPERR) {
3396             report_capture_error(errmsg, "");
3397             break;
3398         }
3399     }
3400     /* did we have an output error while capturing? */
3401     if (global_ld.err == 0) {
3402         write_ok = TRUE;
3403     } else {
3404         capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3405                                 global_ld.err, FALSE);
3406         report_capture_error(errmsg, please_report);
3407         write_ok = FALSE;
3408     }
3409
3410     if (capture_opts->saving_to_file) {
3411         /* close the output file */
3412         close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3413     } else
3414         close_ok = TRUE;
3415
3416     /* there might be packets not yet notified to the parent */
3417     /* (do this after closing the file, so all packets are already flushed) */
3418     if (global_ld.inpkts_to_sync_pipe) {
3419         if (!quiet)
3420             report_packet_count(global_ld.inpkts_to_sync_pipe);
3421         global_ld.inpkts_to_sync_pipe = 0;
3422     }
3423
3424     /* If we've displayed a message about a write error, there's no point
3425        in displaying another message about an error on close. */
3426     if (!close_ok && write_ok) {
3427         capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3428                                 TRUE);
3429         report_capture_error(errmsg, "");
3430     }
3431
3432     /*
3433      * XXX We exhibit different behaviour between normal mode and sync mode
3434      * when the pipe is stdin and not already at EOF.  If we're a child, the
3435      * parent's stdin isn't closed, so if the user starts another capture,
3436      * cap_pipe_open_live() will very likely not see the expected magic bytes and
3437      * will say "Unrecognized libpcap format".  On the other hand, in normal
3438      * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3439      */
3440
3441     report_capture_count(TRUE);
3442
3443     /* get packet drop statistics from pcap */
3444     for (i = 0; i < capture_opts->ifaces->len; i++) {
3445         guint32 received;
3446         guint32 pcap_dropped = 0;
3447
3448         pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3449         interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3450         received = pcap_src->received;
3451         if (pcap_src->pcap_h != NULL) {
3452             g_assert(!pcap_src->from_cap_pipe);
3453             /* Get the capture statistics, so we know how many packets were dropped. */
3454             /*
3455              * Older versions of libpcap didn't set ps_ifdrop on some
3456              * platforms; initialize it to 0 to handle that.
3457              */
3458             stats->ps_ifdrop = 0;
3459             if (pcap_stats(pcap_src->pcap_h, stats) >= 0) {
3460                 *stats_known = TRUE;
3461                 /* Let the parent process know. */
3462                 pcap_dropped += stats->ps_drop;
3463             } else {
3464                 g_snprintf(errmsg, sizeof(errmsg),
3465                            "Can't get packet-drop statistics: %s",
3466                            pcap_geterr(pcap_src->pcap_h));
3467                 report_capture_error(errmsg, please_report);
3468             }
3469         }
3470         report_packet_drops(received, pcap_dropped, pcap_src->dropped, pcap_src->flushed, stats->ps_ifdrop, interface_opts.console_display_name);
3471     }
3472
3473     /* close the input file (pcap or capture pipe) */
3474     capture_loop_close_input(&global_ld);
3475
3476     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
3477
3478     /* ok, if the write and the close were successful. */
3479     return write_ok && close_ok;
3480
3481 error:
3482     if (capture_opts->multi_files_on) {
3483         /* cleanup ringbuffer */
3484         ringbuf_error_cleanup();
3485     } else {
3486         /* We can't use the save file, and we have no FILE * for the stream
3487            to close in order to close it, so close the FD directly. */
3488         if (global_ld.save_file_fd != -1) {
3489             ws_close(global_ld.save_file_fd);
3490         }
3491
3492         /* We couldn't even start the capture, so get rid of the capture
3493            file. */
3494         if (capture_opts->save_file != NULL) {
3495             ws_unlink(capture_opts->save_file);
3496             g_free(capture_opts->save_file);
3497         }
3498     }
3499     capture_opts->save_file = NULL;
3500     if (cfilter_error)
3501         report_cfilter_error(capture_opts, error_index, errmsg);
3502     else
3503         report_capture_error(errmsg, secondary_errmsg);
3504
3505     /* close the input file (pcap or cap_pipe) */
3506     capture_loop_close_input(&global_ld);
3507
3508     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3509
3510     return FALSE;
3511 }
3512
3513
3514 static void
3515 capture_loop_stop(void)
3516 {
3517 #ifdef HAVE_PCAP_BREAKLOOP
3518     guint        i;
3519     capture_src *pcap_src;
3520
3521     for (i = 0; i < global_ld.pcaps->len; i++) {
3522         pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3523         if (pcap_src->pcap_h != NULL)
3524             pcap_breakloop(pcap_src->pcap_h);
3525     }
3526 #endif
3527     global_ld.go = FALSE;
3528 }
3529
3530
3531 static void
3532 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3533                         int err, gboolean is_close)
3534 {
3535     switch (err) {
3536
3537     case ENOSPC:
3538         g_snprintf(errmsg, errmsglen,
3539                    "Not all the packets could be written to the file"
3540                    " to which the capture was being saved\n"
3541                    "(\"%s\") because there is no space left on the file system\n"
3542                    "on which that file resides.",
3543                    fname);
3544         break;
3545
3546 #ifdef EDQUOT
3547     case EDQUOT:
3548         g_snprintf(errmsg, errmsglen,
3549                    "Not all the packets could be written to the file"
3550                    " to which the capture was being saved\n"
3551                    "(\"%s\") because you are too close to, or over,"
3552                    " your disk quota\n"
3553                    "on the file system on which that file resides.",
3554                    fname);
3555         break;
3556 #endif
3557
3558     default:
3559         if (is_close) {
3560             g_snprintf(errmsg, errmsglen,
3561                        "The file to which the capture was being saved\n"
3562                        "(\"%s\") could not be closed: %s.",
3563                        fname, g_strerror(err));
3564         } else {
3565             g_snprintf(errmsg, errmsglen,
3566                        "An error occurred while writing to the file"
3567                        " to which the capture was being saved\n"
3568                        "(\"%s\"): %s.",
3569                        fname, g_strerror(err));
3570         }
3571         break;
3572     }
3573 }
3574
3575
3576 /* one packet was captured, process it */
3577 static void
3578 capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
3579                              const u_char *pd)
3580 {
3581     capture_src *pcap_src = (capture_src *) (void *) pcap_src_p;
3582     int          err;
3583     guint        ts_mul    = pcap_src->ts_nsec ? 1000000000 : 1000000;
3584
3585     /* We may be called multiple times from pcap_dispatch(); if we've set
3586        the "stop capturing" flag, ignore this packet, as we're not
3587        supposed to be saving any more packets. */
3588     if (!global_ld.go) {
3589         pcap_src->flushed++;
3590         return;
3591     }
3592
3593     if (global_ld.pdh) {
3594         gboolean successful;
3595
3596         /* We're supposed to write the packet to a file; do so.
3597            If this fails, set "ld->go" to FALSE, to stop the capture, and set
3598            "ld->err" to the error. */
3599         if (global_capture_opts.use_pcapng) {
3600             successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
3601                                                             NULL,
3602                                                             phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
3603                                                             phdr->caplen, phdr->len,
3604                                                             pcap_src->interface_id,
3605                                                             ts_mul,
3606                                                             pd, 0,
3607                                                             &global_ld.bytes_written, &err);
3608         } else {
3609             successful = libpcap_write_packet(global_ld.pdh,
3610                                               phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
3611                                               phdr->caplen, phdr->len,
3612                                               pd,
3613                                               &global_ld.bytes_written, &err);
3614         }
3615         if (!successful) {
3616             global_ld.go = FALSE;
3617             global_ld.err = err;
3618             pcap_src->dropped++;
3619         } else {
3620 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3621             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3622                   "Wrote a packet of length %d captured on interface %u.",
3623                    phdr->caplen, pcap_src->interface_id);
3624 #endif
3625             global_ld.packet_count++;
3626             pcap_src->received++;
3627             /* if the user told us to stop after x packets, do we already have enough? */
3628             if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
3629                 global_ld.go = FALSE;
3630             }
3631         }
3632     }
3633 }
3634
3635 /* one packet was captured, queue it */
3636 static void
3637 capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
3638                              const u_char *pd)
3639 {
3640     capture_src        *pcap_src = (capture_src *) (void *) pcap_src_p;
3641     pcap_queue_element *queue_element;
3642     gboolean            limit_reached;
3643
3644     /* We may be called multiple times from pcap_dispatch(); if we've set
3645        the "stop capturing" flag, ignore this packet, as we're not
3646        supposed to be saving any more packets. */
3647     if (!global_ld.go) {
3648         pcap_src->flushed++;
3649         return;
3650     }
3651
3652     queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
3653     if (queue_element == NULL) {
3654        pcap_src->dropped++;
3655        return;
3656     }
3657     queue_element->pcap_src = pcap_src;
3658     queue_element->phdr = *phdr;
3659     queue_element->pd = (u_char *)g_malloc(phdr->caplen);
3660     if (queue_element->pd == NULL) {
3661         pcap_src->dropped++;
3662         g_free(queue_element);
3663         return;
3664     }
3665     memcpy(queue_element->pd, pd, phdr->caplen);
3666     g_async_queue_lock(pcap_queue);
3667     if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
3668         ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
3669         limit_reached = FALSE;
3670         g_async_queue_push_unlocked(pcap_queue, queue_element);
3671         pcap_queue_bytes += phdr->caplen;
3672         pcap_queue_packets += 1;
3673     } else {
3674         limit_reached = TRUE;
3675     }
3676     g_async_queue_unlock(pcap_queue);
3677     if (limit_reached) {
3678         pcap_src->dropped++;
3679         g_free(queue_element->pd);
3680         g_free(queue_element);
3681         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3682               "Dropped a packet of length %d captured on interface %u.",
3683               phdr->caplen, pcap_src->interface_id);
3684     } else {
3685         pcap_src->received++;
3686         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3687               "Queued a packet of length %d captured on interface %u.",
3688               phdr->caplen, pcap_src->interface_id);
3689     }
3690     /* I don't want to hold the mutex over the debug output. So the
3691        output may be wrong */
3692     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3693           "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
3694           pcap_queue_bytes, pcap_queue_packets);
3695 }
3696
3697 static int
3698 set_80211_channel(const char *iface, const char *opt)
3699 {
3700     guint32 freq = 0;
3701     int type = -1;
3702     guint32 center_freq1 = 0;
3703     guint32 center_freq2 = 0;
3704     int args;
3705     int ret = 0;
3706     gchar **options = NULL;
3707
3708     options = g_strsplit_set(opt, ",", 4);
3709     for (args = 0; options[args]; args++);
3710
3711     if (options[0])
3712         freq = get_nonzero_guint32(options[0], "802.11 channel frequency");
3713
3714     if (args >= 1 && options[1]) {
3715         type = ws80211_str_to_chan_type(options[1]);
3716         if (type == -1) {
3717             cmdarg_err("\"%s\" is not a valid 802.11 channel type", options[1]);
3718             ret = EINVAL;
3719             goto out;
3720         }
3721     }
3722
3723     if (args >= 2 && options[2])
3724         center_freq1 = get_nonzero_guint32(options[2], "VHT center frequency");
3725
3726     if (args >= 3 && options[3])
3727         center_freq2 = get_nonzero_guint32(options[3], "VHT center frequency 2");
3728
3729     ret = ws80211_init();
3730     if (ret) {
3731         cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
3732         ret = 2;
3733         goto out;
3734     }
3735     ret = ws80211_set_freq(iface, freq, type, center_freq1, center_freq2);
3736
3737     if (ret) {
3738         cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
3739         ret = 2;
3740         goto out;
3741     }
3742
3743     if (capture_child)
3744         pipe_write_block(2, SP_SUCCESS, NULL);
3745
3746 out:
3747     g_strfreev(options);
3748     return ret;
3749 }
3750
3751 static void
3752 get_dumpcap_compiled_info(GString *str)
3753 {
3754     /* Capture libraries */
3755     g_string_append(str, ", ");
3756     get_compiled_caplibs_version(str);
3757 }
3758
3759 static void
3760 get_dumpcap_runtime_info(GString *str)
3761 {
3762     /* Capture libraries */
3763     g_string_append(str, ", ");
3764     get_runtime_caplibs_version(str);
3765 }
3766
3767 /* And now our feature presentation... [ fade to music ] */
3768 int
3769 main(int argc, char *argv[])
3770 {
3771     GString          *comp_info_str;
3772     GString          *runtime_info_str;
3773     int               opt;
3774     static const struct option long_options[] = {
3775         {"help", no_argument, NULL, 'h'},
3776         {"version", no_argument, NULL, 'v'},
3777         LONGOPT_CAPTURE_COMMON
3778         {0, 0, 0, 0 }
3779     };
3780
3781     gboolean          arg_error             = FALSE;
3782
3783 #ifdef _WIN32
3784     int               result;
3785     WSADATA           wsaData;
3786 #else
3787     struct sigaction  action, oldaction;
3788 #endif
3789
3790     gboolean          start_capture         = TRUE;
3791     gboolean          stats_known;
3792     struct pcap_stat  stats;
3793     GLogLevelFlags    log_flags;
3794     gboolean          list_interfaces       = FALSE;
3795     gboolean          list_link_layer_types = FALSE;
3796 #ifdef HAVE_BPF_IMAGE
3797     gboolean          print_bpf_code        = FALSE;
3798 #endif
3799     gboolean          set_chan              = FALSE;
3800     gchar            *set_chan_arg          = NULL;
3801     gboolean          machine_readable      = FALSE;
3802     gboolean          print_statistics      = FALSE;
3803     int               status, run_once_args = 0;
3804     gint              i;
3805     guint             j;
3806 #if defined(__APPLE__) && defined(__LP64__)
3807     struct utsname    osinfo;
3808 #endif
3809     GString          *str;
3810
3811     cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
3812
3813     /* Get the compile-time version information string */
3814     comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
3815
3816     /* Get the run-time version information string */
3817     runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
3818
3819     /* Add it to the information to be reported on a crash. */
3820     ws_add_crash_info("Dumpcap (Wireshark) %s\n"
3821            "\n"
3822            "%s"
3823            "\n"
3824            "%s",
3825         get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
3826     g_string_free(comp_info_str, TRUE);
3827     g_string_free(runtime_info_str, TRUE);
3828
3829 #ifdef _WIN32
3830     arg_list_utf_16to8(argc, argv);
3831     create_app_running_mutex();
3832
3833     /*
3834      * Initialize our DLL search path. MUST be called before LoadLibrary
3835      * or g_module_open.
3836      */
3837     ws_init_dll_search_path();
3838 #endif
3839
3840 #ifdef HAVE_BPF_IMAGE
3841 #define OPTSTRING_d "d"
3842 #else
3843 #define OPTSTRING_d ""
3844 #endif
3845
3846 #ifdef HAVE_PCAP_REMOTE
3847 #define OPTSTRING_r "r"
3848 #define OPTSTRING_u "u"
3849 #else
3850 #define OPTSTRING_r ""
3851 #define OPTSTRING_u ""
3852 #endif
3853
3854 #ifdef HAVE_PCAP_SETSAMPLING
3855 #define OPTSTRING_m "m:"
3856 #else
3857 #define OPTSTRING_m ""
3858 #endif
3859
3860 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
3861
3862 #ifdef DEBUG_CHILD_DUMPCAP
3863     if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
3864         fprintf (stderr, "Unable to open debug log file .\n");
3865         exit (1);
3866     }
3867 #endif
3868
3869 #if defined(__APPLE__) && defined(__LP64__)
3870     /*
3871      * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4?  If so, we need
3872      * a bug workaround - timeouts less than 1 second don't work with libpcap
3873      * in 64-bit code.  (The bug was introduced in 10.6, fixed in 10.6.2,
3874      * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
3875      * The problem is extremely unlikely to be reintroduced in a future
3876      * release.)
3877      */
3878     if (uname(&osinfo) == 0) {
3879         /*
3880          * {Mac} OS X/macOS 10.x uses Darwin {x+4}.0.0; 10.x.y uses Darwin
3881          * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
3882          * number of 10.0.0, not 10.1.0 - go figure).
3883          */
3884         if (strcmp(osinfo.release, "10.0.0") == 0 ||    /* 10.6, 10.6.1 */
3885             strcmp(osinfo.release, "10.3.0") == 0 ||    /* 10.6.3 */
3886             strcmp(osinfo.release, "10.4.0") == 0)              /* 10.6.4 */
3887             need_timeout_workaround = TRUE;
3888     }
3889 #endif
3890
3891     /*
3892      * Determine if dumpcap is being requested to run in a special
3893      * capture_child mode by going thru the command line args to see if
3894      * a -Z is present. (-Z is a hidden option).
3895      *
3896      * The primary result of running in capture_child mode is that
3897      * all messages sent out on stderr are in a special type/len/string
3898      * format to allow message processing by type.  These messages include
3899      * error messages if dumpcap fails to start the operation it was
3900      * requested to do, as well as various "status" messages which are sent
3901      * when an actual capture is in progress, and a "success" message sent
3902      * if dumpcap was requested to perform an operation other than a
3903      * capture.
3904      *
3905      * Capture_child mode would normally be requested by a parent process
3906      * which invokes dumpcap and obtains dumpcap stderr output via a pipe
3907      * to which dumpcap stderr has been redirected.  It might also have
3908      * another pipe to obtain dumpcap stdout output; for operations other
3909      * than a capture, that information is formatted specially for easier
3910      * parsing by the parent process.
3911      *
3912      * Capture_child mode needs to be determined immediately upon
3913      * startup so that any messages generated by dumpcap in this mode
3914      * (eg: during initialization) will be formatted properly.
3915      */
3916
3917     for (i=1; i<argc; i++) {
3918         if (strcmp("-Z", argv[i]) == 0) {
3919             capture_child    = TRUE;
3920             machine_readable = TRUE;  /* request machine-readable output */
3921 #ifdef _WIN32
3922             /* set output pipe to binary mode, to avoid ugly text conversions */
3923             _setmode(2, O_BINARY);
3924 #endif
3925         }
3926     }
3927
3928     /* The default_log_handler will use stdout, which makes trouble in   */
3929     /* capture child mode, as it uses stdout for its sync_pipe.          */
3930     /* So: the filtering is done in the console_log_handler and not here.*/
3931     /* We set the log handlers right up front to make sure that any log  */
3932     /* messages when running as child will be sent back to the parent    */
3933     /* with the correct format.                                          */
3934
3935     log_flags =
3936         (GLogLevelFlags)(
3937         G_LOG_LEVEL_ERROR|
3938         G_LOG_LEVEL_CRITICAL|
3939         G_LOG_LEVEL_WARNING|
3940         G_LOG_LEVEL_MESSAGE|
3941         G_LOG_LEVEL_INFO|
3942         G_LOG_LEVEL_DEBUG|
3943         G_LOG_FLAG_FATAL|
3944         G_LOG_FLAG_RECURSION);
3945
3946     g_log_set_handler(NULL,
3947                       log_flags,
3948                       console_log_handler, NULL /* user_data */);
3949     g_log_set_handler(LOG_DOMAIN_MAIN,
3950                       log_flags,
3951                       console_log_handler, NULL /* user_data */);
3952     g_log_set_handler(LOG_DOMAIN_CAPTURE,
3953                       log_flags,
3954                       console_log_handler, NULL /* user_data */);
3955     g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
3956                       log_flags,
3957                       console_log_handler, NULL /* user_data */);
3958
3959     /* Initialize the pcaps list */
3960     global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(capture_src *));
3961
3962 #if !GLIB_CHECK_VERSION(2,31,0)
3963     /* Initialize the thread system */
3964     g_thread_init(NULL);
3965 #endif
3966
3967 #ifdef _WIN32
3968     /* Load wpcap if possible. Do this before collecting the run-time version information */
3969     load_wpcap();
3970
3971     /* ... and also load the packet.dll from wpcap */
3972     /* XXX - currently not required, may change later. */
3973     /*wpcap_packet_load();*/
3974
3975     /* Start windows sockets */
3976     result = WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
3977     if (result != 0)
3978     {
3979         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_ERROR,
3980                           "ERROR: WSAStartup failed with error: %d", result);
3981         exit_main(1);
3982     }
3983
3984     /* Set handler for Ctrl+C key */
3985     SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
3986 #else
3987     /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
3988        and exit.  Do the same with SIGPIPE, in case, for example,
3989        we're writing to our standard output and it's a pipe.
3990        Do the same with SIGHUP if it's not being ignored (if we're
3991        being run under nohup, it might be ignored, in which case we
3992        should leave it ignored).
3993
3994        XXX - apparently, Coverity complained that part of action
3995        wasn't initialized.  Perhaps it's running on Linux, where
3996        struct sigaction has an ignored "sa_restorer" element and
3997        where "sa_handler" and "sa_sigaction" might not be two
3998        members of a union. */
3999     memset(&action, 0, sizeof(action));
4000     action.sa_handler = capture_cleanup_handler;
4001     /*
4002      * Arrange that system calls not get restarted, because when
4003      * our signal handler returns we don't want to restart
4004      * a call that was waiting for packets to arrive.
4005      */
4006     action.sa_flags = 0;
4007     sigemptyset(&action.sa_mask);
4008     sigaction(SIGTERM, &action, NULL);
4009     sigaction(SIGINT, &action, NULL);
4010     sigaction(SIGPIPE, &action, NULL);
4011     sigaction(SIGHUP, NULL, &oldaction);
4012     if (oldaction.sa_handler == SIG_DFL)
4013         sigaction(SIGHUP, &action, NULL);
4014
4015 #ifdef SIGINFO
4016     /* Catch SIGINFO and, if we get it and we're capturing in
4017        quiet mode, report the number of packets we've captured. */
4018     action.sa_handler = report_counts_siginfo;
4019     action.sa_flags = SA_RESTART;
4020     sigemptyset(&action.sa_mask);
4021     sigaction(SIGINFO, &action, NULL);
4022 #endif /* SIGINFO */
4023 #endif  /* _WIN32 */
4024
4025 #ifdef __linux__
4026     enable_kernel_bpf_jit_compiler();
4027 #endif
4028
4029     /* ----------------------------------------------------------------- */
4030     /* Privilege and capability handling                                 */
4031     /* Cases:                                                            */
4032     /* 1. Running not as root or suid root; no special capabilities.     */
4033     /*    Action: none                                                   */
4034     /*                                                                   */
4035     /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap.  */
4036     /*    Action: none                                                   */
4037     /*                                                                   */
4038     /* 3. Running logged in as root (euid=0; ruid=0). Using libcap.      */
4039     /*    Action:                                                        */
4040     /*      - Near start of program: Enable NET_RAW and NET_ADMIN        */
4041     /*        capabilities; Drop all other capabilities;                 */
4042     /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
4043     /*        else: after  pcap_open_live() in capture_loop_open_input() */
4044     /*         drop all capabilities (NET_RAW and NET_ADMIN);            */
4045     /*         (Note: this means that the process, although logged in    */
4046     /*          as root, does not have various permissions such as the   */
4047     /*          ability to bypass file access permissions).              */
4048     /*      XXX: Should we just leave capabilities alone in this case    */
4049     /*          so that user gets expected effect that root can do       */
4050     /*          anything ??                                              */
4051     /*                                                                   */
4052     /* 4. Running as suid root (euid=0, ruid=n); Not using libcap.       */
4053     /*    Action:                                                        */
4054     /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
4055     /*        else: after  pcap_open_live() in capture_loop_open_input() */
4056     /*         drop suid root (set euid=ruid).(ie: keep suid until after */
4057     /*         pcap_open_live).                                          */
4058     /*                                                                   */
4059     /* 5. Running as suid root (euid=0, ruid=n); Using libcap.           */
4060     /*    Action:                                                        */
4061     /*      - Near start of program: Enable NET_RAW and NET_ADMIN        */
4062     /*        capabilities; Drop all other capabilities;                 */
4063     /*        Drop suid privileges (euid=ruid);                          */
4064     /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
4065     /*        else: after  pcap_open_live() in capture_loop_open_input() */
4066     /*         drop all capabilities (NET_RAW and NET_ADMIN).            */
4067     /*                                                                   */
4068     /*      XXX: For some Linux versions/distros with capabilities       */
4069     /*        a 'normal' process with any capabilities cannot be         */
4070     /*        'killed' (signaled) from another (same uid) non-privileged */
4071     /*        process.                                                   */
4072     /*        For example: If (non-suid) Wireshark forks a               */
4073     /*        child suid dumpcap which acts as described here (case 5),  */
4074     /*        Wireshark will be unable to kill (signal) the child        */
4075     /*        dumpcap process until the capabilities have been dropped   */
4076     /*        (after pcap_open_live()).                                  */
4077     /*        This behaviour will apparently be changed in the kernel    */
4078     /*        to allow the kill (signal) in this case.                   */
4079     /*        See the following for details:                             */
4080     /*           https://www.mail-archive.com/  [wrapped]                */
4081     /*             linux-security-module@vger.kernel.org/msg02913.html   */
4082     /*                                                                   */
4083     /*        It is therefore conceivable that if dumpcap somehow hangs  */
4084     /*        in pcap_open_live or before that wireshark will not        */
4085     /*        be able to stop dumpcap using a signal (INT, TERM, etc).   */
4086     /*        In this case, exiting wireshark will kill the child        */
4087     /*        dumpcap process.                                           */
4088     /*                                                                   */
4089     /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN        */
4090     /*     capabilities; Using libcap.  Note: capset cmd (which see)     */
4091     /*     used to assign capabilities to file.                          */
4092     /*    Action:                                                        */
4093     /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
4094     /*        else: after  pcap_open_live() in capture_loop_open_input() */
4095     /*         drop all capabilities (NET_RAW and NET_ADMIN)             */
4096     /*                                                                   */
4097     /* ToDo: -S (stats) should drop privileges/capabilities when no      */
4098     /*       longer required (similar to capture).                       */
4099     /*                                                                   */
4100     /* ----------------------------------------------------------------- */
4101
4102     init_process_policies();
4103
4104 #ifdef HAVE_LIBCAP
4105     /* If 'started with special privileges' (and using libcap)  */
4106     /*   Set to keep only NET_RAW and NET_ADMIN capabilities;   */
4107     /*   Set euid/egid = ruid/rgid to remove suid privileges    */
4108     relinquish_privs_except_capture();
4109 #endif
4110
4111     /* Set the initial values in the capture options. This might be overwritten
4112        by the command line parameters. */
4113     capture_opts_init(&global_capture_opts);
4114     /* We always save to a file - if no file was specified, we save to a
4115        temporary file. */
4116     global_capture_opts.saving_to_file      = TRUE;
4117     global_capture_opts.has_ring_num_files  = TRUE;
4118
4119     /* Pass on capture_child mode for capture_opts */
4120     global_capture_opts.capture_child = capture_child;
4121
4122     /* Now get our args */
4123     while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4124         switch (opt) {
4125         case 'h':        /* Print help and exit */
4126             printf("Dumpcap (Wireshark) %s\n"
4127                    "Capture network packets and dump them into a pcapng or pcap file.\n"
4128                    "See https://www.wireshark.org for more information.\n",
4129                    get_ws_vcs_version_info());
4130             print_usage(stdout);
4131             exit_main(0);
4132             break;
4133         case 'v':        /* Show version and exit */
4134             comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
4135             runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
4136             show_version("Dumpcap (Wireshark)", comp_info_str, runtime_info_str);
4137             g_string_free(comp_info_str, TRUE);
4138             g_string_free(runtime_info_str, TRUE);
4139             exit_main(0);
4140             break;
4141         /*** capture option specific ***/
4142         case 'a':        /* autostop criteria */
4143         case 'b':        /* Ringbuffer option */
4144         case 'c':        /* Capture x packets */
4145         case 'f':        /* capture filter */
4146         case 'g':        /* enable group read access on file(s) */
4147         case 'i':        /* Use interface x */
4148         case 'n':        /* Use pcapng format */
4149         case 'p':        /* Don't capture in promiscuous mode */
4150         case 'P':        /* Use pcap format */
4151         case 's':        /* Set the snapshot (capture) length */
4152         case 'w':        /* Write to capture file x */
4153         case 'y':        /* Set the pcap data link type */
4154         case  LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4155 #ifdef HAVE_PCAP_REMOTE
4156         case 'u':        /* Use UDP for data transfer */
4157         case 'r':        /* Capture own RPCAP traffic too */
4158         case 'A':        /* Authentication */
4159 #endif
4160 #ifdef HAVE_PCAP_SETSAMPLING
4161         case 'm':        /* Sampling */
4162 #endif
4163 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
4164         case 'B':        /* Buffer size */
4165 #endif
4166 #ifdef HAVE_PCAP_CREATE
4167         case 'I':        /* Monitor mode */
4168 #endif
4169             status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4170             if (status != 0) {
4171                 exit_main(status);
4172             }
4173             break;
4174             /*** hidden option: Wireshark child mode (using binary output messages) ***/
4175         case 'Z':
4176             capture_child = TRUE;
4177 #ifdef _WIN32
4178             /* set output pipe to binary mode, to avoid ugly text conversions */
4179             _setmode(2, O_BINARY);
4180             /*
4181              * optarg = the control ID, aka the PPID, currently used for the
4182              * signal pipe name.
4183              */
4184             if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4185                 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4186                 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4187                                              GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4188
4189                 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4190                     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4191                           "Signal pipe: Unable to open %s.  Dead parent?",
4192                           sig_pipe_name);
4193                     exit_main(1);
4194                 }
4195             }
4196 #endif
4197             break;
4198
4199         case 'q':        /* Quiet */
4200             quiet = TRUE;
4201             break;
4202         case 't':
4203             use_threads = TRUE;
4204             break;
4205             /*** all non capture option specific ***/
4206         case 'D':        /* Print a list of capture devices and exit */
4207             if (!list_interfaces) {
4208                 list_interfaces = TRUE;
4209                 run_once_args++;
4210             }
4211             break;
4212         case 'L':        /* Print list of link-layer types and exit */
4213             if (!list_link_layer_types) {
4214                 list_link_layer_types = TRUE;
4215                 run_once_args++;
4216             }
4217             break;
4218 #ifdef HAVE_BPF_IMAGE
4219         case 'd':        /* Print BPF code for capture filter and exit */
4220             if (!print_bpf_code) {
4221                 print_bpf_code = TRUE;
4222                 run_once_args++;
4223             }
4224             break;
4225 #endif
4226         case 'S':        /* Print interface statistics once a second */
4227             if (!print_statistics) {
4228                 print_statistics = TRUE;
4229                 run_once_args++;
4230             }
4231             break;
4232         case 'k':        /* Set wireless channel */
4233             if (!set_chan) {
4234                 set_chan = TRUE;
4235                 set_chan_arg = optarg;
4236                 run_once_args++;
4237             } else {
4238                 cmdarg_err("Only one -k flag may be specified");
4239                 arg_error = TRUE;
4240             }
4241             break;
4242         case 'M':        /* For -D, -L, and -S, print machine-readable output */
4243             machine_readable = TRUE;
4244             break;
4245         case 'C':
4246             pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4247             break;
4248         case 'N':
4249             pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4250             break;
4251         default:
4252             cmdarg_err("Invalid Option: %s", argv[optind-1]);
4253             /* FALLTHROUGH */
4254         case '?':        /* Bad flag - print usage message */
4255             arg_error = TRUE;
4256             break;
4257         }
4258     }
4259     if (!arg_error) {
4260         argc -= optind;
4261         argv += optind;
4262         if (argc >= 1) {
4263             /* user specified file name as regular command-line argument */
4264             /* XXX - use it as the capture file name (or something else)? */
4265             argc--;
4266             argv++;
4267         }
4268         if (argc != 0) {
4269             /*
4270              * Extra command line arguments were specified; complain.
4271              * XXX - interpret as capture filter, as tcpdump and tshark do?
4272              */
4273             cmdarg_err("Invalid argument: %s", argv[0]);
4274             arg_error = TRUE;
4275         }
4276     }
4277
4278     if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4279         use_threads = TRUE;
4280     }
4281     if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4282         /* Use some default if the user hasn't specified some */
4283         /* XXX: Are these defaults good enough? */
4284         pcap_queue_byte_limit = 1000 * 1000;
4285         pcap_queue_packet_limit = 1000;
4286     }
4287     if (arg_error) {
4288         print_usage(stderr);
4289         exit_main(1);
4290     }
4291
4292     if (run_once_args > 1) {
4293 #ifdef HAVE_BPF_IMAGE
4294         cmdarg_err("Only one of -D, -L, -d, -k, or -S may be supplied.");
4295 #else
4296         cmdarg_err("Only one of -D, -L, -k, or -S may be supplied.");
4297 #endif
4298         exit_main(1);
4299     } else if (run_once_args == 1) {
4300         /* We're supposed to print some information, rather than
4301            to capture traffic; did they specify a ring buffer option? */
4302         if (global_capture_opts.multi_files_on) {
4303             cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4304             exit_main(1);
4305         }
4306     } else {
4307         /* We're supposed to capture traffic; */
4308
4309         /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4310         if (global_capture_opts.ifaces->len > 1) {
4311             use_threads = TRUE;
4312             global_capture_opts.use_pcapng = TRUE;
4313         }
4314
4315         if (global_capture_opts.capture_comment &&
4316             (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4317             /* XXX - for ringbuffer, should we apply the comment to each file? */
4318             cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4319             exit_main(1);
4320         }
4321
4322         /* Was the ring buffer option specified and, if so, does it make sense? */
4323         if (global_capture_opts.multi_files_on) {
4324             /* Ring buffer works only under certain conditions:
4325                a) ring buffer does not work with temporary files;
4326                b) it makes no sense to enable the ring buffer if the maximum
4327                file size is set to "infinite". */
4328             if (global_capture_opts.save_file == NULL) {
4329                 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4330                 global_capture_opts.multi_files_on = FALSE;
4331             }
4332             if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4333                 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4334 #if 0
4335                 /* XXX - this must be redesigned as the conditions changed */
4336                 global_capture_opts.multi_files_on = FALSE;
4337 #endif
4338             }
4339         }
4340     }
4341
4342     /*
4343      * "-D" requires no interface to be selected; it's supposed to list
4344      * all interfaces.
4345      */
4346     if (list_interfaces) {
4347         /* Get the list of interfaces */
4348         GList *if_list;
4349         int    err;
4350         gchar *err_str;
4351
4352         if_list = capture_interface_list(&err, &err_str,NULL);
4353         if (if_list == NULL) {
4354             if (err == 0) {
4355                 /*
4356                  * If we're being run by another program, just give them
4357                  * an empty list of interfaces, don't report this as
4358                  * an error; that lets them decide whether to report
4359                  * this as an error or not.
4360                  */
4361                 if (!machine_readable) {
4362                     cmdarg_err("There are no interfaces on which a capture can be done");
4363                     exit_main(2);
4364                 }
4365             } else {
4366                 cmdarg_err("%s", err_str);
4367                 g_free(err_str);
4368                 exit_main(2);
4369             }
4370         }
4371
4372         if (machine_readable)      /* tab-separated values to stdout */
4373             print_machine_readable_interfaces(if_list);
4374         else
4375             capture_opts_print_interfaces(if_list);
4376         free_interface_list(if_list);
4377         exit_main(0);
4378     }
4379
4380     /*
4381      * "-S" requires no interface to be selected; it gives statistics
4382      * for all interfaces.
4383      */
4384     if (print_statistics) {
4385         status = print_statistics_loop(machine_readable);
4386         exit_main(status);
4387     }
4388
4389     if (set_chan) {
4390         interface_options interface_opts;
4391
4392         if (global_capture_opts.ifaces->len != 1) {
4393             cmdarg_err("Need one interface");
4394             exit_main(2);
4395         }
4396
4397         interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4398         status = set_80211_channel(interface_opts.name, set_chan_arg);
4399         exit_main(status);
4400     }
4401
4402     /*
4403      * "-L", "-d", and capturing act on a particular interface, so we have to
4404      * have an interface; if none was specified, pick a default.
4405      */
4406     status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4407     if (status != 0) {
4408         /* cmdarg_err() already called .... */
4409         exit_main(status);
4410     }
4411
4412     if (list_link_layer_types) {
4413         /* Get the list of link-layer types for the capture device. */
4414         if_capabilities_t *caps;
4415         gchar *err_str;
4416         guint  ii;
4417
4418         for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4419             interface_options interface_opts;
4420
4421             interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4422
4423             caps = get_if_capabilities(&interface_opts, &err_str);
4424             if (caps == NULL) {
4425                 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4426                            "Please check to make sure you have sufficient permissions, and that\n"
4427                            "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4428                 g_free(err_str);
4429                 exit_main(2);
4430             }
4431             if (caps->data_link_types == NULL) {
4432                 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4433                 exit_main(2);
4434             }
4435             if (machine_readable)      /* tab-separated values to stdout */
4436                 /* XXX: We need to change the format and adopt consumers */
4437                 print_machine_readable_if_capabilities(caps);
4438             else
4439                 /* XXX: We might want to print also the interface name */
4440                 capture_opts_print_if_capabilities(caps, interface_opts.name,
4441                                                    interface_opts.monitor_mode);
4442             free_if_capabilities(caps);
4443         }
4444         exit_main(0);
4445     }
4446
4447     /* We're supposed to do a capture, or print the BPF code for a filter. */
4448
4449     /* Let the user know what interfaces were chosen. */
4450     if (capture_child) {
4451         for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4452             interface_options interface_opts;
4453
4454             interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4455             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4456                   interface_opts.name);
4457         }
4458     } else {
4459         str = g_string_new("");
4460 #ifdef _WIN32
4461         if (global_capture_opts.ifaces->len < 2)
4462 #else
4463         if (global_capture_opts.ifaces->len < 4)
4464 #endif
4465         {
4466             for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4467                 interface_options interface_opts;
4468
4469                 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4470                 if (j > 0) {
4471                     if (global_capture_opts.ifaces->len > 2) {
4472                         g_string_append_printf(str, ",");
4473                     }
4474                     g_string_append_printf(str, " ");
4475                     if (j == global_capture_opts.ifaces->len - 1) {
4476                         g_string_append_printf(str, "and ");
4477                     }
4478                 }
4479                 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
4480             }
4481         } else {
4482             g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4483         }
4484         fprintf(stderr, "Capturing on %s\n", str->str);
4485         g_string_free(str, TRUE);
4486     }
4487
4488     /* Process the snapshot length, as that affects the generated BPF code. */
4489     capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4490
4491 #ifdef HAVE_BPF_IMAGE
4492     if (print_bpf_code) {
4493         show_filter_code(&global_capture_opts);
4494         exit_main(0);
4495     }
4496 #endif
4497
4498     /* We're supposed to do a capture.  Process the ring buffer arguments. */
4499     capture_opts_trim_ring_num_files(&global_capture_opts);
4500
4501     /* flush stderr prior to starting the main capture loop */
4502     fflush(stderr);
4503
4504     /* Now start the capture. */
4505     if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4506         /* capture ok */
4507         exit_main(0);
4508     } else {
4509         /* capture failed */
4510         exit_main(1);
4511     }
4512     return 0; /* never here, make compiler happy */
4513 }
4514
4515
4516 static void
4517 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4518                     const char *message, gpointer user_data _U_)
4519 {
4520     time_t      curr;
4521     struct tm  *today;
4522     const char *level;
4523     gchar      *msg;
4524
4525     /* ignore log message, if log_level isn't interesting */
4526     if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4527 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4528         return;
4529 #endif
4530     }
4531
4532     switch(log_level & G_LOG_LEVEL_MASK) {
4533     case G_LOG_LEVEL_ERROR:
4534         level = "Err ";
4535         break;
4536     case G_LOG_LEVEL_CRITICAL:
4537         level = "Crit";
4538         break;
4539     case G_LOG_LEVEL_WARNING:
4540         level = "Warn";
4541         break;
4542     case G_LOG_LEVEL_MESSAGE:
4543         level = "Msg ";
4544         break;
4545     case G_LOG_LEVEL_INFO:
4546         level = "Info";
4547         break;
4548     case G_LOG_LEVEL_DEBUG:
4549         level = "Dbg ";
4550         break;
4551     default:
4552         fprintf(stderr, "unknown log_level %d\n", log_level);
4553         level = NULL;
4554         g_assert_not_reached();
4555     }
4556
4557     /* Generate the output message                                  */
4558     if (log_level & G_LOG_LEVEL_MESSAGE) {
4559         /* normal user messages without additional infos */
4560         msg =  g_strdup_printf("%s\n", message);
4561     } else {
4562         /* create a "timestamp" */
4563         time(&curr);
4564         today = localtime(&curr);
4565
4566         /* info/debug messages with additional infos */
4567         if (today != NULL)
4568             msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4569                                   today->tm_hour, today->tm_min, today->tm_sec,
4570                                   log_domain != NULL ? log_domain : "",
4571                                   level, message);
4572         else
4573             msg = g_strdup_printf("Time not representable %8s %s %s\n",
4574                                   log_domain != NULL ? log_domain : "",
4575                                   level, message);
4576     }
4577
4578     /* DEBUG & INFO msgs (if we're debugging today)                 */
4579 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4580     if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4581 #ifdef DEBUG_DUMPCAP
4582         fprintf(stderr, "%s", msg);
4583         fflush(stderr);
4584 #endif
4585 #ifdef DEBUG_CHILD_DUMPCAP
4586         fprintf(debug_log, "%s", msg);
4587         fflush(debug_log);
4588 #endif
4589         g_free(msg);
4590         return;
4591     }
4592 #endif
4593
4594     /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or    */
4595     /*  to parent especially formatted if dumpcap running as child. */
4596     if (capture_child) {
4597         sync_pipe_errmsg_to_parent(2, msg, "");
4598     } else {
4599         fprintf(stderr, "%s", msg);
4600         fflush(stderr);
4601     }
4602     g_free(msg);
4603 }
4604
4605
4606 /****************************************************************************************************************/
4607 /* indication report routines */
4608
4609
4610 static void
4611 report_packet_count(unsigned int packet_count)
4612 {
4613     char tmp[SP_DECISIZE+1+1];
4614     static unsigned int count = 0;
4615
4616     if (capture_child) {
4617         g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
4618         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
4619         pipe_write_block(2, SP_PACKET_COUNT, tmp);
4620     } else {
4621         count += packet_count;
4622         fprintf(stderr, "\rPackets: %u ", count);
4623         /* stderr could be line buffered */
4624         fflush(stderr);
4625     }
4626 }
4627
4628 static void
4629 report_new_capture_file(const char *filename)
4630 {
4631     if (capture_child) {
4632         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
4633         pipe_write_block(2, SP_FILE, filename);
4634     } else {
4635 #ifdef SIGINFO
4636         /*
4637          * Prevent a SIGINFO handler from writing to the standard error
4638          * while we're doing so; instead, have it just set a flag telling
4639          * us to print that information when we're done.
4640          */
4641         infodelay = TRUE;
4642 #endif /* SIGINFO */
4643         fprintf(stderr, "File: %s\n", filename);
4644         /* stderr could be line buffered */
4645         fflush(stderr);
4646
4647 #ifdef SIGINFO
4648         /*
4649          * Allow SIGINFO handlers to write.
4650          */
4651         infodelay = FALSE;
4652
4653         /*
4654          * If a SIGINFO handler asked us to write out capture counts, do so.
4655          */
4656         if (infoprint)
4657           report_counts_for_siginfo();
4658 #endif /* SIGINFO */
4659     }
4660 }
4661
4662 static void
4663 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
4664 {
4665     interface_options interface_opts;
4666     char tmp[MSG_MAX_LENGTH+1+6];
4667
4668     if (i < capture_opts->ifaces->len) {
4669         if (capture_child) {
4670             g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
4671             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
4672             pipe_write_block(2, SP_BAD_FILTER, tmp);
4673         } else {
4674             /*
4675              * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
4676              * the error message below.
4677              */
4678             interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
4679             cmdarg_err(
4680               "Invalid capture filter \"%s\" for interface '%s'.\n"
4681               "\n"
4682               "That string isn't a valid capture filter (%s).\n"
4683               "See the User's Guide for a description of the capture filter syntax.",
4684               interface_opts.cfilter, interface_opts.name, errmsg);
4685         }
4686     }
4687 }
4688
4689 static void
4690 report_capture_error(const char *error_msg, const char *secondary_error_msg)
4691 {
4692     if (capture_child) {
4693         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4694             "Primary Error: %s", error_msg);
4695         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4696             "Secondary Error: %s", secondary_error_msg);
4697         sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
4698     } else {
4699         cmdarg_err("%s", error_msg);
4700         if (secondary_error_msg[0] != '\0')
4701           cmdarg_err_cont("%s", secondary_error_msg);
4702     }
4703 }
4704
4705 static void
4706 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
4707 {
4708     char tmp[SP_DECISIZE+1+1];
4709     guint32 total_drops = pcap_drops + drops + flushed;
4710
4711     g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
4712
4713     if (capture_child) {
4714         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4715             "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
4716             name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
4717         /* XXX: Need to provide interface id, changes to consumers required. */
4718         pipe_write_block(2, SP_DROPS, tmp);
4719     } else {
4720         fprintf(stderr,
4721             "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
4722             name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
4723             received ? 100.0 * received / (received + total_drops) : 0.0);
4724         /* stderr could be line buffered */
4725         fflush(stderr);
4726     }
4727 }
4728
4729
4730 /************************************************************************************************/
4731 /* signal_pipe handling */
4732
4733
4734 #ifdef _WIN32
4735 static gboolean
4736 signal_pipe_check_running(void)
4737 {
4738     /* any news from our parent? -> just stop the capture */
4739     DWORD    avail = 0;
4740     gboolean result;
4741
4742     /* if we are running standalone, no check required */
4743     if (!capture_child) {
4744         return TRUE;
4745     }
4746
4747     if (!sig_pipe_name || !sig_pipe_handle) {
4748         /* This shouldn't happen */
4749         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4750             "Signal pipe: No name or handle");
4751         return FALSE;
4752     }
4753
4754     /*
4755      * XXX - We should have the process ID of the parent (from the "-Z" flag)
4756      * at this point.  Should we check to see if the parent is still alive,
4757      * e.g. by using OpenProcess?
4758      */
4759
4760     result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
4761
4762     if (!result || avail > 0) {
4763         /* peek failed or some bytes really available */
4764         /* (if not piping from stdin this would fail) */
4765         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4766             "Signal pipe: Stop capture: %s", sig_pipe_name);
4767         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4768             "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
4769             sig_pipe_handle, result, avail);
4770         return FALSE;
4771     } else {
4772         /* pipe ok and no bytes available */
4773         return TRUE;
4774     }
4775 }
4776 #endif
4777
4778 /*
4779  * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
4780  *
4781  * Local variables:
4782  * c-basic-offset: 4
4783  * tab-width: 8
4784  * indent-tabs-mode: nil
4785  * End:
4786  *
4787  * vi: set shiftwidth=4 tabstop=8 expandtab:
4788  * :indentSize=4:tabSize=8:noTabs=true:
4789  */