Remove ADDRESS macros and just have their lower-case equivalents.
[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(interface_options *interface_opts, char **err_str)
1218 {
1219     if_capabilities_t *caps;
1220     char errbuf[PCAP_ERRBUF_SIZE];
1221     pcap_t *pch;
1222 #ifdef HAVE_PCAP_CREATE
1223     int status;
1224 #endif
1225     int deflt;
1226 #ifdef HAVE_PCAP_LIST_DATALINKS
1227     int *linktypes;
1228     int i, nlt;
1229 #endif
1230     data_link_info_t *data_link_info;
1231
1232     /*
1233      * Allocate the interface capabilities structure.
1234      */
1235     caps = (if_capabilities_t *)g_malloc(sizeof *caps);
1236
1237     /*
1238      * WinPcap 4.1.2, and possibly earlier versions, have a bug
1239      * wherein, when an open with an rpcap: URL fails, the error
1240      * message for the error is not copied to errbuf and whatever
1241      * on-the-stack junk is in errbuf is treated as the error
1242      * message.
1243      *
1244      * To work around that (and any other bugs of that sort, we
1245      * initialize errbuf to an empty string.  If we get an error
1246      * and the string is empty, we report it as an unknown error.
1247      * (If we *don't* get an error, and the string is *non*-empty,
1248      * that could be a warning returned, such as "can't turn
1249      * promiscuous mode on"; we currently don't do so.)
1250      */
1251     errbuf[0] = '\0';
1252 #ifdef HAVE_PCAP_OPEN
1253 #ifdef HAVE_PCAP_REMOTE
1254     if (strncmp (interface_opts->name, "rpcap://", 8) == 0) {
1255         struct pcap_rmtauth auth;
1256
1257         auth.type = interface_opts->auth_type == CAPTURE_AUTH_PWD ?
1258             RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
1259         auth.username = interface_opts->auth_username;
1260         auth.password = interface_opts->auth_password;
1261
1262         pch = pcap_open(interface_opts->name, MIN_PACKET_SIZE, 0, 0, &auth, errbuf);
1263     } else
1264 #endif
1265         pch = pcap_open(interface_opts->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1266     caps->can_set_rfmon = FALSE;
1267     if (pch == NULL) {
1268         if (err_str != NULL)
1269             *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1270         g_free(caps);
1271         return NULL;
1272     }
1273 #elif defined(HAVE_PCAP_CREATE)
1274     pch = pcap_create(interface_opts->name, errbuf);
1275     if (pch == NULL) {
1276         if (err_str != NULL)
1277             *err_str = g_strdup(errbuf);
1278         g_free(caps);
1279         return NULL;
1280     }
1281     if (is_linux_bonding_device(interface_opts->name)) {
1282         /*
1283          * Linux bonding device; not Wi-Fi, so no monitor mode, and
1284          * calling pcap_can_set_rfmon() might get a "no such device"
1285          * error.
1286          */
1287         status = 0;
1288     } else {
1289         /*
1290          * Not a Linux bonding device, so go ahead.
1291          */
1292         status = pcap_can_set_rfmon(pch);
1293     }
1294     if (status < 0) {
1295         /* Error. */
1296         if (status == PCAP_ERROR)
1297             *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
1298                                        pcap_geterr(pch));
1299         else
1300             *err_str = g_strdup(pcap_statustostr(status));
1301         pcap_close(pch);
1302         g_free(caps);
1303         return NULL;
1304     }
1305     if (status == 0)
1306         caps->can_set_rfmon = FALSE;
1307     else if (status == 1) {
1308         caps->can_set_rfmon = TRUE;
1309         if (interface_opts->monitor_mode)
1310             pcap_set_rfmon(pch, 1);
1311     } else {
1312         if (err_str != NULL) {
1313             *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
1314                                        status);
1315         }
1316         pcap_close(pch);
1317         g_free(caps);
1318         return NULL;
1319     }
1320
1321     status = pcap_activate(pch);
1322     if (status < 0) {
1323         /* Error.  We ignore warnings (status > 0). */
1324         if (err_str != NULL) {
1325             if (status == PCAP_ERROR)
1326                 *err_str = g_strdup_printf("pcap_activate() failed: %s",
1327                                            pcap_geterr(pch));
1328             else
1329                 *err_str = g_strdup(pcap_statustostr(status));
1330         }
1331         pcap_close(pch);
1332         g_free(caps);
1333         return NULL;
1334     }
1335 #else
1336     pch = pcap_open_live(interface_opts->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1337     caps->can_set_rfmon = FALSE;
1338     if (pch == NULL) {
1339         if (err_str != NULL)
1340             *err_str = g_strdup(errbuf[0] == '\0' ? "Unknown error (pcap bug; actual error cause not reported)" : errbuf);
1341         g_free(caps);
1342         return NULL;
1343     }
1344 #endif
1345     deflt = get_pcap_linktype(pch, interface_opts->name);
1346 #ifdef HAVE_PCAP_LIST_DATALINKS
1347     nlt = pcap_list_datalinks(pch, &linktypes);
1348     if (nlt == 0 || linktypes == NULL) {
1349         pcap_close(pch);
1350         if (err_str != NULL)
1351             *err_str = NULL; /* an empty list doesn't mean an error */
1352         g_free(caps);
1353         return NULL;
1354     }
1355     caps->data_link_types = NULL;
1356     for (i = 0; i < nlt; i++) {
1357         data_link_info = create_data_link_info(linktypes[i]);
1358
1359         /*
1360          * XXX - for 802.11, make the most detailed 802.11
1361          * version the default, rather than the one the
1362          * device has as the default?
1363          */
1364         if (linktypes[i] == deflt)
1365             caps->data_link_types = g_list_prepend(caps->data_link_types,
1366                                                    data_link_info);
1367         else
1368             caps->data_link_types = g_list_append(caps->data_link_types,
1369                                                   data_link_info);
1370     }
1371 #ifdef HAVE_PCAP_FREE_DATALINKS
1372     pcap_free_datalinks(linktypes);
1373 #else
1374     /*
1375      * In Windows, there's no guarantee that if you have a library
1376      * built with one version of the MSVC++ run-time library, and
1377      * it returns a pointer to allocated data, you can free that
1378      * data from a program linked with another version of the
1379      * MSVC++ run-time library.
1380      *
1381      * This is not an issue on UN*X.
1382      *
1383      * See the mail threads starting at
1384      *
1385      *    https://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
1386      *
1387      * and
1388      *
1389      *    https://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
1390      */
1391 #ifndef _WIN32
1392 #define xx_free free  /* hack so checkAPIs doesn't complain */
1393     xx_free(linktypes);
1394 #endif /* _WIN32 */
1395 #endif /* HAVE_PCAP_FREE_DATALINKS */
1396 #else /* HAVE_PCAP_LIST_DATALINKS */
1397
1398     data_link_info = create_data_link_info(deflt);
1399     caps->data_link_types = g_list_append(caps->data_link_types,
1400                                           data_link_info);
1401 #endif /* HAVE_PCAP_LIST_DATALINKS */
1402
1403     pcap_close(pch);
1404
1405     if (err_str != NULL)
1406         *err_str = NULL;
1407     return caps;
1408 }
1409
1410 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
1411 /*
1412  * Output a machine readable list of the interfaces
1413  * This list is retrieved by the sync_interface_list_open() function
1414  * The actual output of this function can be viewed with the command "dumpcap -D -Z none"
1415  */
1416 static void
1417 print_machine_readable_interfaces(GList *if_list)
1418 {
1419     int         i;
1420     GList       *if_entry;
1421     if_info_t   *if_info;
1422     GSList      *addr;
1423     if_addr_t   *if_addr;
1424     char        addr_str[ADDRSTRLEN];
1425
1426     if (capture_child) {
1427         /* Let our parent know we succeeded. */
1428         pipe_write_block(2, SP_SUCCESS, NULL);
1429     }
1430
1431     i = 1;  /* Interface id number */
1432     for (if_entry = g_list_first(if_list); if_entry != NULL;
1433          if_entry = g_list_next(if_entry)) {
1434         if_info = (if_info_t *)if_entry->data;
1435         printf("%d. %s\t", i++, if_info->name);
1436
1437         /*
1438          * Print the contents of the if_entry struct in a parseable format.
1439          * Each if_entry element is tab-separated.  Addresses are comma-
1440          * separated.
1441          */
1442         /* XXX - Make sure our description doesn't contain a tab */
1443         if (if_info->vendor_description != NULL)
1444             printf("%s\t", if_info->vendor_description);
1445         else
1446             printf("\t");
1447
1448         /* XXX - Make sure our friendly name doesn't contain a tab */
1449         if (if_info->friendly_name != NULL)
1450             printf("%s\t", if_info->friendly_name);
1451         else
1452             printf("\t");
1453
1454         printf("%i\t", if_info->type);
1455
1456         for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
1457                     addr = g_slist_next(addr)) {
1458             if (addr != g_slist_nth(if_info->addrs, 0))
1459                 printf(",");
1460
1461             if_addr = (if_addr_t *)addr->data;
1462             switch(if_addr->ifat_type) {
1463             case IF_AT_IPv4:
1464                 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
1465                               ADDRSTRLEN)) {
1466                     printf("%s", addr_str);
1467                 } else {
1468                     printf("<unknown IPv4>");
1469                 }
1470                 break;
1471             case IF_AT_IPv6:
1472                 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
1473                               addr_str, ADDRSTRLEN)) {
1474                     printf("%s", addr_str);
1475                 } else {
1476                     printf("<unknown IPv6>");
1477                 }
1478                 break;
1479             default:
1480                 printf("<type unknown %i>", if_addr->ifat_type);
1481             }
1482         }
1483
1484         if (if_info->loopback)
1485             printf("\tloopback");
1486         else
1487             printf("\tnetwork");
1488 #ifdef HAVE_EXTCAP
1489         printf("\t%s", if_info->extcap);
1490 #endif
1491         printf("\n");
1492     }
1493 }
1494
1495 /*
1496  * If you change the machine-readable output format of this function,
1497  * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
1498  */
1499 static void
1500 print_machine_readable_if_capabilities(if_capabilities_t *caps)
1501 {
1502     GList *lt_entry;
1503     data_link_info_t *data_link_info;
1504     const gchar *desc_str;
1505
1506     if (capture_child) {
1507         /* Let our parent know we succeeded. */
1508         pipe_write_block(2, SP_SUCCESS, NULL);
1509     }
1510
1511     if (caps->can_set_rfmon)
1512         printf("1\n");
1513     else
1514         printf("0\n");
1515     for (lt_entry = caps->data_link_types; lt_entry != NULL;
1516          lt_entry = g_list_next(lt_entry)) {
1517       data_link_info = (data_link_info_t *)lt_entry->data;
1518       if (data_link_info->description != NULL)
1519         desc_str = data_link_info->description;
1520       else
1521         desc_str = "(not supported)";
1522       printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
1523              desc_str);
1524     }
1525 }
1526
1527 typedef struct {
1528     char *name;
1529     pcap_t *pch;
1530 } if_stat_t;
1531
1532 /* Print the number of packets captured for each interface until we're killed. */
1533 static int
1534 print_statistics_loop(gboolean machine_readable)
1535 {
1536     GList       *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1537     if_info_t   *if_info;
1538     if_stat_t   *if_stat;
1539     int         err;
1540     gchar       *err_str;
1541     pcap_t      *pch;
1542     char        errbuf[PCAP_ERRBUF_SIZE];
1543     struct pcap_stat ps;
1544
1545     if_list = get_interface_list(&err, &err_str);
1546     if (if_list == NULL) {
1547        if (err == 0)
1548             cmdarg_err("There are no interfaces on which a capture can be done");
1549         else {
1550             cmdarg_err("%s", err_str);
1551             g_free(err_str);
1552         }
1553         return err;
1554     }
1555
1556     for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1557         if_info = (if_info_t *)if_entry->data;
1558
1559 #ifdef __linux__
1560         /* On Linux nf* interfaces don't collect stats properly and don't allows multiple
1561          * connections. We avoid collecting stats on them.
1562          */
1563         if (!strncmp(if_info->name, "nf", 2)) {
1564             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Skipping interface %s for stats",
1565                 if_info->name);
1566             continue;
1567         }
1568 #endif
1569
1570 #ifdef HAVE_PCAP_OPEN
1571         pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1572 #else
1573         pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1574 #endif
1575
1576         if (pch) {
1577             if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
1578             if_stat->name = g_strdup(if_info->name);
1579             if_stat->pch = pch;
1580             stat_list = g_list_append(stat_list, if_stat);
1581         }
1582     }
1583
1584     if (!stat_list) {
1585         cmdarg_err("There are no interfaces on which a capture can be done");
1586         return 2;
1587     }
1588
1589     if (capture_child) {
1590         /* Let our parent know we succeeded. */
1591         pipe_write_block(2, SP_SUCCESS, NULL);
1592     }
1593
1594     if (!machine_readable) {
1595         printf("%-15s  %10s  %10s\n", "Interface", "Received",
1596             "Dropped");
1597     }
1598
1599     global_ld.go = TRUE;
1600     while (global_ld.go) {
1601         for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1602             if_stat = (if_stat_t *)stat_entry->data;
1603             pcap_stats(if_stat->pch, &ps);
1604
1605             if (!machine_readable) {
1606                 printf("%-15s  %10u  %10u\n", if_stat->name,
1607                     ps.ps_recv, ps.ps_drop);
1608             } else {
1609                 printf("%s\t%u\t%u\n", if_stat->name,
1610                     ps.ps_recv, ps.ps_drop);
1611                 fflush(stdout);
1612             }
1613         }
1614 #ifdef _WIN32
1615         /* If we have a dummy signal pipe check it */
1616         if (!signal_pipe_check_running()) {
1617             global_ld.go = FALSE;
1618         }
1619         Sleep(1 * 1000);
1620 #else
1621         sleep(1);
1622 #endif
1623     }
1624
1625     /* XXX - Not reached.  Should we look for 'q' in stdin? */
1626     for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1627         if_stat = (if_stat_t *)stat_entry->data;
1628         pcap_close(if_stat->pch);
1629         g_free(if_stat->name);
1630         g_free(if_stat);
1631     }
1632     g_list_free(stat_list);
1633     free_interface_list(if_list);
1634
1635     return 0;
1636 }
1637
1638
1639 #ifdef _WIN32
1640 static BOOL WINAPI
1641 capture_cleanup_handler(DWORD dwCtrlType)
1642 {
1643     /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1644        Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1645        is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1646        like SIGTERM at least when the machine's shutting down.
1647
1648        For now, if we're running as a command rather than a capture child,
1649        we handle all but CTRL_LOGOFF_EVENT as indications that we should
1650        clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1651        in that way on UN*X.
1652
1653        If we're not running as a capture child, we might be running as
1654        a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1655        user logs out.  (XXX - can we explicitly check whether we're
1656        running as a service?) */
1657
1658     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1659         "Console: Control signal");
1660     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1661         "Console: Control signal, CtrlType: %u", dwCtrlType);
1662
1663     /* Keep capture running if we're a service and a user logs off */
1664     if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1665         capture_loop_stop();
1666         return TRUE;
1667     } else {
1668         return FALSE;
1669     }
1670 }
1671 #else
1672 static void
1673 capture_cleanup_handler(int signum _U_)
1674 {
1675     /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1676        SIGTERM.  We assume that if the user wanted it to keep running
1677        after they logged out, they'd have nohupped it. */
1678
1679     /* Note: don't call g_log() in the signal handler: if we happened to be in
1680      * g_log() in process context when the signal came in, g_log will detect
1681      * the "recursion" and abort.
1682      */
1683
1684     capture_loop_stop();
1685 }
1686 #endif
1687
1688
1689 static void
1690 report_capture_count(gboolean reportit)
1691 {
1692     /* Don't print this if we're a capture child. */
1693     if (!capture_child && reportit) {
1694         fprintf(stderr, "\rPackets captured: %d\n", global_ld.packet_count);
1695         /* stderr could be line buffered */
1696         fflush(stderr);
1697     }
1698 }
1699
1700
1701 #ifdef SIGINFO
1702 static void
1703 report_counts_for_siginfo(void)
1704 {
1705     report_capture_count(quiet);
1706     infoprint = FALSE; /* we just reported it */
1707 }
1708
1709 static void
1710 report_counts_siginfo(int signum _U_)
1711 {
1712     int sav_errno = errno;
1713
1714     /* If we've been told to delay printing, just set a flag asking
1715        that we print counts (if we're supposed to), otherwise print
1716        the count of packets captured (if we're supposed to). */
1717     if (infodelay)
1718         infoprint = TRUE;
1719     else
1720         report_counts_for_siginfo();
1721     errno = sav_errno;
1722 }
1723 #endif /* SIGINFO */
1724
1725 static void
1726 exit_main(int status)
1727 {
1728 #ifdef _WIN32
1729     /* Shutdown windows sockets */
1730     WSACleanup();
1731
1732     /* can be helpful for debugging */
1733 #ifdef DEBUG_DUMPCAP
1734     printf("Press any key\n");
1735     _getch();
1736 #endif
1737
1738 #endif /* _WIN32 */
1739
1740     exit(status);
1741 }
1742
1743 #ifdef HAVE_LIBCAP
1744 /*
1745  * If we were linked with libcap (not related to libpcap), make sure we have
1746  * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1747  * (See comment in main() for details)
1748  */
1749 static void
1750 relinquish_privs_except_capture(void)
1751 {
1752     /* If 'started_with_special_privs' (ie: suid) then enable for
1753      *  ourself the  NET_ADMIN and NET_RAW capabilities and then
1754      *  drop our suid privileges.
1755      *
1756      * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1757      *                stuff we don't need (and shouldn't have).
1758      * CAP_NET_RAW:   Packet capture (raw sockets).
1759      */
1760
1761     if (started_with_special_privs()) {
1762         cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1763         int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1764
1765         cap_t caps = cap_init();    /* all capabilities initialized to off */
1766
1767         print_caps("Pre drop, pre set");
1768
1769         if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1770             cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1771         }
1772
1773         cap_set_flag(caps, CAP_PERMITTED,   cl_len, cap_list, CAP_SET);
1774         cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1775
1776         if (cap_set_proc(caps)) {
1777             cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1778         }
1779         print_caps("Pre drop, post set");
1780
1781         relinquish_special_privs_perm();
1782
1783         print_caps("Post drop, pre set");
1784         cap_set_flag(caps, CAP_EFFECTIVE,   cl_len, cap_list, CAP_SET);
1785         if (cap_set_proc(caps)) {
1786             cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1787         }
1788         print_caps("Post drop, post set");
1789
1790         cap_free(caps);
1791     }
1792 }
1793
1794 #endif /* HAVE_LIBCAP */
1795
1796 /* Take care of byte order in the libpcap headers read from pipes.
1797  * (function taken from wiretap/libpcap.c) */
1798 static void
1799 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1800 {
1801     if (byte_swapped) {
1802         /* Byte-swap the record header fields. */
1803         rechdr->ts_sec = GUINT32_SWAP_LE_BE(rechdr->ts_sec);
1804         rechdr->ts_usec = GUINT32_SWAP_LE_BE(rechdr->ts_usec);
1805         rechdr->incl_len = GUINT32_SWAP_LE_BE(rechdr->incl_len);
1806         rechdr->orig_len = GUINT32_SWAP_LE_BE(rechdr->orig_len);
1807     }
1808
1809     /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1810        swapped, in order to match the BPF header layout.
1811
1812        Unfortunately, some files were, according to a comment in the "libpcap"
1813        source, written with version 2.3 in their headers but without the
1814        interchanged fields, so if "incl_len" is greater than "orig_len" - which
1815        would make no sense - we assume that we need to swap them.  */
1816     if (hdr->version_major == 2 &&
1817         (hdr->version_minor < 3 ||
1818          (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1819         guint32 temp;
1820
1821         temp = rechdr->orig_len;
1822         rechdr->orig_len = rechdr->incl_len;
1823         rechdr->incl_len = temp;
1824     }
1825 }
1826
1827 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1828  * or just read().
1829  */
1830 static ssize_t
1831 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1832 {
1833 #ifdef _WIN32
1834    if (from_socket) {
1835       return recv(pipe_fd, buf, (int)sz, 0);
1836    } else {
1837       return -1;
1838    }
1839 #else
1840    return ws_read(pipe_fd, buf, sz);
1841 #endif
1842 }
1843
1844 #if defined(_WIN32)
1845 /*
1846  * Thread function that reads from a pipe and pushes the data
1847  * to the main application thread.
1848  */
1849 /*
1850  * XXX Right now we use async queues for basic signaling. The main thread
1851  * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1852  * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1853  * Iff the read is successful cap_pipe_read pushes an item onto
1854  * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1855  * the queues themselves (yet).
1856  *
1857  * We might want to move some of the cap_pipe_dispatch logic here so that
1858  * we can let cap_thread_read run independently, queuing up multiple reads
1859  * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1860  */
1861 static void *cap_thread_read(void *arg)
1862 {
1863     pcap_options *pcap_opts;
1864 #ifdef _WIN32
1865     BOOL res;
1866     DWORD b, last_err, bytes_read;
1867 #else /* _WIN32 */
1868     size_t bytes_read;
1869     int b;
1870 #endif /* _WIN32 */
1871
1872     pcap_opts = (pcap_options *)arg;
1873     while (pcap_opts->cap_pipe_err == PIPOK) {
1874         g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1875         g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1876         bytes_read = 0;
1877         while (bytes_read < pcap_opts->cap_pipe_bytes_to_read) {
1878            if ((pcap_opts->from_cap_socket)
1879 #ifndef _WIN32
1880               || 1
1881 #endif
1882               )
1883            {
1884                b = cap_pipe_read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1885                         pcap_opts->cap_pipe_bytes_to_read - bytes_read, pcap_opts->from_cap_socket);
1886                if (b <= 0) {
1887                    if (b == 0) {
1888                        pcap_opts->cap_pipe_err = PIPEOF;
1889                        bytes_read = 0;
1890                        break;
1891                    } else {
1892                        pcap_opts->cap_pipe_err = PIPERR;
1893                        bytes_read = -1;
1894                        break;
1895                    }
1896                } else {
1897                    bytes_read += b;
1898                }
1899            }
1900 #ifdef _WIN32
1901            else
1902            {
1903                /* If we try to use read() on a named pipe on Windows with partial
1904                 * data it appears to return EOF.
1905                 */
1906                res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1907                               pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1908                               &b, NULL);
1909
1910                bytes_read += b;
1911                if (!res) {
1912                    last_err = GetLastError();
1913                    if (last_err == ERROR_MORE_DATA) {
1914                        continue;
1915                    } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1916                        pcap_opts->cap_pipe_err = PIPEOF;
1917                        bytes_read = 0;
1918                        break;
1919                    }
1920                    pcap_opts->cap_pipe_err = PIPERR;
1921                    bytes_read = -1;
1922                    break;
1923                } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1924                    pcap_opts->cap_pipe_err = PIPEOF;
1925                    bytes_read = 0;
1926                    break;
1927                }
1928            }
1929 #endif /*_WIN32 */
1930         }
1931         pcap_opts->cap_pipe_bytes_read = bytes_read;
1932         if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1933             g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1934         }
1935         g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1936     }
1937     return NULL;
1938 }
1939 #endif
1940
1941 /* Provide select() functionality for a single file descriptor
1942  * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1943  *
1944  * Returns the same values as select.
1945  */
1946 static int
1947 cap_pipe_select(int pipe_fd)
1948 {
1949     fd_set      rfds;
1950     struct timeval timeout;
1951
1952     FD_ZERO(&rfds);
1953     FD_SET(pipe_fd, &rfds);
1954
1955     timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1956     timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1957
1958     return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1959 }
1960
1961 #define DEF_TCP_PORT 19000
1962
1963 static int
1964 cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errmsgl)
1965 {
1966   char *sockname = pipename + 4;
1967   struct sockaddr_in sa;
1968   char buf[16];
1969   char *p;
1970   unsigned long port;
1971   size_t len;
1972   int fd;
1973
1974   memset(&sa, 0, sizeof(sa));
1975
1976   p = strchr(sockname, ':');
1977   if (p == NULL) {
1978     len = strlen(sockname);
1979     port = DEF_TCP_PORT;
1980   }
1981   else {
1982     len = p - sockname;
1983     port = strtoul(p + 1, &p, 10);
1984     if (*p || port > 65535) {
1985       goto fail_invalid;
1986     }
1987   }
1988
1989   if (len > 15) {
1990     goto fail_invalid;
1991   }
1992
1993   g_snprintf ( buf,(gulong)len + 1, "%s", sockname );
1994   buf[len] = '\0';
1995   if (inet_pton(AF_INET, buf, &sa.sin_addr) <= 0) {
1996     goto fail_invalid;
1997   }
1998
1999   sa.sin_family = AF_INET;
2000   sa.sin_port = g_htons((u_short)port);
2001
2002   if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
2003       (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
2004 #ifdef _WIN32
2005       LPTSTR errorText = NULL;
2006       int lastError;
2007
2008       lastError = WSAGetLastError();
2009       FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2010                     FORMAT_MESSAGE_ALLOCATE_BUFFER |
2011                     FORMAT_MESSAGE_IGNORE_INSERTS,
2012                     NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2013                     (LPTSTR)&errorText, 0, NULL);
2014 #endif
2015       g_snprintf(errmsg, errmsgl,
2016       "The capture session could not be initiated due to the socket error: \n"
2017 #ifdef _WIN32
2018       "         %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
2019       if (errorText)
2020           LocalFree(errorText);
2021 #else
2022       "         %d: %s", errno, g_strerror(errno));
2023 #endif
2024       pcap_opts->cap_pipe_err = PIPERR;
2025
2026       if (fd >= 0)
2027           cap_pipe_close(fd, TRUE);
2028       return -1;
2029   }
2030
2031   pcap_opts->from_cap_socket = TRUE;
2032   return fd;
2033
2034 fail_invalid:
2035   g_snprintf(errmsg, errmsgl,
2036       "The capture session could not be initiated because\n"
2037       "\"%s\" is not a valid socket specification", pipename);
2038   pcap_opts->cap_pipe_err = PIPERR;
2039   return -1;
2040 }
2041
2042 /* Wrapper: distinguish between closesocket on Windows; use ws_close
2043  * otherwise.
2044  */
2045 static void
2046 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
2047 {
2048 #ifdef _WIN32
2049    if (from_socket) {
2050       closesocket(pipe_fd);
2051    }
2052 #else
2053    ws_close(pipe_fd);
2054 #endif
2055 }
2056
2057 /* Mimic pcap_open_live() for pipe captures
2058
2059  * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
2060  * open it, and read the header.
2061  *
2062  * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
2063  * because we can't seek on pipes (see wiretap/libpcap.c for details) */
2064 static void
2065 cap_pipe_open_live(char *pipename,
2066                    pcap_options *pcap_opts,
2067                    struct pcap_hdr *hdr,
2068                    char *errmsg, int errmsgl)
2069 {
2070 #ifndef _WIN32
2071     ws_statb64         pipe_stat;
2072     struct sockaddr_un sa;
2073 #else /* _WIN32 */
2074     char    *pncopy, *pos;
2075     wchar_t *err_str;
2076     interface_options interface_opts;
2077 #ifdef HAVE_EXTCAP
2078     char* extcap_pipe_name;
2079     gboolean extcap_pipe;
2080 #endif
2081 #endif
2082     ssize_t  b;
2083     int      fd = -1, sel_ret;
2084     size_t   bytes_read;
2085     guint32  magic = 0;
2086     pcap_opts->cap_pipe_fd = -1;
2087 #ifdef _WIN32
2088     pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2089 #endif
2090
2091     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
2092
2093     /*
2094      * XXX - this blocks until a pcap per-file header has been written to
2095      * the pipe, so it could block indefinitely.
2096      */
2097     if (strcmp(pipename, "-") == 0) {
2098 #ifndef _WIN32
2099         fd = 0; /* read from stdin */
2100 #else /* _WIN32 */
2101         pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
2102 #endif  /* _WIN32 */
2103     } else if (!strncmp(pipename, "TCP@", 4)) {
2104        if ((fd = cap_open_socket(pipename, pcap_opts, errmsg, errmsgl)) < 0) {
2105           return;
2106        }
2107     } else {
2108 #ifndef _WIN32
2109         if (ws_stat64(pipename, &pipe_stat) < 0) {
2110             if (errno == ENOENT || errno == ENOTDIR)
2111                 pcap_opts->cap_pipe_err = PIPNEXIST;
2112             else {
2113                 g_snprintf(errmsg, errmsgl,
2114                            "The capture session could not be initiated "
2115                            "due to error getting information on pipe/socket: %s", g_strerror(errno));
2116                 pcap_opts->cap_pipe_err = PIPERR;
2117             }
2118             return;
2119         }
2120         if (S_ISFIFO(pipe_stat.st_mode)) {
2121             fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
2122             if (fd == -1) {
2123                 g_snprintf(errmsg, errmsgl,
2124                            "The capture session could not be initiated "
2125                            "due to error on pipe open: %s", g_strerror(errno));
2126                 pcap_opts->cap_pipe_err = PIPERR;
2127                 return;
2128             }
2129         } else if (S_ISSOCK(pipe_stat.st_mode)) {
2130             fd = socket(AF_UNIX, SOCK_STREAM, 0);
2131             if (fd == -1) {
2132                 g_snprintf(errmsg, errmsgl,
2133                            "The capture session could not be initiated "
2134                            "due to error on socket create: %s", g_strerror(errno));
2135                 pcap_opts->cap_pipe_err = PIPERR;
2136                 return;
2137             }
2138             sa.sun_family = AF_UNIX;
2139             /*
2140              * The Single UNIX Specification says:
2141              *
2142              *   The size of sun_path has intentionally been left undefined.
2143              *   This is because different implementations use different sizes.
2144              *   For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
2145              *   of 104. Since most implementations originate from BSD versions,
2146              *   the size is typically in the range 92 to 108.
2147              *
2148              *   Applications should not assume a particular length for sun_path
2149              *   or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
2150              *
2151              * It also says
2152              *
2153              *   The <sys/un.h> header shall define the sockaddr_un structure,
2154              *   which shall include at least the following members:
2155              *
2156              *   sa_family_t  sun_family  Address family.
2157              *   char         sun_path[]  Socket pathname.
2158              *
2159              * so we assume that it's an array, with a specified size,
2160              * and that the size reflects the maximum path length.
2161              */
2162             if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
2163                 /* Path name too long */
2164                 g_snprintf(errmsg, errmsgl,
2165                            "The capture session coud not be initiated "
2166                            "due to error on socket connect: Path name too long");
2167                 pcap_opts->cap_pipe_err = PIPERR;
2168                 ws_close(fd);
2169                 return;
2170             }
2171             b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
2172             if (b == -1) {
2173                 g_snprintf(errmsg, errmsgl,
2174                            "The capture session coud not be initiated "
2175                            "due to error on socket connect: %s", g_strerror(errno));
2176                 pcap_opts->cap_pipe_err = PIPERR;
2177                 ws_close(fd);
2178                 return;
2179             }
2180         } else {
2181             if (S_ISCHR(pipe_stat.st_mode)) {
2182                 /*
2183                  * Assume the user specified an interface on a system where
2184                  * interfaces are in /dev.  Pretend we haven't seen it.
2185                  */
2186                 pcap_opts->cap_pipe_err = PIPNEXIST;
2187             } else {
2188                 g_snprintf(errmsg, errmsgl,
2189                            "The capture session could not be initiated because\n"
2190                            "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
2191                 pcap_opts->cap_pipe_err = PIPERR;
2192             }
2193             return;
2194         }
2195 #else /* _WIN32 */
2196 #define PIPE_STR "\\pipe\\"
2197         /* Under Windows, named pipes _must_ have the form
2198          * "\\<server>\pipe\<pipename>".  <server> may be "." for localhost.
2199          */
2200         pncopy = g_strdup(pipename);
2201         if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
2202             pos = strchr(pncopy + 3, '\\');
2203             if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
2204                 pos = NULL;
2205         }
2206
2207         g_free(pncopy);
2208
2209         if (!pos) {
2210             g_snprintf(errmsg, errmsgl,
2211                        "The capture session could not be initiated because\n"
2212                        "\"%s\" is neither an interface nor a pipe", pipename);
2213             pcap_opts->cap_pipe_err = PIPNEXIST;
2214             return;
2215         }
2216
2217         interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
2218 #ifdef HAVE_EXTCAP
2219         extcap_pipe_name = g_strconcat("\\\\.\\pipe\\", EXTCAP_PIPE_PREFIX, NULL);
2220         extcap_pipe = strstr(interface_opts.name, extcap_pipe_name) ? TRUE : FALSE;
2221         g_free(extcap_pipe_name);
2222 #endif
2223
2224         /* Wait for the pipe to appear */
2225         while (1) {
2226
2227 #ifdef HAVE_EXTCAP
2228             if(extcap_pipe)
2229                 pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
2230             else
2231 #endif
2232                 pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
2233                                                    OPEN_EXISTING, 0, NULL);
2234
2235             if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
2236                 break;
2237
2238             if (GetLastError() != ERROR_PIPE_BUSY) {
2239                 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2240                               NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2241                 g_snprintf(errmsg, errmsgl,
2242                            "The capture session on \"%s\" could not be started "
2243                            "due to error on pipe open: %s (error %d)",
2244                            pipename, utf_16to8(err_str), GetLastError());
2245                 LocalFree(err_str);
2246                 pcap_opts->cap_pipe_err = PIPERR;
2247                 return;
2248             }
2249
2250             if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
2251                 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2252                              NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2253                 g_snprintf(errmsg, errmsgl,
2254                            "The capture session on \"%s\" timed out during "
2255                            "pipe open: %s (error %d)",
2256                            pipename, utf_16to8(err_str), GetLastError());
2257                 LocalFree(err_str);
2258                 pcap_opts->cap_pipe_err = PIPERR;
2259                 return;
2260             }
2261         }
2262 #endif /* _WIN32 */
2263     }
2264
2265     pcap_opts->from_cap_pipe = TRUE;
2266
2267 #ifdef _WIN32
2268     if (pcap_opts->from_cap_socket)
2269 #endif
2270     {
2271         /* read the pcap header */
2272         bytes_read = 0;
2273         while (bytes_read < sizeof magic) {
2274             if (fd == -1) {
2275                 g_snprintf(errmsg, errmsgl, "Invalid file descriptor");
2276                 goto error;
2277             }
2278
2279             sel_ret = cap_pipe_select(fd);
2280             if (sel_ret < 0) {
2281                 g_snprintf(errmsg, errmsgl,
2282                            "Unexpected error from select: %s", g_strerror(errno));
2283                 goto error;
2284             } else if (sel_ret > 0) {
2285                 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
2286                                   sizeof magic-bytes_read,
2287                                   pcap_opts->from_cap_socket);
2288                 if (b <= 0) {
2289                     if (b == 0)
2290                         g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2291                     else
2292                         g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2293                                    g_strerror(errno));
2294                     goto error;
2295                 }
2296                 bytes_read += b;
2297             }
2298         }
2299     }
2300 #ifdef _WIN32
2301     else {
2302 #if GLIB_CHECK_VERSION(2,31,0)
2303         g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_opts);
2304 #else
2305         g_thread_create(&cap_thread_read, pcap_opts, FALSE, NULL);
2306 #endif
2307
2308         pcap_opts->cap_pipe_buf = (char *) &magic;
2309         pcap_opts->cap_pipe_bytes_read = 0;
2310         pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
2311         /* We don't have to worry about cap_pipe_read_mtx here */
2312         g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2313         g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2314         if (pcap_opts->cap_pipe_bytes_read <= 0) {
2315             if (pcap_opts->cap_pipe_bytes_read == 0)
2316                 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2317             else
2318                 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2319                            g_strerror(errno));
2320             goto error;
2321         }
2322     }
2323 #endif
2324
2325     switch (magic) {
2326     case PCAP_MAGIC:
2327     case PCAP_NSEC_MAGIC:
2328         /* Host that wrote it has our byte order, and was running
2329            a program using either standard or ss990417 libpcap. */
2330         pcap_opts->cap_pipe_byte_swapped = FALSE;
2331         pcap_opts->cap_pipe_modified = FALSE;
2332         pcap_opts->ts_nsec = magic == PCAP_NSEC_MAGIC;
2333         break;
2334     case PCAP_MODIFIED_MAGIC:
2335         /* Host that wrote it has our byte order, but was running
2336            a program using either ss990915 or ss991029 libpcap. */
2337         pcap_opts->cap_pipe_byte_swapped = FALSE;
2338         pcap_opts->cap_pipe_modified = TRUE;
2339         break;
2340     case PCAP_SWAPPED_MAGIC:
2341     case PCAP_SWAPPED_NSEC_MAGIC:
2342         /* Host that wrote it has a byte order opposite to ours,
2343            and was running a program using either standard or
2344            ss990417 libpcap. */
2345         pcap_opts->cap_pipe_byte_swapped = TRUE;
2346         pcap_opts->cap_pipe_modified = FALSE;
2347         pcap_opts->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
2348         break;
2349     case PCAP_SWAPPED_MODIFIED_MAGIC:
2350         /* Host that wrote it out has a byte order opposite to
2351            ours, and was running a program using either ss990915
2352            or ss991029 libpcap. */
2353         pcap_opts->cap_pipe_byte_swapped = TRUE;
2354         pcap_opts->cap_pipe_modified = TRUE;
2355         break;
2356     default:
2357         /* Not a "libpcap" type we know about. */
2358         g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
2359         goto error;
2360     }
2361
2362 #ifdef _WIN32
2363     if (pcap_opts->from_cap_socket)
2364 #endif
2365     {
2366         /* Read the rest of the header */
2367         bytes_read = 0;
2368         while (bytes_read < sizeof(struct pcap_hdr)) {
2369             sel_ret = cap_pipe_select(fd);
2370             if (sel_ret < 0) {
2371                 g_snprintf(errmsg, errmsgl,
2372                            "Unexpected error from select: %s", g_strerror(errno));
2373                 goto error;
2374             } else if (sel_ret > 0) {
2375                 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
2376                                   sizeof(struct pcap_hdr) - bytes_read,
2377                                   pcap_opts->from_cap_socket);
2378                 if (b <= 0) {
2379                     if (b == 0)
2380                         g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2381                     else
2382                         g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
2383                                    g_strerror(errno));
2384                     goto error;
2385                 }
2386                 bytes_read += b;
2387             }
2388         }
2389     }
2390 #ifdef _WIN32
2391     else {
2392         pcap_opts->cap_pipe_buf = (char *) hdr;
2393         pcap_opts->cap_pipe_bytes_read = 0;
2394         pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
2395         g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2396         g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2397         if (pcap_opts->cap_pipe_bytes_read <= 0) {
2398             if (pcap_opts->cap_pipe_bytes_read == 0)
2399                 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2400             else
2401                 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
2402                            g_strerror(errno));
2403             goto error;
2404         }
2405     }
2406 #endif
2407
2408     if (pcap_opts->cap_pipe_byte_swapped) {
2409         /* Byte-swap the header fields about which we care. */
2410         hdr->version_major = GUINT16_SWAP_LE_BE(hdr->version_major);
2411         hdr->version_minor = GUINT16_SWAP_LE_BE(hdr->version_minor);
2412         hdr->snaplen = GUINT32_SWAP_LE_BE(hdr->snaplen);
2413         hdr->network = GUINT32_SWAP_LE_BE(hdr->network);
2414     }
2415     pcap_opts->linktype = hdr->network;
2416
2417     if (hdr->version_major < 2) {
2418         g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
2419         goto error;
2420     }
2421
2422     pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2423     pcap_opts->cap_pipe_err = PIPOK;
2424     pcap_opts->cap_pipe_fd = fd;
2425     return;
2426
2427 error:
2428     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
2429     pcap_opts->cap_pipe_err = PIPERR;
2430     cap_pipe_close(fd, pcap_opts->from_cap_socket);
2431     pcap_opts->cap_pipe_fd = -1;
2432 }
2433
2434
2435 /* We read one record from the pipe, take care of byte order in the record
2436  * header, write the record to the capture file, and update capture statistics. */
2437 static int
2438 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
2439 {
2440     struct pcap_pkthdr  phdr;
2441     enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2442            PD_ERR } result;
2443 #ifdef _WIN32
2444 #if !GLIB_CHECK_VERSION(2,31,18)
2445     GTimeVal  wait_time;
2446 #endif
2447     gpointer  q_status;
2448     wchar_t  *err_str;
2449 #endif
2450     ssize_t   b;
2451
2452 #ifdef LOG_CAPTURE_VERBOSE
2453     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
2454 #endif
2455
2456     switch (pcap_opts->cap_pipe_state) {
2457
2458     case STATE_EXPECT_REC_HDR:
2459 #ifdef _WIN32
2460         if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2461 #endif
2462
2463             pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
2464             pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
2465                 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2466             pcap_opts->cap_pipe_bytes_read = 0;
2467
2468 #ifdef _WIN32
2469             pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
2470             g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2471             g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2472         }
2473 #endif
2474         /* Fall through */
2475
2476     case STATE_READ_REC_HDR:
2477 #ifdef _WIN32
2478         if (pcap_opts->from_cap_socket)
2479 #endif
2480         {
2481             b = cap_pipe_read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
2482                  pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
2483             if (b <= 0) {
2484                 if (b == 0)
2485                     result = PD_PIPE_EOF;
2486                 else
2487                     result = PD_PIPE_ERR;
2488                 break;
2489             }
2490             pcap_opts->cap_pipe_bytes_read += b;
2491         }
2492 #ifdef _WIN32
2493         else {
2494 #if GLIB_CHECK_VERSION(2,31,18)
2495             q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2496 #else
2497             g_get_current_time(&wait_time);
2498             g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2499             q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2500 #endif
2501             if (pcap_opts->cap_pipe_err == PIPEOF) {
2502                 result = PD_PIPE_EOF;
2503                 break;
2504             } else if (pcap_opts->cap_pipe_err == PIPERR) {
2505                 result = PD_PIPE_ERR;
2506                 break;
2507             }
2508             if (!q_status) {
2509                 return 0;
2510             }
2511         }
2512 #endif
2513         if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2514             return 0;
2515         result = PD_REC_HDR_READ;
2516         break;
2517
2518     case STATE_EXPECT_DATA:
2519 #ifdef _WIN32
2520         if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2521 #endif
2522
2523             pcap_opts->cap_pipe_state = STATE_READ_DATA;
2524             pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2525             pcap_opts->cap_pipe_bytes_read = 0;
2526
2527 #ifdef _WIN32
2528             pcap_opts->cap_pipe_buf = (char *) data;
2529             g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2530             g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2531         }
2532 #endif
2533         /* Fall through */
2534
2535     case STATE_READ_DATA:
2536 #ifdef _WIN32
2537         if (pcap_opts->from_cap_socket)
2538 #endif
2539         {
2540             b = cap_pipe_read(pcap_opts->cap_pipe_fd,
2541                               data+pcap_opts->cap_pipe_bytes_read,
2542                               pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read,
2543                               pcap_opts->from_cap_socket);
2544             if (b <= 0) {
2545                 if (b == 0)
2546                     result = PD_PIPE_EOF;
2547                 else
2548                     result = PD_PIPE_ERR;
2549                 break;
2550             }
2551             pcap_opts->cap_pipe_bytes_read += b;
2552         }
2553 #ifdef _WIN32
2554         else {
2555
2556 #if GLIB_CHECK_VERSION(2,31,18)
2557             q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2558 #else
2559             g_get_current_time(&wait_time);
2560             g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2561             q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2562 #endif /* GLIB_CHECK_VERSION(2,31,18) */
2563             if (pcap_opts->cap_pipe_err == PIPEOF) {
2564                 result = PD_PIPE_EOF;
2565                 break;
2566             } else if (pcap_opts->cap_pipe_err == PIPERR) {
2567                 result = PD_PIPE_ERR;
2568                 break;
2569             }
2570             if (!q_status) {
2571                 return 0;
2572             }
2573         }
2574 #endif /* _WIN32 */
2575         if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2576             return 0;
2577         result = PD_DATA_READ;
2578         break;
2579
2580     default:
2581         g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2582         result = PD_ERR;
2583
2584     } /* switch (pcap_opts->cap_pipe_state) */
2585
2586     /*
2587      * We've now read as much data as we were expecting, so process it.
2588      */
2589     switch (result) {
2590
2591     case PD_REC_HDR_READ:
2592         /* We've read the header. Take care of byte order. */
2593         cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
2594                                &pcap_opts->cap_pipe_rechdr.hdr);
2595         if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2596             g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2597                        ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
2598             break;
2599         }
2600
2601         if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2602             pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2603             return 0;
2604         }
2605         /* no data to read? fall through */
2606
2607     case PD_DATA_READ:
2608         /* Fill in a "struct pcap_pkthdr", and process the packet. */
2609         phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2610         phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2611         phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2612         phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2613
2614         if (use_threads) {
2615             capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2616         } else {
2617             capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2618         }
2619         pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2620         return 1;
2621
2622     case PD_PIPE_EOF:
2623         pcap_opts->cap_pipe_err = PIPEOF;
2624         return -1;
2625
2626     case PD_PIPE_ERR:
2627 #ifdef _WIN32
2628         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2629                       NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2630         g_snprintf(errmsg, errmsgl,
2631                    "Error reading from pipe: %s (error %d)",
2632                    utf_16to8(err_str), GetLastError());
2633         LocalFree(err_str);
2634 #else
2635         g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2636                    g_strerror(errno));
2637 #endif
2638         /* Fall through */
2639     case PD_ERR:
2640         break;
2641     }
2642
2643     pcap_opts->cap_pipe_err = PIPERR;
2644     /* Return here rather than inside the switch to prevent GCC warning */
2645     return -1;
2646 }
2647
2648
2649 /** Open the capture input file (pcap or capture pipe).
2650  *  Returns TRUE if it succeeds, FALSE otherwise. */
2651 static gboolean
2652 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2653                         char *errmsg, size_t errmsg_len,
2654                         char *secondary_errmsg, size_t secondary_errmsg_len)
2655 {
2656     gchar             open_err_str[PCAP_ERRBUF_SIZE];
2657     gchar             *sync_msg_str;
2658     interface_options interface_opts;
2659     pcap_options      *pcap_opts;
2660     guint             i;
2661 #ifdef _WIN32
2662     int         err;
2663     WORD        wVersionRequested;
2664     WSADATA     wsaData;
2665 #endif
2666
2667 /* XXX - opening Winsock on tshark? */
2668
2669     /* Initialize Windows Socket if we are in a Win32 OS
2670        This needs to be done before querying the interface for network/netmask */
2671 #ifdef _WIN32
2672     /* XXX - do we really require 1.1 or earlier?
2673        Are there any versions that support only 2.0 or higher? */
2674     wVersionRequested = MAKEWORD(1, 1);
2675     err = WSAStartup(wVersionRequested, &wsaData);
2676     if (err != 0) {
2677         switch (err) {
2678
2679         case WSASYSNOTREADY:
2680             g_snprintf(errmsg, (gulong) errmsg_len,
2681                        "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2682             break;
2683
2684         case WSAVERNOTSUPPORTED:
2685             g_snprintf(errmsg, (gulong) errmsg_len,
2686                        "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2687                        LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2688             break;
2689
2690         case WSAEINPROGRESS:
2691             g_snprintf(errmsg, (gulong) errmsg_len,
2692                        "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2693             break;
2694
2695         case WSAEPROCLIM:
2696             g_snprintf(errmsg, (gulong) errmsg_len,
2697                        "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2698             break;
2699
2700         case WSAEFAULT:
2701             g_snprintf(errmsg, (gulong) errmsg_len,
2702                        "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2703             break;
2704
2705         default:
2706             g_snprintf(errmsg, (gulong) errmsg_len,
2707                        "Couldn't initialize Windows Sockets: error %d", err);
2708             break;
2709         }
2710         g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2711         return FALSE;
2712     }
2713 #endif
2714     if ((use_threads == FALSE) &&
2715         (capture_opts->ifaces->len > 1)) {
2716         g_snprintf(errmsg, (gulong) errmsg_len,
2717                    "Using threads is required for capturing on multiple interfaces.");
2718         return FALSE;
2719     }
2720
2721     for (i = 0; i < capture_opts->ifaces->len; i++) {
2722         interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2723         pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2724         if (pcap_opts == NULL) {
2725             g_snprintf(errmsg, (gulong) errmsg_len,
2726                    "Could not allocate memory.");
2727             return FALSE;
2728         }
2729         pcap_opts->received = 0;
2730         pcap_opts->dropped = 0;
2731         pcap_opts->flushed = 0;
2732         pcap_opts->pcap_h = NULL;
2733 #ifdef MUST_DO_SELECT
2734         pcap_opts->pcap_fd = -1;
2735 #endif
2736         pcap_opts->pcap_err = FALSE;
2737         pcap_opts->interface_id = i;
2738         pcap_opts->tid = NULL;
2739         pcap_opts->snaplen = 0;
2740         pcap_opts->linktype = -1;
2741         pcap_opts->ts_nsec = FALSE;
2742         pcap_opts->from_cap_pipe = FALSE;
2743         pcap_opts->from_cap_socket = FALSE;
2744         memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2745         memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2746 #ifdef _WIN32
2747         pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2748 #endif
2749         pcap_opts->cap_pipe_fd = -1;
2750         pcap_opts->cap_pipe_modified = FALSE;
2751         pcap_opts->cap_pipe_byte_swapped = FALSE;
2752 #ifdef _WIN32
2753         pcap_opts->cap_pipe_buf = NULL;
2754 #endif
2755         pcap_opts->cap_pipe_bytes_to_read = 0;
2756         pcap_opts->cap_pipe_bytes_read = 0;
2757         pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2758         pcap_opts->cap_pipe_err = PIPOK;
2759 #ifdef _WIN32
2760 #if GLIB_CHECK_VERSION(2,31,0)
2761         pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2762         g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2763 #else
2764         pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2765 #endif
2766         pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2767         pcap_opts->cap_pipe_done_q = g_async_queue_new();
2768 #endif
2769         g_array_append_val(ld->pcaps, pcap_opts);
2770
2771         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2772         pcap_opts->pcap_h = open_capture_device(capture_opts, &interface_opts, &open_err_str);
2773
2774         if (pcap_opts->pcap_h != NULL) {
2775             /* we've opened "iface" as a network device */
2776
2777 #ifdef HAVE_PCAP_SET_TSTAMP_PRECISION
2778             /* Find out if we're getting nanosecond-precision time stamps */
2779             pcap_opts->ts_nsec = have_high_resolution_timestamp(pcap_opts->pcap_h);
2780 #endif
2781
2782 #if defined(HAVE_PCAP_SETSAMPLING)
2783             if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2784                 struct pcap_samp *samp;
2785
2786                 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2787                     switch (interface_opts.sampling_method) {
2788                     case CAPTURE_SAMP_BY_COUNT:
2789                         samp->method = PCAP_SAMP_1_EVERY_N;
2790                         break;
2791
2792                     case CAPTURE_SAMP_BY_TIMER:
2793                         samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2794                         break;
2795
2796                     default:
2797                         sync_msg_str = g_strdup_printf(
2798                             "Unknown sampling method %d specified,\n"
2799                             "continue without packet sampling",
2800                             interface_opts.sampling_method);
2801                         report_capture_error("Couldn't set the capture "
2802                                              "sampling", sync_msg_str);
2803                         g_free(sync_msg_str);
2804                     }
2805                     samp->value = interface_opts.sampling_param;
2806                 } else {
2807                     report_capture_error("Couldn't set the capture sampling",
2808                                          "Cannot get packet sampling data structure");
2809                 }
2810             }
2811 #endif
2812
2813             /* setting the data link type only works on real interfaces */
2814             if (!set_pcap_linktype(pcap_opts->pcap_h, interface_opts.linktype, interface_opts.name,
2815                                    errmsg, errmsg_len,
2816                                    secondary_errmsg, secondary_errmsg_len)) {
2817                 return FALSE;
2818             }
2819             pcap_opts->linktype = get_pcap_linktype(pcap_opts->pcap_h, interface_opts.name);
2820         } else {
2821             /* We couldn't open "iface" as a network device. */
2822             /* Try to open it as a pipe */
2823             cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2824
2825 #ifndef _WIN32
2826             if (pcap_opts->cap_pipe_fd == -1) {
2827 #else
2828             if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2829 #endif
2830                 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2831                     /* Pipe doesn't exist, so output message for interface */
2832                     get_capture_device_open_failure_messages(open_err_str,
2833                                                              interface_opts.name,
2834                                                              errmsg,
2835                                                              errmsg_len,
2836                                                              secondary_errmsg,
2837                                                              secondary_errmsg_len);
2838                 }
2839                 /*
2840                  * Else pipe (or file) does exist and cap_pipe_open_live() has
2841                  * filled in errmsg
2842                  */
2843                 return FALSE;
2844             } else {
2845                 /* cap_pipe_open_live() succeeded; don't want
2846                    error message from pcap_open_live() */
2847                 open_err_str[0] = '\0';
2848             }
2849         }
2850
2851 /* XXX - will this work for tshark? */
2852 #ifdef MUST_DO_SELECT
2853         if (!pcap_opts->from_cap_pipe) {
2854 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2855             pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2856 #else
2857             pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2858 #endif
2859         }
2860 #endif
2861
2862         /* Does "open_err_str" contain a non-empty string?  If so, "pcap_open_live()"
2863            returned a warning; print it, but keep capturing. */
2864         if (open_err_str[0] != '\0') {
2865             sync_msg_str = g_strdup_printf("%s.", open_err_str);
2866             report_capture_error(sync_msg_str, "");
2867             g_free(sync_msg_str);
2868         }
2869         capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2870         g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2871     }
2872
2873     /* If not using libcap: we now can now set euid/egid to ruid/rgid         */
2874     /*  to remove any suid privileges.                                        */
2875     /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities  */
2876     /*  (euid/egid have already previously been set to ruid/rgid.             */
2877     /* (See comment in main() for details)                                    */
2878 #ifndef HAVE_LIBCAP
2879     relinquish_special_privs_perm();
2880 #else
2881     relinquish_all_capabilities();
2882 #endif
2883     return TRUE;
2884 }
2885
2886 /* close the capture input file (pcap or capture pipe) */
2887 static void capture_loop_close_input(loop_data *ld)
2888 {
2889     guint         i;
2890     pcap_options *pcap_opts;
2891
2892     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2893
2894     for (i = 0; i < ld->pcaps->len; i++) {
2895         pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2896         /* if open, close the capture pipe "input file" */
2897         if (pcap_opts->cap_pipe_fd >= 0) {
2898             g_assert(pcap_opts->from_cap_pipe);
2899             cap_pipe_close(pcap_opts->cap_pipe_fd, pcap_opts->from_cap_socket);
2900             pcap_opts->cap_pipe_fd = -1;
2901         }
2902 #ifdef _WIN32
2903         if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2904             CloseHandle(pcap_opts->cap_pipe_h);
2905             pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2906         }
2907 #endif
2908         /* if open, close the pcap "input file" */
2909         if (pcap_opts->pcap_h != NULL) {
2910             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2911             pcap_close(pcap_opts->pcap_h);
2912             pcap_opts->pcap_h = NULL;
2913         }
2914     }
2915
2916     ld->go = FALSE;
2917
2918 #ifdef _WIN32
2919     /* Shut down windows sockets */
2920     WSACleanup();
2921 #endif
2922 }
2923
2924
2925 /* init the capture filter */
2926 static initfilter_status_t
2927 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2928                          const gchar * name, const gchar * cfilter)
2929 {
2930     struct bpf_program fcode;
2931
2932     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2933
2934     /* capture filters only work on real interfaces */
2935     if (cfilter && !from_cap_pipe) {
2936         /* A capture filter was specified; set it up. */
2937         if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2938             /* Treat this specially - our caller might try to compile this
2939                as a display filter and, if that succeeds, warn the user that
2940                the display and capture filter syntaxes are different. */
2941             return INITFILTER_BAD_FILTER;
2942         }
2943         if (pcap_setfilter(pcap_h, &fcode) < 0) {
2944 #ifdef HAVE_PCAP_FREECODE
2945             pcap_freecode(&fcode);
2946 #endif
2947             return INITFILTER_OTHER_ERROR;
2948         }
2949 #ifdef HAVE_PCAP_FREECODE
2950         pcap_freecode(&fcode);
2951 #endif
2952     }
2953
2954     return INITFILTER_NO_ERROR;
2955 }
2956
2957
2958 /* set up to write to the already-opened capture output file/files */
2959 static gboolean
2960 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2961 {
2962     int                err;
2963     guint              i;
2964     pcap_options      *pcap_opts;
2965     interface_options  interface_opts;
2966     gboolean           successful;
2967
2968     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2969
2970     if ((capture_opts->use_pcapng == FALSE) &&
2971         (capture_opts->ifaces->len > 1)) {
2972         g_snprintf(errmsg, errmsg_len,
2973                    "Using PCAPNG is required for capturing on multiple interfaces. Use the -n option.");
2974         return FALSE;
2975     }
2976
2977     /* Set up to write to the capture file. */
2978     if (capture_opts->multi_files_on) {
2979         ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2980     } else {
2981         ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2982         if (ld->pdh == NULL) {
2983             err = errno;
2984         }
2985     }
2986     if (ld->pdh) {
2987         if (capture_opts->use_pcapng) {
2988             char    *appname;
2989             GString *os_info_str;
2990
2991             os_info_str = g_string_new("");
2992             get_os_version_info(os_info_str);
2993
2994             appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
2995             successful = pcapng_write_session_header_block(ld->pdh,
2996                                 (const char *)capture_opts->capture_comment,   /* Comment*/
2997                                 NULL,                        /* HW*/
2998                                 os_info_str->str,            /* OS*/
2999                                 appname,
3000                                 -1,                          /* section_length */
3001                                 &ld->bytes_written,
3002                                 &err);
3003             g_free(appname);
3004
3005             for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3006                 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3007                 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
3008                 if (pcap_opts->from_cap_pipe) {
3009                     pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
3010                 } else {
3011                     pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
3012                 }
3013                 successful = pcapng_write_interface_description_block(global_ld.pdh,
3014                                                                       NULL,                       /* OPT_COMMENT       1 */
3015                                                                       interface_opts.name,        /* IDB_NAME          2 */
3016                                                                       interface_opts.descr,       /* IDB_DESCRIPTION   3 */
3017                                                                       interface_opts.cfilter,     /* IDB_FILTER       11 */
3018                                                                       os_info_str->str,           /* IDB_OS           12 */
3019                                                                       pcap_opts->linktype,
3020                                                                       pcap_opts->snaplen,
3021                                                                       &(global_ld.bytes_written),
3022                                                                       0,                          /* IDB_IF_SPEED      8 */
3023                                                                       pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL       9 */
3024                                                                       &global_ld.err);
3025             }
3026
3027             g_string_free(os_info_str, TRUE);
3028
3029         } else {
3030             pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
3031             if (pcap_opts->from_cap_pipe) {
3032                 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
3033             } else {
3034                 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
3035             }
3036             successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
3037                                                    pcap_opts->ts_nsec, &ld->bytes_written, &err);
3038         }
3039         if (!successful) {
3040             fclose(ld->pdh);
3041             ld->pdh = NULL;
3042         }
3043     }
3044
3045     if (ld->pdh == NULL) {
3046         /* We couldn't set up to write to the capture file. */
3047         /* XXX - use cf_open_error_message from tshark instead? */
3048         switch (err) {
3049
3050         default:
3051             if (err < 0) {
3052                 g_snprintf(errmsg, errmsg_len,
3053                            "The file to which the capture would be"
3054                            " saved (\"%s\") could not be opened: Error %d.",
3055                            capture_opts->save_file, err);
3056             } else {
3057                 g_snprintf(errmsg, errmsg_len,
3058                            "The file to which the capture would be"
3059                            " saved (\"%s\") could not be opened: %s.",
3060                            capture_opts->save_file, g_strerror(err));
3061             }
3062             break;
3063         }
3064
3065         return FALSE;
3066     }
3067
3068     return TRUE;
3069 }
3070
3071 static gboolean
3072 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
3073 {
3074
3075     unsigned int  i;
3076     pcap_options *pcap_opts;
3077     guint64       end_time = create_timestamp();
3078
3079     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
3080
3081     if (capture_opts->multi_files_on) {
3082         return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
3083     } else {
3084         if (capture_opts->use_pcapng) {
3085             for (i = 0; i < global_ld.pcaps->len; i++) {
3086                 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3087                 if (!pcap_opts->from_cap_pipe) {
3088                     guint64 isb_ifrecv, isb_ifdrop;
3089                     struct pcap_stat stats;
3090
3091                     if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
3092                         isb_ifrecv = pcap_opts->received;
3093                         isb_ifdrop = stats.ps_drop + pcap_opts->dropped + pcap_opts->flushed;
3094                    } else {
3095                         isb_ifrecv = G_MAXUINT64;
3096                         isb_ifdrop = G_MAXUINT64;
3097                     }
3098                     pcapng_write_interface_statistics_block(ld->pdh,
3099                                                             i,
3100                                                             &ld->bytes_written,
3101                                                             "Counters provided by dumpcap",
3102                                                             start_time,
3103                                                             end_time,
3104                                                             isb_ifrecv,
3105                                                             isb_ifdrop,
3106                                                             err_close);
3107                 }
3108             }
3109         }
3110         if (fclose(ld->pdh) == EOF) {
3111             if (err_close != NULL) {
3112                 *err_close = errno;
3113             }
3114             return (FALSE);
3115         } else {
3116             return (TRUE);
3117         }
3118     }
3119 }
3120
3121 /* dispatch incoming packets (pcap or capture pipe)
3122  *
3123  * Waits for incoming packets to be available, and calls pcap_dispatch()
3124  * to cause them to be processed.
3125  *
3126  * Returns the number of packets which were processed.
3127  *
3128  * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
3129  * packet-batching behaviour does not cause packets to get held back
3130  * indefinitely.
3131  */
3132 static int
3133 capture_loop_dispatch(loop_data *ld,
3134                       char *errmsg, int errmsg_len, pcap_options *pcap_opts)
3135 {
3136     int    inpkts;
3137     gint   packet_count_before;
3138     guchar pcap_data[WTAP_MAX_PACKET_SIZE];
3139 #ifndef _WIN32
3140     int    sel_ret;
3141 #endif
3142
3143     packet_count_before = ld->packet_count;
3144     if (pcap_opts->from_cap_pipe) {
3145         /* dispatch from capture pipe */
3146 #ifdef LOG_CAPTURE_VERBOSE
3147         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
3148 #endif
3149 #ifndef _WIN32
3150         sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
3151         if (sel_ret <= 0) {
3152             if (sel_ret < 0 && errno != EINTR) {
3153                 g_snprintf(errmsg, errmsg_len,
3154                            "Unexpected error from select: %s", g_strerror(errno));
3155                 report_capture_error(errmsg, please_report);
3156                 ld->go = FALSE;
3157             }
3158         } else {
3159             /*
3160              * "select()" says we can read from the pipe without blocking
3161              */
3162 #endif
3163             inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
3164             if (inpkts < 0) {
3165                 ld->go = FALSE;
3166             }
3167 #ifndef _WIN32
3168         }
3169 #endif
3170     }
3171     else
3172     {
3173         /* dispatch from pcap */
3174 #ifdef MUST_DO_SELECT
3175         /*
3176          * If we have "pcap_get_selectable_fd()", we use it to get the
3177          * descriptor on which to select; if that's -1, it means there
3178          * is no descriptor on which you can do a "select()" (perhaps
3179          * because you're capturing on a special device, and that device's
3180          * driver unfortunately doesn't support "select()", in which case
3181          * we don't do the select - which means it might not be possible
3182          * to stop a capture until a packet arrives.  If that's unacceptable,
3183          * plead with whoever supplies the software for that device to add
3184          * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3185          * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3186          * later, so it can use pcap_breakloop().
3187          */
3188 #ifdef LOG_CAPTURE_VERBOSE
3189         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3190 #endif
3191         if (pcap_opts->pcap_fd != -1) {
3192             sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
3193             if (sel_ret > 0) {
3194                 /*
3195                  * "select()" says we can read from it without blocking; go for
3196                  * it.
3197                  *
3198                  * We don't have pcap_breakloop(), so we only process one packet
3199                  * per pcap_dispatch() call, to allow a signal to stop the
3200                  * processing immediately, rather than processing all packets
3201                  * in a batch before quitting.
3202                  */
3203                 if (use_threads) {
3204                     inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3205                 } else {
3206                     inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3207                 }
3208                 if (inpkts < 0) {
3209                     if (inpkts == -1) {
3210                         /* Error, rather than pcap_breakloop(). */
3211                         pcap_opts->pcap_err = TRUE;
3212                     }
3213                     ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3214                 }
3215             } else {
3216                 if (sel_ret < 0 && errno != EINTR) {
3217                     g_snprintf(errmsg, errmsg_len,
3218                                "Unexpected error from select: %s", g_strerror(errno));
3219                     report_capture_error(errmsg, please_report);
3220                     ld->go = FALSE;
3221                 }
3222             }
3223         }
3224         else
3225 #endif /* MUST_DO_SELECT */
3226         {
3227             /* dispatch from pcap without select */
3228 #if 1
3229 #ifdef LOG_CAPTURE_VERBOSE
3230             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3231 #endif
3232 #ifdef _WIN32
3233             /*
3234              * On Windows, we don't support asynchronously telling a process to
3235              * stop capturing; instead, we check for an indication on a pipe
3236              * after processing packets.  We therefore process only one packet
3237              * at a time, so that we can check the pipe after every packet.
3238              */
3239             if (use_threads) {
3240                 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3241             } else {
3242                 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3243             }
3244 #else
3245             if (use_threads) {
3246                 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3247             } else {
3248                 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3249             }
3250 #endif
3251             if (inpkts < 0) {
3252                 if (inpkts == -1) {
3253                     /* Error, rather than pcap_breakloop(). */
3254                     pcap_opts->pcap_err = TRUE;
3255                 }
3256                 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3257             }
3258 #else /* pcap_next_ex */
3259 #ifdef LOG_CAPTURE_VERBOSE
3260             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3261 #endif
3262             /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3263
3264             /*
3265              * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3266              * see https://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
3267              * This should be fixed in the WinPcap 4.0 alpha release.
3268              *
3269              * For reference, an example remote interface:
3270              * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3271              */
3272
3273             /* emulate dispatch from pcap */
3274             {
3275                 int in;
3276                 struct pcap_pkthdr *pkt_header;
3277                 u_char *pkt_data;
3278
3279                 in = 0;
3280                 while(ld->go &&
3281                       (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
3282                     if (use_threads) {
3283                         capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3284                     } else {
3285                         capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3286                     }
3287                 }
3288
3289                 if (in < 0) {
3290                     pcap_opts->pcap_err = TRUE;
3291                     ld->go = FALSE;
3292                 }
3293             }
3294 #endif /* pcap_next_ex */
3295         }
3296     }
3297
3298 #ifdef LOG_CAPTURE_VERBOSE
3299     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3300 #endif
3301
3302     return ld->packet_count - packet_count_before;
3303 }
3304
3305 #ifdef _WIN32
3306 /* Isolate the Universally Unique Identifier from the interface.  Basically, we
3307  * want to grab only the characters between the '{' and '}' delimiters.
3308  *
3309  * Returns a GString that must be freed with g_string_free(). */
3310 static GString *
3311 isolate_uuid(const char *iface)
3312 {
3313     gchar   *ptr;
3314     GString *gstr;
3315
3316     ptr = strchr(iface, '{');
3317     if (ptr == NULL)
3318         return g_string_new(iface);
3319     gstr = g_string_new(ptr + 1);
3320
3321     ptr = strchr(gstr->str, '}');
3322     if (ptr == NULL)
3323         return gstr;
3324
3325     gstr = g_string_truncate(gstr, ptr - gstr->str);
3326     return gstr;
3327 }
3328 #endif
3329
3330 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3331 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3332 static gboolean
3333 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3334                          char *errmsg, int errmsg_len)
3335 {
3336     char     *tmpname;
3337     gchar    *capfile_name;
3338     gchar    *prefix;
3339     gboolean  is_tempfile;
3340
3341     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3342           (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3343
3344     if (capture_opts->save_file != NULL) {
3345         /* We return to the caller while the capture is in progress.
3346          * Therefore we need to take a copy of save_file in
3347          * case the caller destroys it after we return.
3348          */
3349         capfile_name = g_strdup(capture_opts->save_file);
3350
3351         if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3352             if (capture_opts->multi_files_on) {
3353                 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3354                 g_snprintf(errmsg, errmsg_len,
3355                            "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3356                 g_free(capfile_name);
3357                 return FALSE;
3358             }
3359             if (strcmp(capfile_name, "-") == 0) {
3360                 /* write to stdout */
3361                 *save_file_fd = 1;
3362 #ifdef _WIN32
3363                 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF)  */
3364                 _setmode(1, O_BINARY);
3365 #endif
3366             }
3367         } /* if (...output_to_pipe ... */
3368
3369         else {
3370             if (capture_opts->multi_files_on) {
3371                 /* ringbuffer is enabled */
3372                 *save_file_fd = ringbuf_init(capfile_name,
3373                                              (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3374                                              capture_opts->group_read_access);
3375
3376                 /* we need the ringbuf name */
3377                 if (*save_file_fd != -1) {
3378                     g_free(capfile_name);
3379                     capfile_name = g_strdup(ringbuf_current_filename());
3380                 }
3381             } else {
3382                 /* Try to open/create the specified file for use as a capture buffer. */
3383                 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
3384                                         (capture_opts->group_read_access) ? 0640 : 0600);
3385             }
3386         }
3387         is_tempfile = FALSE;
3388     } else {
3389         /* Choose a random name for the temporary capture buffer */
3390         if (global_capture_opts.ifaces->len > 1) {
3391             prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3392         } else {
3393             gchar *basename;
3394             basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
3395 #ifdef _WIN32
3396             /* use the generic portion of the interface guid to form the basis of the filename */
3397             if (strncmp("NPF_{", basename, 5)==0)
3398             {
3399                 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
3400                 GString *iface;
3401                 iface = isolate_uuid(basename);
3402                 g_free(basename);
3403                 basename = g_strdup(iface->str);
3404                 g_string_free(iface, TRUE);
3405             }
3406 #endif
3407             /* generate the temp file name prefix...
3408              * It would be nice if we could specify a pcapng/pcap filename suffix,
3409              * create_tempfile() however currently uses mkstemp() which doesn't allow this - one day perhaps*/
3410             if (capture_opts->use_pcapng) {
3411                 prefix = g_strconcat("wireshark_pcapng_", basename, NULL);
3412             }else{
3413                 prefix = g_strconcat("wireshark_pcap_", basename, NULL);
3414             }
3415             g_free(basename);
3416         }
3417         *save_file_fd = create_tempfile(&tmpname, prefix);
3418         g_free(prefix);
3419         capfile_name = g_strdup(tmpname);
3420         is_tempfile = TRUE;
3421     }
3422
3423     /* did we fail to open the output file? */
3424     if (*save_file_fd == -1) {
3425         if (is_tempfile) {
3426             g_snprintf(errmsg, errmsg_len,
3427                        "The temporary file to which the capture would be saved (\"%s\") "
3428                        "could not be opened: %s.", capfile_name, g_strerror(errno));
3429         } else {
3430             if (capture_opts->multi_files_on) {
3431                 ringbuf_error_cleanup();
3432             }
3433
3434             g_snprintf(errmsg, errmsg_len,
3435                        "The file to which the capture would be saved (\"%s\") "
3436                        "could not be opened: %s.", capfile_name,
3437                        g_strerror(errno));
3438         }
3439         g_free(capfile_name);
3440         return FALSE;
3441     }
3442
3443     if (capture_opts->save_file != NULL) {
3444         g_free(capture_opts->save_file);
3445     }
3446     capture_opts->save_file = capfile_name;
3447     /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3448        "g_free(capfile_name)". */
3449
3450     return TRUE;
3451 }
3452
3453
3454 /* Do the work of handling either the file size or file duration capture
3455    conditions being reached, and switching files or stopping. */
3456 static gboolean
3457 do_file_switch_or_stop(capture_options *capture_opts,
3458                        condition *cnd_autostop_files,
3459                        condition *cnd_autostop_size,
3460                        condition *cnd_file_duration)
3461 {
3462     guint              i;
3463     pcap_options      *pcap_opts;
3464     interface_options  interface_opts;
3465     gboolean           successful;
3466
3467     if (capture_opts->multi_files_on) {
3468         if (cnd_autostop_files != NULL &&
3469             cnd_eval(cnd_autostop_files, (guint64)++global_ld.autostop_files)) {
3470             /* no files left: stop here */
3471             global_ld.go = FALSE;
3472             return FALSE;
3473         }
3474
3475         /* Switch to the next ringbuffer file */
3476         if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3477                                 &global_ld.save_file_fd, &global_ld.err)) {
3478
3479             /* File switch succeeded: reset the conditions */
3480             global_ld.bytes_written = 0;
3481             if (capture_opts->use_pcapng) {
3482                 char    *appname;
3483                 GString *os_info_str;
3484
3485                 os_info_str = g_string_new("");
3486                 get_os_version_info(os_info_str);
3487
3488                 appname = g_strdup_printf("Dumpcap (Wireshark) %s", get_ws_vcs_version_info());
3489                 successful = pcapng_write_session_header_block(global_ld.pdh,
3490                                 NULL,                        /* Comment */
3491                                 NULL,                        /* HW */
3492                                 os_info_str->str,            /* OS */
3493                                 appname,
3494                                                                 -1,                          /* section_length */
3495                                 &(global_ld.bytes_written),
3496                                 &global_ld.err);
3497                 g_free(appname);
3498
3499                 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3500                     interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3501                     pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3502                     successful = pcapng_write_interface_description_block(global_ld.pdh,
3503                                                                           NULL,                       /* OPT_COMMENT       1 */
3504                                                                           interface_opts.name,        /* IDB_NAME          2 */
3505                                                                           interface_opts.descr,       /* IDB_DESCRIPTION   3 */
3506                                                                           interface_opts.cfilter,     /* IDB_FILTER       11 */
3507                                                                           os_info_str->str,           /* IDB_OS           12 */
3508                                                                           pcap_opts->linktype,
3509                                                                           pcap_opts->snaplen,
3510                                                                           &(global_ld.bytes_written),
3511                                                                           0,                          /* IDB_IF_SPEED      8 */
3512                                                                           pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL       9 */
3513                                                                           &global_ld.err);
3514                 }
3515
3516                 g_string_free(os_info_str, TRUE);
3517
3518             } else {
3519                 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3520                 successful = libpcap_write_file_header(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
3521                                                        pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3522             }
3523             if (!successful) {
3524                 fclose(global_ld.pdh);
3525                 global_ld.pdh = NULL;
3526                 global_ld.go = FALSE;
3527                 return FALSE;
3528             }
3529             if (cnd_autostop_size)
3530                 cnd_reset(cnd_autostop_size);
3531             if (cnd_file_duration)
3532                 cnd_reset(cnd_file_duration);
3533             fflush(global_ld.pdh);
3534             if (!quiet)
3535                 report_packet_count(global_ld.inpkts_to_sync_pipe);
3536             global_ld.inpkts_to_sync_pipe = 0;
3537             report_new_capture_file(capture_opts->save_file);
3538         } else {
3539             /* File switch failed: stop here */
3540             global_ld.go = FALSE;
3541             return FALSE;
3542         }
3543     } else {
3544         /* single file, stop now */
3545         global_ld.go = FALSE;
3546         return FALSE;
3547     }
3548     return TRUE;
3549 }
3550
3551 static void *
3552 pcap_read_handler(void* arg)
3553 {
3554     pcap_options *pcap_opts;
3555     char          errmsg[MSG_MAX_LENGTH+1];
3556
3557     pcap_opts = (pcap_options *)arg;
3558
3559     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3560           pcap_opts->interface_id);
3561
3562     while (global_ld.go) {
3563         /* dispatch incoming packets */
3564         capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3565     }
3566     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3567           pcap_opts->interface_id);
3568     g_thread_exit(NULL);
3569     return (NULL);
3570 }
3571
3572 /* Do the low-level work of a capture.
3573    Returns TRUE if it succeeds, FALSE otherwise. */
3574 static gboolean
3575 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3576 {
3577 #ifdef _WIN32
3578     DWORD              upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3579 #else
3580     struct timeval     upd_time, cur_time;
3581 #endif
3582     int                err_close;
3583     int                inpkts;
3584     condition         *cnd_file_duration     = NULL;
3585     condition         *cnd_autostop_files    = NULL;
3586     condition         *cnd_autostop_size     = NULL;
3587     condition         *cnd_autostop_duration = NULL;
3588     gboolean           write_ok;
3589     gboolean           close_ok;
3590     gboolean           cfilter_error         = FALSE;
3591     char               errmsg[MSG_MAX_LENGTH+1];
3592     char               secondary_errmsg[MSG_MAX_LENGTH+1];
3593     pcap_options      *pcap_opts;
3594     interface_options  interface_opts;
3595     guint              i, error_index        = 0;
3596
3597     *errmsg           = '\0';
3598     *secondary_errmsg = '\0';
3599
3600     /* init the loop data */
3601     global_ld.go                  = TRUE;
3602     global_ld.packet_count        = 0;
3603 #ifdef SIGINFO
3604     global_ld.report_packet_count = FALSE;
3605 #endif
3606     if (capture_opts->has_autostop_packets)
3607         global_ld.packet_max      = capture_opts->autostop_packets;
3608     else
3609         global_ld.packet_max      = 0;        /* no limit */
3610     global_ld.inpkts_to_sync_pipe = 0;
3611     global_ld.err                 = 0;  /* no error seen yet */
3612     global_ld.pdh                 = NULL;
3613     global_ld.autostop_files      = 0;
3614     global_ld.save_file_fd        = -1;
3615
3616     /* We haven't yet gotten the capture statistics. */
3617     *stats_known      = FALSE;
3618
3619     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3620     capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3621
3622     /* open the "input file" from network interface or capture pipe */
3623     if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3624                                  secondary_errmsg, sizeof(secondary_errmsg))) {
3625         goto error;
3626     }
3627     for (i = 0; i < capture_opts->ifaces->len; i++) {
3628         pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3629         interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3630         /* init the input filter from the network interface (capture pipe will do nothing) */
3631         /*
3632          * When remote capturing WinPCap crashes when the capture filter
3633          * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3634          * string.
3635          */
3636         switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3637                                          interface_opts.name,
3638                                          interface_opts.cfilter?interface_opts.cfilter:"")) {
3639
3640         case INITFILTER_NO_ERROR:
3641             break;
3642
3643         case INITFILTER_BAD_FILTER:
3644             cfilter_error = TRUE;
3645             error_index = i;
3646             g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3647             goto error;
3648
3649         case INITFILTER_OTHER_ERROR:
3650             g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3651                        pcap_geterr(pcap_opts->pcap_h));
3652             g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3653             goto error;
3654         }
3655     }
3656
3657     /* If we're supposed to write to a capture file, open it for output
3658        (temporary/specified name/ringbuffer) */
3659     if (capture_opts->saving_to_file) {
3660         if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3661                                       errmsg, sizeof(errmsg))) {
3662             goto error;
3663         }
3664
3665         /* set up to write to the already-opened capture output file/files */
3666         if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3667                                       sizeof(errmsg))) {
3668             goto error;
3669         }
3670
3671         /* XXX - capture SIGTERM and close the capture, in case we're on a
3672            Linux 2.0[.x] system and you have to explicitly close the capture
3673            stream in order to turn promiscuous mode off?  We need to do that
3674            in other places as well - and I don't think that works all the
3675            time in any case, due to libpcap bugs. */
3676
3677         /* Well, we should be able to start capturing.
3678
3679            Sync out the capture file, so the header makes it to the file system,
3680            and send a "capture started successfully and capture file created"
3681            message to our parent so that they'll open the capture file and
3682            update its windows to indicate that we have a live capture in
3683            progress. */
3684         fflush(global_ld.pdh);
3685         report_new_capture_file(capture_opts->save_file);
3686     }
3687
3688     /* initialize capture stop (and alike) conditions */
3689     init_capture_stop_conditions();
3690     /* create stop conditions */
3691     if (capture_opts->has_autostop_filesize) {
3692         if (capture_opts->autostop_filesize > (((guint32)INT_MAX + 1) / 1000)) {
3693             capture_opts->autostop_filesize = ((guint32)INT_MAX + 1) / 1000;
3694         }
3695         cnd_autostop_size =
3696             cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_filesize * 1000);
3697     }
3698     if (capture_opts->has_autostop_duration)
3699         cnd_autostop_duration =
3700             cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3701
3702     if (capture_opts->multi_files_on) {
3703         if (capture_opts->has_file_duration)
3704             cnd_file_duration =
3705                 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3706
3707         if (capture_opts->has_autostop_files)
3708             cnd_autostop_files =
3709                 cnd_new(CND_CLASS_CAPTURESIZE, (guint64)capture_opts->autostop_files);
3710     }
3711
3712     /* init the time values */
3713 #ifdef _WIN32
3714     upd_time = GetTickCount();
3715 #else
3716     gettimeofday(&upd_time, NULL);
3717 #endif
3718     start_time = create_timestamp();
3719     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running.");
3720
3721     /* WOW, everything is prepared! */
3722     /* please fasten your seat belts, we will enter now the actual capture loop */
3723     if (use_threads) {
3724         pcap_queue = g_async_queue_new();
3725         pcap_queue_bytes = 0;
3726         pcap_queue_packets = 0;
3727         for (i = 0; i < global_ld.pcaps->len; i++) {
3728             pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3729 #if GLIB_CHECK_VERSION(2,31,0)
3730             /* XXX - Add an interface name here? */
3731             pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3732 #else
3733             pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3734 #endif
3735         }
3736     }
3737     while (global_ld.go) {
3738         /* dispatch incoming packets */
3739         if (use_threads) {
3740             pcap_queue_element *queue_element;
3741 #if GLIB_CHECK_VERSION(2,31,18)
3742
3743             g_async_queue_lock(pcap_queue);
3744             queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3745 #else
3746             GTimeVal write_thread_time;
3747
3748             g_get_current_time(&write_thread_time);
3749             g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3750             g_async_queue_lock(pcap_queue);
3751             queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3752 #endif
3753             if (queue_element) {
3754                 pcap_queue_bytes -= queue_element->phdr.caplen;
3755                 pcap_queue_packets -= 1;
3756             }
3757             g_async_queue_unlock(pcap_queue);
3758             if (queue_element) {
3759                 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3760                       "Dequeued a packet of length %d captured on interface %d.",
3761                       queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3762
3763                 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3764                                              &queue_element->phdr,
3765                                              queue_element->pd);
3766                 g_free(queue_element->pd);
3767                 g_free(queue_element);
3768                 inpkts = 1;
3769             } else {
3770                 inpkts = 0;
3771             }
3772         } else {
3773             pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3774             inpkts = capture_loop_dispatch(&global_ld, errmsg,
3775                                            sizeof(errmsg), pcap_opts);
3776         }
3777 #ifdef SIGINFO
3778         /* Were we asked to print packet counts by the SIGINFO handler? */
3779         if (global_ld.report_packet_count) {
3780             fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3781                     plurality(global_ld.packet_count, "", "s"));
3782             global_ld.report_packet_count = FALSE;
3783         }
3784 #endif
3785
3786 #ifdef _WIN32
3787         /* any news from our parent (signal pipe)? -> just stop the capture */
3788         if (!signal_pipe_check_running()) {
3789             global_ld.go = FALSE;
3790         }
3791 #endif
3792
3793         if (inpkts > 0) {
3794             global_ld.inpkts_to_sync_pipe += inpkts;
3795
3796             /* check capture size condition */
3797             if (cnd_autostop_size != NULL &&
3798                 cnd_eval(cnd_autostop_size, global_ld.bytes_written)) {
3799                 /* Capture size limit reached, do we have another file? */
3800                 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3801                                             cnd_autostop_size, cnd_file_duration))
3802                     continue;
3803             } /* cnd_autostop_size */
3804             if (capture_opts->output_to_pipe) {
3805                 fflush(global_ld.pdh);
3806             }
3807         } /* inpkts */
3808
3809         /* Only update once every 500ms so as not to overload slow displays.
3810          * This also prevents too much context-switching between the dumpcap
3811          * and wireshark processes.
3812          */
3813 #define DUMPCAP_UPD_TIME 500
3814
3815 #ifdef _WIN32
3816         cur_time = GetTickCount();  /* Note: wraps to 0 if sys runs for 49.7 days */
3817         if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3818 #else
3819         gettimeofday(&cur_time, NULL);
3820         if (((guint64)cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3821             ((guint64)upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3822 #endif
3823
3824             upd_time = cur_time;
3825
3826 #if 0
3827             if (pcap_stats(pch, stats) >= 0) {
3828                 *stats_known = TRUE;
3829             }
3830 #endif
3831             /* Let the parent process know. */
3832             if (global_ld.inpkts_to_sync_pipe) {
3833                 /* do sync here */
3834                 fflush(global_ld.pdh);
3835
3836                 /* Send our parent a message saying we've written out
3837                    "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3838                 if (!quiet)
3839                     report_packet_count(global_ld.inpkts_to_sync_pipe);
3840
3841                 global_ld.inpkts_to_sync_pipe = 0;
3842             }
3843
3844             /* check capture duration condition */
3845             if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3846                 /* The maximum capture time has elapsed; stop the capture. */
3847                 global_ld.go = FALSE;
3848                 continue;
3849             }
3850
3851             /* check capture file duration condition */
3852             if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3853                 /* duration limit reached, do we have another file? */
3854                 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3855                                             cnd_autostop_size, cnd_file_duration))
3856                     continue;
3857             } /* cnd_file_duration */
3858         }
3859     }
3860
3861     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3862     if (use_threads) {
3863         pcap_queue_element *queue_element;
3864
3865         for (i = 0; i < global_ld.pcaps->len; i++) {
3866             pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3867             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3868                   pcap_opts->interface_id);
3869             g_thread_join(pcap_opts->tid);
3870             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3871                   pcap_opts->interface_id);
3872         }
3873         while (1) {
3874             g_async_queue_lock(pcap_queue);
3875             queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3876             if (queue_element) {
3877                 pcap_queue_bytes -= queue_element->phdr.caplen;
3878                 pcap_queue_packets -= 1;
3879             }
3880             g_async_queue_unlock(pcap_queue);
3881             if (queue_element == NULL) {
3882                 break;
3883             }
3884             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3885                   "Dequeued a packet of length %d captured on interface %d.",
3886                   queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3887             capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3888                                          &queue_element->phdr,
3889                                          queue_element->pd);
3890             g_free(queue_element->pd);
3891             g_free(queue_element);
3892             global_ld.inpkts_to_sync_pipe += 1;
3893             if (capture_opts->output_to_pipe) {
3894                 fflush(global_ld.pdh);
3895             }
3896         }
3897     }
3898
3899
3900     /* delete stop conditions */
3901     if (cnd_file_duration != NULL)
3902         cnd_delete(cnd_file_duration);
3903     if (cnd_autostop_files != NULL)
3904         cnd_delete(cnd_autostop_files);
3905     if (cnd_autostop_size != NULL)
3906         cnd_delete(cnd_autostop_size);
3907     if (cnd_autostop_duration != NULL)
3908         cnd_delete(cnd_autostop_duration);
3909
3910     /* did we have a pcap (input) error? */
3911     for (i = 0; i < capture_opts->ifaces->len; i++) {
3912         pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3913         if (pcap_opts->pcap_err) {
3914             /* On Linux, if an interface goes down while you're capturing on it,
3915                you'll get a "recvfrom: Network is down" or
3916                "The interface went down" error (ENETDOWN).
3917                (At least you will if g_strerror() doesn't show a local translation
3918                of the error.)
3919
3920                On FreeBSD and OS X, if a network adapter disappears while
3921                you're capturing on it, you'll get a "read: Device not configured"
3922                error (ENXIO).  (See previous parenthetical note.)
3923
3924                On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3925
3926                These should *not* be reported to the Wireshark developers. */
3927             char *cap_err_str;
3928
3929             cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3930             if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3931                 strcmp(cap_err_str, "The interface went down") == 0 ||
3932                 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3933                 strcmp(cap_err_str, "read: I/O error") == 0 ||
3934                 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3935                 report_capture_error("The network adapter on which the capture was being done "
3936                                      "is no longer running; the capture has stopped.",
3937                                      "");
3938             } else {
3939                 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3940                            cap_err_str);
3941                 report_capture_error(errmsg, please_report);
3942             }
3943             break;
3944         } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3945             report_capture_error(errmsg, "");
3946             break;
3947         }
3948     }
3949     /* did we have an output error while capturing? */
3950     if (global_ld.err == 0) {
3951         write_ok = TRUE;
3952     } else {
3953         capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3954                                 global_ld.err, FALSE);
3955         report_capture_error(errmsg, please_report);
3956         write_ok = FALSE;
3957     }
3958
3959     if (capture_opts->saving_to_file) {
3960         /* close the output file */
3961         close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3962     } else
3963         close_ok = TRUE;
3964
3965     /* there might be packets not yet notified to the parent */
3966     /* (do this after closing the file, so all packets are already flushed) */
3967     if (global_ld.inpkts_to_sync_pipe) {
3968         if (!quiet)
3969             report_packet_count(global_ld.inpkts_to_sync_pipe);
3970         global_ld.inpkts_to_sync_pipe = 0;
3971     }
3972
3973     /* If we've displayed a message about a write error, there's no point
3974        in displaying another message about an error on close. */
3975     if (!close_ok && write_ok) {
3976         capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3977                                 TRUE);
3978         report_capture_error(errmsg, "");
3979     }
3980
3981     /*
3982      * XXX We exhibit different behaviour between normal mode and sync mode
3983      * when the pipe is stdin and not already at EOF.  If we're a child, the
3984      * parent's stdin isn't closed, so if the user starts another capture,
3985      * cap_pipe_open_live() will very likely not see the expected magic bytes and
3986      * will say "Unrecognized libpcap format".  On the other hand, in normal
3987      * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3988      */
3989
3990     report_capture_count(TRUE);
3991
3992     /* get packet drop statistics from pcap */
3993     for (i = 0; i < capture_opts->ifaces->len; i++) {
3994         guint32 received;
3995         guint32 pcap_dropped = 0;
3996
3997         pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3998         interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3999         received = pcap_opts->received;
4000         if (pcap_opts->pcap_h != NULL) {
4001             g_assert(!pcap_opts->from_cap_pipe);
4002             /* Get the capture statistics, so we know how many packets were dropped. */
4003             /*
4004              * Older versions of libpcap didn't set ps_ifdrop on some
4005              * platforms; initialize it to 0 to handle that.
4006              */
4007             stats->ps_ifdrop = 0;
4008             if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
4009                 *stats_known = TRUE;
4010                 /* Let the parent process know. */
4011                 pcap_dropped += stats->ps_drop;
4012             } else {
4013                 g_snprintf(errmsg, sizeof(errmsg),
4014                            "Can't get packet-drop statistics: %s",
4015                            pcap_geterr(pcap_opts->pcap_h));
4016                 report_capture_error(errmsg, please_report);
4017             }
4018         }
4019         report_packet_drops(received, pcap_dropped, pcap_opts->dropped, pcap_opts->flushed, stats->ps_ifdrop, interface_opts.console_display_name);
4020     }
4021
4022     /* close the input file (pcap or capture pipe) */
4023     capture_loop_close_input(&global_ld);
4024
4025     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped.");
4026
4027     /* ok, if the write and the close were successful. */
4028     return write_ok && close_ok;
4029
4030 error:
4031     if (capture_opts->multi_files_on) {
4032         /* cleanup ringbuffer */
4033         ringbuf_error_cleanup();
4034     } else {
4035         /* We can't use the save file, and we have no FILE * for the stream
4036            to close in order to close it, so close the FD directly. */
4037         if (global_ld.save_file_fd != -1) {
4038             ws_close(global_ld.save_file_fd);
4039         }
4040
4041         /* We couldn't even start the capture, so get rid of the capture
4042            file. */
4043         if (capture_opts->save_file != NULL) {
4044             ws_unlink(capture_opts->save_file);
4045             g_free(capture_opts->save_file);
4046         }
4047     }
4048     capture_opts->save_file = NULL;
4049     if (cfilter_error)
4050         report_cfilter_error(capture_opts, error_index, errmsg);
4051     else
4052         report_capture_error(errmsg, secondary_errmsg);
4053
4054     /* close the input file (pcap or cap_pipe) */
4055     capture_loop_close_input(&global_ld);
4056
4057     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
4058
4059     return FALSE;
4060 }
4061
4062
4063 static void
4064 capture_loop_stop(void)
4065 {
4066 #ifdef HAVE_PCAP_BREAKLOOP
4067     guint         i;
4068     pcap_options *pcap_opts;
4069
4070     for (i = 0; i < global_ld.pcaps->len; i++) {
4071         pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
4072         if (pcap_opts->pcap_h != NULL)
4073             pcap_breakloop(pcap_opts->pcap_h);
4074     }
4075 #endif
4076     global_ld.go = FALSE;
4077 }
4078
4079
4080 static void
4081 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
4082                         int err, gboolean is_close)
4083 {
4084     switch (err) {
4085
4086     case ENOSPC:
4087         g_snprintf(errmsg, errmsglen,
4088                    "Not all the packets could be written to the file"
4089                    " to which the capture was being saved\n"
4090                    "(\"%s\") because there is no space left on the file system\n"
4091                    "on which that file resides.",
4092                    fname);
4093         break;
4094
4095 #ifdef EDQUOT
4096     case EDQUOT:
4097         g_snprintf(errmsg, errmsglen,
4098                    "Not all the packets could be written to the file"
4099                    " to which the capture was being saved\n"
4100                    "(\"%s\") because you are too close to, or over,"
4101                    " your disk quota\n"
4102                    "on the file system on which that file resides.",
4103                    fname);
4104         break;
4105 #endif
4106
4107     default:
4108         if (is_close) {
4109             g_snprintf(errmsg, errmsglen,
4110                        "The file to which the capture was being saved\n"
4111                        "(\"%s\") could not be closed: %s.",
4112                        fname, g_strerror(err));
4113         } else {
4114             g_snprintf(errmsg, errmsglen,
4115                        "An error occurred while writing to the file"
4116                        " to which the capture was being saved\n"
4117                        "(\"%s\"): %s.",
4118                        fname, g_strerror(err));
4119         }
4120         break;
4121     }
4122 }
4123
4124
4125 /* one packet was captured, process it */
4126 static void
4127 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4128                              const u_char *pd)
4129 {
4130     pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4131     int           err;
4132     guint         ts_mul    = pcap_opts->ts_nsec ? 1000000000 : 1000000;
4133
4134     /* We may be called multiple times from pcap_dispatch(); if we've set
4135        the "stop capturing" flag, ignore this packet, as we're not
4136        supposed to be saving any more packets. */
4137     if (!global_ld.go) {
4138         pcap_opts->flushed++;
4139         return;
4140     }
4141
4142     if (global_ld.pdh) {
4143         gboolean successful;
4144
4145         /* We're supposed to write the packet to a file; do so.
4146            If this fails, set "ld->go" to FALSE, to stop the capture, and set
4147            "ld->err" to the error. */
4148         if (global_capture_opts.use_pcapng) {
4149             successful = pcapng_write_enhanced_packet_block(global_ld.pdh,
4150                                                             NULL,
4151                                                             phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4152                                                             phdr->caplen, phdr->len,
4153                                                             pcap_opts->interface_id,
4154                                                             ts_mul,
4155                                                             pd, 0,
4156                                                             &global_ld.bytes_written, &err);
4157         } else {
4158             successful = libpcap_write_packet(global_ld.pdh,
4159                                               phdr->ts.tv_sec, (gint32)phdr->ts.tv_usec,
4160                                               phdr->caplen, phdr->len,
4161                                               pd,
4162                                               &global_ld.bytes_written, &err);
4163         }
4164         if (!successful) {
4165             global_ld.go = FALSE;
4166             global_ld.err = err;
4167             pcap_opts->dropped++;
4168         } else {
4169 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4170             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4171                   "Wrote a packet of length %d captured on interface %u.",
4172                    phdr->caplen, pcap_opts->interface_id);
4173 #endif
4174             global_ld.packet_count++;
4175             pcap_opts->received++;
4176             /* if the user told us to stop after x packets, do we already have enough? */
4177             if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
4178                 global_ld.go = FALSE;
4179             }
4180         }
4181     }
4182 }
4183
4184 /* one packet was captured, queue it */
4185 static void
4186 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4187                              const u_char *pd)
4188 {
4189     pcap_options       *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4190     pcap_queue_element *queue_element;
4191     gboolean            limit_reached;
4192
4193     /* We may be called multiple times from pcap_dispatch(); if we've set
4194        the "stop capturing" flag, ignore this packet, as we're not
4195        supposed to be saving any more packets. */
4196     if (!global_ld.go) {
4197         pcap_opts->flushed++;
4198         return;
4199     }
4200
4201     queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4202     if (queue_element == NULL) {
4203        pcap_opts->dropped++;
4204        return;
4205     }
4206     queue_element->pcap_opts = pcap_opts;
4207     queue_element->phdr = *phdr;
4208     queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4209     if (queue_element->pd == NULL) {
4210         pcap_opts->dropped++;
4211         g_free(queue_element);
4212         return;
4213     }
4214     memcpy(queue_element->pd, pd, phdr->caplen);
4215     g_async_queue_lock(pcap_queue);
4216     if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4217         ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4218         limit_reached = FALSE;
4219         g_async_queue_push_unlocked(pcap_queue, queue_element);
4220         pcap_queue_bytes += phdr->caplen;
4221         pcap_queue_packets += 1;
4222     } else {
4223         limit_reached = TRUE;
4224     }
4225     g_async_queue_unlock(pcap_queue);
4226     if (limit_reached) {
4227         pcap_opts->dropped++;
4228         g_free(queue_element->pd);
4229         g_free(queue_element);
4230         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4231               "Dropped a packet of length %d captured on interface %u.",
4232               phdr->caplen, pcap_opts->interface_id);
4233     } else {
4234         pcap_opts->received++;
4235         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4236               "Queued a packet of length %d captured on interface %u.",
4237               phdr->caplen, pcap_opts->interface_id);
4238     }
4239     /* I don't want to hold the mutex over the debug output. So the
4240        output may be wrong */
4241     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4242           "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4243           pcap_queue_bytes, pcap_queue_packets);
4244 }
4245
4246 static int
4247 set_80211_channel(const char *iface, const char *opt)
4248 {
4249     int     freq    = 0, type, ret;
4250     gchar **options = NULL;
4251
4252     options = g_strsplit_set(opt, ",", 2);
4253
4254     if (options[0])
4255         freq = atoi(options[0]);
4256
4257     if (options[1]) {
4258         type = ws80211_str_to_chan_type(options[1]);
4259         if (type == -1) {
4260             ret = EINVAL;
4261             goto out;
4262         }
4263     }
4264     else
4265         type = -1;
4266
4267     ret = ws80211_init();
4268     if (ret) {
4269         cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4270         ret = 2;
4271         goto out;
4272     }
4273     ret = ws80211_set_freq(iface, freq, type);
4274
4275     if (ret) {
4276         cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4277         ret = 2;
4278         goto out;
4279     }
4280
4281     if (capture_child)
4282         pipe_write_block(2, SP_SUCCESS, NULL);
4283     ret = 0;
4284
4285 out:
4286     g_strfreev(options);
4287     return ret;
4288 }
4289
4290 static void
4291 get_dumpcap_compiled_info(GString *str)
4292 {
4293     /* Capture libraries */
4294     g_string_append(str, ", ");
4295     get_compiled_caplibs_version(str);
4296
4297     /* LIBZ */
4298     g_string_append(str, ", ");
4299 #ifdef HAVE_LIBZ
4300     g_string_append(str, "with libz ");
4301 #ifdef ZLIB_VERSION
4302     g_string_append(str, ZLIB_VERSION);
4303 #else /* ZLIB_VERSION */
4304     g_string_append(str, "(version unknown)");
4305 #endif /* ZLIB_VERSION */
4306 #else /* HAVE_LIBZ */
4307     g_string_append(str, "without libz");
4308 #endif /* HAVE_LIBZ */
4309 }
4310
4311 static void
4312 get_dumpcap_runtime_info(GString *str)
4313 {
4314     /* Capture libraries */
4315     g_string_append(str, ", ");
4316     get_runtime_caplibs_version(str);
4317
4318     /* zlib */
4319 #if defined(HAVE_LIBZ) && !defined(_WIN32)
4320     g_string_append_printf(str, ", with libz %s", zlibVersion());
4321 #endif
4322 }
4323
4324 /* And now our feature presentation... [ fade to music ] */
4325 int
4326 main(int argc, char *argv[])
4327 {
4328     GString          *comp_info_str;
4329     GString          *runtime_info_str;
4330     int               opt;
4331 DIAG_OFF(cast-qual)
4332     static const struct option long_options[] = {
4333         {(char *)"help", no_argument, NULL, 'h'},
4334         {(char *)"version", no_argument, NULL, 'v'},
4335         LONGOPT_CAPTURE_COMMON
4336         {0, 0, 0, 0 }
4337     };
4338 DIAG_ON(cast-qual)
4339
4340     gboolean          arg_error             = FALSE;
4341
4342 #ifdef _WIN32
4343     WSADATA           wsaData;
4344 #else
4345     struct sigaction  action, oldaction;
4346 #endif
4347
4348     gboolean          start_capture         = TRUE;
4349     gboolean          stats_known;
4350     struct pcap_stat  stats;
4351     GLogLevelFlags    log_flags;
4352     gboolean          list_interfaces       = FALSE;
4353     gboolean          list_link_layer_types = FALSE;
4354 #ifdef HAVE_BPF_IMAGE
4355     gboolean          print_bpf_code        = FALSE;
4356 #endif
4357     gboolean          set_chan              = FALSE;
4358     gchar            *set_chan_arg          = NULL;
4359     gboolean          machine_readable      = FALSE;
4360     gboolean          print_statistics      = FALSE;
4361     int               status, run_once_args = 0;
4362     gint              i;
4363     guint             j;
4364 #if defined(__APPLE__) && defined(__LP64__)
4365     struct utsname    osinfo;
4366 #endif
4367     GString          *str;
4368
4369     cmdarg_err_init(dumpcap_cmdarg_err, dumpcap_cmdarg_err_cont);
4370
4371     /* Get the compile-time version information string */
4372     comp_info_str = get_compiled_version_info(NULL, get_dumpcap_compiled_info);
4373
4374     /* Get the run-time version information string */
4375     runtime_info_str = get_runtime_version_info(get_dumpcap_runtime_info);
4376
4377     /* Add it to the information to be reported on a crash. */
4378     ws_add_crash_info("Dumpcap (Wireshark) %s\n"
4379            "\n"
4380            "%s"
4381            "\n"
4382            "%s",
4383         get_ws_vcs_version_info(), comp_info_str->str, runtime_info_str->str);
4384
4385 #ifdef _WIN32
4386     arg_list_utf_16to8(argc, argv);
4387     create_app_running_mutex();
4388
4389     /*
4390      * Initialize our DLL search path. MUST be called before LoadLibrary
4391      * or g_module_open.
4392      */
4393     ws_init_dll_search_path();
4394 #endif
4395
4396 #ifdef HAVE_BPF_IMAGE
4397 #define OPTSTRING_d "d"
4398 #else
4399 #define OPTSTRING_d ""
4400 #endif
4401
4402 #ifdef HAVE_PCAP_REMOTE
4403 #define OPTSTRING_r "r"
4404 #define OPTSTRING_u "u"
4405 #else
4406 #define OPTSTRING_r ""
4407 #define OPTSTRING_u ""
4408 #endif
4409
4410 #ifdef HAVE_PCAP_SETSAMPLING
4411 #define OPTSTRING_m "m:"
4412 #else
4413 #define OPTSTRING_m ""
4414 #endif
4415
4416 #define OPTSTRING OPTSTRING_CAPTURE_COMMON "C:" OPTSTRING_d "gh" "k:" OPTSTRING_m "MN:nPq" OPTSTRING_r "St" OPTSTRING_u "vw:Z:"
4417
4418 #ifdef DEBUG_CHILD_DUMPCAP
4419     if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4420         fprintf (stderr, "Unable to open debug log file .\n");
4421         exit (1);
4422     }
4423 #endif
4424
4425 #if defined(__APPLE__) && defined(__LP64__)
4426     /*
4427      * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4?  If so, we need
4428      * a bug workaround - timeouts less than 1 second don't work with libpcap
4429      * in 64-bit code.  (The bug was introduced in 10.6, fixed in 10.6.2,
4430      * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4431      * The problem is extremely unlikely to be reintroduced in a future
4432      * release.)
4433      */
4434     if (uname(&osinfo) == 0) {
4435         /*
4436          * Mac OS X 10.x uses Darwin {x+4}.0.0.  Mac OS X 10.x.y uses Darwin
4437          * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4438          * number of 10.0.0, not 10.1.0 - go figure).
4439          */
4440         if (strcmp(osinfo.release, "10.0.0") == 0 ||    /* 10.6, 10.6.1 */
4441             strcmp(osinfo.release, "10.3.0") == 0 ||    /* 10.6.3 */
4442             strcmp(osinfo.release, "10.4.0") == 0)              /* 10.6.4 */
4443             need_timeout_workaround = TRUE;
4444     }
4445 #endif
4446
4447     /*
4448      * Determine if dumpcap is being requested to run in a special
4449      * capture_child mode by going thru the command line args to see if
4450      * a -Z is present. (-Z is a hidden option).
4451      *
4452      * The primary result of running in capture_child mode is that
4453      * all messages sent out on stderr are in a special type/len/string
4454      * format to allow message processing by type.  These messages include
4455      * error messages if dumpcap fails to start the operation it was
4456      * requested to do, as well as various "status" messages which are sent
4457      * when an actual capture is in progress, and a "success" message sent
4458      * if dumpcap was requested to perform an operation other than a
4459      * capture.
4460      *
4461      * Capture_child mode would normally be requested by a parent process
4462      * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4463      * to which dumpcap stderr has been redirected.  It might also have
4464      * another pipe to obtain dumpcap stdout output; for operations other
4465      * than a capture, that information is formatted specially for easier
4466      * parsing by the parent process.
4467      *
4468      * Capture_child mode needs to be determined immediately upon
4469      * startup so that any messages generated by dumpcap in this mode
4470      * (eg: during initialization) will be formatted properly.
4471      */
4472
4473     for (i=1; i<argc; i++) {
4474         if (strcmp("-Z", argv[i]) == 0) {
4475             capture_child    = TRUE;
4476             machine_readable = TRUE;  /* request machine-readable output */
4477 #ifdef _WIN32
4478             /* set output pipe to binary mode, to avoid ugly text conversions */
4479             _setmode(2, O_BINARY);
4480 #endif
4481         }
4482     }
4483
4484     /* The default_log_handler will use stdout, which makes trouble in   */
4485     /* capture child mode, as it uses stdout for its sync_pipe.          */
4486     /* So: the filtering is done in the console_log_handler and not here.*/
4487     /* We set the log handlers right up front to make sure that any log  */
4488     /* messages when running as child will be sent back to the parent    */
4489     /* with the correct format.                                          */
4490
4491     log_flags =
4492         (GLogLevelFlags)(
4493         G_LOG_LEVEL_ERROR|
4494         G_LOG_LEVEL_CRITICAL|
4495         G_LOG_LEVEL_WARNING|
4496         G_LOG_LEVEL_MESSAGE|
4497         G_LOG_LEVEL_INFO|
4498         G_LOG_LEVEL_DEBUG|
4499         G_LOG_FLAG_FATAL|
4500         G_LOG_FLAG_RECURSION);
4501
4502     g_log_set_handler(NULL,
4503                       log_flags,
4504                       console_log_handler, NULL /* user_data */);
4505     g_log_set_handler(LOG_DOMAIN_MAIN,
4506                       log_flags,
4507                       console_log_handler, NULL /* user_data */);
4508     g_log_set_handler(LOG_DOMAIN_CAPTURE,
4509                       log_flags,
4510                       console_log_handler, NULL /* user_data */);
4511     g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4512                       log_flags,
4513                       console_log_handler, NULL /* user_data */);
4514
4515     /* Initialize the pcaps list */
4516     global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
4517
4518 #if !GLIB_CHECK_VERSION(2,31,0)
4519     /* Initialize the thread system */
4520     g_thread_init(NULL);
4521 #endif
4522
4523 #ifdef _WIN32
4524     /* Load wpcap if possible. Do this before collecting the run-time version information */
4525     load_wpcap();
4526
4527     /* ... and also load the packet.dll from wpcap */
4528     /* XXX - currently not required, may change later. */
4529     /*wpcap_packet_load();*/
4530
4531     /* Start windows sockets */
4532     WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4533
4534     /* Set handler for Ctrl+C key */
4535     SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4536 #else
4537     /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4538        and exit.  Do the same with SIGPIPE, in case, for example,
4539        we're writing to our standard output and it's a pipe.
4540        Do the same with SIGHUP if it's not being ignored (if we're
4541        being run under nohup, it might be ignored, in which case we
4542        should leave it ignored).
4543
4544        XXX - apparently, Coverity complained that part of action
4545        wasn't initialized.  Perhaps it's running on Linux, where
4546        struct sigaction has an ignored "sa_restorer" element and
4547        where "sa_handler" and "sa_sigaction" might not be two
4548        members of a union. */
4549     memset(&action, 0, sizeof(action));
4550     action.sa_handler = capture_cleanup_handler;
4551     /*
4552      * Arrange that system calls not get restarted, because when
4553      * our signal handler returns we don't want to restart
4554      * a call that was waiting for packets to arrive.
4555      */
4556     action.sa_flags = 0;
4557     sigemptyset(&action.sa_mask);
4558     sigaction(SIGTERM, &action, NULL);
4559     sigaction(SIGINT, &action, NULL);
4560     sigaction(SIGPIPE, &action, NULL);
4561     sigaction(SIGHUP, NULL, &oldaction);
4562     if (oldaction.sa_handler == SIG_DFL)
4563         sigaction(SIGHUP, &action, NULL);
4564
4565 #ifdef SIGINFO
4566     /* Catch SIGINFO and, if we get it and we're capturing in
4567        quiet mode, report the number of packets we've captured. */
4568     action.sa_handler = report_counts_siginfo;
4569     action.sa_flags = SA_RESTART;
4570     sigemptyset(&action.sa_mask);
4571     sigaction(SIGINFO, &action, NULL);
4572 #endif /* SIGINFO */
4573 #endif  /* _WIN32 */
4574
4575 #ifdef __linux__
4576     enable_kernel_bpf_jit_compiler();
4577 #endif
4578
4579     /* ----------------------------------------------------------------- */
4580     /* Privilege and capability handling                                 */
4581     /* Cases:                                                            */
4582     /* 1. Running not as root or suid root; no special capabilities.     */
4583     /*    Action: none                                                   */
4584     /*                                                                   */
4585     /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap.  */
4586     /*    Action: none                                                   */
4587     /*                                                                   */
4588     /* 3. Running logged in as root (euid=0; ruid=0). Using libcap.      */
4589     /*    Action:                                                        */
4590     /*      - Near start of program: Enable NET_RAW and NET_ADMIN        */
4591     /*        capabilities; Drop all other capabilities;                 */
4592     /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
4593     /*        else: after  pcap_open_live() in capture_loop_open_input() */
4594     /*         drop all capabilities (NET_RAW and NET_ADMIN);            */
4595     /*         (Note: this means that the process, although logged in    */
4596     /*          as root, does not have various permissions such as the   */
4597     /*          ability to bypass file access permissions).              */
4598     /*      XXX: Should we just leave capabilities alone in this case    */
4599     /*          so that user gets expected effect that root can do       */
4600     /*          anything ??                                              */
4601     /*                                                                   */
4602     /* 4. Running as suid root (euid=0, ruid=n); Not using libcap.       */
4603     /*    Action:                                                        */
4604     /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
4605     /*        else: after  pcap_open_live() in capture_loop_open_input() */
4606     /*         drop suid root (set euid=ruid).(ie: keep suid until after */
4607     /*         pcap_open_live).                                          */
4608     /*                                                                   */
4609     /* 5. Running as suid root (euid=0, ruid=n); Using libcap.           */
4610     /*    Action:                                                        */
4611     /*      - Near start of program: Enable NET_RAW and NET_ADMIN        */
4612     /*        capabilities; Drop all other capabilities;                 */
4613     /*        Drop suid privileges (euid=ruid);                          */
4614     /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
4615     /*        else: after  pcap_open_live() in capture_loop_open_input() */
4616     /*         drop all capabilities (NET_RAW and NET_ADMIN).            */
4617     /*                                                                   */
4618     /*      XXX: For some Linux versions/distros with capabilities       */
4619     /*        a 'normal' process with any capabilities cannot be         */
4620     /*        'killed' (signaled) from another (same uid) non-privileged */
4621     /*        process.                                                   */
4622     /*        For example: If (non-suid) Wireshark forks a               */
4623     /*        child suid dumpcap which acts as described here (case 5),  */
4624     /*        Wireshark will be unable to kill (signal) the child        */
4625     /*        dumpcap process until the capabilities have been dropped   */
4626     /*        (after pcap_open_live()).                                  */
4627     /*        This behaviour will apparently be changed in the kernel    */
4628     /*        to allow the kill (signal) in this case.                   */
4629     /*        See the following for details:                             */
4630     /*           https://www.mail-archive.com/  [wrapped]                */
4631     /*             linux-security-module@vger.kernel.org/msg02913.html   */
4632     /*                                                                   */
4633     /*        It is therefore conceivable that if dumpcap somehow hangs  */
4634     /*        in pcap_open_live or before that wireshark will not        */
4635     /*        be able to stop dumpcap using a signal (INT, TERM, etc).   */
4636     /*        In this case, exiting wireshark will kill the child        */
4637     /*        dumpcap process.                                           */
4638     /*                                                                   */
4639     /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN        */
4640     /*     capabilities; Using libcap.  Note: capset cmd (which see)     */
4641     /*     used to assign capabilities to file.                          */
4642     /*    Action:                                                        */
4643     /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
4644     /*        else: after  pcap_open_live() in capture_loop_open_input() */
4645     /*         drop all capabilities (NET_RAW and NET_ADMIN)             */
4646     /*                                                                   */
4647     /* ToDo: -S (stats) should drop privileges/capabilities when no      */
4648     /*       longer required (similar to capture).                       */
4649     /*                                                                   */
4650     /* ----------------------------------------------------------------- */
4651
4652     init_process_policies();
4653
4654 #ifdef HAVE_LIBCAP
4655     /* If 'started with special privileges' (and using libcap)  */
4656     /*   Set to keep only NET_RAW and NET_ADMIN capabilities;   */
4657     /*   Set euid/egid = ruid/rgid to remove suid privileges    */
4658     relinquish_privs_except_capture();
4659 #endif
4660
4661     /* Set the initial values in the capture options. This might be overwritten
4662        by the command line parameters. */
4663     capture_opts_init(&global_capture_opts);
4664     /* We always save to a file - if no file was specified, we save to a
4665        temporary file. */
4666     global_capture_opts.saving_to_file      = TRUE;
4667     global_capture_opts.has_ring_num_files  = TRUE;
4668
4669     /* Pass on capture_child mode for capture_opts */
4670     global_capture_opts.capture_child = capture_child;
4671
4672     /* Now get our args */
4673     while ((opt = getopt_long(argc, argv, OPTSTRING, long_options, NULL)) != -1) {
4674         switch (opt) {
4675         case 'h':        /* Print help and exit */
4676             printf("Dumpcap (Wireshark) %s\n"
4677                    "Capture network packets and dump them into a pcapng or pcap file.\n"
4678                    "See https://www.wireshark.org for more information.\n",
4679                    get_ws_vcs_version_info());
4680             print_usage(stdout);
4681             exit_main(0);
4682             break;
4683         case 'v':        /* Show version and exit */
4684         {
4685             show_version("Dumpcap (Wireshark)", comp_info_str, runtime_info_str);
4686             g_string_free(comp_info_str, TRUE);
4687             g_string_free(runtime_info_str, TRUE);
4688             exit_main(0);
4689             break;
4690         }
4691         /*** capture option specific ***/
4692         case 'a':        /* autostop criteria */
4693         case 'b':        /* Ringbuffer option */
4694         case 'c':        /* Capture x packets */
4695         case 'f':        /* capture filter */
4696         case 'g':        /* enable group read access on file(s) */
4697         case 'i':        /* Use interface x */
4698         case 'n':        /* Use pcapng format */
4699         case 'p':        /* Don't capture in promiscuous mode */
4700         case 'P':        /* Use pcap format */
4701         case 's':        /* Set the snapshot (capture) length */
4702         case 'w':        /* Write to capture file x */
4703         case 'y':        /* Set the pcap data link type */
4704         case  LONGOPT_NUM_CAP_COMMENT: /* add a capture comment */
4705 #ifdef HAVE_PCAP_REMOTE
4706         case 'u':        /* Use UDP for data transfer */
4707         case 'r':        /* Capture own RPCAP traffic too */
4708         case 'A':        /* Authentication */
4709 #endif
4710 #ifdef HAVE_PCAP_SETSAMPLING
4711         case 'm':        /* Sampling */
4712 #endif
4713 #ifdef CAN_SET_CAPTURE_BUFFER_SIZE
4714         case 'B':        /* Buffer size */
4715 #endif
4716 #ifdef HAVE_PCAP_CREATE
4717         case 'I':        /* Monitor mode */
4718 #endif
4719             status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4720             if (status != 0) {
4721                 exit_main(status);
4722             }
4723             break;
4724             /*** hidden option: Wireshark child mode (using binary output messages) ***/
4725         case 'Z':
4726             capture_child = TRUE;
4727 #ifdef _WIN32
4728             /* set output pipe to binary mode, to avoid ugly text conversions */
4729             _setmode(2, O_BINARY);
4730             /*
4731              * optarg = the control ID, aka the PPID, currently used for the
4732              * signal pipe name.
4733              */
4734             if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4735                 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4736                 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4737                                              GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4738
4739                 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4740                     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4741                           "Signal pipe: Unable to open %s.  Dead parent?",
4742                           sig_pipe_name);
4743                     exit_main(1);
4744                 }
4745             }
4746 #endif
4747             break;
4748
4749         case 'q':        /* Quiet */
4750             quiet = TRUE;
4751             break;
4752         case 't':
4753             use_threads = TRUE;
4754             break;
4755             /*** all non capture option specific ***/
4756         case 'D':        /* Print a list of capture devices and exit */
4757             if (!list_interfaces) {
4758                 list_interfaces = TRUE;
4759                 run_once_args++;
4760             }
4761             break;
4762         case 'L':        /* Print list of link-layer types and exit */
4763             if (!list_link_layer_types) {
4764                 list_link_layer_types = TRUE;
4765                 run_once_args++;
4766             }
4767             break;
4768 #ifdef HAVE_BPF_IMAGE
4769         case 'd':        /* Print BPF code for capture filter and exit */
4770             if (!print_bpf_code) {
4771                 print_bpf_code = TRUE;
4772                 run_once_args++;
4773             }
4774             break;
4775 #endif
4776         case 'S':        /* Print interface statistics once a second */
4777             if (!print_statistics) {
4778                 print_statistics = TRUE;
4779                 run_once_args++;
4780             }
4781             break;
4782         case 'k':        /* Set wireless channel */
4783             if (!set_chan) {
4784                 set_chan = TRUE;
4785                 set_chan_arg = optarg;
4786                 run_once_args++;
4787             } else {
4788                 cmdarg_err("Only one -k flag may be specified");
4789                 arg_error = TRUE;
4790             }
4791             break;
4792         case 'M':        /* For -D, -L, and -S, print machine-readable output */
4793             machine_readable = TRUE;
4794             break;
4795         case 'C':
4796             pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4797             break;
4798         case 'N':
4799             pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4800             break;
4801         default:
4802             cmdarg_err("Invalid Option: %s", argv[optind-1]);
4803             /* FALLTHROUGH */
4804         case '?':        /* Bad flag - print usage message */
4805             arg_error = TRUE;
4806             break;
4807         }
4808     }
4809     if (!arg_error) {
4810         argc -= optind;
4811         argv += optind;
4812         if (argc >= 1) {
4813             /* user specified file name as regular command-line argument */
4814             /* XXX - use it as the capture file name (or something else)? */
4815             argc--;
4816             argv++;
4817         }
4818         if (argc != 0) {
4819             /*
4820              * Extra command line arguments were specified; complain.
4821              * XXX - interpret as capture filter, as tcpdump and tshark do?
4822              */
4823             cmdarg_err("Invalid argument: %s", argv[0]);
4824             arg_error = TRUE;
4825         }
4826     }
4827
4828     if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4829         use_threads = TRUE;
4830     }
4831     if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4832         /* Use some default if the user hasn't specified some */
4833         /* XXX: Are these defaults good enough? */
4834         pcap_queue_byte_limit = 1000 * 1000;
4835         pcap_queue_packet_limit = 1000;
4836     }
4837     if (arg_error) {
4838         print_usage(stderr);
4839         exit_main(1);
4840     }
4841
4842     if (run_once_args > 1) {
4843 #ifdef HAVE_BPF_IMAGE
4844         cmdarg_err("Only one of -D, -L, -d, -k, or -S may be supplied.");
4845 #else
4846         cmdarg_err("Only one of -D, -L, -k, or -S may be supplied.");
4847 #endif
4848         exit_main(1);
4849     } else if (run_once_args == 1) {
4850         /* We're supposed to print some information, rather than
4851            to capture traffic; did they specify a ring buffer option? */
4852         if (global_capture_opts.multi_files_on) {
4853             cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4854             exit_main(1);
4855         }
4856     } else {
4857         /* We're supposed to capture traffic; */
4858
4859         /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4860         if (global_capture_opts.ifaces->len > 1) {
4861             use_threads = TRUE;
4862             global_capture_opts.use_pcapng = TRUE;
4863         }
4864
4865         if (global_capture_opts.capture_comment &&
4866             (!global_capture_opts.use_pcapng || global_capture_opts.multi_files_on)) {
4867             /* XXX - for ringbuffer, should we apply the comment to each file? */
4868             cmdarg_err("A capture comment can only be set if we capture into a single pcapng file.");
4869             exit_main(1);
4870         }
4871
4872         /* Was the ring buffer option specified and, if so, does it make sense? */
4873         if (global_capture_opts.multi_files_on) {
4874             /* Ring buffer works only under certain conditions:
4875                a) ring buffer does not work with temporary files;
4876                b) it makes no sense to enable the ring buffer if the maximum
4877                file size is set to "infinite". */
4878             if (global_capture_opts.save_file == NULL) {
4879                 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4880                 global_capture_opts.multi_files_on = FALSE;
4881             }
4882             if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4883                 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4884 #if 0
4885                 /* XXX - this must be redesigned as the conditions changed */
4886                 global_capture_opts.multi_files_on = FALSE;
4887 #endif
4888             }
4889         }
4890     }
4891
4892     /*
4893      * "-D" requires no interface to be selected; it's supposed to list
4894      * all interfaces.
4895      */
4896     if (list_interfaces) {
4897         /* Get the list of interfaces */
4898         GList *if_list;
4899         int    err;
4900         gchar *err_str;
4901
4902         if_list = capture_interface_list(&err, &err_str,NULL);
4903         if (if_list == NULL) {
4904             if (err == 0) {
4905                 /*
4906                  * If we're being run by another program, just give them
4907                  * an empty list of interfaces, don't report this as
4908                  * an error; that lets them decide whether to report
4909                  * this as an error or not.
4910                  */
4911                 if (!machine_readable) {
4912                     cmdarg_err("There are no interfaces on which a capture can be done");
4913                     exit_main(2);
4914                 }
4915             } else {
4916                 cmdarg_err("%s", err_str);
4917                 g_free(err_str);
4918                 exit_main(2);
4919             }
4920         }
4921
4922         if (machine_readable)      /* tab-separated values to stdout */
4923             print_machine_readable_interfaces(if_list);
4924         else
4925             capture_opts_print_interfaces(if_list);
4926         free_interface_list(if_list);
4927         exit_main(0);
4928     }
4929
4930     /*
4931      * "-S" requires no interface to be selected; it gives statistics
4932      * for all interfaces.
4933      */
4934     if (print_statistics) {
4935         status = print_statistics_loop(machine_readable);
4936         exit_main(status);
4937     }
4938
4939     if (set_chan) {
4940         interface_options interface_opts;
4941
4942         if (global_capture_opts.ifaces->len != 1) {
4943             cmdarg_err("Need one interface");
4944             exit_main(2);
4945         }
4946
4947         interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4948         status = set_80211_channel(interface_opts.name, set_chan_arg);
4949         exit_main(status);
4950     }
4951
4952     /*
4953      * "-L", "-d", and capturing act on a particular interface, so we have to
4954      * have an interface; if none was specified, pick a default.
4955      */
4956     status = capture_opts_default_iface_if_necessary(&global_capture_opts, NULL);
4957     if (status != 0) {
4958         /* cmdarg_err() already called .... */
4959         exit_main(status);
4960     }
4961
4962     if (list_link_layer_types) {
4963         /* Get the list of link-layer types for the capture device. */
4964         if_capabilities_t *caps;
4965         gchar *err_str;
4966         guint  ii;
4967
4968         for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4969             interface_options interface_opts;
4970
4971             interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4972
4973             caps = get_if_capabilities(&interface_opts, &err_str);
4974             if (caps == NULL) {
4975                 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4976                            "Please check to make sure you have sufficient permissions, and that\n"
4977                            "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4978                 g_free(err_str);
4979                 exit_main(2);
4980             }
4981             if (caps->data_link_types == NULL) {
4982                 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4983                 exit_main(2);
4984             }
4985             if (machine_readable)      /* tab-separated values to stdout */
4986                 /* XXX: We need to change the format and adopt consumers */
4987                 print_machine_readable_if_capabilities(caps);
4988             else
4989                 /* XXX: We might want to print also the interface name */
4990                 capture_opts_print_if_capabilities(caps, interface_opts.name,
4991                                                    interface_opts.monitor_mode);
4992             free_if_capabilities(caps);
4993         }
4994         exit_main(0);
4995     }
4996
4997     /* We're supposed to do a capture, or print the BPF code for a filter. */
4998
4999     /* Let the user know what interfaces were chosen. */
5000     if (capture_child) {
5001         for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5002             interface_options interface_opts;
5003
5004             interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
5005             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
5006                   interface_opts.name);
5007         }
5008     } else {
5009         str = g_string_new("");
5010 #ifdef _WIN32
5011         if (global_capture_opts.ifaces->len < 2)
5012 #else
5013         if (global_capture_opts.ifaces->len < 4)
5014 #endif
5015         {
5016             for (j = 0; j < global_capture_opts.ifaces->len; j++) {
5017                 interface_options interface_opts;
5018
5019                 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
5020                 if (j > 0) {
5021                     if (global_capture_opts.ifaces->len > 2) {
5022                         g_string_append_printf(str, ",");
5023                     }
5024                     g_string_append_printf(str, " ");
5025                     if (j == global_capture_opts.ifaces->len - 1) {
5026                         g_string_append_printf(str, "and ");
5027                     }
5028                 }
5029                 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
5030             }
5031         } else {
5032             g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
5033         }
5034         fprintf(stderr, "Capturing on %s\n", str->str);
5035         g_string_free(str, TRUE);
5036     }
5037
5038     /* Process the snapshot length, as that affects the generated BPF code. */
5039     capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
5040
5041 #ifdef HAVE_BPF_IMAGE
5042     if (print_bpf_code) {
5043         show_filter_code(&global_capture_opts);
5044         exit_main(0);
5045     }
5046 #endif
5047
5048     /* We're supposed to do a capture.  Process the ring buffer arguments. */
5049     capture_opts_trim_ring_num_files(&global_capture_opts);
5050
5051     /* flush stderr prior to starting the main capture loop */
5052     fflush(stderr);
5053
5054     /* Now start the capture. */
5055     if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
5056         /* capture ok */
5057         exit_main(0);
5058     } else {
5059         /* capture failed */
5060         exit_main(1);
5061     }
5062     return 0; /* never here, make compiler happy */
5063 }
5064
5065
5066 static void
5067 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
5068                     const char *message, gpointer user_data _U_)
5069 {
5070     time_t      curr;
5071     struct tm  *today;
5072     const char *level;
5073     gchar      *msg;
5074
5075     /* ignore log message, if log_level isn't interesting */
5076     if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5077 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
5078         return;
5079 #endif
5080     }
5081
5082     /* create a "timestamp" */
5083     time(&curr);
5084     today = localtime(&curr);
5085
5086     switch(log_level & G_LOG_LEVEL_MASK) {
5087     case G_LOG_LEVEL_ERROR:
5088         level = "Err ";
5089         break;
5090     case G_LOG_LEVEL_CRITICAL:
5091         level = "Crit";
5092         break;
5093     case G_LOG_LEVEL_WARNING:
5094         level = "Warn";
5095         break;
5096     case G_LOG_LEVEL_MESSAGE:
5097         level = "Msg ";
5098         break;
5099     case G_LOG_LEVEL_INFO:
5100         level = "Info";
5101         break;
5102     case G_LOG_LEVEL_DEBUG:
5103         level = "Dbg ";
5104         break;
5105     default:
5106         fprintf(stderr, "unknown log_level %d\n", log_level);
5107         level = NULL;
5108         g_assert_not_reached();
5109     }
5110
5111     /* Generate the output message                                  */
5112     if (log_level & G_LOG_LEVEL_MESSAGE) {
5113         /* normal user messages without additional infos */
5114         msg =  g_strdup_printf("%s\n", message);
5115     } else {
5116         /* info/debug messages with additional infos */
5117         msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
5118                               today->tm_hour, today->tm_min, today->tm_sec,
5119                               log_domain != NULL ? log_domain : "",
5120                               level, message);
5121     }
5122
5123     /* DEBUG & INFO msgs (if we're debugging today)                 */
5124 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
5125     if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
5126 #ifdef DEBUG_DUMPCAP
5127         fprintf(stderr, "%s", msg);
5128         fflush(stderr);
5129 #endif
5130 #ifdef DEBUG_CHILD_DUMPCAP
5131         fprintf(debug_log, "%s", msg);
5132         fflush(debug_log);
5133 #endif
5134         g_free(msg);
5135         return;
5136     }
5137 #endif
5138
5139     /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or    */
5140     /*  to parent especially formatted if dumpcap running as child. */
5141     if (capture_child) {
5142         sync_pipe_errmsg_to_parent(2, msg, "");
5143     } else {
5144         fprintf(stderr, "%s", msg);
5145         fflush(stderr);
5146     }
5147     g_free(msg);
5148 }
5149
5150
5151 /****************************************************************************************************************/
5152 /* indication report routines */
5153
5154
5155 static void
5156 report_packet_count(unsigned int packet_count)
5157 {
5158     char tmp[SP_DECISIZE+1+1];
5159     static unsigned int count = 0;
5160
5161     if (capture_child) {
5162         g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
5163         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
5164         pipe_write_block(2, SP_PACKET_COUNT, tmp);
5165     } else {
5166         count += packet_count;
5167         fprintf(stderr, "\rPackets: %u ", count);
5168         /* stderr could be line buffered */
5169         fflush(stderr);
5170     }
5171 }
5172
5173 static void
5174 report_new_capture_file(const char *filename)
5175 {
5176     if (capture_child) {
5177         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
5178         pipe_write_block(2, SP_FILE, filename);
5179     } else {
5180 #ifdef SIGINFO
5181         /*
5182          * Prevent a SIGINFO handler from writing to the standard error
5183          * while we're doing so; instead, have it just set a flag telling
5184          * us to print that information when we're done.
5185          */
5186         infodelay = TRUE;
5187 #endif /* SIGINFO */
5188         fprintf(stderr, "File: %s\n", filename);
5189         /* stderr could be line buffered */
5190         fflush(stderr);
5191
5192 #ifdef SIGINFO
5193         /*
5194          * Allow SIGINFO handlers to write.
5195          */
5196         infodelay = FALSE;
5197
5198         /*
5199          * If a SIGINFO handler asked us to write out capture counts, do so.
5200          */
5201         if (infoprint)
5202           report_counts_for_siginfo();
5203 #endif /* SIGINFO */
5204     }
5205 }
5206
5207 static void
5208 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
5209 {
5210     interface_options interface_opts;
5211     char tmp[MSG_MAX_LENGTH+1+6];
5212
5213     if (i < capture_opts->ifaces->len) {
5214         if (capture_child) {
5215             g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
5216             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
5217             pipe_write_block(2, SP_BAD_FILTER, tmp);
5218         } else {
5219             /*
5220              * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
5221              * the error message below.
5222              */
5223             interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
5224             cmdarg_err(
5225               "Invalid capture filter \"%s\" for interface '%s'.\n"
5226               "\n"
5227               "That string isn't a valid capture filter (%s).\n"
5228               "See the User's Guide for a description of the capture filter syntax.",
5229               interface_opts.cfilter, interface_opts.name, errmsg);
5230         }
5231     }
5232 }
5233
5234 static void
5235 report_capture_error(const char *error_msg, const char *secondary_error_msg)
5236 {
5237     if (capture_child) {
5238         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5239             "Primary Error: %s", error_msg);
5240         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5241             "Secondary Error: %s", secondary_error_msg);
5242         sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5243     } else {
5244         cmdarg_err("%s", error_msg);
5245         if (secondary_error_msg[0] != '\0')
5246           cmdarg_err_cont("%s", secondary_error_msg);
5247     }
5248 }
5249
5250 static void
5251 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, guint32 ps_ifdrop, gchar *name)
5252 {
5253     char tmp[SP_DECISIZE+1+1];
5254     guint32 total_drops = pcap_drops + drops + flushed;
5255
5256     g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
5257
5258     if (capture_child) {
5259         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5260             "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u)",
5261             name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop);
5262         /* XXX: Need to provide interface id, changes to consumers required. */
5263         pipe_write_block(2, SP_DROPS, tmp);
5264     } else {
5265         fprintf(stderr,
5266             "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u/ps_ifdrop:%u) (%.1f%%)\n",
5267             name, received, total_drops, pcap_drops, drops, flushed, ps_ifdrop,
5268             received ? 100.0 * received / (received + total_drops) : 0.0);
5269         /* stderr could be line buffered */
5270         fflush(stderr);
5271     }
5272 }
5273
5274
5275 /************************************************************************************************/
5276 /* signal_pipe handling */
5277
5278
5279 #ifdef _WIN32
5280 static gboolean
5281 signal_pipe_check_running(void)
5282 {
5283     /* any news from our parent? -> just stop the capture */
5284     DWORD    avail = 0;
5285     gboolean result;
5286
5287     /* if we are running standalone, no check required */
5288     if (!capture_child) {
5289         return TRUE;
5290     }
5291
5292     if (!sig_pipe_name || !sig_pipe_handle) {
5293         /* This shouldn't happen */
5294         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5295             "Signal pipe: No name or handle");
5296         return FALSE;
5297     }
5298
5299     /*
5300      * XXX - We should have the process ID of the parent (from the "-Z" flag)
5301      * at this point.  Should we check to see if the parent is still alive,
5302      * e.g. by using OpenProcess?
5303      */
5304
5305     result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5306
5307     if (!result || avail > 0) {
5308         /* peek failed or some bytes really available */
5309         /* (if not piping from stdin this would fail) */
5310         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5311             "Signal pipe: Stop capture: %s", sig_pipe_name);
5312         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5313             "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
5314             sig_pipe_handle, result, avail);
5315         return FALSE;
5316     } else {
5317         /* pipe ok and no bytes available */
5318         return TRUE;
5319     }
5320 }
5321 #endif
5322
5323
5324
5325
5326
5327 /*
5328  * Editor modelines  -  https://www.wireshark.org/tools/modelines.html
5329  *
5330  * Local variables:
5331  * c-basic-offset: 4
5332  * tab-width: 8
5333  * indent-tabs-mode: nil
5334  * End:
5335  *
5336  * vi: set shiftwidth=4 tabstop=8 expandtab:
5337  * :indentSize=4:tabSize=8:noTabs=true:
5338  */