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