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