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