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