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