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