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