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