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