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