debug keys
[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 #include <sys/types.h>
19
20 #ifdef HAVE_SYS_SOCKET_H
21 #include <sys/socket.h>
22 #endif
23
24 #ifdef HAVE_NETINET_IN_H
25 #include <netinet/in.h>
26 #endif
27
28 #ifdef HAVE_GETOPT_H
29 #include <getopt.h>
30 #endif
31
32 #ifdef HAVE_ARPA_INET_H
33 #include <arpa/inet.h>
34 #endif
35
36 #if defined(__APPLE__) && defined(__LP64__)
37 #include <sys/utsname.h>
38 #endif
39
40 #include <signal.h>
41 #include <errno.h>
42
43 #include <ui/cmdarg_err.h>
44 #include <wsutil/strtoi.h>
45 #include <cli_main.h>
46 #include <version_info.h>
47
48 #ifndef HAVE_GETOPT_LONG
49 #include "wsutil/wsgetopt.h"
50 #endif
51
52 #ifdef HAVE_LIBCAP
53 # include <sys/prctl.h>
54 # include <sys/capability.h>
55 #endif
56
57 #include "ringbuffer.h"
58
59 #include "caputils/capture_ifinfo.h"
60 #include "caputils/capture-pcap-util.h"
61 #include "caputils/capture-pcap-util-int.h"
62 #ifdef _WIN32
63 #include "caputils/capture-wpcap.h"
64 #endif /* _WIN32 */
65
66 #include "writecap/pcapio.h"
67
68 #ifndef _WIN32
69 #include <sys/un.h>
70 #endif
71
72 #include <ui/clopts_common.h>
73 #include <wsutil/privileges.h>
74
75 #include "sync_pipe.h"
76
77 #include "capture_opts.h"
78 #include <capchild/capture_session.h>
79 #include <capchild/capture_sync.h>
80
81 #include "wsutil/tempfile.h"
82 #include "log.h"
83 #include "wsutil/file_util.h"
84 #include "wsutil/cpu_info.h"
85 #include "wsutil/os_version_info.h"
86 #include "wsutil/str_util.h"
87 #include "wsutil/inet_addr.h"
88 #include "wsutil/time_util.h"
89
90 #include "caputils/ws80211_utils.h"
91
92 #include "extcap.h"
93
94 /*
95  * Get information about libpcap format from "wiretap/libpcap.h".
96  * Get information about pcapng format from "wiretap/pcapng_module.h".
97  * XXX - can we just use pcap_open_offline() to read the pipe?
98  */
99 #include "wiretap/libpcap.h"
100 #include "wiretap/pcapng_module.h"
101 #include "wiretap/pcapng.h"
102
103 /**#define DEBUG_DUMPCAP**/
104 /**#define DEBUG_CHILD_DUMPCAP**/
105
106 #ifdef _WIN32
107 #ifdef DEBUG_DUMPCAP
108 #include <conio.h>          /* _getch() */
109 #endif
110 #endif
111
112 #ifdef DEBUG_CHILD_DUMPCAP
113 FILE *debug_log;   /* for logging debug messages to  */
114                    /*  a file if DEBUG_CHILD_DUMPCAP */
115                    /*  is defined                    */
116 #endif
117
118 static GAsyncQueue *pcap_queue;
119 static gint64 pcap_queue_bytes;
120 static gint64 pcap_queue_packets;
121 static gint64 pcap_queue_byte_limit = 0;
122 static gint64 pcap_queue_packet_limit = 0;
123
124 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
125 #ifdef _WIN32
126 static gchar *sig_pipe_name = NULL;
127 static HANDLE sig_pipe_handle = NULL;
128 static gboolean signal_pipe_check_running(void);
129 #endif
130
131 #ifdef SIGINFO
132 static gboolean infodelay;      /* if TRUE, don't print capture info in SIGINFO handler */
133 static gboolean infoprint;      /* if TRUE, print capture info after clearing infodelay */
134 #endif /* SIGINFO */
135
136 /** Stop a low-level capture (stops the capture child). */
137 static void capture_loop_stop(void);
138 /** Close a pipe, or socket if \a from_socket is TRUE */
139 static void cap_pipe_close(int pipe_fd, gboolean from_socket);
140
141 #if !defined (__linux__)
142 #ifndef HAVE_PCAP_BREAKLOOP
143 /*
144  * We don't have pcap_breakloop(), which is the only way to ensure that
145  * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
146  * won't, if the call to read the next packet or batch of packets is
147  * is interrupted by a signal on UN*X, just go back and try again to
148  * read again.
149  *
150  * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
151  * the signal handler, set a flag to stop capturing; however, without
152  * a guarantee of that sort, we can't guarantee that we'll stop capturing
153  * if the read will be retried and won't time out if no packets arrive.
154  *
155  * Therefore, on at least some platforms, we work around the lack of
156  * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
157  * to wait for packets to arrive, so that we're probably going to be
158  * blocked in the select() when the signal arrives, and can just bail
159  * out of the loop at that point.
160  *
161  * However, we don't want to do that on BSD (because "select()" doesn't work
162  * correctly on BPF devices on at least some releases of some flavors of
163  * BSD), and we don't want to do it on Windows (because "select()" is
164  * something for sockets, not for arbitrary handles).  (Note that "Windows"
165  * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
166  * using WinPcap, not a UNIX libpcap.)
167  *
168  * Fortunately, we don't need to do it on BSD, because the libpcap timeout
169  * on BSD times out even if no packets have arrived, so we'll eventually
170  * exit pcap_dispatch() with an indication that no packets have arrived,
171  * and will break out of the capture loop at that point.
172  *
173  * On Windows, we can't send a SIGINT to stop capturing, so none of this
174  * applies in any case.
175  *
176  * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
177  * want to include it if it's not present on this platform, however.
178  */
179 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
180     !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
181     !defined(__CYGWIN__)
182 #  define MUST_DO_SELECT
183 # endif /* avoid select */
184 #endif /* HAVE_PCAP_BREAKLOOP */
185 #else /* linux */
186 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
187  * in pcap_dispatch(); on the other hand, select() works just fine there.
188  * Hence we use a select for that come what may.
189  *
190  * XXX - with TPACKET_V1 and TPACKET_V2, it currently uses select()
191  * internally, and, with TPACKET_V3, once that's supported, it'll
192  * support timeouts, at least as I understand the way the code works.
193  */
194 #define MUST_DO_SELECT
195 #endif
196
197 /** init the capture filter */
198 typedef enum {
199     INITFILTER_NO_ERROR,
200     INITFILTER_BAD_FILTER,
201     INITFILTER_OTHER_ERROR
202 } initfilter_status_t;
203
204 typedef enum {
205     STATE_EXPECT_REC_HDR,
206     STATE_READ_REC_HDR,
207     STATE_EXPECT_DATA,
208     STATE_READ_DATA
209 } cap_pipe_state_t;
210
211 typedef enum {
212     PIPOK,
213     PIPEOF,
214     PIPERR,
215     PIPNEXIST
216 } cap_pipe_err_t;
217
218 typedef struct _pcap_pipe_info {
219     gboolean                     byte_swapped; /**< TRUE if data in the pipe is byte swapped. */
220     struct pcap_hdr              hdr;          /**< Pcap header when capturing from a pipe */
221     struct pcaprec_modified_hdr  rechdr;       /**< Pcap record header when capturing from a pipe */
222 } pcap_pipe_info_t;
223
224 typedef struct _pcapng_pipe_info {
225     struct pcapng_block_header_s         bh;  /**< Pcapng general block header when capturing from a pipe */
226     GArray *src_iface_to_global;               /**< Int array mapping local IDB numbers to global_ld.interface_data */
227 } pcapng_pipe_info_t;
228
229 struct _loop_data; /* forward declaration so we can use it in the cap_pipe_dispatch function pointer */
230
231 /*
232  * A source of packets from which we're capturing.
233  */
234 typedef struct _capture_src {
235     guint32                      received;
236     guint32                      dropped;
237     guint32                      flushed;
238     pcap_t                      *pcap_h;
239 #ifdef MUST_DO_SELECT
240     int                          pcap_fd;                /**< pcap file descriptor */
241 #endif
242     gboolean                     pcap_err;
243     guint                        interface_id;
244     GThread                     *tid;
245     int                          snaplen;
246     int                          linktype;
247     gboolean                     ts_nsec;                /**< TRUE if we're using nanosecond precision. */
248                                                          /**< capture pipe (unix only "input file") */
249     gboolean                     from_cap_pipe;          /**< TRUE if we are capturing data from a capture pipe */
250     gboolean                     from_cap_socket;        /**< TRUE if we're capturing from socket */
251     gboolean                     from_pcapng;            /**< TRUE if we're capturing from pcapng format */
252     union {
253         pcap_pipe_info_t         pcap;                   /**< Pcap info when capturing from a pipe */
254         pcapng_pipe_info_t       pcapng;                 /**< Pcapng info when capturing from a pipe */
255     } cap_pipe_info;
256 #ifdef _WIN32
257     HANDLE                       cap_pipe_h;             /**< The handle of the capture pipe */
258 #endif
259     int                          cap_pipe_fd;            /**< the file descriptor of the capture pipe */
260     gboolean                     cap_pipe_modified;      /**< TRUE if data in the pipe uses modified pcap headers */
261     char *                       cap_pipe_databuf;       /**< Pointer to the data buffer we've allocated */
262     size_t                       cap_pipe_databuf_size;  /**< Current size of the data buffer */
263     guint                        cap_pipe_max_pkt_size;  /**< Maximum packet size allowed */
264 #if defined(_WIN32)
265     char *                       cap_pipe_buf;           /**< Pointer to the buffer we read into */
266     DWORD                        cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
267     DWORD                        cap_pipe_bytes_read;    /**< Used by cap_pipe_dispatch */
268 #else
269     size_t                       cap_pipe_bytes_to_read; /**< Used by cap_pipe_dispatch */
270     size_t                       cap_pipe_bytes_read;    /**< Used by cap_pipe_dispatch */
271 #endif
272     int (*cap_pipe_dispatch)(struct _loop_data *, struct _capture_src *, char *, size_t);
273     cap_pipe_state_t cap_pipe_state;
274     cap_pipe_err_t cap_pipe_err;
275
276 #if defined(_WIN32)
277     GMutex                      *cap_pipe_read_mtx;
278     GAsyncQueue                 *cap_pipe_pending_q, *cap_pipe_done_q;
279 #endif
280 } capture_src;
281
282 typedef struct _saved_idb {
283     gboolean deleted;
284     guint interface_id; /* capture_src->interface_id for the associated SHB */
285     guint8 *idb;        /* If non-NULL, IDB read from capture_src. This is an interface specified on the command line otherwise. */
286     guint idb_len;
287 } saved_idb_t;
288
289 /*
290  * Global capture loop state.
291  */
292 typedef struct _loop_data {
293     /* common */
294     gboolean  go;                  /**< TRUE as long as we're supposed to keep capturing */
295     int       err;                 /**< if non-zero, error seen while capturing */
296     gint      packets_captured;    /**< Number of packets we have already captured */
297     guint     inpkts_to_sync_pipe; /**< Packets not already send out to the sync_pipe */
298 #ifdef SIGINFO
299     gboolean  report_packet_count; /**< Set by SIGINFO handler; print packet count */
300 #endif
301     GArray   *pcaps;               /**< Array of capture_src's on which we're capturing */
302     gboolean  pcapng_passthrough;  /**< We have one source and it's pcapng. Pass its SHB and IDBs through. */
303     guint8   *saved_shb;           /**< SHB to write when we have one pcapng input */
304     GArray   *saved_idbs;          /**< Array of saved_idb_t, written when we have a new section or output file. */
305     GRWLock   saved_shb_idb_lock;  /**< Saved IDB RW mutex */
306     /* output file(s) */
307     FILE     *pdh;
308     int       save_file_fd;
309     guint64   bytes_written;       /**< Bytes written for the current file. */
310     /* autostop conditions */
311     int       packets_written;     /**< Packets written for the current file. */
312     int       file_count;
313     /* ring buffer conditions */
314     GTimer  *file_duration_timer;
315     time_t   next_interval_time;
316     int      interval_s;
317 } loop_data;
318
319 typedef struct _pcap_queue_element {
320     capture_src        *pcap_src;
321     union {
322         struct pcap_pkthdr  phdr;
323         struct pcapng_block_header_s  bh;
324     } u;
325     u_char             *pd;
326 } pcap_queue_element;
327
328 /*
329  * Standard secondary message for unexpected errors.
330  */
331 static const char please_report[] =
332     "Please report this to the Wireshark developers.\n"
333     "https://bugs.wireshark.org/\n"
334     "(This is not a crash; please do not report it as such.)";
335
336 /*
337  * This needs to be static, so that the SIGINT handler can clear the "go"
338  * flag and for saved_shb_idb_lock.
339  */
340 static loop_data   global_ld;
341
342 /*
343  * Timeout, in milliseconds, for reads from the stream of captured packets
344  * from a capture device.
345  *
346  * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
347  * 64-bit applications, with sub-second timeouts not to work.  The bug is
348  * fixed in 10.6.2, re-broken in 10.6.3, and again fixed in 10.6.5.
349  */
350 #if defined(__APPLE__) && defined(__LP64__)
351 static gboolean need_timeout_workaround;
352
353 #define CAP_READ_TIMEOUT        (need_timeout_workaround ? 1000 : 250)
354 #else
355 #define CAP_READ_TIMEOUT        250
356 #endif
357
358 /*
359  * Timeout, in microseconds, for reads from the stream of captured packets
360  * from a pipe.  Pipes don't have the same problem that BPF devices do
361  * in Mac OS X 10.6, 10.6.1, 10.6.3, and 10.6.4, so we always use a timeout
362  * of 250ms, i.e. the same value as CAP_READ_TIMEOUT when not on one
363  * of the offending versions of Snow Leopard.
364  *
365  * On Windows this value is converted to milliseconds and passed to
366  * WaitForSingleObject. If it's less than 1000 WaitForSingleObject
367  * will return immediately.
368  */
369 #if defined(_WIN32)
370 #define PIPE_READ_TIMEOUT   100000
371 #else
372 #define PIPE_READ_TIMEOUT   250000
373 #endif
374
375 #define WRITER_THREAD_TIMEOUT 100000 /* usecs */
376
377 static void
378 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
379                     const char *message, gpointer user_data _U_);
380
381 /* capture related options */
382 static capture_options global_capture_opts;
383 static gboolean quiet = FALSE;
384 static gboolean use_threads = FALSE;
385 static guint64 start_time;
386
387 static void capture_loop_write_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
388                                          const u_char *pd);
389 static void capture_loop_queue_packet_cb(u_char *pcap_src_p, const struct pcap_pkthdr *phdr,
390                                          const u_char *pd);
391 static void capture_loop_write_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, u_char *pd);
392 static void capture_loop_queue_pcapng_cb(capture_src *pcap_src, const struct pcapng_block_header_s *bh, u_char *pd);
393 static void capture_loop_get_errmsg(char *errmsg, size_t errmsglen,
394                                     char *secondary_errmsg,
395                                     size_t secondary_errmsglen,
396                                     const char *fname, int err,
397                                     gboolean is_close);
398
399 static void WS_NORETURN exit_main(int err);
400
401 static void report_new_capture_file(const char *filename);
402 static void report_packet_count(unsigned int packet_count);
403 static void report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name);
404 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
405 static void report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg);
406
407 #define MSG_MAX_LENGTH 4096
408
409 static void
410 print_usage(FILE *output)
411 {
412     fprintf(output, "\nUsage: dumpcap [options] ...\n");
413     fprintf(output, "\n");
414     fprintf(output, "Capture interface:\n");
415     fprintf(output, "  -i <interface>           name or idx of interface (def: first non-loopback),\n"
416                     "                           or for remote capturing, use one of these formats:\n"
417                     "                               rpcap://<host>/<interface>\n"
418                     "                               TCP@<host>:<port>\n");
419     fprintf(output, "  -f <capture filter>      packet filter in libpcap filter syntax\n");
420 #ifdef HAVE_PCAP_CREATE
421     fprintf(output, "  -s <snaplen>             packet snapshot length (def: appropriate maximum)\n");
422 #else
423     fprintf(output, "  -s <snaplen>             packet snapshot length (def: %u)\n", WTAP_MAX_PACKET_SIZE_STANDARD);
424 #endif
425     fprintf(output, "  -p                       don't capture in promiscuous mode\n");
426 #ifdef HAVE_PCAP_CREATE
427     fprintf(output, "  -I                       capture in monitor mode, if available\n");
428 #endif
429 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
430     fprintf(output, "  -B <buffer size>         size of kernel buffer in MiB (def: %dMiB)\n", DEFAULT_CAPTURE_BUFFER_SIZE);
431 #endif
432     fprintf(output, "  -y <link type>           link layer type (def: first appropriate)\n");
433     fprintf(output, "  --time-stamp-type <type> timestamp method for interface\n");
434     fprintf(output, "  -D                       print list of interfaces and exit\n");
435     fprintf(output, "  -L                       print list of link-layer types of iface and exit\n");
436     fprintf(output, "  --list-time-stamp-types  print list of timestamp types for iface and exit\n");
437 #ifdef HAVE_BPF_IMAGE
438     fprintf(output, "  -d                       print generated BPF code for capture filter\n");
439 #endif
440     fprintf(output, "  -k                       set channel on wifi interface:\n"
441                     "                           <freq>,[<type>],[<center_freq1>],[<center_freq2>]\n");
442     fprintf(output, "  -S                       print statistics for each interface once per second\n");
443     fprintf(output, "  -M                       for -D, -L, and -S, produce machine-readable output\n");
444     fprintf(output, "\n");
445 #ifdef HAVE_PCAP_REMOTE
446     fprintf(output, "RPCAP options:\n");
447     fprintf(output, "  -r                       don't ignore own RPCAP traffic in capture\n");
448     fprintf(output, "  -u                       use UDP for RPCAP data transfer\n");
449     fprintf(output, "  -A <user>:<password>     use RPCAP password authentication\n");
450 #ifdef HAVE_PCAP_SETSAMPLING
451     fprintf(output, "  -m <sampling type>       use packet sampling\n");
452     fprintf(output, "                           count:NUM - capture one packet of every NUM\n");
453     fprintf(output, "                           timer:NUM - capture no more than 1 packet in NUM ms\n");
454 #endif
455 #endif
456     fprintf(output, "Stop conditions:\n");
457     fprintf(output, "  -c <packet count>        stop after n packets (def: infinite)\n");
458     fprintf(output, "  -a <autostop cond.> ...  duration:NUM - stop after NUM seconds\n");
459     fprintf(output, "                           filesize:NUM - stop this file after NUM kB\n");
460     fprintf(output, "                              files:NUM - stop after NUM files\n");
461     fprintf(output, "                            packets:NUM - stop after NUM packets\n");
462     /*fprintf(output, "\n");*/
463     fprintf(output, "Output (files):\n");
464     fprintf(output, "  -w <filename>            name of file to save (def: tempfile)\n");
465     fprintf(output, "  -g                       enable group read access on the output file(s)\n");
466     fprintf(output, "  -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
467     fprintf(output, "                           interval:NUM - create time intervals of NUM secs\n");
468     fprintf(output, "                           filesize:NUM - switch to next file after NUM kB\n");
469     fprintf(output, "                              files:NUM - ringbuffer: replace after NUM files\n");
470     fprintf(output, "                            packets:NUM - ringbuffer: replace after NUM packets\n");
471     fprintf(output, "  -n                       use pcapng format instead of pcap (default)\n");
472     fprintf(output, "  -P                       use libpcap format instead of pcapng\n");
473     fprintf(output, "  --capture-comment <comment>\n");
474     fprintf(output, "                           add a capture comment to the output file\n");
475     fprintf(output, "                           (only for pcapng)\n");
476     fprintf(output, "\n");
477     fprintf(output, "Miscellaneous:\n");
478     fprintf(output, "  -N <packet_limit>        maximum number of packets buffered within dumpcap\n");
479     fprintf(output, "  -C <byte_limit>          maximum number of bytes used for buffering packets\n");
480     fprintf(output, "                           within dumpcap\n");
481     fprintf(output, "  -t                       use a separate thread per interface\n");
482     fprintf(output, "  -q                       don't report packet capture counts\n");
483     fprintf(output, "  -v                       print version information and exit\n");
484     fprintf(output, "  -h                       display this help and exit\n");
485     fprintf(output, "\n");
486 #ifdef __linux__
487     fprintf(output, "Dumpcap can benefit from an enabled BPF JIT compiler if available.\n");
488     fprintf(output, "You might want to enable it by executing:\n");
489     fprintf(output, " \"echo 1 > /proc/sys/net/core/bpf_jit_enable\"\n");
490     fprintf(output, "Note that this can make your system less secure!\n");
491     fprintf(output, "\n");
492 #endif
493     fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcapng\n");
494     fprintf(output, "\"Capture packets from interface eth0 until 60s passed into output.pcapng\"\n");
495     fprintf(output, "\n");
496     fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
497 }
498
499 /*
500  * Report an error in command-line arguments.
501  * If we're a capture child, send a message back to the parent, otherwise
502  * just print it.
503  */
504 static void
505 dumpcap_cmdarg_err(const char *fmt, va_list ap)
506 {
507     if (capture_child) {
508         gchar *msg;
509         /* Generate a 'special format' message back to parent */
510         msg = g_strdup_vprintf(fmt, ap);
511         sync_pipe_errmsg_to_parent(2, msg, "");
512         g_free(msg);
513     } else {
514         fprintf(stderr, "dumpcap: ");
515         vfprintf(stderr, fmt, ap);
516         fprintf(stderr, "\n");
517     }
518 }
519
520 /*
521  * Report additional information for an error in command-line arguments.
522  * If we're a capture child, send a message back to the parent, otherwise
523  * just print it.
524  */
525 static void
526 dumpcap_cmdarg_err_cont(const char *fmt, va_list ap)
527 {
528     if (capture_child) {
529         gchar *msg;
530         msg = g_strdup_vprintf(fmt, ap);
531         sync_pipe_errmsg_to_parent(2, msg, "");
532         g_free(msg);
533     } else {
534         vfprintf(stderr, fmt, ap);
535         fprintf(stderr, "\n");
536     }
537 }
538
539 #ifdef HAVE_LIBCAP
540 static void
541 #if 0 /* Set to enable capability debugging */
542 /* see 'man cap_to_text()' for explanation of output                         */
543 /* '='   means 'all= '  ie: no capabilities                                  */
544 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
545 /* ....                                                                      */
546 print_caps(const char *pfx) {
547     cap_t caps = cap_get_proc();
548     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
549           "%s: EUID: %d  Capabilities: %s", pfx,
550           geteuid(), cap_to_text(caps, NULL));
551     cap_free(caps);
552 }
553 #else
554 print_caps(const char *pfx _U_) {
555 }
556 #endif
557
558 static void
559 relinquish_all_capabilities(void)
560 {
561     /* Drop any and all capabilities this process may have.            */
562     /* Allowed whether or not process has any privileges.              */
563     cap_t caps = cap_init();    /* all capabilities initialized to off */
564     print_caps("Pre-clear");
565     if (cap_set_proc(caps)) {
566         cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
567     }
568     print_caps("Post-clear");
569     cap_free(caps);
570 }
571 #endif
572
573 /*
574  * Platform-dependent suggestions for fixing permissions.
575  */
576 #if defined(__linux__)
577   #define PLATFORM_PERMISSIONS_SUGGESTION \
578     "\n\n" \
579     "On Debian and Debian derivatives such as Ubuntu, if you have " \
580     "installed Wireshark from a package, try running" \
581     "\n\n" \
582     "    sudo dpkg-reconfigure wireshark-common" \
583     "\n\n" \
584     "selecting \"<Yes>\" in response to the question" \
585     "\n\n" \
586     "    Should non-superusers be able to capture packets?" \
587     "\n\n" \
588     "adding yourself to the \"wireshark\" group by running" \
589     "\n\n" \
590     "    sudo usermod -a -G wireshark {your username}" \
591     "\n\n" \
592     "and then logging out and logging back in again."
593 #elif defined(__APPLE__)
594   #define PLATFORM_PERMISSIONS_SUGGESTION \
595     "\n\n" \
596     "If you installed Wireshark using the package from wireshark.org, "\
597     "Try re-installing it and checking the box for the \"Set capture " \
598     "permissions on startup\" item."
599 #else
600   #define PLATFORM_PERMISSIONS_SUGGESTION
601 #endif
602
603 static const char *
604 get_pcap_failure_secondary_error_message(cap_device_open_err open_err,
605                                          const char *open_err_str
606 #ifndef __hpux
607                                                                   _U_
608 #endif
609                                          )
610 {
611 #ifdef _WIN32
612     /*
613      * On Windows, first make sure they *have* WinPcap installed.
614      */
615     if (!has_wpcap) {
616         return
617             "In order to capture packets, WinPcap must be installed; see\n"
618             "\n"
619             "        https://www.winpcap.org/\n"
620             "\n"
621             "for a downloadable version of WinPcap and for instructions on how to install\n"
622             "WinPcap.";
623     }
624 #endif
625
626     /*
627      * Now deal with ancient versions of libpcap that, on HP-UX, don't
628      * correctly figure out how to open a device given the device name.
629      */
630 #ifdef __hpux
631     /* HP-UX-specific suggestion. */
632     static const char ppamsg[] = "can't find PPA for ";
633
634     if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0) {
635         return
636             "You are running (T)Wireshark with a version of the libpcap library\n"
637             "that doesn't handle HP-UX network devices well; this means that\n"
638             "(T)Wireshark may not be able to capture packets.\n"
639             "\n"
640             "To fix this, you should install libpcap 0.6.2, or a later version\n"
641             "of libpcap, rather than libpcap 0.4 or 0.5.x.  It is available in\n"
642             "packaged binary form from the Software Porting And Archive Centre\n"
643             "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
644             "at the URL lists a number of mirror sites.";
645     }
646 #endif
647
648     /*
649      * OK, now just return a largely platform-independent error that might
650      * have platform-specific suggestions at the end (for example, suggestions
651      * for how to get permission to capture).
652      */
653     if (open_err == CAP_DEVICE_OPEN_ERR_GENERIC) {
654         /*
655          * We don't know what kind of error it is, so throw all the
656          * suggestions at the user.
657          */
658         return
659                "Please check to make sure you have sufficient permissions, and that you have "
660                "the proper interface or pipe specified."
661                PLATFORM_PERMISSIONS_SUGGESTION;
662     } else if (open_err == CAP_DEVICE_OPEN_ERR_PERMISSIONS) {
663         /*
664          * This is a permissions error, so no need to specify any other
665          * warnings.
666          */
667         return
668                "Please check to make sure you have sufficient permissions."
669                PLATFORM_PERMISSIONS_SUGGESTION;
670     } else {
671         /*
672          * This is not a permissons error, so no need to suggest
673          * checking permissions.
674          */
675         return
676             "Please check that you have the proper interface or pipe specified.";
677     }
678 }
679
680 static void
681 get_capture_device_open_failure_messages(cap_device_open_err open_err,
682                                          const char *open_err_str,
683                                          const char *iface,
684                                          char *errmsg, size_t errmsg_len,
685                                          char *secondary_errmsg,
686                                          size_t secondary_errmsg_len)
687 {
688     g_snprintf(errmsg, (gulong) errmsg_len,
689                "The capture session could not be initiated on interface '%s' (%s).",
690                iface, open_err_str);
691     g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, "%s",
692                get_pcap_failure_secondary_error_message(open_err, open_err_str));
693 }
694
695 static gboolean
696 compile_capture_filter(const char *iface, pcap_t *pcap_h,
697                        struct bpf_program *fcode, const char *cfilter)
698 {
699     bpf_u_int32 netnum, netmask;
700     gchar       lookup_net_err_str[PCAP_ERRBUF_SIZE];
701
702     if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
703         /*
704          * Well, we can't get the netmask for this interface; it's used
705          * only for filters that check for broadcast IP addresses, so
706          * we just punt and use 0.  It might be nice to warn the user,
707          * but that's a pain in a GUI application, as it'd involve popping
708          * up a message box, and it's not clear how often this would make
709          * a difference (only filters that check for IP broadcast addresses
710          * use the netmask).
711          */
712         /*cmdarg_err(
713           "Warning:  Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
714         netmask = 0;
715     }
716
717     /*
718      * Sigh.  Older versions of libpcap don't properly declare the
719      * third argument to pcap_compile() as a const pointer.  Cast
720      * away the warning.
721      */
722 DIAG_OFF(cast-qual)
723     if (pcap_compile(pcap_h, fcode, (char *)cfilter, 1, netmask) < 0)
724         return FALSE;
725 DIAG_ON(cast-qual)
726     return TRUE;
727 }
728
729 #ifdef HAVE_BPF_IMAGE
730 static gboolean
731 show_filter_code(capture_options *capture_opts)
732 {
733     interface_options *interface_opts;
734     pcap_t *pcap_h;
735     cap_device_open_err open_err;
736     gchar open_err_str[PCAP_ERRBUF_SIZE];
737     char errmsg[MSG_MAX_LENGTH+1];
738     char secondary_errmsg[MSG_MAX_LENGTH+1];
739     struct bpf_program fcode;
740     struct bpf_insn *insn;
741     u_int i;
742     guint j;
743
744     for (j = 0; j < capture_opts->ifaces->len; j++) {
745         interface_opts = &g_array_index(capture_opts->ifaces, interface_options, j);
746         pcap_h = open_capture_device(capture_opts, interface_opts,
747             CAP_READ_TIMEOUT, &open_err, &open_err_str);
748         if (pcap_h == NULL) {
749             /* Open failed; get messages */
750             get_capture_device_open_failure_messages(open_err, open_err_str,
751                                                      interface_opts->name,
752                                                      errmsg, sizeof errmsg,
753                                                      secondary_errmsg,
754                                                      sizeof secondary_errmsg);
755             /* And report them */
756             report_capture_error(errmsg, secondary_errmsg);
757             return FALSE;
758         }
759
760         /* Set the link-layer type. */
761         if (!set_pcap_datalink(pcap_h, interface_opts->linktype, interface_opts->name,
762                                errmsg, sizeof errmsg,
763                                secondary_errmsg, sizeof secondary_errmsg)) {
764             pcap_close(pcap_h);
765             report_capture_error(errmsg, secondary_errmsg);
766             return FALSE;
767         }
768
769         /* OK, try to compile the capture filter. */
770         if (!compile_capture_filter(interface_opts->name, pcap_h, &fcode,
771                                     interface_opts->cfilter)) {
772             pcap_close(pcap_h);
773             report_cfilter_error(capture_opts, j, errmsg);
774             return FALSE;
775         }
776         pcap_close(pcap_h);
777
778         /* Now print the filter code. */
779         insn = fcode.bf_insns;
780
781         for (i = 0; i < fcode.bf_len; insn++, i++)
782             printf("%s\n", bpf_image(insn, i));
783     }
784     /* If not using libcap: we now can now set euid/egid to ruid/rgid         */
785     /*  to remove any suid privileges.                                        */
786     /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities  */
787     /*  (euid/egid have already previously been set to ruid/rgid.             */
788     /* (See comment in main() for details)                                    */
789 #ifndef HAVE_LIBCAP
790     relinquish_special_privs_perm();
791 #else
792     relinquish_all_capabilities();
793 #endif
794     if (capture_child) {
795         /* Let our parent know we succeeded. */
796         pipe_write_block(2, SP_SUCCESS, NULL);
797     }
798     return TRUE;
799 }
800 #endif
801
802 /*
803  * capture_interface_list() is expected to do the right thing to get
804  * a list of interfaces.
805  *
806  * In most of the programs in the Wireshark suite, "the right thing"
807  * is to run dumpcap and ask it for the list, because dumpcap may
808  * be the only program in the suite with enough privileges to get
809  * the list.
810  *
811  * In dumpcap itself, however, we obviously can't run dumpcap to
812  * ask for the list.  Therefore, our capture_interface_list() should
813  * just call get_interface_list().
814  */
815 GList *
816 capture_interface_list(int *err, char **err_str, void(*update_cb)(void) _U_)
817 {
818     return get_interface_list(err, err_str);
819 }
820
821 /*
822  * Output a machine readable list of the interfaces
823  * This list is retrieved by the sync_interface_list_open() function
824  * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
825  */
826 static void
827 print_machine_readable_interfaces(GList *if_list)
828 {
829     int         i;
830     GList       *if_entry;
831     if_info_t   *if_info;
832     GSList      *addr;
833     if_addr_t   *if_addr;
834     char        addr_str[WS_INET6_ADDRSTRLEN];
835
836     if (capture_child) {
837         /* Let our parent know we succeeded. */
838         pipe_write_block(2, SP_SUCCESS, NULL);
839     }
840
841     i = 1;  /* Interface id number */
842     for (if_entry = g_list_first(if_list); if_entry != NULL;
843          if_entry = g_list_next(if_entry)) {
844         if_info = (if_info_t *)if_entry->data;
845         printf("%d. %s\t", i++, if_info->name);
846
847         /*
848          * Print the contents of the if_entry struct in a parseable format.
849          * Each if_entry element is tab-separated.  Addresses are comma-
850          * separated.
851          */
852         /* XXX - Make sure our description doesn't contain a tab */
853         if (if_info->vendor_description != NULL)
854             printf("%s\t", if_info->vendor_description);
855         else
856             printf("\t");
857
858         /* XXX - Make sure our friendly name doesn't contain a tab */
859         if (if_info->friendly_name != NULL)
860             printf("%s\t", if_info->friendly_name);
861         else
862             printf("\t");
863
864         printf("%i\t", if_info->type);
865
866         for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
867                     addr = g_slist_next(addr)) {
868             if (addr != g_slist_nth(if_info->addrs, 0))
869                 printf(",");
870
871             if_addr = (if_addr_t *)addr->data;
872             switch(if_addr->ifat_type) {
873             case IF_AT_IPv4:
874                 printf("%s", ws_inet_ntop4(&if_addr->addr.ip4_addr, addr_str, sizeof(addr_str)));
875                 break;
876             case IF_AT_IPv6:
877                 printf("%s", ws_inet_ntop6(&if_addr->addr.ip6_addr, addr_str, sizeof(addr_str)));
878                 break;
879             default:
880                 printf("<type unknown %i>", if_addr->ifat_type);
881             }
882         }
883
884         if (if_info->loopback)
885             printf("\tloopback");
886         else
887             printf("\tnetwork");
888         printf("\t%s", if_info->extcap);
889         printf("\n");
890     }
891 }
892
893 /*
894  * If you change the machine-readable output format of this function,
895  * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
896  */
897 static void
898 print_machine_readable_if_capabilities(if_capabilities_t *caps, int queries)
899 {
900     GList *lt_entry, *ts_entry;
901     const gchar *desc_str;
902
903     if (capture_child) {
904         /* Let our parent know we succeeded. */
905         pipe_write_block(2, SP_SUCCESS, NULL);
906     }
907
908     if (queries & CAPS_QUERY_LINK_TYPES) {
909         if (caps->can_set_rfmon)
910             printf("1\n");
911         else
912             printf("0\n");
913         for (lt_entry = caps->data_link_types; lt_entry != NULL;
914              lt_entry = g_list_next(lt_entry)) {
915           data_link_info_t *data_link_info = (data_link_info_t *)lt_entry->data;
916           if (data_link_info->description != NULL)
917             desc_str = data_link_info->description;
918           else
919             desc_str = "(not supported)";
920           printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
921                  desc_str);
922         }
923     }
924     printf("\n");
925     if (queries & CAPS_QUERY_TIMESTAMP_TYPES) {
926         for (ts_entry = caps->timestamp_types; ts_entry != NULL;
927              ts_entry = g_list_next(ts_entry)) {
928           timestamp_info_t *timestamp = (timestamp_info_t *)ts_entry->data;
929           if (timestamp->description != NULL)
930             desc_str = timestamp->description;
931           else
932             desc_str = "(none)";
933           printf("%s\t%s\n", timestamp->name, desc_str);
934         }
935     }
936 }
937
938 typedef struct {
939     char *name;
940     pcap_t *pch;
941 } if_stat_t;
942
943 /* Print the number of packets captured for each interface until we're killed. */
944 static int
945 print_statistics_loop(gboolean machine_readable)
946 {
947     GList       *if_list, *if_entry, *stat_list = NULL, *stat_entry;
948     if_info_t   *if_info;
949     if_stat_t   *if_stat;
950     int         err;
951     gchar       *err_str;
952     pcap_t      *pch;
953     char        errbuf[PCAP_ERRBUF_SIZE];
954     struct pcap_stat ps;
955
956     if_list = get_interface_list(&err, &err_str);
957     if (if_list == NULL) {
958        if (err == 0)
959             cmdarg_err("There are no interfaces on which a capture can be done");
960         else {
961             cmdarg_err("%s", err_str);
962             g_free(err_str);
963         }
964         return err;
965     }
966
967     for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
968         if_info = (if_info_t *)if_entry->data;
969
970 #ifdef __linux__
971         /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
972          * connections. We avoid collecting stats on them.
973          */
974         if (!strncmp(if_info->name, "nf", 2)) {
975             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
976                 if_info->name);
977             continue;
978         }
979 #endif
980
981 #ifdef HAVE_PCAP_OPEN
982         pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
983 #else
984         pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
985 #endif
986
987         if (pch) {
988             if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
989             if_stat->name = g_strdup(if_info->name);
990             if_stat->pch = pch;
991             stat_list = g_list_append(stat_list, if_stat);
992         }
993     }
994
995     if (!stat_list) {
996         cmdarg_err("There are no interfaces on which a capture can be done");
997         return 2;
998     }
999
1000     if (capture_child) {
1001         /* Let our parent know we succeeded. */
1002         pipe_write_block(2, SP_SUCCESS, NULL);
1003     }
1004
1005     if (!machine_readable) {
1006         printf("%-15s  %10s  %10s\n", "Interface", "Received",
1007             "Dropped");
1008     }
1009
1010     global_ld.go = TRUE;
1011     while (global_ld.go) {
1012         for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1013             if_stat = (if_stat_t *)stat_entry->data;
1014             pcap_stats(if_stat->pch, &ps);
1015
1016             if (!machine_readable) {
1017                 printf("%-15s  %10u  %10u\n", if_stat->name,
1018                     ps.ps_recv, ps.ps_drop);
1019             } else {
1020                 printf("%s\t%u\t%u\n", if_stat->name,
1021                     ps.ps_recv, ps.ps_drop);
1022                 fflush(stdout);
1023             }
1024         }
1025 #ifdef _WIN32
1026         /* If we have a dummy signal pipe check it */
1027         if (!signal_pipe_check_running()) {
1028             global_ld.go = FALSE;
1029         }
1030         Sleep(1 * 1000);
1031 #else
1032         sleep(1);
1033 #endif
1034     }
1035
1036     /* XXX - Not reached.  Should we look for 'q' in stdin? */
1037     for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1038         if_stat = (if_stat_t *)stat_entry->data;
1039         pcap_close(if_stat->pch);
1040         g_free(if_stat->name);
1041         g_free(if_stat);
1042     }
1043     g_list_free(stat_list);
1044     free_interface_list(if_list);
1045
1046     return 0;
1047 }
1048
1049
1050 #ifdef _WIN32
1051 static BOOL WINAPI
1052 capture_cleanup_handler(DWORD dwCtrlType)
1053 {
1054     /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1055        Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1056        is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1057        like SIGTERM at least when the machine's shutting down.
1058
1059        For now, if we're running as a command rather than a capture child,
1060        we handle all but CTRL_LOGOFF_EVENT as indications that we should
1061        clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1062        in that way on UN*X.
1063
1064        If we're not running as a capture child, we might be running as
1065        a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1066        user logs out.  (XXX - can we explicitly check whether we're
1067        running as a service?) */
1068
1069     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1070         "Console: Control signal");
1071     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1072         "Console: Control signal, CtrlType: %lu", dwCtrlType);
1073
1074     /* Keep capture running if we're a service and a user logs off */
1075     if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1076         capture_loop_stop();
1077         return TRUE;
1078     } else {
1079         return FALSE;
1080     }
1081 }
1082 #else
1083 static void
1084 capture_cleanup_handler(int signum _U_)
1085 {
1086     /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1087        SIGTERM.  We assume that if the user wanted it to keep running
1088        after they logged out, they'd have nohupped it. */
1089
1090     /* Note: don't call g_log() in the signal handler: if we happened to be in
1091      * g_log() in process context when the signal came in, g_log will detect
1092      * the "recursion" and abort.
1093      */
1094
1095     capture_loop_stop();
1096 }
1097 #endif
1098
1099
1100 static void
1101 report_capture_count(gboolean reportit)
1102 {
1103     /* Don't print this if we're a capture child. */
1104     if (!capture_child && reportit) {
1105         fprintf(stderr, "\rPackets captured: %d\n", global_ld.packets_captured);
1106         /* stderr could be line buffered */
1107         fflush(stderr);
1108     }
1109 }
1110
1111
1112 #ifdef SIGINFO
1113 static void
1114 report_counts_for_siginfo(void)
1115 {
1116     report_capture_count(quiet);
1117     infoprint = FALSE; /* we just reported it */
1118 }
1119
1120 static void
1121 report_counts_siginfo(int signum _U_)
1122 {
1123     int sav_errno = errno;
1124
1125     /* If we've been told to delay printing, just set a flag asking
1126        that we print counts (if we're supposed to), otherwise print
1127        the count of packets captured (if we're supposed to). */
1128     if (infodelay)
1129         infoprint = TRUE;
1130     else
1131         report_counts_for_siginfo();
1132     errno = sav_errno;
1133 }
1134 #endif /* SIGINFO */
1135
1136 static void
1137 exit_main(int status)
1138 {
1139 #ifdef _WIN32
1140     /* Shutdown windows sockets */
1141     WSACleanup();
1142
1143     /* can be helpful for debugging */
1144 #ifdef DEBUG_DUMPCAP
1145     printf("Press any key\n");
1146     _getch();
1147 #endif
1148
1149 #endif /* _WIN32 */
1150
1151     capture_opts_cleanup(&global_capture_opts);
1152     exit(status);
1153 }
1154
1155 #ifdef HAVE_LIBCAP
1156 /*
1157  * If we were linked with libcap (not related to libpcap), make sure we have
1158  * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1159  * (See comment in main() for details)
1160  */
1161 static void
1162 relinquish_privs_except_capture(void)
1163 {
1164     /* If 'started_with_special_privs' (ie: suid) then enable for
1165      *  ourself the  NET_ADMIN and NET_RAW capabilities and then
1166      *  drop our suid privileges.
1167      *
1168      * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1169      *                stuff we don't need (and shouldn't have).
1170      * CAP_NET_RAW:   Packet capture (raw sockets).
1171      */
1172
1173     if (started_with_special_privs()) {
1174         cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1175         int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1176
1177         cap_t caps = cap_init();    /* all capabilities initialized to off */
1178
1179         print_caps("Pre drop, pre set");
1180
1181         if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1182             cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1183         }
1184
1185         cap_set_flag(caps, CAP_PERMITTED,   cl_len, cap_list, CAP_SET);
1186         cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1187
1188         if (cap_set_proc(caps)) {
1189             cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1190         }
1191         print_caps("Pre drop, post set");
1192
1193         relinquish_special_privs_perm();
1194
1195         print_caps("Post drop, pre set");
1196         cap_set_flag(caps, CAP_EFFECTIVE,   cl_len, cap_list, CAP_SET);
1197         if (cap_set_proc(caps)) {
1198             cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1199         }
1200         print_caps("Post drop, post set");
1201
1202         cap_free(caps);
1203     }
1204 }
1205
1206 #endif /* HAVE_LIBCAP */
1207
1208 /* Take care of byte order in the libpcap headers read from pipes.
1209  * (function taken from wiretap/libpcap.c) */
1210 static void
1211 cap_pipe_adjust_pcap_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1212 {
1213     if (byte_swapped) {
1214         /* Byte-swap the record header fields. */
1215         rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1216         rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1217         rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1218         rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1219     }
1220
1221     /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1222        swapped, in order to match the BPF header layout.
1223
1224        Unfortunately, some files were, according to a comment in the "libpcap"
1225        source, written with version 2.3 in their headers but without the
1226        interchanged fields, so if "incl_len" is greater than "orig_len" - which
1227        would make no sense - we assume that we need to swap them.  */
1228     if (hdr->version_major == 2 &&
1229         (hdr->version_minor < 3 ||
1230          (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1231         guint32 temp;
1232
1233         temp = rechdr->orig_len;
1234         rechdr->orig_len = rechdr->incl_len;
1235         rechdr->incl_len = temp;
1236     }
1237 }
1238
1239 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1240  * or just read().
1241  */
1242 static ssize_t
1243 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1244 {
1245 #ifdef _WIN32
1246     if (from_socket) {
1247         return recv(pipe_fd, buf, (int)sz, 0);
1248     } else {
1249         return -1;
1250     }
1251 #else
1252     return ws_read(pipe_fd, buf, sz);
1253 #endif
1254 }
1255
1256 #if defined(_WIN32)
1257 /*
1258  * Thread function that reads from a pipe and pushes the data
1259  * to the main application thread.
1260  */
1261 /*
1262  * XXX Right now we use async queues for basic signaling. The main thread
1263  * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1264  * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1265  * Iff the read is successful cap_pipe_read pushes an item onto
1266  * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1267  * the queues themselves (yet).
1268  *
1269  * We might want to move some of the cap_pipe_dispatch logic here so that
1270  * we can let cap_thread_read run independently, queuing up multiple reads
1271  * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1272  */
1273 static void *cap_thread_read(void *arg)
1274 {
1275     capture_src *pcap_src;
1276 #ifdef _WIN32
1277     BOOL res;
1278     DWORD last_err, bytes_read;
1279 #else /* _WIN32 */
1280     size_t bytes_read;
1281 #endif /* _WIN32 */
1282
1283     pcap_src = (capture_src *)arg;
1284     while (pcap_src->cap_pipe_err == PIPOK) {
1285         g_async_queue_pop(pcap_src->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1286         g_mutex_lock(pcap_src->cap_pipe_read_mtx);
1287         bytes_read = 0;
1288         while (bytes_read < pcap_src->cap_pipe_bytes_to_read) {
1289            if ((pcap_src->from_cap_socket)
1290 #ifndef _WIN32
1291               || 1
1292 #endif
1293               )
1294            {
1295                ssize_t b;
1296                b = cap_pipe_read(pcap_src->cap_pipe_fd, pcap_src->cap_pipe_buf+bytes_read,
1297                         pcap_src->cap_pipe_bytes_to_read - bytes_read, pcap_src->from_cap_socket);
1298                if (b <= 0) {
1299                    if (b == 0) {
1300                        pcap_src->cap_pipe_err = PIPEOF;
1301                        bytes_read = 0;
1302                        break;
1303                    } else {
1304                        pcap_src->cap_pipe_err = PIPERR;
1305                        bytes_read = -1;
1306                        break;
1307                    }
1308                } else {
1309                    bytes_read += b;
1310                }
1311            }
1312 #ifdef _WIN32
1313            else
1314            {
1315                /* If we try to use read() on a named pipe on Windows with partial
1316                 * data it appears to return EOF.
1317                 */
1318                DWORD b;
1319                res = ReadFile(pcap_src->cap_pipe_h, pcap_src->cap_pipe_buf+bytes_read,
1320                               pcap_src->cap_pipe_bytes_to_read - bytes_read,
1321                               &b, NULL);
1322
1323                bytes_read += b;
1324                if (!res) {
1325                    last_err = GetLastError();
1326                    if (last_err == ERROR_MORE_DATA) {
1327                        continue;
1328                    } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1329                        pcap_src->cap_pipe_err = PIPEOF;
1330                        bytes_read = 0;
1331                        break;
1332                    }
1333                    pcap_src->cap_pipe_err = PIPERR;
1334                    bytes_read = -1;
1335                    break;
1336                } else if (b == 0 && pcap_src->cap_pipe_bytes_to_read > 0) {
1337                    pcap_src->cap_pipe_err = PIPEOF;
1338                    bytes_read = 0;
1339                    break;
1340                }
1341            }
1342 #endif /*_WIN32 */
1343         }
1344         pcap_src->cap_pipe_bytes_read = bytes_read;
1345         if (pcap_src->cap_pipe_bytes_read >= pcap_src->cap_pipe_bytes_to_read) {
1346             g_async_queue_push(pcap_src->cap_pipe_done_q, pcap_src->cap_pipe_buf); /* Any non-NULL value will do */
1347         }
1348         g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
1349     }
1350     return NULL;
1351 }
1352 #endif
1353
1354 /* Provide select() functionality for a single file descriptor
1355  * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1356  *
1357  * Returns the same values as select.
1358  */
1359 static int
1360 cap_pipe_select(int pipe_fd)
1361 {
1362     fd_set      rfds;
1363     struct timeval timeout;
1364
1365     FD_ZERO(&rfds);
1366     FD_SET(pipe_fd, &rfds);
1367
1368     timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1369     timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1370
1371     return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1372 }
1373
1374 #define DEF_TCP_PORT 19000
1375
1376 static int
1377 cap_open_socket(char *pipename, capture_src *pcap_src, char *errmsg, size_t errmsgl)
1378 {
1379     char *sockname = pipename + 4;
1380     struct sockaddr_in sa;
1381     char buf[16];
1382     char *p;
1383     unsigned long port;
1384     size_t len;
1385     int fd;
1386
1387     memset(&sa, 0, sizeof(sa));
1388
1389     p = strchr(sockname, ':');
1390     if (p == NULL) {
1391         len = strlen(sockname);
1392         port = DEF_TCP_PORT;
1393     }
1394     else {
1395         len = p - sockname;
1396         port = strtoul(p + 1, &p, 10);
1397         if (*p || port > 65535) {
1398             goto fail_invalid;
1399         }
1400     }
1401
1402     if (len > 15) {
1403       goto fail_invalid;
1404     }
1405
1406     g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
1407     buf[len] = '\0';
1408     if (!ws_inet_pton4(buf, (guint32 *)&sa.sin_addr)) {
1409         goto fail_invalid;
1410     }
1411
1412     sa.sin_family = AF_INET;
1413     sa.sin_port = g_htons((u_short)port);
1414
1415     if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1416          (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1417 #ifdef _WIN32
1418         LPTSTR errorText = NULL;
1419         int lastError;
1420
1421         lastError = WSAGetLastError();
1422         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1423                       FORMAT_MESSAGE_ALLOCATE_BUFFER |
1424                       FORMAT_MESSAGE_IGNORE_INSERTS,
1425                       NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1426                       (LPTSTR)&errorText, 0, NULL);
1427 #endif
1428         g_snprintf(errmsg, (gulong)errmsgl,
1429             "The capture session could not be initiated due to the socket error: \n"
1430 #ifdef _WIN32
1431             "         %d: %s", lastError, errorText ? (char *)errorText : "Unknown");
1432         if (errorText)
1433             LocalFree(errorText);
1434 #else
1435             "         %d: %s", errno, g_strerror(errno));
1436 #endif
1437         pcap_src->cap_pipe_err = PIPERR;
1438
1439         if (fd >= 0)
1440             cap_pipe_close(fd, TRUE);
1441         return -1;
1442     }
1443
1444     pcap_src->from_cap_socket = TRUE;
1445     return fd;
1446
1447 fail_invalid:
1448     g_snprintf(errmsg, (gulong)errmsgl,
1449         "The capture session could not be initiated because\n"
1450         "\"%s\" is not a valid socket specification", pipename);
1451     pcap_src->cap_pipe_err = PIPERR;
1452     return -1;
1453 }
1454
1455 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1456  * otherwise.
1457  */
1458 static void
1459 cap_pipe_close(int pipe_fd, gboolean from_socket)
1460 {
1461 #ifdef _WIN32
1462     if (from_socket) {
1463         closesocket(pipe_fd);
1464     }
1465 #else
1466     (void) from_socket; /* Mark unused, similar to Q_UNUSED */
1467     ws_close(pipe_fd);
1468 #endif
1469 }
1470
1471 /** Read bytes from a capture source, which is assumed to be a pipe.
1472  *
1473  * Returns -1, or the number of bytes read similar to read(2).
1474  * Sets pcap_src->cap_pipe_err on error or EOF.
1475  */
1476 static ssize_t
1477 cap_pipe_read_data_bytes(capture_src *pcap_src, char *errmsg, size_t errmsgl)
1478 {
1479     int sel_ret;
1480     int fd = pcap_src->cap_pipe_fd;
1481 #ifdef _WIN32
1482     DWORD sz, bytes_read = 0;
1483 #else /* _WIN32 */
1484     ssize_t sz, bytes_read = 0;
1485 #endif /* _WIN32 */
1486     ssize_t b;
1487
1488 #ifdef LOG_CAPTURE_VERBOSE
1489     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_read_data_bytes read %lu of %lu",
1490           pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1491 #endif
1492     sz = pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read;
1493     while (bytes_read < sz) {
1494         if (fd == -1) {
1495             g_snprintf(errmsg, (gulong)errmsgl, "Invalid file descriptor.");
1496             pcap_src->cap_pipe_err = PIPNEXIST;
1497             return -1;
1498         }
1499
1500         sel_ret = cap_pipe_select(fd);
1501         if (sel_ret < 0) {
1502             g_snprintf(errmsg, (gulong)errmsgl,
1503                        "Unexpected error from select: %s.", g_strerror(errno));
1504             pcap_src->cap_pipe_err = PIPERR;
1505             return -1;
1506         } else if (sel_ret > 0) {
1507             b = cap_pipe_read(fd, pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read+bytes_read,
1508                               sz-bytes_read, pcap_src->from_cap_socket);
1509             if (b <= 0) {
1510                 if (b == 0) {
1511                     g_snprintf(errmsg, (gulong)errmsgl,
1512                                "End of file on pipe during cap_pipe_read.");
1513                     pcap_src->cap_pipe_err = PIPEOF;
1514                 } else {
1515 #ifdef _WIN32
1516                     LPTSTR errorText = NULL;
1517                     int lastError = WSAGetLastError();
1518                     errno = lastError;
1519                     FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1520                                 FORMAT_MESSAGE_ALLOCATE_BUFFER |
1521                                 FORMAT_MESSAGE_IGNORE_INSERTS,
1522                                 NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1523                                 (LPTSTR)&errorText, 0, NULL);
1524                     g_snprintf(errmsg, (gulong)errmsgl,
1525                                "Error on pipe data during cap_pipe_read: "
1526                                "         %d: %s", lastError,
1527                                errorText ? (char *)errorText : "Unknown");
1528                     if (errorText)
1529                         LocalFree(errorText);
1530 #else
1531                     g_snprintf(errmsg, (gulong)errmsgl,
1532                                "Error on pipe data during cap_pipe_read: %s.",
1533                                g_strerror(errno));
1534 #endif
1535                     pcap_src->cap_pipe_err = PIPERR;
1536                 }
1537                 return -1;
1538             }
1539             bytes_read += b;
1540         }
1541     }
1542     pcap_src->cap_pipe_bytes_read += bytes_read;
1543 #ifdef LOG_CAPTURE_VERBOSE
1544     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_read_data_bytes read %lu of %lu",
1545           pcap_src->cap_pipe_bytes_read, pcap_src->cap_pipe_bytes_to_read);
1546 #endif
1547     return bytes_read;
1548 }
1549
1550 /* Some forward declarations for breaking up cap_pipe_open_live for pcap and pcapng formats */
1551 static void pcap_pipe_open_live(int fd, capture_src *pcap_src,
1552                                 struct pcap_hdr *hdr,
1553                                 char *errmsg, size_t errmsgl,
1554                                 char *secondary_errmsg, size_t secondary_errmsgl);
1555 static void pcapng_pipe_open_live(int fd, capture_src *pcap_src,
1556                                   char *errmsg, size_t errmsgl);
1557 static int pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src,
1558                                 char *errmsg, size_t errmsgl);
1559
1560 /* For problems that are probably Not Our Fault. */
1561 static char not_our_bug[] =
1562     "Please report this to the developers of the program writing to the pipe.";
1563
1564 /* Mimic pcap_open_live() for pipe captures
1565
1566  * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1567  * open it, and read the header.
1568  *
1569  * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1570  * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1571 static void
1572 cap_pipe_open_live(char *pipename,
1573                    capture_src *pcap_src,
1574                    void *hdr,
1575                    char *errmsg, size_t errmsgl,
1576                    char *secondary_errmsg, size_t secondary_errmsgl)
1577 {
1578 #ifndef _WIN32
1579     ws_statb64         pipe_stat;
1580     struct sockaddr_un sa;
1581 #else /* _WIN32 */
1582     char    *pncopy, *pos;
1583     wchar_t *err_str;
1584     char* extcap_pipe_name;
1585 #endif
1586     gboolean extcap_pipe = FALSE;
1587     ssize_t  b;
1588     int      fd = -1, sel_ret;
1589     size_t   bytes_read;
1590     guint32  magic = 0;
1591     pcap_src->cap_pipe_fd = -1;
1592 #ifdef _WIN32
1593     pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1594 #endif
1595
1596     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1597
1598     /*
1599      * XXX - this blocks until a pcap per-file header has been written to
1600      * the pipe, so it could block indefinitely.
1601      */
1602     if (strcmp(pipename, "-") == 0) {
1603 #ifndef _WIN32
1604         fd = 0; /* read from stdin */
1605 #else /* _WIN32 */
1606         pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1607 #endif  /* _WIN32 */
1608     } else if (!strncmp(pipename, "TCP@", 4)) {
1609        if ((fd = cap_open_socket(pipename, pcap_src, errmsg, errmsgl)) < 0) {
1610           return;
1611        }
1612     } else {
1613 #ifndef _WIN32
1614         if ( g_strrstr(pipename, EXTCAP_PIPE_PREFIX) != NULL )
1615             extcap_pipe = TRUE;
1616
1617         if (ws_stat64(pipename, &pipe_stat) < 0) {
1618             if (errno == ENOENT || errno == ENOTDIR)
1619                 pcap_src->cap_pipe_err = PIPNEXIST;
1620             else {
1621                 g_snprintf(errmsg, (gulong)errmsgl,
1622                            "The capture session could not be initiated "
1623                            "due to error getting information on pipe/socket: %s.", g_strerror(errno));
1624                 pcap_src->cap_pipe_err = PIPERR;
1625             }
1626             return;
1627         }
1628         if (S_ISFIFO(pipe_stat.st_mode)) {
1629             fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1630             if (fd == -1) {
1631                 g_snprintf(errmsg, (gulong)errmsgl,
1632                            "The capture session could not be initiated "
1633                            "due to error on pipe open: %s.", g_strerror(errno));
1634                 pcap_src->cap_pipe_err = PIPERR;
1635                 return;
1636             }
1637         } else if (S_ISSOCK(pipe_stat.st_mode)) {
1638             fd = socket(AF_UNIX, SOCK_STREAM, 0);
1639             if (fd == -1) {
1640                 g_snprintf(errmsg, (gulong)errmsgl,
1641                            "The capture session could not be initiated "
1642                            "due to error on socket create: %s.", g_strerror(errno));
1643                 pcap_src->cap_pipe_err = PIPERR;
1644                 return;
1645             }
1646             sa.sun_family = AF_UNIX;
1647             /*
1648              * The Single UNIX Specification says:
1649              *
1650              *   The size of sun_path has intentionally been left undefined.
1651              *   This is because different implementations use different sizes.
1652              *   For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1653              *   of 104. Since most implementations originate from BSD versions,
1654              *   the size is typically in the range 92 to 108.
1655              *
1656              *   Applications should not assume a particular length for sun_path
1657              *   or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1658              *
1659              * It also says
1660              *
1661              *   The <sys/un.h> header shall define the sockaddr_un structure,
1662              *   which shall include at least the following members:
1663              *
1664              *   sa_family_t  sun_family  Address family.
1665              *   char         sun_path[]  Socket pathname.
1666              *
1667              * so we assume that it's an array, with a specified size,
1668              * and that the size reflects the maximum path length.
1669              */
1670             if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1671                 /* Path name too long */
1672                 g_snprintf(errmsg, (gulong)errmsgl,
1673                            "The capture session coud not be initiated "
1674                            "due to error on socket connect: Path name too long.");
1675                 pcap_src->cap_pipe_err = PIPERR;
1676                 ws_close(fd);
1677                 return;
1678             }
1679             b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1680             if (b == -1) {
1681                 g_snprintf(errmsg, (gulong)errmsgl,
1682                            "The capture session coud not be initiated "
1683                            "due to error on socket connect: %s.", g_strerror(errno));
1684                 pcap_src->cap_pipe_err = PIPERR;
1685                 ws_close(fd);
1686                 return;
1687             }
1688         } else {
1689             if (S_ISCHR(pipe_stat.st_mode)) {
1690                 /*
1691                  * Assume the user specified an interface on a system where
1692                  * interfaces are in /dev.  Pretend we haven't seen it.
1693                  */
1694                 pcap_src->cap_pipe_err = PIPNEXIST;
1695             } else {
1696                 g_snprintf(errmsg, (gulong)errmsgl,
1697                            "The capture session could not be initiated because\n"
1698                            "\"%s\" is neither an interface nor a socket nor a pipe.", pipename);
1699                 pcap_src->cap_pipe_err = PIPERR;
1700             }
1701             return;
1702         }
1703
1704 #else /* _WIN32 */
1705 #define PIPE_STR "\\pipe\\"
1706         /* Under Windows, named pipes _must_ have the form
1707          * "\\<server>\pipe\<pipename>".  <server> may be "." for localhost.
1708          */
1709         pncopy = g_strdup(pipename);
1710         if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1711             pos = strchr(pncopy + 3, '\\');
1712             if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1713                 pos = NULL;
1714         }
1715
1716         g_free(pncopy);
1717
1718         if (!pos) {
1719             g_snprintf(errmsg, (gulong)errmsgl,
1720                        "The capture session could not be initiated because\n"
1721                        "\"%s\" is neither an interface nor a pipe.", pipename);
1722             pcap_src->cap_pipe_err = PIPNEXIST;
1723             return;
1724         }
1725         extcap_pipe_name = g_strconcat("\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, NULL);
1726         extcap_pipe = strstr(pipename, extcap_pipe_name) ? TRUE : FALSE;
1727         g_free(extcap_pipe_name);
1728
1729         /* Wait for the pipe to appear */
1730         while (1) {
1731             if(extcap_pipe)
1732                 pcap_src->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1733             else
1734                 pcap_src->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1735                                                    OPEN_EXISTING, 0, NULL);
1736
1737             if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE)
1738                 break;
1739
1740             if (GetLastError() != ERROR_PIPE_BUSY) {
1741                 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1742                               NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1743                 g_snprintf(errmsg, (gulong)errmsgl,
1744                            "The capture session on \"%s\" could not be started "
1745                            "due to error on pipe open: %s (error %lu).",
1746                            pipename, utf_16to8(err_str), GetLastError());
1747                 LocalFree(err_str);
1748                 pcap_src->cap_pipe_err = PIPERR;
1749                 return;
1750             }
1751
1752             if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1753                 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
1754                              NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1755                 g_snprintf(errmsg, (gulong)errmsgl,
1756                            "The capture session on \"%s\" timed out during "
1757                            "pipe open: %s (error %lu).",
1758                            pipename, utf_16to8(err_str), GetLastError());
1759                 LocalFree(err_str);
1760                 pcap_src->cap_pipe_err = PIPERR;
1761                 return;
1762             }
1763         }
1764 #endif /* _WIN32 */
1765     }
1766
1767     pcap_src->from_cap_pipe = TRUE;
1768
1769     /*
1770      * We start with a 2KB buffer for packet data, which should be
1771      * large enough for most regular network packets.  We increase it,
1772      * up to the maximum size we allow, as necessary.
1773      */
1774     pcap_src->cap_pipe_databuf = (char*)g_malloc(2048);
1775     pcap_src->cap_pipe_databuf_size = 2048;
1776
1777 #ifdef _WIN32
1778     if (pcap_src->from_cap_socket)
1779 #endif
1780     {
1781         /* read the pcap header */
1782         bytes_read = 0;
1783         while (bytes_read < sizeof magic) {
1784             sel_ret = cap_pipe_select(fd);
1785             if (sel_ret < 0) {
1786                 g_snprintf(errmsg, (gulong)errmsgl,
1787                            "Unexpected error from select: %s.",
1788                            g_strerror(errno));
1789                 goto error;
1790             } else if (sel_ret > 0) {
1791                 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
1792                                   sizeof magic-bytes_read,
1793                                   pcap_src->from_cap_socket);
1794                 /* jump messaging, if extcap had an error, stderr will provide the correct message */
1795                 if (extcap_pipe && b <= 0)
1796                     goto error;
1797
1798                 if (b <= 0) {
1799                     if (b == 0)
1800                         g_snprintf(errmsg, (gulong)errmsgl,
1801                                    "End of file on pipe magic during open.");
1802                     else
1803                         g_snprintf(errmsg, (gulong)errmsgl,
1804                                    "Error on pipe magic during open: %s.",
1805                                    g_strerror(errno));
1806                     goto error;
1807                 }
1808                 bytes_read += b;
1809             }
1810         }
1811     }
1812 #ifdef _WIN32
1813     else {
1814         g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
1815
1816         pcap_src->cap_pipe_buf = (char *) &magic;
1817         pcap_src->cap_pipe_bytes_read = 0;
1818         pcap_src->cap_pipe_bytes_to_read = sizeof(magic);
1819         /* We don't have to worry about cap_pipe_read_mtx here */
1820         g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1821         g_async_queue_pop(pcap_src->cap_pipe_done_q);
1822         /* jump messaging, if extcap had an error, stderr will provide the correct message */
1823         if (pcap_src->cap_pipe_bytes_read <= 0 && extcap_pipe)
1824             goto error;
1825
1826         if (pcap_src->cap_pipe_bytes_read <= 0) {
1827             if (pcap_src->cap_pipe_bytes_read == 0)
1828                 g_snprintf(errmsg, (gulong)errmsgl,
1829                            "End of file on pipe magic during open.");
1830             else
1831                 g_snprintf(errmsg, (gulong)errmsgl,
1832                            "Error on pipe magic during open: %s.",
1833                            g_strerror(errno));
1834             goto error;
1835         }
1836     }
1837 #endif
1838
1839     switch (magic) {
1840     case PCAP_MAGIC:
1841     case PCAP_NSEC_MAGIC:
1842         /* Host that wrote it has our byte order, and was running
1843            a program using either standard or ss990417 libpcap. */
1844         pcap_src->cap_pipe_info.pcap.byte_swapped = FALSE;
1845         pcap_src->cap_pipe_modified = FALSE;
1846         pcap_src->ts_nsec = magic == PCAP_NSEC_MAGIC;
1847         break;
1848     case PCAP_MODIFIED_MAGIC:
1849         /* Host that wrote it has our byte order, but was running
1850            a program using either ss990915 or ss991029 libpcap. */
1851         pcap_src->cap_pipe_info.pcap.byte_swapped = FALSE;
1852         pcap_src->cap_pipe_modified = TRUE;
1853         break;
1854     case PCAP_SWAPPED_MAGIC:
1855     case PCAP_SWAPPED_NSEC_MAGIC:
1856         /* Host that wrote it has a byte order opposite to ours,
1857            and was running a program using either standard or
1858            ss990417 libpcap. */
1859         pcap_src->cap_pipe_info.pcap.byte_swapped = TRUE;
1860         pcap_src->cap_pipe_modified = FALSE;
1861         pcap_src->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
1862         break;
1863     case PCAP_SWAPPED_MODIFIED_MAGIC:
1864         /* Host that wrote it out has a byte order opposite to
1865            ours, and was running a program using either ss990915
1866            or ss991029 libpcap. */
1867         pcap_src->cap_pipe_info.pcap.byte_swapped = TRUE;
1868         pcap_src->cap_pipe_modified = TRUE;
1869         break;
1870     case BLOCK_TYPE_SHB:
1871         /* This isn't pcap, it's pcapng. */
1872         pcap_src->from_pcapng = TRUE;
1873         pcap_src->cap_pipe_dispatch = pcapng_pipe_dispatch;
1874         pcap_src->cap_pipe_info.pcapng.src_iface_to_global = g_array_new(FALSE, FALSE, sizeof(guint32));
1875         global_capture_opts.use_pcapng = TRUE;      /* we can only output in pcapng format */
1876         pcapng_pipe_open_live(fd, pcap_src, errmsg, errmsgl);
1877         return;
1878     default:
1879         /* Not a pcap type we know about, or not pcap at all. */
1880         g_snprintf(errmsg, (gulong)errmsgl,
1881                    "Data written to the pipe is neither in a supported pcap format nor in pcapng format.");
1882         g_snprintf(secondary_errmsg, (gulong)secondary_errmsgl, "%s",
1883                    not_our_bug);
1884         goto error;
1885     }
1886
1887     pcap_pipe_open_live(fd, pcap_src, (struct pcap_hdr *) hdr, errmsg, errmsgl,
1888                         secondary_errmsg, secondary_errmsgl);
1889     return;
1890
1891 error:
1892     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1893     pcap_src->cap_pipe_err = PIPERR;
1894     cap_pipe_close(fd, pcap_src->from_cap_socket);
1895     pcap_src->cap_pipe_fd = -1;
1896 #ifdef _WIN32
1897     pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
1898 #endif
1899 }
1900
1901 static void
1902 pcap_pipe_open_live(int fd,
1903                     capture_src *pcap_src,
1904                     struct pcap_hdr *hdr,
1905                     char *errmsg, size_t errmsgl,
1906                     char *secondary_errmsg, size_t secondary_errmsgl)
1907 {
1908     size_t   bytes_read;
1909     ssize_t  b;
1910     int      sel_ret;
1911 #ifdef _WIN32
1912     if (pcap_src->from_cap_socket)
1913 #endif
1914     {
1915         /* Read the rest of the header */
1916         bytes_read = 0;
1917         while (bytes_read < sizeof(struct pcap_hdr)) {
1918             sel_ret = cap_pipe_select(fd);
1919             if (sel_ret < 0) {
1920                 g_snprintf(errmsg, (gulong)errmsgl,
1921                            "Unexpected error from select: %s.",
1922                            g_strerror(errno));
1923                 goto error;
1924             } else if (sel_ret > 0) {
1925                 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
1926                                   sizeof(struct pcap_hdr) - bytes_read,
1927                                   pcap_src->from_cap_socket);
1928                 if (b <= 0) {
1929                     if (b == 0)
1930                         g_snprintf(errmsg, (gulong)errmsgl,
1931                                    "End of file on pipe header during open.");
1932                     else
1933                         g_snprintf(errmsg, (gulong)errmsgl,
1934                                    "Error on pipe header during open: %s.",
1935                                    g_strerror(errno));
1936                     g_snprintf(secondary_errmsg, (gulong)secondary_errmsgl,
1937                                "%s", not_our_bug);
1938                     goto error;
1939                 }
1940                 bytes_read += b;
1941             }
1942         }
1943     }
1944 #ifdef _WIN32
1945     else {
1946         pcap_src->cap_pipe_buf = (char *) hdr;
1947         pcap_src->cap_pipe_bytes_read = 0;
1948         pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1949         g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
1950         g_async_queue_pop(pcap_src->cap_pipe_done_q);
1951         if (pcap_src->cap_pipe_bytes_read <= 0) {
1952             if (pcap_src->cap_pipe_bytes_read == 0)
1953                 g_snprintf(errmsg, (gulong)errmsgl,
1954                            "End of file on pipe header during open.");
1955             else
1956                 g_snprintf(errmsg, (gulong)errmsgl,
1957                            "Error on pipe header header during open: %s.",
1958                            g_strerror(errno));
1959             g_snprintf(secondary_errmsg, (gulong)secondary_errmsgl, "%s",
1960                        not_our_bug);
1961             goto error;
1962         }
1963     }
1964 #endif
1965
1966     if (pcap_src->cap_pipe_info.pcap.byte_swapped) {
1967         /* Byte-swap the header fields about which we care. */
1968         hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
1969         hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
1970         hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
1971         hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
1972     }
1973     pcap_src->linktype = hdr->network;
1974 #ifdef DLT_DBUS
1975     if (pcap_src->linktype == DLT_DBUS) {
1976         /*
1977          * The maximum D-Bus message size is 128MB, so allow packets up
1978          * to that size.
1979          */
1980         pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_DBUS;
1981     } else
1982 #endif
1983     if (pcap_src->linktype == 279) {             /* DLT_EBHSCR */
1984         /*
1985          * The maximum EBHSCR message size is 8MB, so allow packets up
1986          * to that size.
1987          */
1988         pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_EBHSCR;
1989     }
1990     else {
1991         pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
1992     }
1993
1994     if (hdr->version_major < 2) {
1995         g_snprintf(errmsg, (gulong)errmsgl,
1996                    "The old pcap format version %d.%d is not supported.",
1997                    hdr->version_major, hdr->version_minor);
1998         g_snprintf(secondary_errmsg, (gulong)secondary_errmsgl, "%s",
1999                    not_our_bug);
2000         goto error;
2001     }
2002
2003     pcap_src->cap_pipe_fd = fd;
2004     return;
2005
2006 error:
2007     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcap_pipe_open_live: error %s", errmsg);
2008     pcap_src->cap_pipe_err = PIPERR;
2009     cap_pipe_close(fd, pcap_src->from_cap_socket);
2010     pcap_src->cap_pipe_fd = -1;
2011 #ifdef _WIN32
2012     pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2013 #endif
2014 }
2015
2016 /* Read the pcapng section header block */
2017 static int
2018 pcapng_read_shb(capture_src *pcap_src,
2019                 char *errmsg,
2020                 size_t errmsgl)
2021 {
2022     struct pcapng_section_header_block_s shb;
2023
2024 #ifdef _WIN32
2025     if (pcap_src->from_cap_socket)
2026 #endif
2027     {
2028         pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_block_header_s) + sizeof(struct pcapng_section_header_block_s);
2029         if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2030             return -1;
2031         }
2032     }
2033 #ifdef _WIN32
2034     else {
2035         pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf + sizeof(struct pcapng_block_header_s);
2036         pcap_src->cap_pipe_bytes_read = 0;
2037         pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_section_header_block_s);
2038         g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2039         g_async_queue_pop(pcap_src->cap_pipe_done_q);
2040         if (pcap_src->cap_pipe_bytes_read <= 0) {
2041             if (pcap_src->cap_pipe_bytes_read == 0)
2042                 g_snprintf(errmsg, (gulong)errmsgl,
2043                            "End of file on pipe section header during open.");
2044             else
2045                 g_snprintf(errmsg, (gulong)errmsgl,
2046                            "Error on pipe section header during open: %s.",
2047                            g_strerror(errno));
2048             return -1;
2049         }
2050         /* Continuing with STATE_EXPECT_DATA requires reading into cap_pipe_databuf at offset cap_pipe_bytes_read */
2051         pcap_src->cap_pipe_bytes_read = sizeof(struct pcapng_block_header_s) + sizeof(struct pcapng_section_header_block_s);
2052     }
2053 #endif
2054     memcpy(&shb, pcap_src->cap_pipe_databuf + sizeof(struct pcapng_block_header_s), sizeof(struct pcapng_section_header_block_s));
2055     switch (shb.magic)
2056     {
2057     case PCAPNG_MAGIC:
2058         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng SHB MAGIC");
2059         break;
2060     case PCAPNG_SWAPPED_MAGIC:
2061         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng SHB SWAPPED MAGIC");
2062         /*
2063          * pcapng sources can contain all sorts of block types. Rather than add a bunch of
2064          * complexity to this code (which is often privileged), punt and tell the user to
2065          * swap bytes elsewhere.
2066          */
2067 #if G_BYTE_ORDER == G_BIG_ENDIAN
2068 #define OUR_ENDIAN "big"
2069 #define IFACE_ENDIAN "little"
2070 #else
2071 #define OUR_ENDIAN "little"
2072 #define IFACE_ENDIAN "big"
2073 #endif
2074         g_snprintf(errmsg, (gulong)errmsgl,
2075                    "Interface %u is " IFACE_ENDIAN " endian but we're " OUR_ENDIAN " endian.",
2076                    pcap_src->interface_id);
2077         return -1;
2078     default:
2079         /* Not a pcapng type we know about, or not pcapng at all. */
2080         g_snprintf(errmsg, (gulong)errmsgl,
2081                    "Unrecognized pcapng format or not pcapng data.");
2082         return -1;
2083     }
2084
2085     pcap_src->cap_pipe_max_pkt_size = WTAP_MAX_PACKET_SIZE_STANDARD;
2086
2087     /* Setup state to capture any options following the section header block */
2088     pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2089
2090     return 0;
2091 }
2092
2093 /*
2094  * Save IDB blocks for playback whenever we change output files.
2095  * Rewrite EPB and ISB interface IDs.
2096  */
2097 static gboolean
2098 pcapng_adjust_block(capture_src *pcap_src, const struct pcapng_block_header_s *bh, u_char *pd)
2099 {
2100     switch(bh->block_type) {
2101     case BLOCK_TYPE_SHB:
2102     {
2103         if (global_ld.pcapng_passthrough) {
2104             /*
2105              * We have a single pcapng input. We pass the SHB through when
2106              * writing a single output file and for the first ring buffer
2107              * file. We need to save it for the second and subsequent ring
2108              * buffer files.
2109              */
2110             g_free(global_ld.saved_shb);
2111             global_ld.saved_shb = (guint8 *) g_memdup(pd, bh->block_total_length);
2112
2113             /*
2114              * We're dealing with one section at a time, so we can (and must)
2115              * get rid of our old IDBs.
2116              */
2117             for (unsigned i = 0; i < global_ld.saved_idbs->len; i++) {
2118                 saved_idb_t *idb_source = &g_array_index(global_ld.saved_idbs, saved_idb_t, i);
2119                 g_free(idb_source->idb);
2120             }
2121             g_array_set_size(global_ld.saved_idbs, 0);
2122         } else {
2123             /*
2124              * We have a new SHB from this capture source. We need to keep
2125              * global_ld.saved_idbs intact, so we mark IDBs we previously
2126              * collected from this source as deleted.
2127              */
2128             for (unsigned i = 0; i < pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len; i++) {
2129                 guint32 iface_id = g_array_index(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, guint32, i);
2130                 saved_idb_t *idb_source = &g_array_index(global_ld.saved_idbs, saved_idb_t, iface_id);
2131                 g_assert(idb_source->interface_id == pcap_src->interface_id);
2132                 g_free(idb_source->idb);
2133                 memset(idb_source, 0, sizeof(saved_idb_t));
2134                 idb_source->deleted = TRUE;
2135                 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: deleted pcapng IDB %u", G_STRFUNC, iface_id);
2136             }
2137         }
2138         g_array_set_size(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, 0);
2139     }
2140         break;
2141     case BLOCK_TYPE_IDB:
2142     {
2143         /*
2144          * Always gather IDBs. We can remove them or mark them as deleted
2145          * when we get a new SHB.
2146          */
2147         saved_idb_t idb_source = { 0 };
2148         idb_source.interface_id = pcap_src->interface_id;
2149         idb_source.idb_len = bh->block_total_length;
2150         idb_source.idb = (guint8 *) g_memdup(pd, idb_source.idb_len);
2151         g_array_append_val(global_ld.saved_idbs, idb_source);
2152         guint32 iface_id = global_ld.saved_idbs->len - 1;
2153         g_array_append_val(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, iface_id);
2154         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: mapped pcapng IDB %u -> %u from source %u",
2155               G_STRFUNC, pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len - 1, iface_id, pcap_src->interface_id);
2156     }
2157         break;
2158     case BLOCK_TYPE_EPB:
2159     case BLOCK_TYPE_ISB:
2160     {
2161         if (global_ld.pcapng_passthrough) {
2162             /* Our input and output interface IDs are the same. */
2163             break;
2164         }
2165         /* The interface ID is the first 32-bit field after the BH for both EPBs and ISBs. */
2166         guint32 iface_id;
2167         memcpy(&iface_id, pd + sizeof(struct pcapng_block_header_s), 4);
2168         if (iface_id < pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len) {
2169             memcpy(pd + sizeof(struct pcapng_block_header_s),
2170                    &g_array_index(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, guint32, iface_id), 4);
2171         } else {
2172             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: pcapng EPB or ISB interface id %u > max %u", G_STRFUNC, iface_id, pcap_src->cap_pipe_info.pcapng.src_iface_to_global->len);
2173             return FALSE;
2174         }
2175     }
2176         break;
2177     default:
2178         break;
2179     }
2180
2181     return TRUE;
2182 }
2183
2184 static void
2185 pcapng_pipe_open_live(int fd,
2186                       capture_src *pcap_src,
2187                       char *errmsg,
2188                       size_t errmsgl)
2189 {
2190     guint32 type = BLOCK_TYPE_SHB;
2191     struct pcapng_block_header_s *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2192
2193     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_open_live: fd %d", fd);
2194 #ifdef _WIN32
2195     if (pcap_src->from_cap_socket)
2196 #endif
2197     {
2198         memcpy(pcap_src->cap_pipe_databuf, &type, sizeof(guint32));
2199         /* read the rest of the pcapng general block header */
2200         pcap_src->cap_pipe_bytes_read = sizeof(guint32);
2201         pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_block_header_s);
2202         pcap_src->cap_pipe_fd = fd;
2203         if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2204             goto error;
2205         }
2206         memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(struct pcapng_block_header_s));
2207     }
2208 #ifdef _WIN32
2209     else {
2210         g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_src);
2211
2212         bh->block_type = type;
2213         pcap_src->cap_pipe_buf = (char *) &bh->block_total_length;
2214         pcap_src->cap_pipe_bytes_read = 0;
2215         pcap_src->cap_pipe_bytes_to_read = sizeof(bh->block_total_length);
2216         /* We don't have to worry about cap_pipe_read_mtx here */
2217         g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2218         g_async_queue_pop(pcap_src->cap_pipe_done_q);
2219         if (pcap_src->cap_pipe_bytes_read <= 0) {
2220             if (pcap_src->cap_pipe_bytes_read == 0)
2221                 g_snprintf(errmsg, (gulong)errmsgl,
2222                            "End of file on pipe block_total_length during open.");
2223             else
2224                 g_snprintf(errmsg, (gulong)errmsgl,
2225                            "Error on pipe block_total_length during open: %s.",
2226                            g_strerror(errno));
2227             goto error;
2228         }
2229         pcap_src->cap_pipe_bytes_read = sizeof(struct pcapng_block_header_s);
2230         memcpy(pcap_src->cap_pipe_databuf, bh, sizeof(struct pcapng_block_header_s));
2231         pcap_src->cap_pipe_fd = fd;
2232     }
2233 #endif
2234     if (pcapng_read_shb(pcap_src, errmsg, errmsgl)) {
2235         goto error;
2236     }
2237
2238     return;
2239
2240 error:
2241     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_open_live: error %s", errmsg);
2242     pcap_src->cap_pipe_err = PIPERR;
2243     cap_pipe_close(fd, pcap_src->from_cap_socket);
2244     pcap_src->cap_pipe_fd = -1;
2245 #ifdef _WIN32
2246     pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2247 #endif
2248 }
2249
2250 /* We read one record from the pipe, take care of byte order in the record
2251  * header, write the record to the capture file, and update capture statistics. */
2252 static int
2253 pcap_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, size_t errmsgl)
2254 {
2255     struct pcap_pkthdr  phdr;
2256     enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2257            PD_ERR } result;
2258 #ifdef _WIN32
2259     gpointer  q_status;
2260     wchar_t  *err_str;
2261 #endif
2262     ssize_t   b;
2263     guint new_bufsize;
2264     pcap_pipe_info_t *pcap_info = &pcap_src->cap_pipe_info.pcap;
2265
2266 #ifdef LOG_CAPTURE_VERBOSE
2267     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcap_pipe_dispatch");
2268 #endif
2269
2270     switch (pcap_src->cap_pipe_state) {
2271
2272     case STATE_EXPECT_REC_HDR:
2273 #ifdef _WIN32
2274         if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2275 #endif
2276
2277             pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2278             pcap_src->cap_pipe_bytes_to_read = pcap_src->cap_pipe_modified ?
2279                 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2280             pcap_src->cap_pipe_bytes_read = 0;
2281
2282 #ifdef _WIN32
2283             pcap_src->cap_pipe_buf = (char *) &pcap_info->rechdr;
2284             g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2285             g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2286         }
2287 #endif
2288         /* Fall through */
2289
2290     case STATE_READ_REC_HDR:
2291 #ifdef _WIN32
2292         if (pcap_src->from_cap_socket)
2293 #endif
2294         {
2295             b = cap_pipe_read(pcap_src->cap_pipe_fd, ((char *)&pcap_info->rechdr)+pcap_src->cap_pipe_bytes_read,
2296                  pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read, pcap_src->from_cap_socket);
2297             if (b <= 0) {
2298                 if (b == 0)
2299                     result = PD_PIPE_EOF;
2300                 else
2301                     result = PD_PIPE_ERR;
2302                 break;
2303             }
2304             pcap_src->cap_pipe_bytes_read += b;
2305         }
2306 #ifdef _WIN32
2307         else {
2308             q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2309             if (pcap_src->cap_pipe_err == PIPEOF) {
2310                 result = PD_PIPE_EOF;
2311                 break;
2312             } else if (pcap_src->cap_pipe_err == PIPERR) {
2313                 result = PD_PIPE_ERR;
2314                 break;
2315             }
2316             if (!q_status) {
2317                 return 0;
2318             }
2319         }
2320 #endif
2321         if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2322             return 0;
2323         result = PD_REC_HDR_READ;
2324         break;
2325
2326     case STATE_EXPECT_DATA:
2327 #ifdef _WIN32
2328         if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2329 #endif
2330
2331             pcap_src->cap_pipe_state = STATE_READ_DATA;
2332             pcap_src->cap_pipe_bytes_to_read = pcap_info->rechdr.hdr.incl_len;
2333             pcap_src->cap_pipe_bytes_read = 0;
2334
2335 #ifdef _WIN32
2336             pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2337             g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2338             g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2339         }
2340 #endif
2341         /* Fall through */
2342
2343     case STATE_READ_DATA:
2344 #ifdef _WIN32
2345         if (pcap_src->from_cap_socket)
2346 #endif
2347         {
2348             b = cap_pipe_read(pcap_src->cap_pipe_fd,
2349                               pcap_src->cap_pipe_databuf+pcap_src->cap_pipe_bytes_read,
2350                               pcap_src->cap_pipe_bytes_to_read - pcap_src->cap_pipe_bytes_read,
2351                               pcap_src->from_cap_socket);
2352             if (b <= 0) {
2353                 if (b == 0)
2354                     result = PD_PIPE_EOF;
2355                 else
2356                     result = PD_PIPE_ERR;
2357                 break;
2358             }
2359             pcap_src->cap_pipe_bytes_read += b;
2360         }
2361 #ifdef _WIN32
2362         else {
2363
2364             q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2365             if (pcap_src->cap_pipe_err == PIPEOF) {
2366                 result = PD_PIPE_EOF;
2367                 break;
2368             } else if (pcap_src->cap_pipe_err == PIPERR) {
2369                 result = PD_PIPE_ERR;
2370                 break;
2371             }
2372             if (!q_status) {
2373                 return 0;
2374             }
2375         }
2376 #endif /* _WIN32 */
2377         if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read)
2378             return 0;
2379         result = PD_DATA_READ;
2380         break;
2381
2382     default:
2383         g_snprintf(errmsg, (gulong)errmsgl,
2384                    "pcap_pipe_dispatch: invalid state");
2385         result = PD_ERR;
2386
2387     } /* switch (pcap_src->cap_pipe_state) */
2388
2389     /*
2390      * We've now read as much data as we were expecting, so process it.
2391      */
2392     switch (result) {
2393
2394     case PD_REC_HDR_READ:
2395         /* We've read the header. Take care of byte order. */
2396         cap_pipe_adjust_pcap_header(pcap_src->cap_pipe_info.pcap.byte_swapped, &pcap_info->hdr,
2397                                &pcap_info->rechdr.hdr);
2398         if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_max_pkt_size) {
2399             /*
2400              * The record contains more data than the advertised/allowed in the
2401              * pcap header, do not try to read more data (do not change to
2402              * STATE_EXPECT_DATA) as that would not fit in the buffer and
2403              * instead stop with an error.
2404              */
2405             g_snprintf(errmsg, (gulong)errmsgl, "Frame %u too long (%d bytes)",
2406                        ld->packets_captured+1, pcap_info->rechdr.hdr.incl_len);
2407             break;
2408         }
2409
2410         if (pcap_info->rechdr.hdr.incl_len > pcap_src->cap_pipe_databuf_size) {
2411             /*
2412              * Grow the buffer to the packet size, rounded up to a power of
2413              * 2.
2414              */
2415             new_bufsize = pcap_info->rechdr.hdr.incl_len;
2416             /*
2417              * http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2418              */
2419             new_bufsize--;
2420             new_bufsize |= new_bufsize >> 1;
2421             new_bufsize |= new_bufsize >> 2;
2422             new_bufsize |= new_bufsize >> 4;
2423             new_bufsize |= new_bufsize >> 8;
2424             new_bufsize |= new_bufsize >> 16;
2425             new_bufsize++;
2426             pcap_src->cap_pipe_databuf = (char*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2427             pcap_src->cap_pipe_databuf_size = new_bufsize;
2428         }
2429
2430         /*
2431          * The record has some data following the header, try to read it next
2432          * time.
2433          */
2434         if (pcap_info->rechdr.hdr.incl_len) {
2435             pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2436             return 0;
2437         }
2438
2439         /*
2440          * No data following the record header? Then no more data needs to be
2441          * read and we will fallthrough and emit an empty packet.
2442          */
2443         /* FALLTHROUGH */
2444     case PD_DATA_READ:
2445         /* Fill in a "struct pcap_pkthdr", and process the packet. */
2446         phdr.ts.tv_sec = pcap_info->rechdr.hdr.ts_sec;
2447         phdr.ts.tv_usec = pcap_info->rechdr.hdr.ts_usec;
2448         phdr.caplen = pcap_info->rechdr.hdr.incl_len;
2449         phdr.len = pcap_info->rechdr.hdr.orig_len;
2450
2451         if (use_threads) {
2452             capture_loop_queue_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2453         } else {
2454             capture_loop_write_packet_cb((u_char *)pcap_src, &phdr, pcap_src->cap_pipe_databuf);
2455         }
2456         pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2457         return 1;
2458
2459     case PD_PIPE_EOF:
2460         pcap_src->cap_pipe_err = PIPEOF;
2461         return -1;
2462
2463     case PD_PIPE_ERR:
2464 #ifdef _WIN32
2465         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2466                       NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2467         g_snprintf(errmsg, (gulong)errmsgl,
2468                    "Error reading from pipe: %s (error %lu)",
2469                    utf_16to8(err_str), GetLastError());
2470         LocalFree(err_str);
2471 #else
2472         g_snprintf(errmsg, (gulong)errmsgl, "Error reading from pipe: %s",
2473                    g_strerror(errno));
2474 #endif
2475         /* Fall through */
2476     case PD_ERR:
2477         break;
2478     }
2479
2480     pcap_src->cap_pipe_err = PIPERR;
2481     /* Return here rather than inside the switch to prevent GCC warning */
2482     return -1;
2483 }
2484
2485 static int
2486 pcapng_pipe_dispatch(loop_data *ld, capture_src *pcap_src, char *errmsg, size_t errmsgl)
2487 {
2488     enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2489            PD_ERR } result;
2490 #ifdef _WIN32
2491     gpointer  q_status;
2492     wchar_t  *err_str;
2493 #endif
2494     guint new_bufsize;
2495     struct pcapng_block_header_s *bh = &pcap_src->cap_pipe_info.pcapng.bh;
2496
2497 #ifdef LOG_CAPTURE_VERBOSE
2498     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch");
2499 #endif
2500
2501     switch (pcap_src->cap_pipe_state) {
2502
2503     case STATE_EXPECT_REC_HDR:
2504 #ifdef LOG_CAPTURE_VERBOSE
2505         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_EXPECT_REC_HDR");
2506 #endif
2507 #ifdef _WIN32
2508         if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2509 #endif
2510
2511             pcap_src->cap_pipe_state = STATE_READ_REC_HDR;
2512             pcap_src->cap_pipe_bytes_to_read = sizeof(struct pcapng_block_header_s);
2513             pcap_src->cap_pipe_bytes_read = 0;
2514
2515 #ifdef _WIN32
2516             if (!pcap_src->from_cap_socket) {
2517                 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf;
2518                 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2519             }
2520             g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2521         }
2522 #endif
2523         /* Fall through */
2524
2525     case STATE_READ_REC_HDR:
2526 #ifdef LOG_CAPTURE_VERBOSE
2527         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_READ_REC_HDR");
2528 #endif
2529 #ifdef _WIN32
2530         if (pcap_src->from_cap_socket) {
2531 #endif
2532             if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2533                 return -1;
2534             }
2535 #ifdef _WIN32
2536         } else {
2537             q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2538             if (pcap_src->cap_pipe_err == PIPEOF) {
2539                 result = PD_PIPE_EOF;
2540                 break;
2541             } else if (pcap_src->cap_pipe_err == PIPERR) {
2542                 result = PD_PIPE_ERR;
2543                 break;
2544             }
2545             if (!q_status) {
2546                 return 0;
2547             }
2548         }
2549 #endif
2550         if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2551             return 0;
2552         }
2553         memcpy(bh, pcap_src->cap_pipe_databuf, sizeof(struct pcapng_block_header_s));
2554         result = PD_REC_HDR_READ;
2555         break;
2556
2557     case STATE_EXPECT_DATA:
2558 #ifdef LOG_CAPTURE_VERBOSE
2559         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_EXPECT_DATA");
2560 #endif
2561 #ifdef _WIN32
2562         if (g_mutex_trylock(pcap_src->cap_pipe_read_mtx)) {
2563 #endif
2564             pcap_src->cap_pipe_state = STATE_READ_DATA;
2565             pcap_src->cap_pipe_bytes_to_read = bh->block_total_length;
2566
2567 #ifdef _WIN32
2568             if (!pcap_src->from_cap_socket) {
2569                 pcap_src->cap_pipe_bytes_to_read -= pcap_src->cap_pipe_bytes_read;
2570                 pcap_src->cap_pipe_buf = pcap_src->cap_pipe_databuf + pcap_src->cap_pipe_bytes_read;
2571                 pcap_src->cap_pipe_bytes_read = 0;
2572                 g_async_queue_push(pcap_src->cap_pipe_pending_q, pcap_src->cap_pipe_buf);
2573             }
2574             g_mutex_unlock(pcap_src->cap_pipe_read_mtx);
2575         }
2576 #endif
2577         /* Fall through */
2578
2579     case STATE_READ_DATA:
2580 #ifdef LOG_CAPTURE_VERBOSE
2581         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "pcapng_pipe_dispatch STATE_READ_DATA");
2582 #endif
2583 #ifdef _WIN32
2584         if (pcap_src->from_cap_socket) {
2585 #endif
2586             if (cap_pipe_read_data_bytes(pcap_src, errmsg, errmsgl) < 0) {
2587                 return -1;
2588             }
2589 #ifdef _WIN32
2590         } else {
2591
2592             q_status = g_async_queue_timeout_pop(pcap_src->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2593             if (pcap_src->cap_pipe_err == PIPEOF) {
2594                 result = PD_PIPE_EOF;
2595                 break;
2596             } else if (pcap_src->cap_pipe_err == PIPERR) {
2597                 result = PD_PIPE_ERR;
2598                 break;
2599             }
2600             if (!q_status) {
2601                 return 0;
2602             }
2603         }
2604 #endif /* _WIN32 */
2605         if (pcap_src->cap_pipe_bytes_read < pcap_src->cap_pipe_bytes_to_read) {
2606             return 0;
2607         }
2608         result = PD_DATA_READ;
2609         break;
2610
2611     default:
2612         g_snprintf(errmsg, (gulong)errmsgl,
2613                    "pcapng_pipe_dispatch: invalid state");
2614         result = PD_ERR;
2615
2616     } /* switch (pcap_src->cap_pipe_state) */
2617
2618     /*
2619      * We've now read as much data as we were expecting, so process it.
2620      */
2621     switch (result) {
2622
2623     case PD_REC_HDR_READ:
2624         if (bh->block_type == BLOCK_TYPE_SHB) {
2625             /* we need to read ahead to get the endianess before getting the block type and length */
2626             pcapng_read_shb(pcap_src, errmsg, errmsgl);
2627             return 1;
2628         }
2629
2630         if (bh->block_total_length > pcap_src->cap_pipe_max_pkt_size) {
2631             /*
2632             * The record contains more data than the advertised/allowed in the
2633             * pcapng header, do not try to read more data (do not change to
2634             * STATE_EXPECT_DATA) as that would not fit in the buffer and
2635             * instead stop with an error.
2636             */
2637             g_snprintf(errmsg, (gulong)errmsgl, "Frame %u too long (%d bytes)",
2638                     ld->packets_captured+1, bh->block_total_length);
2639             break;
2640         }
2641
2642         if (bh->block_total_length > pcap_src->cap_pipe_databuf_size) {
2643             /*
2644             * Grow the buffer to the packet size, rounded up to a power of
2645             * 2.
2646             */
2647             new_bufsize = bh->block_total_length;
2648             /*
2649             * http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
2650             */
2651             new_bufsize--;
2652             new_bufsize |= new_bufsize >> 1;
2653             new_bufsize |= new_bufsize >> 2;
2654             new_bufsize |= new_bufsize >> 4;
2655             new_bufsize |= new_bufsize >> 8;
2656             new_bufsize |= new_bufsize >> 16;
2657             new_bufsize++;
2658             pcap_src->cap_pipe_databuf = (guchar*)g_realloc(pcap_src->cap_pipe_databuf, new_bufsize);
2659             pcap_src->cap_pipe_databuf_size = new_bufsize;
2660         }
2661
2662         /* The record always has at least the block total length following the header */
2663         if (bh->block_total_length < sizeof(struct pcapng_block_header_s)+sizeof(guint32)) {
2664             g_snprintf(errmsg, (gulong)errmsgl,
2665                        "malformed pcapng block_total_length < minimum");
2666             pcap_src->cap_pipe_err = PIPEOF;
2667             return -1;
2668         }
2669         pcap_src->cap_pipe_state = STATE_EXPECT_DATA;
2670         return 0;
2671
2672     case PD_DATA_READ:
2673         if (use_threads) {
2674             capture_loop_queue_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
2675         } else {
2676             capture_loop_write_pcapng_cb(pcap_src, bh, pcap_src->cap_pipe_databuf);
2677         }
2678         pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2679         return 1;
2680
2681     case PD_PIPE_EOF:
2682         pcap_src->cap_pipe_err = PIPEOF;
2683         return -1;
2684
2685     case PD_PIPE_ERR:
2686 #ifdef _WIN32
2687         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2688                       NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2689         g_snprintf(errmsg, (gulong)errmsgl,
2690                    "Error reading from pipe: %s (error %lu)",
2691                    utf_16to8(err_str), GetLastError());
2692         LocalFree(err_str);
2693 #else
2694         g_snprintf(errmsg, (gulong)errmsgl, "Error reading from pipe: %s",
2695                    g_strerror(errno));
2696 #endif
2697         /* Fall through */
2698     case PD_ERR:
2699         break;
2700     }
2701
2702     pcap_src->cap_pipe_err = PIPERR;
2703     /* Return here rather than inside the switch to prevent GCC warning */
2704     return -1;
2705 }
2706
2707 /** Open the capture input file (pcap or capture pipe).
2708  *  Returns TRUE if it succeeds, FALSE otherwise. */
2709 static gboolean
2710 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2711                         char *errmsg, size_t errmsg_len,
2712                         char *secondary_errmsg, size_t secondary_errmsg_len)
2713 {
2714     cap_device_open_err open_err;
2715     gchar               open_err_str[PCAP_ERRBUF_SIZE];
2716     gchar              *sync_msg_str;
2717     interface_options  *interface_opts;
2718     capture_src        *pcap_src;
2719     guint               i;
2720 #ifdef _WIN32
2721     int                 err;
2722     WORD                wVersionRequested;
2723     WSADATA             wsaData;
2724 #endif
2725
2726 /* XXX - opening Winsock on tshark? */
2727
2728     /* Initialize Windows Socket if we are in a Win32 OS
2729        This needs to be done before querying the interface for network/netmask */
2730 #ifdef _WIN32
2731     /* XXX - do we really require 1.1 or earlier?
2732        Are there any versions that support only 2.0 or higher? */
2733     wVersionRequested = MAKEWORD(1, 1);
2734     err = WSAStartup(wVersionRequested, &wsaData);
2735     if (err != 0) {
2736         switch (err) {
2737
2738         case WSASYSNOTREADY:
2739             g_snprintf(errmsg, (gulong) errmsg_len,
2740                        "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2741             break;
2742
2743         case WSAVERNOTSUPPORTED:
2744             g_snprintf(errmsg, (gulong) errmsg_len,
2745                        "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2746                        LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2747             break;
2748
2749         case WSAEINPROGRESS:
2750             g_snprintf(errmsg, (gulong) errmsg_len,
2751                        "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2752             break;
2753
2754         case WSAEPROCLIM:
2755             g_snprintf(errmsg, (gulong) errmsg_len,
2756                        "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2757             break;
2758
2759         case WSAEFAULT:
2760             g_snprintf(errmsg, (gulong) errmsg_len,
2761                        "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2762             break;
2763
2764         default:
2765             g_snprintf(errmsg, (gulong) errmsg_len,
2766                        "Couldn't initialize Windows Sockets: error %d", err);
2767             break;
2768         }
2769         g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2770         return FALSE;
2771     }
2772 #endif
2773     if ((use_threads == FALSE) &&
2774         (capture_opts->ifaces->len > 1)) {
2775         g_snprintf(errmsg, (gulong) errmsg_len,
2776                    "Using threads is required for capturing on multiple interfaces.");
2777         return FALSE;
2778     }
2779
2780     int pcapng_src_count = 0;
2781     for (i = 0; i < capture_opts->ifaces->len; i++) {
2782         interface_opts = &g_array_index(capture_opts->ifaces, interface_options, i);
2783         pcap_src = (capture_src *)g_malloc0(sizeof (capture_src));
2784         if (pcap_src == NULL) {
2785             g_snprintf(errmsg, (gulong) errmsg_len,
2786                    "Could not allocate memory.");
2787             return FALSE;
2788         }
2789
2790         /*
2791          * Add our pcapng interface entry. This will be deleted further
2792          * down if pcapng_passthrough == TRUE.
2793          */
2794         saved_idb_t idb_source = { 0 };
2795         idb_source.interface_id = i;
2796         g_rw_lock_writer_lock (&ld->saved_shb_idb_lock);
2797         g_array_append_val(global_ld.saved_idbs, idb_source);
2798         g_rw_lock_writer_unlock (&ld->saved_shb_idb_lock);
2799         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: saved capture_opts IDB %u",
2800               G_STRFUNC, i);
2801
2802 #ifdef MUST_DO_SELECT
2803         pcap_src->pcap_fd = -1;
2804 #endif
2805         pcap_src->interface_id = i;
2806         pcap_src->linktype = -1;
2807 #ifdef _WIN32
2808         pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2809 #endif
2810         pcap_src->cap_pipe_fd = -1;
2811         pcap_src->cap_pipe_dispatch = pcap_pipe_dispatch;
2812         pcap_src->cap_pipe_state = STATE_EXPECT_REC_HDR;
2813         pcap_src->cap_pipe_err = PIPOK;
2814 #ifdef _WIN32
2815         pcap_src->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2816         g_mutex_init(pcap_src->cap_pipe_read_mtx);
2817         pcap_src->cap_pipe_pending_q = g_async_queue_new();
2818         pcap_src->cap_pipe_done_q = g_async_queue_new();
2819 #endif
2820         g_array_append_val(ld->pcaps, pcap_src);
2821
2822         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts->name);
2823         pcap_src->pcap_h = open_capture_device(capture_opts, interface_opts,
2824             CAP_READ_TIMEOUT, &open_err, &open_err_str);
2825
2826         if (pcap_src->pcap_h != NULL) {
2827             /* we've opened "iface" as a network device */
2828
2829 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2830             /* Find out if we're getting nanosecond-precision time stamps */
2831             pcap_src->ts_nsec = have_high_resolution_timestamp(pcap_src->pcap_h);
2832 #endif
2833
2834 #if defined(HAVE_PCAP_SETSAMPLING)
2835             if (interface_opts->sampling_method != CAPTURE_SAMP_NONE) {
2836                 struct pcap_samp *samp;
2837
2838                 if ((samp = pcap_setsampling(pcap_src->pcap_h)) != NULL) {
2839                     switch (interface_opts->sampling_method) {
2840                     case CAPTURE_SAMP_BY_COUNT:
2841                         samp->method = PCAP_SAMP_1_EVERY_N;
2842                         break;
2843
2844                     case CAPTURE_SAMP_BY_TIMER:
2845                         samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2846                         break;
2847
2848                     default:
2849                         sync_msg_str = g_strdup_printf(
2850                             "Unknown sampling method %d specified,\n"
2851                             "continue without packet sampling",
2852                             interface_opts->sampling_method);
2853                         report_capture_error("Couldn't set the capture "
2854                                              "sampling", sync_msg_str);
2855                         g_free(sync_msg_str);
2856                     }
2857                     samp->value = interface_opts->sampling_param;
2858                 } else {
2859                     report_capture_error("Couldn't set the capture sampling",
2860                                          "Cannot get packet sampling data structure");
2861                 }
2862             }
2863 #endif
2864
2865             /* setting the data link type only works on real interfaces */
2866             if (!set_pcap_datalink(pcap_src->pcap_h, interface_opts->linktype,
2867                                    interface_opts->name,
2868                                    errmsg, errmsg_len,
2869                                    secondary_errmsg, secondary_errmsg_len)) {
2870                 return FALSE;
2871             }
2872             pcap_src->linktype = get_pcap_datalink(pcap_src->pcap_h, interface_opts->name);
2873         } else {
2874             /* We couldn't open "iface" as a network device. */
2875             /* Try to open it as a pipe */
2876             gboolean pipe_err = FALSE;
2877             cap_pipe_open_live(interface_opts->name, pcap_src,
2878                                &pcap_src->cap_pipe_info.pcap.hdr,
2879                                errmsg, errmsg_len,
2880                                secondary_errmsg, secondary_errmsg_len);
2881
2882 #ifdef _WIN32
2883             if (pcap_src->from_cap_socket) {
2884 #endif
2885                 if (pcap_src->cap_pipe_fd == -1) {
2886                     pipe_err = TRUE;
2887                 }
2888 #ifdef _WIN32
2889             } else {
2890                 if (pcap_src->cap_pipe_h == INVALID_HANDLE_VALUE) {
2891                     pipe_err = TRUE;
2892                 }
2893             }
2894 #endif
2895
2896             if (pipe_err) {
2897                 if (pcap_src->cap_pipe_err == PIPNEXIST) {
2898                     /*
2899                      * We tried opening as an interface, and that failed,
2900                      * so we tried to open it as a pipe, but the pipe
2901                      * doesn't exist.  Report the error message for
2902                      * the interface.
2903                      */
2904                     get_capture_device_open_failure_messages(open_err,
2905                                                              open_err_str,
2906                                                              interface_opts->name,
2907                                                              errmsg,
2908                                                              errmsg_len,
2909                                                              secondary_errmsg,
2910                                                              secondary_errmsg_len);
2911                 }
2912                 /*
2913                  * Else pipe (or file) does exist and cap_pipe_open_live() has
2914                  * filled in errmsg
2915                  */
2916                 return FALSE;
2917             } else {
2918                 /* cap_pipe_open_live() succeeded; don't want
2919                    error message from pcap_open_live() */
2920                 open_err_str[0] = '\0';
2921             }
2922         }
2923
2924 /* XXX - will this work for tshark? */
2925 #ifdef MUST_DO_SELECT
2926         if (!pcap_src->from_cap_pipe) {
2927 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2928             pcap_src->pcap_fd = pcap_get_selectable_fd(pcap_src->pcap_h);
2929 #else
2930             pcap_src->pcap_fd = pcap_fileno(pcap_src->pcap_h);
2931 #endif
2932         }
2933 #endif
2934
2935         /* Does "open_err_str" contain a non-empty string?  If so, "pcap_open_live()"
2936            returned a warning; print it, but keep capturing. */
2937         if (open_err_str[0] != '\0') {
2938             sync_msg_str = g_strdup_printf("%s.", open_err_str);
2939             report_capture_error(sync_msg_str, "");
2940             g_free(sync_msg_str);
2941         }
2942         if (pcap_src->from_pcapng) {
2943             pcapng_src_count++;
2944         }
2945     }
2946     if (capture_opts->ifaces->len == 1 && pcapng_src_count == 1) {
2947         ld->pcapng_passthrough = TRUE;
2948         g_rw_lock_writer_lock (&ld->saved_shb_idb_lock);
2949         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: Clearing %u interfaces for passthrough",
2950               G_STRFUNC, global_ld.saved_idbs->len);
2951         g_array_set_size(global_ld.saved_idbs, 0);
2952         g_rw_lock_writer_unlock (&ld->saved_shb_idb_lock);
2953     }
2954
2955     /* If not using libcap: we now can now set euid/egid to ruid/rgid         */
2956     /*  to remove any suid privileges.                                        */
2957     /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities  */
2958     /*  (euid/egid have already previously been set to ruid/rgid.             */
2959     /* (See comment in main() for details)                                    */
2960 #ifndef HAVE_LIBCAP
2961     relinquish_special_privs_perm();
2962 #else
2963     relinquish_all_capabilities();
2964 #endif
2965     return TRUE;
2966 }
2967
2968 /* close the capture input file (pcap or capture pipe) */
2969 static void capture_loop_close_input(loop_data *ld)
2970 {
2971     guint        i;
2972     capture_src *pcap_src;
2973
2974     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2975
2976     for (i = 0; i < ld->pcaps->len; i++) {
2977         pcap_src = g_array_index(ld->pcaps, capture_src *, i);
2978         /* Pipe, or capture device? */
2979         if (pcap_src->from_cap_pipe) {
2980             /* Pipe. If open, close the capture pipe "input file". */
2981             if (pcap_src->cap_pipe_fd >= 0) {
2982                 cap_pipe_close(pcap_src->cap_pipe_fd, pcap_src->from_cap_socket);
2983                 pcap_src->cap_pipe_fd = -1;
2984             }
2985 #ifdef _WIN32
2986             if (pcap_src->cap_pipe_h != INVALID_HANDLE_VALUE) {
2987                 CloseHandle(pcap_src->cap_pipe_h);
2988                 pcap_src->cap_pipe_h = INVALID_HANDLE_VALUE;
2989             }
2990 #endif
2991             if (pcap_src->cap_pipe_databuf != NULL) {
2992                 /* Free the buffer. */
2993                 g_free(pcap_src->cap_pipe_databuf);
2994                 pcap_src->cap_pipe_databuf = NULL;
2995             }
2996             if (pcap_src->from_pcapng) {
2997                 g_array_free(pcap_src->cap_pipe_info.pcapng.src_iface_to_global, TRUE);
2998                 pcap_src->cap_pipe_info.pcapng.src_iface_to_global = NULL;
2999             }
3000         } else {
3001             /* Capture device.  If open, close the pcap_t. */
3002             if (pcap_src->pcap_h != NULL) {
3003                 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_src->pcap_h);
3004                 pcap_close(pcap_src->pcap_h);
3005                 pcap_src->pcap_h = NULL;
3006             }
3007         }
3008     }
3009
3010     ld->go = FALSE;
3011
3012 #ifdef _WIN32
3013     /* Shut down windows sockets */
3014     WSACleanup();
3015 #endif
3016 }
3017
3018
3019 /* init the capture filter */
3020 static initfilter_status_t
3021 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
3022                          const gchar * name, const gchar * cfilter)
3023 {
3024     struct bpf_program fcode;
3025
3026     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
3027
3028     /* capture filters only work on real interfaces */
3029     if (cfilter && !from_cap_pipe) {
3030         /* A capture filter was specified; set it up. */
3031         if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
3032             /* Treat this specially - our caller might try to compile this
3033                as a display filter and, if that succeeds, warn the user that
3034                the display and capture filter syntaxes are different. */
3035             return INITFILTER_BAD_FILTER;
3036         }
3037         if (pcap_setfilter(pcap_h, &fcode) < 0) {
3038 #ifdef HAVE_PCAP_FREECODE
3039             pcap_freecode(&fcode);
3040 #endif
3041             return INITFILTER_OTHER_ERROR;
3042         }
3043 #ifdef HAVE_PCAP_FREECODE
3044         pcap_freecode(&fcode);
3045 #endif
3046     }
3047
3048     return INITFILTER_NO_ERROR;
3049 }
3050
3051 /*
3052  * Write the dumpcap pcapng SHB and IDBs if needed.
3053  * Called from capture_loop_init_output and do_file_switch_or_stop.
3054  */
3055 static gboolean
3056 capture_loop_init_pcapng_output(capture_options *capture_opts, loop_data *ld)
3057 {
3058     g_rw_lock_reader_lock (&ld->saved_shb_idb_lock);
3059
3060     if (ld->pcapng_passthrough && !ld->saved_shb) {
3061         /* We have a single pcapng capture interface and this is the first or only output file. */
3062         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: skipping dumpcap SHB and IDBs in favor of source", G_STRFUNC);
3063         g_rw_lock_reader_unlock (&ld->saved_shb_idb_lock);
3064         return TRUE;
3065     }
3066
3067     gboolean successful = TRUE;
3068     int      err;
3069     GString *os_info_str = g_string_new("");
3070
3071     get_os_version_info(os_info_str);
3072
3073     if (ld->saved_shb) {
3074         /* We have a single pcapng capture interface and multiple output files. */
3075
3076         struct pcapng_block_header_s bh;
3077
3078         memcpy(&bh, ld->saved_shb, sizeof(struct pcapng_block_header_s));
3079
3080         successful = pcapng_write_block(ld->pdh, ld->saved_shb, bh.block_total_length, &ld->bytes_written, &err);
3081
3082         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: wrote saved passthrough SHB %d", G_STRFUNC, successful);
3083     } else {
3084         GString *cpu_info_str = g_string_new("");
3085         get_cpu_info(cpu_info_str);
3086
3087         successful = pcapng_write_section_header_block(ld->pdh,
3088                                                        (const char *)capture_opts->capture_comment,   /* Comment */
3089                                                        cpu_info_str->str,           /* HW */
3090                                                        os_info_str->str,            /* OS */
3091                                                        get_appname_and_version(),
3092                                                        -1,                          /* section_length */
3093                                                        &ld->bytes_written,
3094                                                        &err);
3095         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: wrote dumpcap SHB %d", G_STRFUNC, successful);
3096         g_string_free(cpu_info_str, TRUE);
3097     }
3098
3099     for (unsigned i = 0; successful && (i < ld->saved_idbs->len); i++) {
3100         saved_idb_t idb_source = g_array_index(ld->saved_idbs, saved_idb_t, i);
3101         if (idb_source.deleted) {
3102             /*
3103              * Our interface is out of scope. Suppose we're writing multiple
3104              * files and a source switches sections. We currently write dummy
3105              * IDBs like so:
3106              *
3107              * File 1: IDB0, IDB1, IDB2
3108              * [ The source of IDBs 1 and 2 writes an SHB with two new IDBs ]
3109              * [ We switch output files ]
3110              * File 2: IDB0, dummy IDB, dummy IDB, IDB3, IDB4
3111              *
3112              * It might make more sense to write the original data so that
3113              * so that our IDB lists are more consistent across files.
3114              */
3115             successful = pcapng_write_interface_description_block(global_ld.pdh,
3116                                                                   "Interface went out of scope",    /* OPT_COMMENT       1 */
3117                                                                   "dummy",                          /* IDB_NAME          2 */
3118                                                                   "Dumpcap dummy interface",        /* IDB_DESCRIPTION   3 */
3119                                                                   NULL,                             /* IDB_FILTER       11 */
3120                                                                   os_info_str->str,                 /* IDB_OS           12 */
3121                                                                   -1,
3122                                                                   0,
3123                                                                   &(global_ld.bytes_written),
3124                                                                   0,                                /* IDB_IF_SPEED      8 */
3125                                                                   6,                                /* IDB_TSRESOL       9 */
3126                                                                   &global_ld.err);
3127             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: skipping deleted pcapng IDB %u", G_STRFUNC, i);
3128         } else if (idb_source.idb && idb_source.idb_len) {
3129             successful = pcapng_write_block(global_ld.pdh, idb_source.idb, idb_source.idb_len, &ld->bytes_written, &err);
3130             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: wrote pcapng IDB %d", G_STRFUNC, successful);
3131         } else if (idb_source.interface_id < capture_opts->ifaces->len) {
3132             unsigned if_id = idb_source.interface_id;
3133             interface_options *interface_opts = &g_array_index(capture_opts->ifaces, interface_options, if_id);
3134             capture_src *pcap_src = g_array_index(ld->pcaps, capture_src *, if_id);
3135             if (pcap_src->from_cap_pipe) {
3136                 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
3137             } else {
3138                 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
3139             }
3140             successful = pcapng_write_interface_description_block(global_ld.pdh,
3141                                                                   NULL,                       /* OPT_COMMENT       1 */
3142                                                                   interface_opts->name,       /* IDB_NAME          2 */
3143                                                                   interface_opts->descr,      /* IDB_DESCRIPTION   3 */
3144                                                                   interface_opts->cfilter,    /* IDB_FILTER       11 */
3145                                                                   os_info_str->str,           /* IDB_OS           12 */
3146                                                                   pcap_src->linktype,
3147                                                                   pcap_src->snaplen,
3148                                                                   &(global_ld.bytes_written),
3149                                                                   0,                          /* IDB_IF_SPEED      8 */
3150                                                                   pcap_src->ts_nsec ? 9 : 6,  /* IDB_TSRESOL       9 */
3151                                                                   &global_ld.err);
3152             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: wrote capture_opts IDB %d: %d", G_STRFUNC, if_id, successful);
3153         }
3154     }
3155     g_rw_lock_reader_unlock (&ld->saved_shb_idb_lock);
3156
3157     g_string_free(os_info_str, TRUE);
3158
3159     return successful;
3160 }
3161
3162 /* set up to write to the already-opened capture output file/files */
3163 static gboolean
3164 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
3165 {
3166     int               err;
3167     gboolean          successful;
3168
3169     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
3170
3171     if ((capture_opts->use_pcapng == FALSE) &&
3172         (capture_opts->ifaces->len > 1)) {
3173         g_snprintf(errmsg, errmsg_len,
3174                    "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
3175         return FALSE;
3176     }
3177
3178     /* Set up to write to the capture file. */
3179     if (capture_opts->multi_files_on) {
3180         ld->pdh = ringbuf_init_libpcap_fdopen(&err);
3181     } else {
3182         ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
3183         if (ld->pdh == NULL) {
3184             err = errno;
3185         }
3186     }
3187     if (ld->pdh) {
3188         if (capture_opts->use_pcapng) {
3189             successful = capture_loop_init_pcapng_output(capture_opts, ld);
3190         } else {
3191             capture_src *pcap_src;
3192             pcap_src = g_array_index(ld->pcaps, capture_src *, 0);
3193             if (pcap_src->from_cap_pipe) {
3194                 pcap_src->snaplen = pcap_src->cap_pipe_info.pcap.hdr.snaplen;
3195             } else {
3196                 pcap_src->snaplen = pcap_snapshot(pcap_src->pcap_h);
3197             }
3198             successful = libpcap_write_file_header(ld->pdh, pcap_src->linktype, pcap_src->snaplen,
3199                                                 pcap_src->ts_nsec, &ld->bytes_written, &err);
3200         }
3201         if (!successful) {
3202             fclose(ld->pdh);
3203             ld->pdh = NULL;
3204         }
3205     }
3206
3207     if (ld->pdh == NULL) {
3208         /* We couldn't set up to write to the capture file. */
3209         /* XXX - use cf_open_error_message from tshark instead? */
3210         switch (err) {
3211
3212         default:
3213             if (err < 0) {
3214                 g_snprintf(errmsg, errmsg_len,
3215                            "The file to which the capture would be"
3216                            " saved (\"%s\") could not be opened: Error %d.",
3217                            capture_opts->save_file, err);
3218             } else {
3219                 g_snprintf(errmsg, errmsg_len,
3220                            "The file to which the capture would be"
3221                            " saved (\"%s\") could not be opened: %s.",
3222                            capture_opts->save_file, g_strerror(err));
3223             }
3224             break;
3225         }
3226
3227         return FALSE;
3228     }
3229
3230     return TRUE;
3231 }
3232
3233 static gboolean
3234 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
3235 {
3236
3237     unsigned int i;
3238     capture_src *pcap_src;
3239     guint64      end_time = create_timestamp();
3240
3241     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
3242
3243     if (capture_opts->multi_files_on) {
3244         return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
3245     } else {
3246         if (capture_opts->use_pcapng) {
3247             for (i = 0; i < global_ld.pcaps->len; i++) {
3248                 pcap_src = g_array_index(global_ld.pcaps, capture_src *, i);
3249                 if (!pcap_src->from_cap_pipe) {
3250                     guint64 isb_ifrecv, isb_ifdrop;
3251                     struct pcap_stat stats;
3252
3253                     if (pcap_stats(pcap_src->pcap_h, &stats) >= 0) {
3254                         isb_ifrecv = pcap_src->received;
3255                         isb_ifdrop = stats.ps_drop + pcap_src->dropped + pcap_src->flushed;
3256                    } else {
3257                         isb_ifrecv = G_MAXUINT64;
3258                         isb_ifdrop = G_MAXUINT64;
3259                     }
3260                     pcapng_write_interface_statistics_block(ld->pdh,
3261                                                             i,
3262                                                             &ld->bytes_written,
3263                                                             "Counters provided by dumpcap",
3264                                                             start_time,
3265                                                             end_time,
3266                                                             isb_ifrecv,
3267                                                             isb_ifdrop,
3268                                                             err_close);
3269                 }
3270             }
3271         }
3272         if (fclose(ld->pdh) == EOF) {
3273             if (err_close != NULL) {
3274                 *err_close = errno;
3275             }
3276             return (FALSE);
3277         } else {
3278             return (TRUE);
3279         }
3280     }
3281 }
3282
3283 /* dispatch incoming packets (pcap or capture pipe)
3284  *
3285  * Waits for incoming packets to be available, and calls pcap_dispatch()
3286  * to cause them to be processed.
3287  *
3288  * Returns the number of packets which were processed.
3289  *
3290  * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3291  * packet-batching behaviour does not cause packets to get held back
3292  * indefinitely.
3293  */
3294 static int
3295 capture_loop_dispatch(loop_data *ld,
3296                       char *errmsg, int errmsg_len, capture_src *pcap_src)
3297 {
3298     int    inpkts = 0;
3299     gint   packet_count_before;
3300     int    sel_ret;
3301
3302     packet_count_before = ld->packets_captured;
3303     if (pcap_src->from_cap_pipe) {
3304         /* dispatch from capture pipe */
3305 #ifdef LOG_CAPTURE_VERBOSE
3306         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
3307 #endif
3308 #ifdef _WIN32
3309         if (pcap_src->from_cap_socket) {
3310 #endif
3311             sel_ret = cap_pipe_select(pcap_src->cap_pipe_fd);
3312             if (sel_ret <= 0) {
3313                 if (sel_ret < 0 && errno != EINTR) {
3314                     g_snprintf(errmsg, errmsg_len,
3315                             "Unexpected error from select: %s", g_strerror(errno));
3316                     report_capture_error(errmsg, please_report);
3317                     ld->go = FALSE;
3318                 }
3319             }
3320 #ifdef _WIN32
3321         } else {
3322             /* Windows does not have select() for pipes. */
3323             /* Proceed with _dispatch() which waits for cap_pipe_done_q
3324              * notification from cap_thread_read() when ReadFile() on
3325              * the pipe has read enough bytes. */
3326             sel_ret = 1;
3327         }
3328 #endif
3329         if (sel_ret > 0) {
3330             /*
3331              * "select()" says we can read from the pipe without blocking
3332              */
3333             inpkts = pcap_src->cap_pipe_dispatch(ld, pcap_src, errmsg, errmsg_len);
3334             if (inpkts < 0) {
3335                 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "%s: src %u pipe reached EOF or err, rcv: %u drop: %u flush: %u",
3336                       G_STRFUNC, pcap_src->interface_id, pcap_src->received, pcap_src->dropped, pcap_src->flushed);
3337                 g_assert(pcap_src->cap_pipe_err != PIPOK);
3338             }
3339         }
3340     }
3341     else
3342     {
3343         /* dispatch from pcap */
3344 #ifdef MUST_DO_SELECT
3345         /*
3346          * If we have "pcap_get_selectable_fd()", we use it to get the
3347          * descriptor on which to select; if that's -1, it means there
3348          * is no descriptor on which you can do a "select()" (perhaps
3349          * because you're capturing on a special device, and that device's
3350          * driver unfortunately doesn't support "select()", in which case
3351          * we don't do the select - which means it might not be possible
3352          * to stop a capture until a packet arrives.  If that's unacceptable,
3353          * plead with whoever supplies the software for that device to add
3354          * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3355          * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3356          * later, so it can use pcap_breakloop().
3357          */
3358 #ifdef LOG_CAPTURE_VERBOSE
3359         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3360 #endif
3361         if (pcap_src->pcap_fd != -1) {
3362             sel_ret = cap_pipe_select(pcap_src->pcap_fd);
3363             if (sel_ret > 0) {
3364                 /*
3365                  * "select()" says we can read from it without blocking; go for
3366                  * it.
3367                  *
3368                  * We don't have pcap_breakloop(), so we only process one packet
3369                  * per pcap_dispatch() call, to allow a signal to stop the
3370                  * processing immediately, rather than processing all packets
3371                  * in a batch before quitting.
3372                  */
3373                 if (use_threads) {
3374                     inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3375                 } else {
3376                     inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3377                 }
3378                 if (inpkts < 0) {
3379                     if (inpkts == -1) {
3380                         /* Error, rather than pcap_breakloop(). */
3381                         pcap_src->pcap_err = TRUE;
3382                     }
3383                     ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3384                 }
3385             } else {
3386                 if (sel_ret < 0 && errno != EINTR) {
3387                     g_snprintf(errmsg, errmsg_len,
3388                                "Unexpected error from select: %s", g_strerror(errno));
3389                     report_capture_error(errmsg, please_report);
3390                     ld->go = FALSE;
3391                 }
3392             }
3393         }
3394         else
3395 #endif /* MUST_DO_SELECT */
3396         {
3397             /* dispatch from pcap without select */
3398 #if 1
3399 #ifdef LOG_CAPTURE_VERBOSE
3400             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3401 #endif
3402 #ifdef _WIN32
3403             /*
3404              * On Windows, we don't support asynchronously telling a process to
3405              * stop capturing; instead, we check for an indication on a pipe
3406              * after processing packets.  We therefore process only one packet
3407              * at a time, so that we can check the pipe after every packet.
3408              */
3409             if (use_threads) {
3410                 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_src);
3411             } else {
3412                 inpkts = pcap_dispatch(pcap_src->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_src);
3413             }
3414 #else
3415             if (use_threads) {
3416                 inpkts = pcap_dispatch(pcap_src->pcap_h, -1, capture_loop_queue