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