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