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