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