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