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