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