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