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