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