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