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