Send the output of the -D and -L options to the standard output rather
[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", 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("\t%s\t", if_info->vendor_description);
1307         else
1308             printf("\t\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         for (addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
1317                     addr = g_slist_next(addr)) {
1318             if (addr != g_slist_nth(if_info->addrs, 0))
1319                 printf(",");
1320
1321             if_addr = (if_addr_t *)addr->data;
1322             switch(if_addr->ifat_type) {
1323             case IF_AT_IPv4:
1324                 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
1325                               ADDRSTRLEN)) {
1326                     printf("%s", addr_str);
1327                 } else {
1328                     printf("<unknown IPv4>");
1329                 }
1330                 break;
1331             case IF_AT_IPv6:
1332                 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
1333                               addr_str, ADDRSTRLEN)) {
1334                     printf("%s", addr_str);
1335                 } else {
1336                     printf("<unknown IPv6>");
1337                 }
1338                 break;
1339             default:
1340                 printf("<type unknown %u>", if_addr->ifat_type);
1341             }
1342         }
1343
1344         if (if_info->loopback)
1345             printf("\tloopback");
1346         else
1347             printf("\tnetwork");
1348
1349         printf("\n");
1350     }
1351 }
1352
1353 /*
1354  * If you change the machine-readable output format of this function,
1355  * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
1356  */
1357 static void
1358 print_machine_readable_if_capabilities(if_capabilities_t *caps)
1359 {
1360     GList *lt_entry;
1361     data_link_info_t *data_link_info;
1362     const gchar *desc_str;
1363
1364     if (capture_child) {
1365         /* Let our parent know we succeeded. */
1366         pipe_write_block(2, SP_SUCCESS, NULL);
1367     }
1368
1369     if (caps->can_set_rfmon)
1370         printf("1\n");
1371     else
1372         printf("0\n");
1373     for (lt_entry = caps->data_link_types; lt_entry != NULL;
1374          lt_entry = g_list_next(lt_entry)) {
1375       data_link_info = (data_link_info_t *)lt_entry->data;
1376       if (data_link_info->description != NULL)
1377         desc_str = data_link_info->description;
1378       else
1379         desc_str = "(not supported)";
1380       printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
1381              desc_str);
1382     }
1383 }
1384
1385 typedef struct {
1386     char *name;
1387     pcap_t *pch;
1388 } if_stat_t;
1389
1390 /* Print the number of packets captured for each interface until we're killed. */
1391 static int
1392 print_statistics_loop(gboolean machine_readable)
1393 {
1394     GList       *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1395     if_info_t   *if_info;
1396     if_stat_t   *if_stat;
1397     int         err;
1398     gchar       *err_str;
1399     pcap_t      *pch;
1400     char        errbuf[PCAP_ERRBUF_SIZE];
1401     struct pcap_stat ps;
1402
1403     if_list = get_interface_list(&err, &err_str);
1404     if (if_list == NULL) {
1405         switch (err) {
1406         case CANT_GET_INTERFACE_LIST:
1407         case DONT_HAVE_PCAP:
1408             cmdarg_err("%s", err_str);
1409             g_free(err_str);
1410             break;
1411
1412         case NO_INTERFACES_FOUND:
1413             cmdarg_err("There are no interfaces on which a capture can be done");
1414             break;
1415         }
1416         return err;
1417     }
1418
1419     for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1420         if_info = (if_info_t *)if_entry->data;
1421 #ifdef HAVE_PCAP_OPEN
1422         pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1423 #else
1424         pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1425 #endif
1426
1427         if (pch) {
1428             if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
1429             if_stat->name = g_strdup(if_info->name);
1430             if_stat->pch = pch;
1431             stat_list = g_list_append(stat_list, if_stat);
1432         }
1433     }
1434
1435     if (!stat_list) {
1436         cmdarg_err("There are no interfaces on which a capture can be done");
1437         return 2;
1438     }
1439
1440     if (capture_child) {
1441         /* Let our parent know we succeeded. */
1442         pipe_write_block(2, SP_SUCCESS, NULL);
1443     }
1444
1445     if (!machine_readable) {
1446         printf("%-15s  %10s  %10s\n", "Interface", "Received",
1447             "Dropped");
1448     }
1449
1450     global_ld.go = TRUE;
1451     while (global_ld.go) {
1452         for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1453             if_stat = (if_stat_t *)stat_entry->data;
1454             pcap_stats(if_stat->pch, &ps);
1455
1456             if (!machine_readable) {
1457                 printf("%-15s  %10u  %10u\n", if_stat->name,
1458                     ps.ps_recv, ps.ps_drop);
1459             } else {
1460                 printf("%s\t%u\t%u\n", if_stat->name,
1461                     ps.ps_recv, ps.ps_drop);
1462                 fflush(stdout);
1463             }
1464         }
1465 #ifdef _WIN32
1466         Sleep(1 * 1000);
1467 #else
1468         sleep(1);
1469 #endif
1470     }
1471
1472     /* XXX - Not reached.  Should we look for 'q' in stdin? */
1473     for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1474         if_stat = (if_stat_t *)stat_entry->data;
1475         pcap_close(if_stat->pch);
1476         g_free(if_stat->name);
1477         g_free(if_stat);
1478     }
1479     g_list_free(stat_list);
1480     free_interface_list(if_list);
1481
1482     return 0;
1483 }
1484
1485
1486 #ifdef _WIN32
1487 static BOOL WINAPI
1488 capture_cleanup_handler(DWORD dwCtrlType)
1489 {
1490     /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1491        Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1492        is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1493        like SIGTERM at least when the machine's shutting down.
1494
1495        For now, if we're running as a command rather than a capture child,
1496        we handle all but CTRL_LOGOFF_EVENT as indications that we should
1497        clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1498        in that way on UN*X.
1499
1500        If we're not running as a capture child, we might be running as
1501        a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1502        user logs out.  (XXX - can we explicitly check whether we're
1503        running as a service?) */
1504
1505     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1506         "Console: Control signal");
1507     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1508         "Console: Control signal, CtrlType: %u", dwCtrlType);
1509
1510     /* Keep capture running if we're a service and a user logs off */
1511     if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1512         capture_loop_stop();
1513         return TRUE;
1514     } else {
1515         return FALSE;
1516     }
1517 }
1518 #else
1519 static void
1520 capture_cleanup_handler(int signum _U_)
1521 {
1522     /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1523        SIGTERM.  We assume that if the user wanted it to keep running
1524        after they logged out, they'd have nohupped it. */
1525
1526     /* Note: don't call g_log() in the signal handler: if we happened to be in
1527      * g_log() in process context when the signal came in, g_log will detect
1528      * the "recursion" and abort.
1529      */
1530
1531     capture_loop_stop();
1532 }
1533 #endif
1534
1535
1536 static void
1537 report_capture_count(gboolean reportit)
1538 {
1539     /* Don't print this if we're a capture child. */
1540     if (!capture_child && reportit) {
1541         fprintf(stderr, "\rPackets captured: %u\n", global_ld.packet_count);
1542         /* stderr could be line buffered */
1543         fflush(stderr);
1544     }
1545 }
1546
1547
1548 #ifdef SIGINFO
1549 static void
1550 report_counts_for_siginfo(void)
1551 {
1552     report_capture_count(quiet);
1553     infoprint = FALSE; /* we just reported it */
1554 }
1555
1556 static void
1557 report_counts_siginfo(int signum _U_)
1558 {
1559     int sav_errno = errno;
1560
1561     /* If we've been told to delay printing, just set a flag asking
1562        that we print counts (if we're supposed to), otherwise print
1563        the count of packets captured (if we're supposed to). */
1564     if (infodelay)
1565         infoprint = TRUE;
1566     else
1567         report_counts_for_siginfo();
1568     errno = sav_errno;
1569 }
1570 #endif /* SIGINFO */
1571
1572 static void
1573 exit_main(int status)
1574 {
1575 #ifdef _WIN32
1576     /* Shutdown windows sockets */
1577     WSACleanup();
1578
1579     /* can be helpful for debugging */
1580 #ifdef DEBUG_DUMPCAP
1581     printf("Press any key\n");
1582     _getch();
1583 #endif
1584
1585 #endif /* _WIN32 */
1586
1587     exit(status);
1588 }
1589
1590 #ifdef HAVE_LIBCAP
1591 /*
1592  * If we were linked with libcap (not related to libpcap), make sure we have
1593  * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1594  * (See comment in main() for details)
1595  */
1596 static void
1597 relinquish_privs_except_capture(void)
1598 {
1599     /* If 'started_with_special_privs' (ie: suid) then enable for
1600      *  ourself the  NET_ADMIN and NET_RAW capabilities and then
1601      *  drop our suid privileges.
1602      *
1603      * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1604      *                stuff we don't need (and shouldn't have).
1605      * CAP_NET_RAW:   Packet capture (raw sockets).
1606      */
1607
1608     if (started_with_special_privs()) {
1609         cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1610         int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1611
1612         cap_t caps = cap_init();    /* all capabilities initialized to off */
1613
1614         print_caps("Pre drop, pre set");
1615
1616         if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1617             cmdarg_err("prctl() fail return: %s", g_strerror(errno));
1618         }
1619
1620         cap_set_flag(caps, CAP_PERMITTED,   cl_len, cap_list, CAP_SET);
1621         cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1622
1623         if (cap_set_proc(caps)) {
1624             cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1625         }
1626         print_caps("Pre drop, post set");
1627
1628         relinquish_special_privs_perm();
1629
1630         print_caps("Post drop, pre set");
1631         cap_set_flag(caps, CAP_EFFECTIVE,   cl_len, cap_list, CAP_SET);
1632         if (cap_set_proc(caps)) {
1633             cmdarg_err("cap_set_proc() fail return: %s", g_strerror(errno));
1634         }
1635         print_caps("Post drop, post set");
1636
1637         cap_free(caps);
1638     }
1639 }
1640
1641 #endif /* HAVE_LIBCAP */
1642
1643 /* Take care of byte order in the libpcap headers read from pipes.
1644  * (function taken from wiretap/libpcap.c) */
1645 static void
1646 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1647 {
1648     if (byte_swapped) {
1649         /* Byte-swap the record header fields. */
1650         rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
1651         rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
1652         rechdr->incl_len = BSWAP32(rechdr->incl_len);
1653         rechdr->orig_len = BSWAP32(rechdr->orig_len);
1654     }
1655
1656     /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1657        swapped, in order to match the BPF header layout.
1658
1659        Unfortunately, some files were, according to a comment in the "libpcap"
1660        source, written with version 2.3 in their headers but without the
1661        interchanged fields, so if "incl_len" is greater than "orig_len" - which
1662        would make no sense - we assume that we need to swap them.  */
1663     if (hdr->version_major == 2 &&
1664         (hdr->version_minor < 3 ||
1665          (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1666         guint32 temp;
1667
1668         temp = rechdr->orig_len;
1669         rechdr->orig_len = rechdr->incl_len;
1670         rechdr->incl_len = temp;
1671     }
1672 }
1673
1674 /* Wrapper: distinguish between recv/read if we're reading on Windows,
1675  * or just read().
1676  */
1677 static ssize_t
1678 cap_pipe_read(int pipe_fd, char *buf, size_t sz, gboolean from_socket _U_)
1679 {
1680 #ifdef _WIN32
1681    if (from_socket) {
1682       return recv(pipe_fd, buf, (int)sz, 0);
1683    } else {
1684       return -1;
1685    }
1686 #else
1687    return ws_read(pipe_fd, buf, sz);
1688 #endif
1689 }
1690
1691 #if defined(_WIN32)
1692 /*
1693  * Thread function that reads from a pipe and pushes the data
1694  * to the main application thread.
1695  */
1696 /*
1697  * XXX Right now we use async queues for basic signaling. The main thread
1698  * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1699  * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1700  * Iff the read is successful cap_pipe_read pushes an item onto
1701  * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1702  * the queues themselves (yet).
1703  *
1704  * We might want to move some of the cap_pipe_dispatch logic here so that
1705  * we can let cap_thread_read run independently, queuing up multiple reads
1706  * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1707  */
1708 static void *cap_thread_read(void *arg)
1709 {
1710     pcap_options *pcap_opts;
1711 #ifdef _WIN32
1712     BOOL res;
1713     DWORD b, last_err, bytes_read;
1714 #else /* _WIN32 */
1715     size_t bytes_read;
1716     int b;
1717 #endif /* _WIN32 */
1718
1719     pcap_opts = (pcap_options *)arg;
1720     while (pcap_opts->cap_pipe_err == PIPOK) {
1721         g_async_queue_pop(pcap_opts->cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1722         g_mutex_lock(pcap_opts->cap_pipe_read_mtx);
1723         bytes_read = 0;
1724         while (bytes_read < pcap_opts->cap_pipe_bytes_to_read) {
1725            if ((pcap_opts->from_cap_socket)
1726 #ifndef _WIN32
1727               || 1
1728 #endif
1729               )
1730            {
1731                b = cap_pipe_read(pcap_opts->cap_pipe_fd, pcap_opts->cap_pipe_buf+bytes_read,
1732                         pcap_opts->cap_pipe_bytes_to_read - bytes_read, pcap_opts->from_cap_socket);
1733                if (b <= 0) {
1734                    if (b == 0) {
1735                        pcap_opts->cap_pipe_err = PIPEOF;
1736                        bytes_read = 0;
1737                        break;
1738                    } else {
1739                        pcap_opts->cap_pipe_err = PIPERR;
1740                        bytes_read = -1;
1741                        break;
1742                    }
1743                } else {
1744                    bytes_read += b;
1745                }
1746            }
1747 #ifdef _WIN32
1748            else
1749            {
1750                /* If we try to use read() on a named pipe on Windows with partial
1751                 * data it appears to return EOF.
1752                 */
1753                res = ReadFile(pcap_opts->cap_pipe_h, pcap_opts->cap_pipe_buf+bytes_read,
1754                               pcap_opts->cap_pipe_bytes_to_read - bytes_read,
1755                               &b, NULL);
1756
1757                bytes_read += b;
1758                if (!res) {
1759                    last_err = GetLastError();
1760                    if (last_err == ERROR_MORE_DATA) {
1761                        continue;
1762                    } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1763                        pcap_opts->cap_pipe_err = PIPEOF;
1764                        bytes_read = 0;
1765                        break;
1766                    }
1767                    pcap_opts->cap_pipe_err = PIPERR;
1768                    bytes_read = -1;
1769                    break;
1770                } else if (b == 0 && pcap_opts->cap_pipe_bytes_to_read > 0) {
1771                    pcap_opts->cap_pipe_err = PIPEOF;
1772                    bytes_read = 0;
1773                    break;
1774                }
1775            }
1776 #endif /*_WIN32 */
1777         }
1778         pcap_opts->cap_pipe_bytes_read = bytes_read;
1779         if (pcap_opts->cap_pipe_bytes_read >= pcap_opts->cap_pipe_bytes_to_read) {
1780             g_async_queue_push(pcap_opts->cap_pipe_done_q, pcap_opts->cap_pipe_buf); /* Any non-NULL value will do */
1781         }
1782         g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
1783     }
1784     return NULL;
1785 }
1786 #endif
1787
1788 /* Provide select() functionality for a single file descriptor
1789  * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1790  *
1791  * Returns the same values as select.
1792  */
1793 static int
1794 cap_pipe_select(int pipe_fd)
1795 {
1796     fd_set      rfds;
1797     struct timeval timeout;
1798
1799     FD_ZERO(&rfds);
1800     FD_SET(pipe_fd, &rfds);
1801
1802     timeout.tv_sec = PIPE_READ_TIMEOUT / 1000000;
1803     timeout.tv_usec = PIPE_READ_TIMEOUT % 1000000;
1804
1805     return select(pipe_fd+1, &rfds, NULL, NULL, &timeout);
1806 }
1807
1808 #define DEF_TCP_PORT 19000
1809
1810 static int
1811 cap_open_socket(char *pipename, pcap_options *pcap_opts, char *errmsg, int errmsgl)
1812 {
1813   char *sockname = pipename + 4;
1814   struct sockaddr_in sa;
1815   char buf[16];
1816   char *p;
1817   unsigned long port;
1818   size_t len;
1819   int fd;
1820
1821   memset(&sa, 0, sizeof(sa));
1822
1823   p = strchr(sockname, ':');
1824   if (p == NULL) {
1825     len = strlen(sockname);
1826     port = DEF_TCP_PORT;
1827   }
1828   else {
1829     len = p - sockname;
1830     port = strtoul(p + 1, &p, 10);
1831     if (*p || port > 65535) {
1832       goto fail_invalid;
1833     }
1834   }
1835
1836   if (len > 15) {
1837     goto fail_invalid;
1838   }
1839
1840   strncpy(buf, sockname, len);
1841   buf[len] = '\0';
1842   if (!inet_pton(AF_INET, buf, &sa.sin_addr)) {
1843     goto fail_invalid;
1844   }
1845
1846   sa.sin_family = AF_INET;
1847   sa.sin_port = htons((u_short)port);
1848
1849   if (((fd = (int)socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
1850       (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0)) {
1851 #ifdef _WIN32
1852       LPTSTR errorText = NULL;
1853       int lastError;
1854
1855       lastError = WSAGetLastError();
1856       FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
1857                     FORMAT_MESSAGE_ALLOCATE_BUFFER |
1858                     FORMAT_MESSAGE_IGNORE_INSERTS,
1859                     NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1860                     (LPTSTR)&errorText, 0, NULL);
1861 #endif
1862       g_snprintf(errmsg, errmsgl,
1863       "The capture session could not be initiated due to the socket error: \n"
1864 #ifdef _WIN32
1865       "         %d: %S", lastError, errorText ? (char *)errorText : "Unknown");
1866       if (errorText)
1867           LocalFree(errorText);
1868 #else
1869       "         %d: %s", errno, strerror(errno));
1870 #endif
1871       pcap_opts->cap_pipe_err = PIPERR;
1872
1873       if (fd >= 0)
1874           cap_pipe_close(fd, TRUE);
1875       return -1;
1876   }
1877
1878   pcap_opts->from_cap_socket = TRUE;
1879   return fd;
1880
1881 fail_invalid:
1882   g_snprintf(errmsg, errmsgl,
1883       "The capture session could not be initiated because\n"
1884       "\"%s\" is not a valid socket specification", pipename);
1885   pcap_opts->cap_pipe_err = PIPERR;
1886   return -1;
1887 }
1888
1889 /* Wrapper: distinguish between closesocket on Windows; use ws_close
1890  * otherwise.
1891  */
1892 static void
1893 cap_pipe_close(int pipe_fd, gboolean from_socket _U_)
1894 {
1895 #ifdef _WIN32
1896    if (from_socket) {
1897       closesocket(pipe_fd);
1898    }
1899 #else
1900    ws_close(pipe_fd);
1901 #endif
1902 }
1903
1904 /* Mimic pcap_open_live() for pipe captures
1905
1906  * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1907  * open it, and read the header.
1908  *
1909  * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1910  * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1911 static void
1912 cap_pipe_open_live(char *pipename,
1913                    pcap_options *pcap_opts,
1914                    struct pcap_hdr *hdr,
1915                    char *errmsg, int errmsgl)
1916 {
1917 #ifndef _WIN32
1918     ws_statb64         pipe_stat;
1919     struct sockaddr_un sa;
1920 #else /* _WIN32 */
1921     char    *pncopy, *pos;
1922     wchar_t *err_str;
1923 #endif
1924     ssize_t  b;
1925     int      fd, sel_ret;
1926     size_t   bytes_read;
1927     guint32  magic = 0;
1928
1929     pcap_opts->cap_pipe_fd = -1;
1930 #ifdef _WIN32
1931     pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
1932 #endif
1933     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1934
1935     /*
1936      * XXX - this blocks until a pcap per-file header has been written to
1937      * the pipe, so it could block indefinitely.
1938      */
1939     if (strcmp(pipename, "-") == 0) {
1940 #ifndef _WIN32
1941         fd = 0; /* read from stdin */
1942 #else /* _WIN32 */
1943         pcap_opts->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1944 #endif  /* _WIN32 */
1945     } else if (!strncmp(pipename, "TCP@", 4)) {
1946        if ((fd = cap_open_socket(pipename, pcap_opts, errmsg, errmsgl)) < 0) {
1947           return;
1948        }
1949     } else {
1950 #ifndef _WIN32
1951         if (ws_stat64(pipename, &pipe_stat) < 0) {
1952             if (errno == ENOENT || errno == ENOTDIR)
1953                 pcap_opts->cap_pipe_err = PIPNEXIST;
1954             else {
1955                 g_snprintf(errmsg, errmsgl,
1956                            "The capture session could not be initiated "
1957                            "due to error getting information on pipe/socket: %s", g_strerror(errno));
1958                 pcap_opts->cap_pipe_err = PIPERR;
1959             }
1960             return;
1961         }
1962         if (S_ISFIFO(pipe_stat.st_mode)) {
1963             fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1964             if (fd == -1) {
1965                 g_snprintf(errmsg, errmsgl,
1966                            "The capture session could not be initiated "
1967                            "due to error on pipe open: %s", g_strerror(errno));
1968                 pcap_opts->cap_pipe_err = PIPERR;
1969                 return;
1970             }
1971         } else if (S_ISSOCK(pipe_stat.st_mode)) {
1972             fd = socket(AF_UNIX, SOCK_STREAM, 0);
1973             if (fd == -1) {
1974                 g_snprintf(errmsg, errmsgl,
1975                            "The capture session could not be initiated "
1976                            "due to error on socket create: %s", g_strerror(errno));
1977                 pcap_opts->cap_pipe_err = PIPERR;
1978                 return;
1979             }
1980             sa.sun_family = AF_UNIX;
1981             /*
1982              * The Single UNIX Specification says:
1983              *
1984              *   The size of sun_path has intentionally been left undefined.
1985              *   This is because different implementations use different sizes.
1986              *   For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1987              *   of 104. Since most implementations originate from BSD versions,
1988              *   the size is typically in the range 92 to 108.
1989              *
1990              *   Applications should not assume a particular length for sun_path
1991              *   or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1992              *
1993              * It also says
1994              *
1995              *   The <sys/un.h> header shall define the sockaddr_un structure,
1996              *   which shall include at least the following members:
1997              *
1998              *   sa_family_t  sun_family  Address family.
1999              *   char         sun_path[]  Socket pathname.
2000              *
2001              * so we assume that it's an array, with a specified size,
2002              * and that the size reflects the maximum path length.
2003              */
2004             if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
2005                 /* Path name too long */
2006                 g_snprintf(errmsg, errmsgl,
2007                            "The capture session coud not be initiated "
2008                            "due to error on socket connect: Path name too long");
2009                 pcap_opts->cap_pipe_err = PIPERR;
2010                 ws_close(fd);
2011                 return;
2012             }
2013             b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
2014             if (b == -1) {
2015                 g_snprintf(errmsg, errmsgl,
2016                            "The capture session coud not be initiated "
2017                            "due to error on socket connect: %s", g_strerror(errno));
2018                 pcap_opts->cap_pipe_err = PIPERR;
2019                 ws_close(fd);
2020                 return;
2021             }
2022         } else {
2023             if (S_ISCHR(pipe_stat.st_mode)) {
2024                 /*
2025                  * Assume the user specified an interface on a system where
2026                  * interfaces are in /dev.  Pretend we haven't seen it.
2027                  */
2028                 pcap_opts->cap_pipe_err = PIPNEXIST;
2029             } else {
2030                 g_snprintf(errmsg, errmsgl,
2031                            "The capture session could not be initiated because\n"
2032                            "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
2033                 pcap_opts->cap_pipe_err = PIPERR;
2034             }
2035             return;
2036         }
2037 #else /* _WIN32 */
2038 #define PIPE_STR "\\pipe\\"
2039         /* Under Windows, named pipes _must_ have the form
2040          * "\\<server>\pipe\<pipename>".  <server> may be "." for localhost.
2041          */
2042         pncopy = g_strdup(pipename);
2043         if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
2044             pos = strchr(pncopy + 3, '\\');
2045             if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
2046                 pos = NULL;
2047         }
2048
2049         g_free(pncopy);
2050
2051         if (!pos) {
2052             g_snprintf(errmsg, errmsgl,
2053                        "The capture session could not be initiated because\n"
2054                        "\"%s\" is neither an interface nor a pipe", pipename);
2055             pcap_opts->cap_pipe_err = PIPNEXIST;
2056             return;
2057         }
2058
2059         /* Wait for the pipe to appear */
2060         while (1) {
2061             pcap_opts->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
2062                                                OPEN_EXISTING, 0, NULL);
2063
2064             if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE)
2065                 break;
2066
2067             if (GetLastError() != ERROR_PIPE_BUSY) {
2068                 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2069                               NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2070                 g_snprintf(errmsg, errmsgl,
2071                            "The capture session on \"%s\" could not be started "
2072                            "due to error on pipe open: %s (error %d)",
2073                            pipename, utf_16to8(err_str), GetLastError());
2074                 LocalFree(err_str);
2075                 pcap_opts->cap_pipe_err = PIPERR;
2076                 return;
2077             }
2078
2079             if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
2080                 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2081                               NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2082                 g_snprintf(errmsg, errmsgl,
2083                            "The capture session on \"%s\" timed out during "
2084                            "pipe open: %s (error %d)",
2085                            pipename, utf_16to8(err_str), GetLastError());
2086                 LocalFree(err_str);
2087                 pcap_opts->cap_pipe_err = PIPERR;
2088                 return;
2089             }
2090         }
2091 #endif /* _WIN32 */
2092     }
2093
2094     pcap_opts->from_cap_pipe = TRUE;
2095
2096 #ifdef _WIN32
2097     if (pcap_opts->from_cap_socket)
2098 #endif
2099     {
2100         /* read the pcap header */
2101         bytes_read = 0;
2102         while (bytes_read < sizeof magic) {
2103             sel_ret = cap_pipe_select(fd);
2104             if (sel_ret < 0) {
2105                 g_snprintf(errmsg, errmsgl,
2106                            "Unexpected error from select: %s", g_strerror(errno));
2107                 goto error;
2108             } else if (sel_ret > 0) {
2109                 b = cap_pipe_read(fd, ((char *)&magic)+bytes_read,
2110                                   sizeof magic-bytes_read,
2111                                   pcap_opts->from_cap_socket);
2112                 if (b <= 0) {
2113                     if (b == 0)
2114                         g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2115                     else
2116                         g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2117                                    g_strerror(errno));
2118                     goto error;
2119                 }
2120                 bytes_read += b;
2121             }
2122         }
2123     }
2124 #ifdef _WIN32
2125     else {
2126 #if GLIB_CHECK_VERSION(2,31,0)
2127         g_thread_new("cap_pipe_open_live", &cap_thread_read, pcap_opts);
2128 #else
2129         g_thread_create(&cap_thread_read, pcap_opts, FALSE, NULL);
2130 #endif
2131
2132         pcap_opts->cap_pipe_buf = (char *) &magic;
2133         pcap_opts->cap_pipe_bytes_read = 0;
2134         pcap_opts->cap_pipe_bytes_to_read = sizeof(magic);
2135         /* We don't have to worry about cap_pipe_read_mtx here */
2136         g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2137         g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2138         if (pcap_opts->cap_pipe_bytes_read <= 0) {
2139             if (pcap_opts->cap_pipe_bytes_read == 0)
2140                 g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
2141             else
2142                 g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
2143                            g_strerror(errno));
2144             goto error;
2145         }
2146     }
2147 #endif
2148
2149     switch (magic) {
2150     case PCAP_MAGIC:
2151     case PCAP_NSEC_MAGIC:
2152         /* Host that wrote it has our byte order, and was running
2153            a program using either standard or ss990417 libpcap. */
2154         pcap_opts->cap_pipe_byte_swapped = FALSE;
2155         pcap_opts->cap_pipe_modified = FALSE;
2156         pcap_opts->ts_nsec = magic == PCAP_NSEC_MAGIC;
2157         break;
2158     case PCAP_MODIFIED_MAGIC:
2159         /* Host that wrote it has our byte order, but was running
2160            a program using either ss990915 or ss991029 libpcap. */
2161         pcap_opts->cap_pipe_byte_swapped = FALSE;
2162         pcap_opts->cap_pipe_modified = TRUE;
2163         break;
2164     case PCAP_SWAPPED_MAGIC:
2165     case PCAP_SWAPPED_NSEC_MAGIC:
2166         /* Host that wrote it has a byte order opposite to ours,
2167            and was running a program using either standard or
2168            ss990417 libpcap. */
2169         pcap_opts->cap_pipe_byte_swapped = TRUE;
2170         pcap_opts->cap_pipe_modified = FALSE;
2171         pcap_opts->ts_nsec = magic == PCAP_SWAPPED_NSEC_MAGIC;
2172         break;
2173     case PCAP_SWAPPED_MODIFIED_MAGIC:
2174         /* Host that wrote it out has a byte order opposite to
2175            ours, and was running a program using either ss990915
2176            or ss991029 libpcap. */
2177         pcap_opts->cap_pipe_byte_swapped = TRUE;
2178         pcap_opts->cap_pipe_modified = TRUE;
2179         break;
2180     default:
2181         /* Not a "libpcap" type we know about. */
2182         g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
2183         goto error;
2184     }
2185
2186 #ifdef _WIN32
2187     if (pcap_opts->from_cap_socket)
2188 #endif
2189     {
2190         /* Read the rest of the header */
2191         bytes_read = 0;
2192         while (bytes_read < sizeof(struct pcap_hdr)) {
2193             sel_ret = cap_pipe_select(fd);
2194             if (sel_ret < 0) {
2195                 g_snprintf(errmsg, errmsgl,
2196                            "Unexpected error from select: %s", g_strerror(errno));
2197                 goto error;
2198             } else if (sel_ret > 0) {
2199                 b = cap_pipe_read(fd, ((char *)hdr)+bytes_read,
2200                                   sizeof(struct pcap_hdr) - bytes_read,
2201                                   pcap_opts->from_cap_socket);
2202                 if (b <= 0) {
2203                     if (b == 0)
2204                         g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2205                     else
2206                         g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
2207                                    g_strerror(errno));
2208                     goto error;
2209                 }
2210                 bytes_read += b;
2211             }
2212         }
2213     }
2214 #ifdef _WIN32
2215     else {
2216         pcap_opts->cap_pipe_buf = (char *) hdr;
2217         pcap_opts->cap_pipe_bytes_read = 0;
2218         pcap_opts->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
2219         g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2220         g_async_queue_pop(pcap_opts->cap_pipe_done_q);
2221         if (pcap_opts->cap_pipe_bytes_read <= 0) {
2222             if (pcap_opts->cap_pipe_bytes_read == 0)
2223                 g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
2224             else
2225                 g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
2226                            g_strerror(errno));
2227             goto error;
2228         }
2229     }
2230 #endif
2231
2232     if (pcap_opts->cap_pipe_byte_swapped) {
2233         /* Byte-swap the header fields about which we care. */
2234         hdr->version_major = BSWAP16(hdr->version_major);
2235         hdr->version_minor = BSWAP16(hdr->version_minor);
2236         hdr->snaplen = BSWAP32(hdr->snaplen);
2237         hdr->network = BSWAP32(hdr->network);
2238     }
2239     pcap_opts->linktype = hdr->network;
2240
2241     if (hdr->version_major < 2) {
2242         g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
2243         goto error;
2244     }
2245
2246     pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2247     pcap_opts->cap_pipe_err = PIPOK;
2248     pcap_opts->cap_pipe_fd = fd;
2249     return;
2250
2251 error:
2252     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
2253     pcap_opts->cap_pipe_err = PIPERR;
2254     cap_pipe_close(fd, pcap_opts->from_cap_socket);
2255     pcap_opts->cap_pipe_fd = -1;
2256 }
2257
2258
2259 /* We read one record from the pipe, take care of byte order in the record
2260  * header, write the record to the capture file, and update capture statistics. */
2261 static int
2262 cap_pipe_dispatch(loop_data *ld, pcap_options *pcap_opts, guchar *data, char *errmsg, int errmsgl)
2263 {
2264     struct pcap_pkthdr  phdr;
2265     enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
2266            PD_ERR } result;
2267 #ifdef _WIN32
2268 #if !GLIB_CHECK_VERSION(2,31,18)
2269     GTimeVal  wait_time;
2270 #endif
2271     gpointer  q_status;
2272     wchar_t  *err_str;
2273 #endif
2274     ssize_t   b;
2275
2276 #ifdef LOG_CAPTURE_VERBOSE
2277     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
2278 #endif
2279
2280     switch (pcap_opts->cap_pipe_state) {
2281
2282     case STATE_EXPECT_REC_HDR:
2283 #ifdef _WIN32
2284         if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2285 #endif
2286
2287             pcap_opts->cap_pipe_state = STATE_READ_REC_HDR;
2288             pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_modified ?
2289                 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
2290             pcap_opts->cap_pipe_bytes_read = 0;
2291
2292 #ifdef _WIN32
2293             pcap_opts->cap_pipe_buf = (char *) &pcap_opts->cap_pipe_rechdr;
2294             g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2295             g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2296         }
2297 #endif
2298         /* Fall through */
2299
2300     case STATE_READ_REC_HDR:
2301 #ifdef _WIN32
2302         if (pcap_opts->from_cap_socket)
2303 #endif
2304         {
2305             b = cap_pipe_read(pcap_opts->cap_pipe_fd, ((char *)&pcap_opts->cap_pipe_rechdr)+pcap_opts->cap_pipe_bytes_read,
2306                  pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read, pcap_opts->from_cap_socket);
2307             if (b <= 0) {
2308                 if (b == 0)
2309                     result = PD_PIPE_EOF;
2310                 else
2311                     result = PD_PIPE_ERR;
2312                 break;
2313             }
2314             pcap_opts->cap_pipe_bytes_read += b;
2315         }
2316 #ifdef _WIN32
2317         else {
2318 #if GLIB_CHECK_VERSION(2,31,18)
2319             q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2320 #else
2321             g_get_current_time(&wait_time);
2322             g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2323             q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2324 #endif
2325             if (pcap_opts->cap_pipe_err == PIPEOF) {
2326                 result = PD_PIPE_EOF;
2327                 break;
2328             } else if (pcap_opts->cap_pipe_err == PIPERR) {
2329                 result = PD_PIPE_ERR;
2330                 break;
2331             }
2332             if (!q_status) {
2333                 return 0;
2334             }
2335         }
2336 #endif
2337         if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2338             return 0;
2339         result = PD_REC_HDR_READ;
2340         break;
2341
2342     case STATE_EXPECT_DATA:
2343 #ifdef _WIN32
2344         if (g_mutex_trylock(pcap_opts->cap_pipe_read_mtx)) {
2345 #endif
2346
2347             pcap_opts->cap_pipe_state = STATE_READ_DATA;
2348             pcap_opts->cap_pipe_bytes_to_read = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2349             pcap_opts->cap_pipe_bytes_read = 0;
2350
2351 #ifdef _WIN32
2352             pcap_opts->cap_pipe_buf = (char *) data;
2353             g_async_queue_push(pcap_opts->cap_pipe_pending_q, pcap_opts->cap_pipe_buf);
2354             g_mutex_unlock(pcap_opts->cap_pipe_read_mtx);
2355         }
2356 #endif
2357         /* Fall through */
2358
2359     case STATE_READ_DATA:
2360 #ifdef _WIN32
2361         if (pcap_opts->from_cap_socket)
2362 #endif
2363         {
2364             b = cap_pipe_read(pcap_opts->cap_pipe_fd,
2365                               data+pcap_opts->cap_pipe_bytes_read,
2366                               pcap_opts->cap_pipe_bytes_to_read - pcap_opts->cap_pipe_bytes_read,
2367                               pcap_opts->from_cap_socket);
2368             if (b <= 0) {
2369                 if (b == 0)
2370                     result = PD_PIPE_EOF;
2371                 else
2372                     result = PD_PIPE_ERR;
2373                 break;
2374             }
2375             pcap_opts->cap_pipe_bytes_read += b;
2376         }
2377 #ifdef _WIN32
2378         else {
2379
2380 #if GLIB_CHECK_VERSION(2,31,18)
2381             q_status = g_async_queue_timeout_pop(pcap_opts->cap_pipe_done_q, PIPE_READ_TIMEOUT);
2382 #else
2383             g_get_current_time(&wait_time);
2384             g_time_val_add(&wait_time, PIPE_READ_TIMEOUT);
2385             q_status = g_async_queue_timed_pop(pcap_opts->cap_pipe_done_q, &wait_time);
2386 #endif /* GLIB_CHECK_VERSION(2,31,18) */
2387             if (pcap_opts->cap_pipe_err == PIPEOF) {
2388                 result = PD_PIPE_EOF;
2389                 break;
2390             } else if (pcap_opts->cap_pipe_err == PIPERR) {
2391                 result = PD_PIPE_ERR;
2392                 break;
2393             }
2394             if (!q_status) {
2395                 return 0;
2396             }
2397         }
2398 #endif /* _WIN32 */
2399         if (pcap_opts->cap_pipe_bytes_read < pcap_opts->cap_pipe_bytes_to_read)
2400             return 0;
2401         result = PD_DATA_READ;
2402         break;
2403
2404     default:
2405         g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2406         result = PD_ERR;
2407
2408     } /* switch (pcap_opts->cap_pipe_state) */
2409
2410     /*
2411      * We've now read as much data as we were expecting, so process it.
2412      */
2413     switch (result) {
2414
2415     case PD_REC_HDR_READ:
2416         /* We've read the header. Take care of byte order. */
2417         cap_pipe_adjust_header(pcap_opts->cap_pipe_byte_swapped, &pcap_opts->cap_pipe_hdr,
2418                                &pcap_opts->cap_pipe_rechdr.hdr);
2419         if (pcap_opts->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2420             g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2421                        ld->packet_count+1, pcap_opts->cap_pipe_rechdr.hdr.incl_len);
2422             break;
2423         }
2424
2425         if (pcap_opts->cap_pipe_rechdr.hdr.incl_len) {
2426             pcap_opts->cap_pipe_state = STATE_EXPECT_DATA;
2427             return 0;
2428         }
2429         /* no data to read? fall through */
2430
2431     case PD_DATA_READ:
2432         /* Fill in a "struct pcap_pkthdr", and process the packet. */
2433         phdr.ts.tv_sec = pcap_opts->cap_pipe_rechdr.hdr.ts_sec;
2434         phdr.ts.tv_usec = pcap_opts->cap_pipe_rechdr.hdr.ts_usec;
2435         phdr.caplen = pcap_opts->cap_pipe_rechdr.hdr.incl_len;
2436         phdr.len = pcap_opts->cap_pipe_rechdr.hdr.orig_len;
2437
2438         if (use_threads) {
2439             capture_loop_queue_packet_cb((u_char *)pcap_opts, &phdr, data);
2440         } else {
2441             capture_loop_write_packet_cb((u_char *)pcap_opts, &phdr, data);
2442         }
2443         pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2444         return 1;
2445
2446     case PD_PIPE_EOF:
2447         pcap_opts->cap_pipe_err = PIPEOF;
2448         return -1;
2449
2450     case PD_PIPE_ERR:
2451 #ifdef _WIN32
2452         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
2453                       NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2454         g_snprintf(errmsg, errmsgl,
2455                    "Error reading from pipe: %s (error %d)",
2456                    utf_16to8(err_str), GetLastError());
2457         LocalFree(err_str);
2458 #else
2459         g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2460                    g_strerror(errno));
2461 #endif
2462         /* Fall through */
2463     case PD_ERR:
2464         break;
2465     }
2466
2467     pcap_opts->cap_pipe_err = PIPERR;
2468     /* Return here rather than inside the switch to prevent GCC warning */
2469     return -1;
2470 }
2471
2472
2473 /** Open the capture input file (pcap or capture pipe).
2474  *  Returns TRUE if it succeeds, FALSE otherwise. */
2475 static gboolean
2476 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2477                         char *errmsg, size_t errmsg_len,
2478                         char *secondary_errmsg, size_t secondary_errmsg_len)
2479 {
2480     gchar             open_err_str[PCAP_ERRBUF_SIZE];
2481     gchar             *sync_msg_str;
2482     interface_options interface_opts;
2483     pcap_options      *pcap_opts;
2484     guint             i;
2485 #ifdef _WIN32
2486     int         err;
2487     gchar      *sync_secondary_msg_str;
2488     WORD        wVersionRequested;
2489     WSADATA     wsaData;
2490 #endif
2491
2492 /* XXX - opening Winsock on tshark? */
2493
2494     /* Initialize Windows Socket if we are in a WIN32 OS
2495        This needs to be done before querying the interface for network/netmask */
2496 #ifdef _WIN32
2497     /* XXX - do we really require 1.1 or earlier?
2498        Are there any versions that support only 2.0 or higher? */
2499     wVersionRequested = MAKEWORD(1, 1);
2500     err = WSAStartup(wVersionRequested, &wsaData);
2501     if (err != 0) {
2502         switch (err) {
2503
2504         case WSASYSNOTREADY:
2505             g_snprintf(errmsg, (gulong) errmsg_len,
2506                        "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2507             break;
2508
2509         case WSAVERNOTSUPPORTED:
2510             g_snprintf(errmsg, (gulong) errmsg_len,
2511                        "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2512                        LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2513             break;
2514
2515         case WSAEINPROGRESS:
2516             g_snprintf(errmsg, (gulong) errmsg_len,
2517                        "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2518             break;
2519
2520         case WSAEPROCLIM:
2521             g_snprintf(errmsg, (gulong) errmsg_len,
2522                        "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2523             break;
2524
2525         case WSAEFAULT:
2526             g_snprintf(errmsg, (gulong) errmsg_len,
2527                        "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2528             break;
2529
2530         default:
2531             g_snprintf(errmsg, (gulong) errmsg_len,
2532                        "Couldn't initialize Windows Sockets: error %d", err);
2533             break;
2534         }
2535         g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2536         return FALSE;
2537     }
2538 #endif
2539     if ((use_threads == FALSE) &&
2540         (capture_opts->ifaces->len > 1)) {
2541         g_snprintf(errmsg, (gulong) errmsg_len,
2542                    "Using threads is required for capturing on multiple interfaces!");
2543         return FALSE;
2544     }
2545
2546     for (i = 0; i < capture_opts->ifaces->len; i++) {
2547         interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2548         pcap_opts = (pcap_options *)g_malloc(sizeof (pcap_options));
2549         if (pcap_opts == NULL) {
2550             g_snprintf(errmsg, (gulong) errmsg_len,
2551                    "Could not allocate memory.");
2552             return FALSE;
2553         }
2554         pcap_opts->received = 0;
2555         pcap_opts->dropped = 0;
2556         pcap_opts->flushed = 0;
2557         pcap_opts->pcap_h = NULL;
2558 #ifdef MUST_DO_SELECT
2559         pcap_opts->pcap_fd = -1;
2560 #endif
2561         pcap_opts->pcap_err = FALSE;
2562         pcap_opts->interface_id = i;
2563         pcap_opts->tid = NULL;
2564         pcap_opts->snaplen = 0;
2565         pcap_opts->linktype = -1;
2566         pcap_opts->ts_nsec = FALSE;
2567         pcap_opts->from_cap_pipe = FALSE;
2568         pcap_opts->from_cap_socket = FALSE;
2569         memset(&pcap_opts->cap_pipe_hdr, 0, sizeof(struct pcap_hdr));
2570         memset(&pcap_opts->cap_pipe_rechdr, 0, sizeof(struct pcaprec_modified_hdr));
2571 #ifdef _WIN32
2572         pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2573 #endif
2574         pcap_opts->cap_pipe_fd = -1;
2575         pcap_opts->cap_pipe_modified = FALSE;
2576         pcap_opts->cap_pipe_byte_swapped = FALSE;
2577 #ifdef _WIN32
2578         pcap_opts->cap_pipe_buf = NULL;
2579 #endif
2580         pcap_opts->cap_pipe_bytes_to_read = 0;
2581         pcap_opts->cap_pipe_bytes_read = 0;
2582         pcap_opts->cap_pipe_state = STATE_EXPECT_REC_HDR;
2583         pcap_opts->cap_pipe_err = PIPOK;
2584 #ifdef _WIN32
2585 #if GLIB_CHECK_VERSION(2,31,0)
2586         pcap_opts->cap_pipe_read_mtx = g_malloc(sizeof(GMutex));
2587         g_mutex_init(pcap_opts->cap_pipe_read_mtx);
2588 #else
2589         pcap_opts->cap_pipe_read_mtx = g_mutex_new();
2590 #endif
2591         pcap_opts->cap_pipe_pending_q = g_async_queue_new();
2592         pcap_opts->cap_pipe_done_q = g_async_queue_new();
2593 #endif
2594         g_array_append_val(ld->pcaps, pcap_opts);
2595
2596         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", interface_opts.name);
2597         pcap_opts->pcap_h = open_capture_device(&interface_opts, &open_err_str);
2598
2599         if (pcap_opts->pcap_h != NULL) {
2600             /* we've opened "iface" as a network device */
2601 #ifdef _WIN32
2602             /* try to set the capture buffer size */
2603             if (interface_opts.buffer_size > 1 &&
2604                 pcap_setbuff(pcap_opts->pcap_h, interface_opts.buffer_size * 1024 * 1024) != 0) {
2605                 sync_secondary_msg_str = g_strdup_printf(
2606                     "The capture buffer size of %dMB seems to be too high for your machine,\n"
2607                     "the default of 1MB will be used.\n"
2608                     "\n"
2609                     "Nonetheless, the capture is started.\n",
2610                     interface_opts.buffer_size);
2611                 report_capture_error("Couldn't set the capture buffer size!",
2612                                      sync_secondary_msg_str);
2613                 g_free(sync_secondary_msg_str);
2614             }
2615 #endif
2616
2617 #if defined(HAVE_PCAP_SETSAMPLING)
2618             if (interface_opts.sampling_method != CAPTURE_SAMP_NONE) {
2619                 struct pcap_samp *samp;
2620
2621                 if ((samp = pcap_setsampling(pcap_opts->pcap_h)) != NULL) {
2622                     switch (interface_opts.sampling_method) {
2623                     case CAPTURE_SAMP_BY_COUNT:
2624                         samp->method = PCAP_SAMP_1_EVERY_N;
2625                         break;
2626
2627                     case CAPTURE_SAMP_BY_TIMER:
2628                         samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2629                         break;
2630
2631                     default:
2632                         sync_msg_str = g_strdup_printf(
2633                             "Unknown sampling method %d specified,\n"
2634                             "continue without packet sampling",
2635                             interface_opts.sampling_method);
2636                         report_capture_error("Couldn't set the capture "
2637                                              "sampling", sync_msg_str);
2638                         g_free(sync_msg_str);
2639                     }
2640                     samp->value = interface_opts.sampling_param;
2641                 } else {
2642                     report_capture_error("Couldn't set the capture sampling",
2643                                          "Cannot get packet sampling data structure");
2644                 }
2645             }
2646 #endif
2647
2648             /* setting the data link type only works on real interfaces */
2649             if (!set_pcap_linktype(pcap_opts->pcap_h, interface_opts.linktype, interface_opts.name,
2650                                    errmsg, errmsg_len,
2651                                    secondary_errmsg, secondary_errmsg_len)) {
2652                 return FALSE;
2653             }
2654             pcap_opts->linktype = get_pcap_linktype(pcap_opts->pcap_h, interface_opts.name);
2655         } else {
2656             /* We couldn't open "iface" as a network device. */
2657             /* Try to open it as a pipe */
2658             cap_pipe_open_live(interface_opts.name, pcap_opts, &pcap_opts->cap_pipe_hdr, errmsg, (int) errmsg_len);
2659
2660 #ifndef _WIN32
2661             if (pcap_opts->cap_pipe_fd == -1) {
2662 #else
2663             if (pcap_opts->cap_pipe_h == INVALID_HANDLE_VALUE) {
2664 #endif
2665                 if (pcap_opts->cap_pipe_err == PIPNEXIST) {
2666                     /* Pipe doesn't exist, so output message for interface */
2667                     get_capture_device_open_failure_messages(open_err_str,
2668                                                              interface_opts.name,
2669                                                              errmsg,
2670                                                              errmsg_len,
2671                                                              secondary_errmsg,
2672                                                              secondary_errmsg_len);
2673                 }
2674                 /*
2675                  * Else pipe (or file) does exist and cap_pipe_open_live() has
2676                  * filled in errmsg
2677                  */
2678                 return FALSE;
2679             } else {
2680                 /* cap_pipe_open_live() succeeded; don't want
2681                    error message from pcap_open_live() */
2682                 open_err_str[0] = '\0';
2683             }
2684         }
2685
2686 /* XXX - will this work for tshark? */
2687 #ifdef MUST_DO_SELECT
2688         if (!pcap_opts->from_cap_pipe) {
2689 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2690             pcap_opts->pcap_fd = pcap_get_selectable_fd(pcap_opts->pcap_h);
2691 #else
2692             pcap_opts->pcap_fd = pcap_fileno(pcap_opts->pcap_h);
2693 #endif
2694         }
2695 #endif
2696
2697         /* Does "open_err_str" contain a non-empty string?  If so, "pcap_open_live()"
2698            returned a warning; print it, but keep capturing. */
2699         if (open_err_str[0] != '\0') {
2700             sync_msg_str = g_strdup_printf("%s.", open_err_str);
2701             report_capture_error(sync_msg_str, "");
2702             g_free(sync_msg_str);
2703         }
2704         capture_opts->ifaces = g_array_remove_index(capture_opts->ifaces, i);
2705         g_array_insert_val(capture_opts->ifaces, i, interface_opts);
2706     }
2707
2708     /* If not using libcap: we now can now set euid/egid to ruid/rgid         */
2709     /*  to remove any suid privileges.                                        */
2710     /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities  */
2711     /*  (euid/egid have already previously been set to ruid/rgid.             */
2712     /* (See comment in main() for details)                                    */
2713 #ifndef HAVE_LIBCAP
2714     relinquish_special_privs_perm();
2715 #else
2716     relinquish_all_capabilities();
2717 #endif
2718     return TRUE;
2719 }
2720
2721 /* close the capture input file (pcap or capture pipe) */
2722 static void capture_loop_close_input(loop_data *ld)
2723 {
2724     guint         i;
2725     pcap_options *pcap_opts;
2726
2727     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2728
2729     for (i = 0; i < ld->pcaps->len; i++) {
2730         pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2731         /* if open, close the capture pipe "input file" */
2732         if (pcap_opts->cap_pipe_fd >= 0) {
2733             g_assert(pcap_opts->from_cap_pipe);
2734             cap_pipe_close(pcap_opts->cap_pipe_fd, pcap_opts->from_cap_socket);
2735             pcap_opts->cap_pipe_fd = -1;
2736         }
2737 #ifdef _WIN32
2738         if (pcap_opts->cap_pipe_h != INVALID_HANDLE_VALUE) {
2739             CloseHandle(pcap_opts->cap_pipe_h);
2740             pcap_opts->cap_pipe_h = INVALID_HANDLE_VALUE;
2741         }
2742 #endif
2743         /* if open, close the pcap "input file" */
2744         if (pcap_opts->pcap_h != NULL) {
2745             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)pcap_opts->pcap_h);
2746             pcap_close(pcap_opts->pcap_h);
2747             pcap_opts->pcap_h = NULL;
2748         }
2749     }
2750
2751     ld->go = FALSE;
2752
2753 #ifdef _WIN32
2754     /* Shut down windows sockets */
2755     WSACleanup();
2756 #endif
2757 }
2758
2759
2760 /* init the capture filter */
2761 static initfilter_status_t
2762 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2763                          const gchar * name, const gchar * cfilter)
2764 {
2765     struct bpf_program fcode;
2766
2767     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2768
2769     /* capture filters only work on real interfaces */
2770     if (cfilter && !from_cap_pipe) {
2771         /* A capture filter was specified; set it up. */
2772         if (!compile_capture_filter(name, pcap_h, &fcode, cfilter)) {
2773             /* Treat this specially - our caller might try to compile this
2774                as a display filter and, if that succeeds, warn the user that
2775                the display and capture filter syntaxes are different. */
2776             return INITFILTER_BAD_FILTER;
2777         }
2778         if (pcap_setfilter(pcap_h, &fcode) < 0) {
2779 #ifdef HAVE_PCAP_FREECODE
2780             pcap_freecode(&fcode);
2781 #endif
2782             return INITFILTER_OTHER_ERROR;
2783         }
2784 #ifdef HAVE_PCAP_FREECODE
2785         pcap_freecode(&fcode);
2786 #endif
2787     }
2788
2789     return INITFILTER_NO_ERROR;
2790 }
2791
2792
2793 /* set up to write to the already-opened capture output file/files */
2794 static gboolean
2795 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len)
2796 {
2797     int                err;
2798     guint              i;
2799     pcap_options      *pcap_opts;
2800     interface_options  interface_opts;
2801     gboolean           successful;
2802
2803     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2804
2805     if ((capture_opts->use_pcapng == FALSE) &&
2806         (capture_opts->ifaces->len > 1)) {
2807         g_snprintf(errmsg, errmsg_len,
2808                    "Using PCAPNG is required for capturing on multiple interfaces! Use the -n option.");
2809         return FALSE;
2810     }
2811
2812     /* Set up to write to the capture file. */
2813     if (capture_opts->multi_files_on) {
2814         ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2815     } else {
2816         ld->pdh = ws_fdopen(ld->save_file_fd, "wb");
2817         if (ld->pdh == NULL) {
2818             err = errno;
2819         }
2820     }
2821     if (ld->pdh) {
2822         if (capture_opts->use_pcapng) {
2823             char appname[100];
2824             GString             *os_info_str;
2825
2826             os_info_str = g_string_new("");
2827             get_os_version_info(os_info_str);
2828
2829             g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2830             successful = libpcap_write_session_header_block(libpcap_write_to_file, ld->pdh,
2831                                 NULL,                        /* Comment*/
2832                                 NULL,                        /* HW*/
2833                                 os_info_str->str,            /* OS*/
2834                                 appname,
2835                                 -1,                          /* section_length */
2836                                 &ld->bytes_written,
2837                                 &err);
2838
2839             for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2840                 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2841                 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2842                 if (pcap_opts->from_cap_pipe) {
2843                     pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2844                 } else {
2845                     pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2846                 }
2847                 successful = libpcap_write_interface_description_block(libpcap_write_to_file, global_ld.pdh,
2848                                                                        NULL,                       /* OPT_COMMENT       1 */
2849                                                                        interface_opts.name,        /* IDB_NAME          2 */
2850                                                                        interface_opts.descr,       /* IDB_DESCRIPTION   3 */
2851                                                                        interface_opts.cfilter,     /* IDB_FILTER       11 */
2852                                                                        os_info_str->str,           /* IDB_OS           12 */
2853                                                                        pcap_opts->linktype,
2854                                                                        pcap_opts->snaplen,
2855                                                                        &(global_ld.bytes_written),
2856                                                                        0,                          /* IDB_IF_SPEED      8 */
2857                                                                        pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL       9 */
2858                                                                        &global_ld.err);
2859             }
2860
2861             g_string_free(os_info_str, TRUE);
2862
2863         } else {
2864             pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
2865             if (pcap_opts->from_cap_pipe) {
2866                 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2867             } else {
2868                 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2869             }
2870             successful = libpcap_write_file_header(libpcap_write_to_file, ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
2871                                                    pcap_opts->ts_nsec, &ld->bytes_written, &err);
2872         }
2873         if (!successful) {
2874             fclose(ld->pdh);
2875             ld->pdh = NULL;
2876         }
2877     }
2878
2879     if (ld->pdh == NULL) {
2880         /* We couldn't set up to write to the capture file. */
2881         /* XXX - use cf_open_error_message from tshark instead? */
2882         switch (err) {
2883
2884         default:
2885             if (err < 0) {
2886                 g_snprintf(errmsg, errmsg_len,
2887                            "The file to which the capture would be"
2888                            " saved (\"%s\") could not be opened: Error %d.",
2889                            capture_opts->save_file, err);
2890             } else {
2891                 g_snprintf(errmsg, errmsg_len,
2892                            "The file to which the capture would be"
2893                            " saved (\"%s\") could not be opened: %s.",
2894                            capture_opts->save_file, g_strerror(err));
2895             }
2896             break;
2897         }
2898
2899         return FALSE;
2900     }
2901
2902     return TRUE;
2903 }
2904
2905 static gboolean
2906 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2907 {
2908
2909     unsigned int  i;
2910     pcap_options *pcap_opts;
2911     guint64       end_time = create_timestamp();
2912
2913     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2914
2915     if (capture_opts->multi_files_on) {
2916         return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2917     } else {
2918         if (capture_opts->use_pcapng) {
2919             for (i = 0; i < global_ld.pcaps->len; i++) {
2920                 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2921                 if (!pcap_opts->from_cap_pipe) {
2922                     guint64 isb_ifrecv, isb_ifdrop;
2923                     struct pcap_stat stats;
2924
2925                     if (pcap_stats(pcap_opts->pcap_h, &stats) >= 0) {
2926                         isb_ifrecv = pcap_opts->received;
2927                         isb_ifdrop = stats.ps_drop + pcap_opts->dropped + pcap_opts->flushed;
2928                    } else {
2929                         isb_ifrecv = G_MAXUINT64;
2930                         isb_ifdrop = G_MAXUINT64;
2931                     }
2932                     libpcap_write_interface_statistics_block(libpcap_write_to_file, ld->pdh,
2933                                                              i,
2934                                                              &ld->bytes_written,
2935                                                              "Counters provided by dumpcap",
2936                                                              start_time,
2937                                                              end_time,
2938                                                              isb_ifrecv,
2939                                                              isb_ifdrop,
2940                                                              err_close);
2941                 }
2942             }
2943         }
2944         if (fclose(ld->pdh) == EOF) {
2945             if (err_close != NULL) {
2946                 *err_close = errno;
2947             }
2948             return (FALSE);
2949         } else {
2950             return (TRUE);
2951         }
2952     }
2953 }
2954
2955 /* dispatch incoming packets (pcap or capture pipe)
2956  *
2957  * Waits for incoming packets to be available, and calls pcap_dispatch()
2958  * to cause them to be processed.
2959  *
2960  * Returns the number of packets which were processed.
2961  *
2962  * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2963  * packet-batching behaviour does not cause packets to get held back
2964  * indefinitely.
2965  */
2966 static int
2967 capture_loop_dispatch(loop_data *ld,
2968                       char *errmsg, int errmsg_len, pcap_options *pcap_opts)
2969 {
2970     int    inpkts;
2971     gint   packet_count_before;
2972     guchar pcap_data[WTAP_MAX_PACKET_SIZE];
2973 #ifndef _WIN32
2974     int    sel_ret;
2975 #endif
2976
2977     packet_count_before = ld->packet_count;
2978     if (pcap_opts->from_cap_pipe) {
2979         /* dispatch from capture pipe */
2980 #ifdef LOG_CAPTURE_VERBOSE
2981         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2982 #endif
2983 #ifndef _WIN32
2984         sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
2985         if (sel_ret <= 0) {
2986             if (sel_ret < 0 && errno != EINTR) {
2987                 g_snprintf(errmsg, errmsg_len,
2988                            "Unexpected error from select: %s", g_strerror(errno));
2989                 report_capture_error(errmsg, please_report);
2990                 ld->go = FALSE;
2991             }
2992         } else {
2993             /*
2994              * "select()" says we can read from the pipe without blocking
2995              */
2996 #endif
2997             inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
2998             if (inpkts < 0) {
2999                 ld->go = FALSE;
3000             }
3001 #ifndef _WIN32
3002         }
3003 #endif
3004     }
3005     else
3006     {
3007         /* dispatch from pcap */
3008 #ifdef MUST_DO_SELECT
3009         /*
3010          * If we have "pcap_get_selectable_fd()", we use it to get the
3011          * descriptor on which to select; if that's -1, it means there
3012          * is no descriptor on which you can do a "select()" (perhaps
3013          * because you're capturing on a special device, and that device's
3014          * driver unfortunately doesn't support "select()", in which case
3015          * we don't do the select - which means it might not be possible
3016          * to stop a capture until a packet arrives.  If that's unacceptable,
3017          * plead with whoever supplies the software for that device to add
3018          * "select()" support, or upgrade to libpcap 0.8.1 or later, and
3019          * rebuild Wireshark or get a version built with libpcap 0.8.1 or
3020          * later, so it can use pcap_breakloop().
3021          */
3022 #ifdef LOG_CAPTURE_VERBOSE
3023         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
3024 #endif
3025         if (pcap_opts->pcap_fd != -1) {
3026             sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
3027             if (sel_ret > 0) {
3028                 /*
3029                  * "select()" says we can read from it without blocking; go for
3030                  * it.
3031                  *
3032                  * We don't have pcap_breakloop(), so we only process one packet
3033                  * per pcap_dispatch() call, to allow a signal to stop the
3034                  * processing immediately, rather than processing all packets
3035                  * in a batch before quitting.
3036                  */
3037                 if (use_threads) {
3038                     inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3039                 } else {
3040                     inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3041                 }
3042                 if (inpkts < 0) {
3043                     if (inpkts == -1) {
3044                         /* Error, rather than pcap_breakloop(). */
3045                         pcap_opts->pcap_err = TRUE;
3046                     }
3047                     ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3048                 }
3049             } else {
3050                 if (sel_ret < 0 && errno != EINTR) {
3051                     g_snprintf(errmsg, errmsg_len,
3052                                "Unexpected error from select: %s", g_strerror(errno));
3053                     report_capture_error(errmsg, please_report);
3054                     ld->go = FALSE;
3055                 }
3056             }
3057         }
3058         else
3059 #endif /* MUST_DO_SELECT */
3060         {
3061             /* dispatch from pcap without select */
3062 #if 1
3063 #ifdef LOG_CAPTURE_VERBOSE
3064             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
3065 #endif
3066 #ifdef _WIN32
3067             /*
3068              * On Windows, we don't support asynchronously telling a process to
3069              * stop capturing; instead, we check for an indication on a pipe
3070              * after processing packets.  We therefore process only one packet
3071              * at a time, so that we can check the pipe after every packet.
3072              */
3073             if (use_threads) {
3074                 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3075             } else {
3076                 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3077             }
3078 #else
3079             if (use_threads) {
3080                 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
3081             } else {
3082                 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
3083             }
3084 #endif
3085             if (inpkts < 0) {
3086                 if (inpkts == -1) {
3087                     /* Error, rather than pcap_breakloop(). */
3088                     pcap_opts->pcap_err = TRUE;
3089                 }
3090                 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
3091             }
3092 #else /* pcap_next_ex */
3093 #ifdef LOG_CAPTURE_VERBOSE
3094             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
3095 #endif
3096             /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
3097
3098             /*
3099              * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
3100              * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
3101              * This should be fixed in the WinPcap 4.0 alpha release.
3102              *
3103              * For reference, an example remote interface:
3104              * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
3105              */
3106
3107             /* emulate dispatch from pcap */
3108             {
3109                 int in;
3110                 struct pcap_pkthdr *pkt_header;
3111                 u_char *pkt_data;
3112
3113                 in = 0;
3114                 while(ld->go &&
3115                       (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
3116                     if (use_threads) {
3117                         capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3118                     } else {
3119                         capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
3120                     }
3121                 }
3122
3123                 if (in < 0) {
3124                     pcap_opts->pcap_err = TRUE;
3125                     ld->go = FALSE;
3126                 }
3127             }
3128 #endif /* pcap_next_ex */
3129         }
3130     }
3131
3132 #ifdef LOG_CAPTURE_VERBOSE
3133     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
3134 #endif
3135
3136     return ld->packet_count - packet_count_before;
3137 }
3138
3139 #ifdef _WIN32
3140 /* Isolate the Universally Unique Identifier from the interface.  Basically, we
3141  * want to grab only the characters between the '{' and '}' delimiters.
3142  *
3143  * Returns a GString that must be freed with g_string_free(). */
3144 static GString *
3145 isolate_uuid(const char *iface)
3146 {
3147     gchar   *ptr;
3148     GString *gstr;
3149
3150     ptr = strchr(iface, '{');
3151     if (ptr == NULL)
3152         return g_string_new(iface);
3153     gstr = g_string_new(ptr + 1);
3154
3155     ptr = strchr(gstr->str, '}');
3156     if (ptr == NULL)
3157         return gstr;
3158
3159     gstr = g_string_truncate(gstr, ptr - gstr->str);
3160     return gstr;
3161 }
3162 #endif
3163
3164 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
3165 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
3166 static gboolean
3167 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
3168                          char *errmsg, int errmsg_len)
3169 {
3170     char     *tmpname;
3171     gchar    *capfile_name;
3172     gchar    *prefix;
3173     gboolean  is_tempfile;
3174
3175     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
3176           (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
3177
3178     if (capture_opts->save_file != NULL) {
3179         /* We return to the caller while the capture is in progress.
3180          * Therefore we need to take a copy of save_file in
3181          * case the caller destroys it after we return.
3182          */
3183         capfile_name = g_strdup(capture_opts->save_file);
3184
3185         if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
3186             if (capture_opts->multi_files_on) {
3187                 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
3188                 g_snprintf(errmsg, errmsg_len,
3189                            "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
3190                 g_free(capfile_name);
3191                 return FALSE;
3192             }
3193             if (strcmp(capfile_name, "-") == 0) {
3194                 /* write to stdout */
3195                 *save_file_fd = 1;
3196 #ifdef _WIN32
3197                 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF)  */
3198                 _setmode(1, O_BINARY);
3199 #endif
3200             }
3201         } /* if (...output_to_pipe ... */
3202
3203         else {
3204             if (capture_opts->multi_files_on) {
3205                 /* ringbuffer is enabled */
3206                 *save_file_fd = ringbuf_init(capfile_name,
3207                                              (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
3208                                              capture_opts->group_read_access);
3209
3210                 /* we need the ringbuf name */
3211                 if (*save_file_fd != -1) {
3212                     g_free(capfile_name);
3213                     capfile_name = g_strdup(ringbuf_current_filename());
3214                 }
3215             } else {
3216                 /* Try to open/create the specified file for use as a capture buffer. */
3217                 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
3218                                         (capture_opts->group_read_access) ? 0640 : 0600);
3219             }
3220         }
3221         is_tempfile = FALSE;
3222     } else {
3223         /* Choose a random name for the temporary capture buffer */
3224         if (global_capture_opts.ifaces->len > 1) {
3225             prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
3226         } else {
3227             gchar *basename;
3228             basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).console_display_name);
3229 #ifdef _WIN32
3230             /* use the generic portion of the interface guid to form the basis of the filename */
3231             if (strncmp("NPF_{", basename, 5)==0)
3232             {
3233                 /* we have a windows guid style device name, extract the guid digits as the basis of the filename */
3234                 GString *iface;
3235                 iface = isolate_uuid(basename);
3236                 g_free(basename);
3237                 basename = g_strdup(iface->str);
3238                 g_string_free(iface, TRUE);
3239             }
3240 #endif
3241             /* generate the temp file name prefix...
3242              * It would be nice if we could specify a pcapng/pcap filename suffix,
3243              * create_tempfile() however currently uses mkstemp() which doesn't allow this - one day perhaps*/
3244             if (capture_opts->use_pcapng) {
3245                 prefix = g_strconcat("wireshark_pcapng_", basename, NULL);
3246             }else{
3247                 prefix = g_strconcat("wireshark_pcap_", basename, NULL);
3248             }
3249             g_free(basename);
3250         }
3251         *save_file_fd = create_tempfile(&tmpname, prefix);
3252         g_free(prefix);
3253         capfile_name = g_strdup(tmpname);
3254         is_tempfile = TRUE;
3255     }
3256
3257     /* did we fail to open the output file? */
3258     if (*save_file_fd == -1) {
3259         if (is_tempfile) {
3260             g_snprintf(errmsg, errmsg_len,
3261                        "The temporary file to which the capture would be saved (\"%s\") "
3262                        "could not be opened: %s.", capfile_name, g_strerror(errno));
3263         } else {
3264             if (capture_opts->multi_files_on) {
3265                 ringbuf_error_cleanup();
3266             }
3267
3268             g_snprintf(errmsg, errmsg_len,
3269                        "The file to which the capture would be saved (\"%s\") "
3270                        "could not be opened: %s.", capfile_name,
3271                        g_strerror(errno));
3272         }
3273         g_free(capfile_name);
3274         return FALSE;
3275     }
3276
3277     if (capture_opts->save_file != NULL) {
3278         g_free(capture_opts->save_file);
3279     }
3280     capture_opts->save_file = capfile_name;
3281     /* capture_opts.save_file is "g_free"ed later, which is equivalent to
3282        "g_free(capfile_name)". */
3283
3284     return TRUE;
3285 }
3286
3287
3288 /* Do the work of handling either the file size or file duration capture
3289    conditions being reached, and switching files or stopping. */
3290 static gboolean
3291 do_file_switch_or_stop(capture_options *capture_opts,
3292                        condition *cnd_autostop_files,
3293                        condition *cnd_autostop_size,
3294                        condition *cnd_file_duration)
3295 {
3296     guint              i;
3297     pcap_options      *pcap_opts;
3298     interface_options  interface_opts;
3299     gboolean           successful;
3300
3301     if (capture_opts->multi_files_on) {
3302         if (cnd_autostop_files != NULL &&
3303             cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
3304             /* no files left: stop here */
3305             global_ld.go = FALSE;
3306             return FALSE;
3307         }
3308
3309         /* Switch to the next ringbuffer file */
3310         if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3311                                 &global_ld.save_file_fd, &global_ld.err)) {
3312
3313             /* File switch succeeded: reset the conditions */
3314             global_ld.bytes_written = 0;
3315             if (capture_opts->use_pcapng) {
3316                 char appname[100];
3317                 GString             *os_info_str;
3318
3319                 os_info_str = g_string_new("");
3320                 get_os_version_info(os_info_str);
3321
3322                 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
3323                 successful = libpcap_write_session_header_block(libpcap_write_to_file, global_ld.pdh,
3324                                 NULL,                        /* Comment */
3325                                 NULL,                        /* HW */
3326                                 os_info_str->str,            /* OS */
3327                                 appname,
3328                                                                 -1,                          /* section_length */
3329                                 &(global_ld.bytes_written),
3330                                 &global_ld.err);
3331
3332                 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3333                     interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3334                     pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3335                     successful = libpcap_write_interface_description_block(libpcap_write_to_file, global_ld.pdh,
3336                                                                            NULL,                       /* OPT_COMMENT       1 */
3337                                                                            interface_opts.name,        /* IDB_NAME          2 */
3338                                                                            interface_opts.descr,       /* IDB_DESCRIPTION   3 */
3339                                                                            interface_opts.cfilter,     /* IDB_FILTER       11 */
3340                                                                            os_info_str->str,           /* IDB_OS           12 */
3341                                                                            pcap_opts->linktype,
3342                                                                            pcap_opts->snaplen,
3343                                                                            &(global_ld.bytes_written),
3344                                                                            0,                          /* IDB_IF_SPEED      8 */
3345                                                                            pcap_opts->ts_nsec ? 9 : 6, /* IDB_TSRESOL       9 */
3346                                                                            &global_ld.err);
3347                 }
3348
3349                 g_string_free(os_info_str, TRUE);
3350
3351             } else {
3352                 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3353                 successful = libpcap_write_file_header(libpcap_write_to_file, global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
3354                                                        pcap_opts->ts_nsec, &global_ld.bytes_written, &global_ld.err);
3355             }
3356             if (!successful) {
3357                 fclose(global_ld.pdh);
3358                 global_ld.pdh = NULL;
3359                 global_ld.go = FALSE;
3360                 return FALSE;
3361             }
3362             if (cnd_autostop_size)
3363                 cnd_reset(cnd_autostop_size);
3364             if (cnd_file_duration)
3365                 cnd_reset(cnd_file_duration);
3366             fflush(global_ld.pdh);
3367             if (!quiet)
3368                 report_packet_count(global_ld.inpkts_to_sync_pipe);
3369             global_ld.inpkts_to_sync_pipe = 0;
3370             report_new_capture_file(capture_opts->save_file);
3371         } else {
3372             /* File switch failed: stop here */
3373             global_ld.go = FALSE;
3374             return FALSE;
3375         }
3376     } else {
3377         /* single file, stop now */
3378         global_ld.go = FALSE;
3379         return FALSE;
3380     }
3381     return TRUE;
3382 }
3383
3384 static void *
3385 pcap_read_handler(void* arg)
3386 {
3387     pcap_options *pcap_opts;
3388     char          errmsg[MSG_MAX_LENGTH+1];
3389
3390     pcap_opts = (pcap_options *)arg;
3391
3392     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3393           pcap_opts->interface_id);
3394
3395     while (global_ld.go) {
3396         /* dispatch incoming packets */
3397         capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3398     }
3399     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3400           pcap_opts->interface_id);
3401     g_thread_exit(NULL);
3402     return (NULL);
3403 }
3404
3405 /* Do the low-level work of a capture.
3406    Returns TRUE if it succeeds, FALSE otherwise. */
3407 static gboolean
3408 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3409 {
3410 #ifdef WIN32
3411     DWORD              upd_time, cur_time; /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3412 #else
3413     struct timeval     upd_time, cur_time;
3414 #endif
3415     int                err_close;
3416     int                inpkts;
3417     condition         *cnd_file_duration     = NULL;
3418     condition         *cnd_autostop_files    = NULL;
3419     condition         *cnd_autostop_size     = NULL;
3420     condition         *cnd_autostop_duration = NULL;
3421     gboolean           write_ok;
3422     gboolean           close_ok;
3423     gboolean           cfilter_error         = FALSE;
3424     char               errmsg[MSG_MAX_LENGTH+1];
3425     char               secondary_errmsg[MSG_MAX_LENGTH+1];
3426     pcap_options      *pcap_opts;
3427     interface_options  interface_opts;
3428     guint              i, error_index        = 0;
3429
3430     *errmsg           = '\0';
3431     *secondary_errmsg = '\0';
3432
3433     /* init the loop data */
3434     global_ld.go                  = TRUE;
3435     global_ld.packet_count        = 0;
3436 #ifdef SIGINFO
3437     global_ld.report_packet_count = FALSE;
3438 #endif
3439     if (capture_opts->has_autostop_packets)
3440         global_ld.packet_max      = capture_opts->autostop_packets;
3441     else
3442         global_ld.packet_max      = 0;        /* no limit */
3443     global_ld.inpkts_to_sync_pipe = 0;
3444     global_ld.err                 = 0;  /* no error seen yet */
3445     global_ld.pdh                 = NULL;
3446     global_ld.autostop_files      = 0;
3447     global_ld.save_file_fd        = -1;
3448
3449     /* We haven't yet gotten the capture statistics. */
3450     *stats_known      = FALSE;
3451
3452     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3453     capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3454
3455     /* open the "input file" from network interface or capture pipe */
3456     if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3457                                  secondary_errmsg, sizeof(secondary_errmsg))) {
3458         goto error;
3459     }
3460     for (i = 0; i < capture_opts->ifaces->len; i++) {
3461         pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3462         interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3463         /* init the input filter from the network interface (capture pipe will do nothing) */
3464         /*
3465          * When remote capturing WinPCap crashes when the capture filter
3466          * is NULL. This might be a bug in WPCap. Therefore we provide an empty
3467          * string.
3468          */
3469         switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3470                                          interface_opts.name,
3471                                          interface_opts.cfilter?interface_opts.cfilter:"")) {
3472
3473         case INITFILTER_NO_ERROR:
3474             break;
3475
3476         case INITFILTER_BAD_FILTER:
3477             cfilter_error = TRUE;
3478             error_index = i;
3479             g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3480             goto error;
3481
3482         case INITFILTER_OTHER_ERROR:
3483             g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3484                        pcap_geterr(pcap_opts->pcap_h));
3485             g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3486             goto error;
3487         }
3488     }
3489
3490     /* If we're supposed to write to a capture file, open it for output
3491        (temporary/specified name/ringbuffer) */
3492     if (capture_opts->saving_to_file) {
3493         if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3494                                       errmsg, sizeof(errmsg))) {
3495             goto error;
3496         }
3497
3498         /* set up to write to the already-opened capture output file/files */
3499         if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3500                                       sizeof(errmsg))) {
3501             goto error;
3502         }
3503
3504         /* XXX - capture SIGTERM and close the capture, in case we're on a
3505            Linux 2.0[.x] system and you have to explicitly close the capture
3506            stream in order to turn promiscuous mode off?  We need to do that
3507            in other places as well - and I don't think that works all the
3508            time in any case, due to libpcap bugs. */
3509
3510         /* Well, we should be able to start capturing.
3511
3512            Sync out the capture file, so the header makes it to the file system,
3513            and send a "capture started successfully and capture file created"
3514            message to our parent so that they'll open the capture file and
3515            update its windows to indicate that we have a live capture in
3516            progress. */
3517         fflush(global_ld.pdh);
3518         report_new_capture_file(capture_opts->save_file);
3519     }
3520
3521     /* initialize capture stop (and alike) conditions */
3522     init_capture_stop_conditions();
3523     /* create stop conditions */
3524     if (capture_opts->has_autostop_filesize)
3525         cnd_autostop_size =
3526             cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
3527     if (capture_opts->has_autostop_duration)
3528         cnd_autostop_duration =
3529             cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3530
3531     if (capture_opts->multi_files_on) {
3532         if (capture_opts->has_file_duration)
3533             cnd_file_duration =
3534                 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3535
3536         if (capture_opts->has_autostop_files)
3537             cnd_autostop_files =
3538                 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
3539     }
3540
3541     /* init the time values */
3542 #ifdef WIN32
3543     upd_time = GetTickCount();
3544 #else
3545     gettimeofday(&upd_time, NULL);
3546 #endif
3547     start_time = create_timestamp();
3548     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
3549
3550     /* WOW, everything is prepared! */
3551     /* please fasten your seat belts, we will enter now the actual capture loop */
3552     if (use_threads) {
3553         pcap_queue = g_async_queue_new();
3554         pcap_queue_bytes = 0;
3555         pcap_queue_packets = 0;
3556         for (i = 0; i < global_ld.pcaps->len; i++) {
3557             pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3558 #if GLIB_CHECK_VERSION(2,31,0)
3559             /* XXX - Add an interface name here? */
3560             pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3561 #else
3562             pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3563 #endif
3564         }
3565     }
3566     while (global_ld.go) {
3567         /* dispatch incoming packets */
3568         if (use_threads) {
3569             pcap_queue_element *queue_element;
3570 #if GLIB_CHECK_VERSION(2,31,18)
3571
3572             g_async_queue_lock(pcap_queue);
3573             queue_element = (pcap_queue_element *)g_async_queue_timeout_pop_unlocked(pcap_queue, WRITER_THREAD_TIMEOUT);
3574 #else
3575             GTimeVal write_thread_time;
3576
3577             g_get_current_time(&write_thread_time);
3578             g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3579             g_async_queue_lock(pcap_queue);
3580             queue_element = (pcap_queue_element *)g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3581 #endif
3582             if (queue_element) {
3583                 pcap_queue_bytes -= queue_element->phdr.caplen;
3584                 pcap_queue_packets -= 1;
3585             }
3586             g_async_queue_unlock(pcap_queue);
3587             if (queue_element) {
3588                 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3589                       "Dequeued a packet of length %d captured on interface %d.",
3590                       queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3591
3592                 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3593                                              &queue_element->phdr,
3594                                              queue_element->pd);
3595                 g_free(queue_element->pd);
3596                 g_free(queue_element);
3597                 inpkts = 1;
3598             } else {
3599                 inpkts = 0;
3600             }
3601         } else {
3602             pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3603             inpkts = capture_loop_dispatch(&global_ld, errmsg,
3604                                            sizeof(errmsg), pcap_opts);
3605         }
3606 #ifdef SIGINFO
3607         /* Were we asked to print packet counts by the SIGINFO handler? */
3608         if (global_ld.report_packet_count) {
3609             fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3610                     plurality(global_ld.packet_count, "", "s"));
3611             global_ld.report_packet_count = FALSE;
3612         }
3613 #endif
3614
3615 #ifdef _WIN32
3616         /* any news from our parent (signal pipe)? -> just stop the capture */
3617         if (!signal_pipe_check_running()) {
3618             global_ld.go = FALSE;
3619         }
3620 #endif
3621
3622         if (inpkts > 0) {
3623             global_ld.inpkts_to_sync_pipe += inpkts;
3624
3625             /* check capture size condition */
3626             if (cnd_autostop_size != NULL &&
3627                 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)) {
3628                 /* Capture size limit reached, do we have another file? */
3629                 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3630                                             cnd_autostop_size, cnd_file_duration))
3631                     continue;
3632             } /* cnd_autostop_size */
3633             if (capture_opts->output_to_pipe) {
3634                 fflush(global_ld.pdh);
3635             }
3636         } /* inpkts */
3637
3638         /* Only update once every 500ms so as not to overload slow displays.
3639          * This also prevents too much context-switching between the dumpcap
3640          * and wireshark processes.
3641          */
3642 #define DUMPCAP_UPD_TIME 500
3643
3644 #ifdef WIN32
3645         cur_time = GetTickCount();  /* Note: wraps to 0 if sys runs for 49.7 days */
3646         if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3647 #else
3648         gettimeofday(&cur_time, NULL);
3649         if ((cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3650             (upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3651 #endif
3652
3653             upd_time = cur_time;
3654
3655 #if 0
3656             if (pcap_stats(pch, stats) >= 0) {
3657                 *stats_known = TRUE;
3658             }
3659 #endif
3660             /* Let the parent process know. */
3661             if (global_ld.inpkts_to_sync_pipe) {
3662                 /* do sync here */
3663                 fflush(global_ld.pdh);
3664
3665                 /* Send our parent a message saying we've written out
3666                    "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3667                 if (!quiet)
3668                     report_packet_count(global_ld.inpkts_to_sync_pipe);
3669
3670                 global_ld.inpkts_to_sync_pipe = 0;
3671             }
3672
3673             /* check capture duration condition */
3674             if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3675                 /* The maximum capture time has elapsed; stop the capture. */
3676                 global_ld.go = FALSE;
3677                 continue;
3678             }
3679
3680             /* check capture file duration condition */
3681             if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3682                 /* duration limit reached, do we have another file? */
3683                 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3684                                             cnd_autostop_size, cnd_file_duration))
3685                     continue;
3686             } /* cnd_file_duration */
3687         }
3688     }
3689
3690     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3691     if (use_threads) {
3692         pcap_queue_element *queue_element;
3693
3694         for (i = 0; i < global_ld.pcaps->len; i++) {
3695             pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3696             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3697                   pcap_opts->interface_id);
3698             g_thread_join(pcap_opts->tid);
3699             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3700                   pcap_opts->interface_id);
3701         }
3702         while (1) {
3703             g_async_queue_lock(pcap_queue);
3704             queue_element = (pcap_queue_element *)g_async_queue_try_pop_unlocked(pcap_queue);
3705             if (queue_element) {
3706                 pcap_queue_bytes -= queue_element->phdr.caplen;
3707                 pcap_queue_packets -= 1;
3708             }
3709             g_async_queue_unlock(pcap_queue);
3710             if (queue_element == NULL) {
3711                 break;
3712             }
3713             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3714                   "Dequeued a packet of length %d captured on interface %d.",
3715                   queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3716             capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3717                                          &queue_element->phdr,
3718                                          queue_element->pd);
3719             g_free(queue_element->pd);
3720             g_free(queue_element);
3721             global_ld.inpkts_to_sync_pipe += 1;
3722             if (capture_opts->output_to_pipe) {
3723                 fflush(global_ld.pdh);
3724             }
3725         }
3726     }
3727
3728
3729     /* delete stop conditions */
3730     if (cnd_file_duration != NULL)
3731         cnd_delete(cnd_file_duration);
3732     if (cnd_autostop_files != NULL)
3733         cnd_delete(cnd_autostop_files);
3734     if (cnd_autostop_size != NULL)
3735         cnd_delete(cnd_autostop_size);
3736     if (cnd_autostop_duration != NULL)
3737         cnd_delete(cnd_autostop_duration);
3738
3739     /* did we have a pcap (input) error? */
3740     for (i = 0; i < capture_opts->ifaces->len; i++) {
3741         pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3742         if (pcap_opts->pcap_err) {
3743             /* On Linux, if an interface goes down while you're capturing on it,
3744                you'll get a "recvfrom: Network is down" or
3745                "The interface went down" error (ENETDOWN).
3746                (At least you will if g_strerror() doesn't show a local translation
3747                of the error.)
3748
3749                On FreeBSD and OS X, if a network adapter disappears while
3750                you're capturing on it, you'll get a "read: Device not configured"
3751                error (ENXIO).  (See previous parenthetical note.)
3752
3753                On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3754
3755                These should *not* be reported to the Wireshark developers. */
3756             char *cap_err_str;
3757
3758             cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3759             if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3760                 strcmp(cap_err_str, "The interface went down") == 0 ||
3761                 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3762                 strcmp(cap_err_str, "read: I/O error") == 0 ||
3763                 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3764                 report_capture_error("The network adapter on which the capture was being done "
3765                                      "is no longer running; the capture has stopped.",
3766                                      "");
3767             } else {
3768                 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3769                            cap_err_str);
3770                 report_capture_error(errmsg, please_report);
3771             }
3772             break;
3773         } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3774             report_capture_error(errmsg, "");
3775             break;
3776         }
3777     }
3778     /* did we have an output error while capturing? */
3779     if (global_ld.err == 0) {
3780         write_ok = TRUE;
3781     } else {
3782         capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3783                                 global_ld.err, FALSE);
3784         report_capture_error(errmsg, please_report);
3785         write_ok = FALSE;
3786     }
3787
3788     if (capture_opts->saving_to_file) {
3789         /* close the output file */
3790         close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3791     } else
3792         close_ok = TRUE;
3793
3794     /* there might be packets not yet notified to the parent */
3795     /* (do this after closing the file, so all packets are already flushed) */
3796     if (global_ld.inpkts_to_sync_pipe) {
3797         if (!quiet)
3798             report_packet_count(global_ld.inpkts_to_sync_pipe);
3799         global_ld.inpkts_to_sync_pipe = 0;
3800     }
3801
3802     /* If we've displayed a message about a write error, there's no point
3803        in displaying another message about an error on close. */
3804     if (!close_ok && write_ok) {
3805         capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3806                                 TRUE);
3807         report_capture_error(errmsg, "");
3808     }
3809
3810     /*
3811      * XXX We exhibit different behaviour between normal mode and sync mode
3812      * when the pipe is stdin and not already at EOF.  If we're a child, the
3813      * parent's stdin isn't closed, so if the user starts another capture,
3814      * cap_pipe_open_live() will very likely not see the expected magic bytes and
3815      * will say "Unrecognized libpcap format".  On the other hand, in normal
3816      * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3817      */
3818
3819     report_capture_count(TRUE);
3820
3821     /* get packet drop statistics from pcap */
3822     for (i = 0; i < capture_opts->ifaces->len; i++) {
3823         guint32 received;
3824         guint32 pcap_dropped = 0;
3825
3826         pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3827         interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3828         received = pcap_opts->received;
3829         if (pcap_opts->pcap_h != NULL) {
3830             g_assert(!pcap_opts->from_cap_pipe);
3831             /* Get the capture statistics, so we know how many packets were dropped. */
3832             if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3833                 *stats_known = TRUE;
3834                 /* Let the parent process know. */
3835                 pcap_dropped += stats->ps_drop;
3836             } else {
3837                 g_snprintf(errmsg, sizeof(errmsg),
3838                            "Can't get packet-drop statistics: %s",
3839                            pcap_geterr(pcap_opts->pcap_h));
3840                 report_capture_error(errmsg, please_report);
3841             }
3842         }
3843         report_packet_drops(received, pcap_dropped, pcap_opts->dropped, pcap_opts->flushed, interface_opts.console_display_name);
3844     }
3845
3846     /* close the input file (pcap or capture pipe) */
3847     capture_loop_close_input(&global_ld);
3848
3849     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
3850
3851     /* ok, if the write and the close were successful. */
3852     return write_ok && close_ok;
3853
3854 error:
3855     if (capture_opts->multi_files_on) {
3856         /* cleanup ringbuffer */
3857         ringbuf_error_cleanup();
3858     } else {
3859         /* We can't use the save file, and we have no FILE * for the stream
3860            to close in order to close it, so close the FD directly. */
3861         if (global_ld.save_file_fd != -1) {
3862             ws_close(global_ld.save_file_fd);
3863         }
3864
3865         /* We couldn't even start the capture, so get rid of the capture
3866            file. */
3867         if (capture_opts->save_file != NULL) {
3868             ws_unlink(capture_opts->save_file);
3869             g_free(capture_opts->save_file);
3870         }
3871     }
3872     capture_opts->save_file = NULL;
3873     if (cfilter_error)
3874         report_cfilter_error(capture_opts, error_index, errmsg);
3875     else
3876         report_capture_error(errmsg, secondary_errmsg);
3877
3878     /* close the input file (pcap or cap_pipe) */
3879     capture_loop_close_input(&global_ld);
3880
3881     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3882
3883     return FALSE;
3884 }
3885
3886
3887 static void
3888 capture_loop_stop(void)
3889 {
3890 #ifdef HAVE_PCAP_BREAKLOOP
3891     guint         i;
3892     pcap_options *pcap_opts;
3893
3894     for (i = 0; i < global_ld.pcaps->len; i++) {
3895         pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3896         if (pcap_opts->pcap_h != NULL)
3897             pcap_breakloop(pcap_opts->pcap_h);
3898     }
3899 #endif
3900     global_ld.go = FALSE;
3901 }
3902
3903
3904 static void
3905 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3906                         int err, gboolean is_close)
3907 {
3908     switch (err) {
3909
3910     case ENOSPC:
3911         g_snprintf(errmsg, errmsglen,
3912                    "Not all the packets could be written to the file"
3913                    " to which the capture was being saved\n"
3914                    "(\"%s\") because there is no space left on the file system\n"
3915                    "on which that file resides.",
3916                    fname);
3917         break;
3918
3919 #ifdef EDQUOT
3920     case EDQUOT:
3921         g_snprintf(errmsg, errmsglen,
3922                    "Not all the packets could be written to the file"
3923                    " to which the capture was being saved\n"
3924                    "(\"%s\") because you are too close to, or over,"
3925                    " your disk quota\n"
3926                    "on the file system on which that file resides.",
3927                    fname);
3928         break;
3929 #endif
3930
3931     default:
3932         if (is_close) {
3933             g_snprintf(errmsg, errmsglen,
3934                        "The file to which the capture was being saved\n"
3935                        "(\"%s\") could not be closed: %s.",
3936                        fname, g_strerror(err));
3937         } else {
3938             g_snprintf(errmsg, errmsglen,
3939                        "An error occurred while writing to the file"
3940                        " to which the capture was being saved\n"
3941                        "(\"%s\"): %s.",
3942                        fname, g_strerror(err));
3943         }
3944         break;
3945     }
3946 }
3947
3948
3949 /* one packet was captured, process it */
3950 static void
3951 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3952                              const u_char *pd)
3953 {
3954     pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3955     int           err;
3956     guint         ts_mul    = pcap_opts->ts_nsec ? 1000000000 : 1000000;
3957
3958     /* We may be called multiple times from pcap_dispatch(); if we've set
3959        the "stop capturing" flag, ignore this packet, as we're not
3960        supposed to be saving any more packets. */
3961     if (!global_ld.go) {
3962         pcap_opts->flushed++;
3963         return;
3964     }
3965
3966     if (global_ld.pdh) {
3967         gboolean successful;
3968
3969         /* We're supposed to write the packet to a file; do so.
3970            If this fails, set "ld->go" to FALSE, to stop the capture, and set
3971            "ld->err" to the error. */
3972         if (global_capture_opts.use_pcapng) {
3973             successful = libpcap_write_enhanced_packet_block(libpcap_write_to_file, global_ld.pdh,
3974                                                              NULL,
3975                                                              phdr->ts.tv_sec, phdr->ts.tv_usec,
3976                                                              phdr->caplen, phdr->len,
3977                                                              pcap_opts->interface_id,
3978                                                              ts_mul,
3979                                                              pd, 0,
3980                                                              &global_ld.bytes_written, &err);
3981         } else {
3982             successful = libpcap_write_packet(libpcap_write_to_file, global_ld.pdh,
3983                                               phdr->ts.tv_sec, phdr->ts.tv_usec,
3984                                               phdr->caplen, phdr->len,
3985                                               pd,
3986                                               &global_ld.bytes_written, &err);
3987         }
3988         if (!successful) {
3989             global_ld.go = FALSE;
3990             global_ld.err = err;
3991             pcap_opts->dropped++;
3992         } else {
3993             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3994                   "Wrote a packet of length %d captured on interface %u.",
3995                    phdr->caplen, pcap_opts->interface_id);
3996             global_ld.packet_count++;
3997             pcap_opts->received++;
3998             /* if the user told us to stop after x packets, do we already have enough? */
3999             if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
4000                 global_ld.go = FALSE;
4001             }
4002         }
4003     }
4004 }
4005
4006 /* one packet was captured, queue it */
4007 static void
4008 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
4009                              const u_char *pd)
4010 {
4011     pcap_options       *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
4012     pcap_queue_element *queue_element;
4013     gboolean            limit_reached;
4014
4015     /* We may be called multiple times from pcap_dispatch(); if we've set
4016        the "stop capturing" flag, ignore this packet, as we're not
4017        supposed to be saving any more packets. */
4018     if (!global_ld.go) {
4019         pcap_opts->flushed++;
4020         return;
4021     }
4022
4023     queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
4024     if (queue_element == NULL) {
4025        pcap_opts->dropped++;
4026        return;
4027     }
4028     queue_element->pcap_opts = pcap_opts;
4029     queue_element->phdr = *phdr;
4030     queue_element->pd = (u_char *)g_malloc(phdr->caplen);
4031     if (queue_element->pd == NULL) {
4032         pcap_opts->dropped++;
4033         g_free(queue_element);
4034         return;
4035     }
4036     memcpy(queue_element->pd, pd, phdr->caplen);
4037     g_async_queue_lock(pcap_queue);
4038     if (((pcap_queue_byte_limit == 0) || (pcap_queue_bytes < pcap_queue_byte_limit)) &&
4039         ((pcap_queue_packet_limit == 0) || (pcap_queue_packets < pcap_queue_packet_limit))) {
4040         limit_reached = FALSE;
4041         g_async_queue_push_unlocked(pcap_queue, queue_element);
4042         pcap_queue_bytes += phdr->caplen;
4043         pcap_queue_packets += 1;
4044     } else {
4045         limit_reached = TRUE;
4046     }
4047     g_async_queue_unlock(pcap_queue);
4048     if (limit_reached) {
4049         pcap_opts->dropped++;
4050         g_free(queue_element->pd);
4051         g_free(queue_element);
4052         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4053               "Dropped a packet of length %d captured on interface %u.",
4054               phdr->caplen, pcap_opts->interface_id);
4055     } else {
4056         pcap_opts->received++;
4057         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4058               "Queued a packet of length %d captured on interface %u.",
4059               phdr->caplen, pcap_opts->interface_id);
4060     }
4061     /* I don't want to hold the mutex over the debug output. So the
4062        output may be wrong */
4063     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4064           "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
4065           pcap_queue_bytes, pcap_queue_packets);
4066 }
4067
4068 static int
4069 set_80211_channel(const char *iface, const char *opt)
4070 {
4071     int     freq    = 0, type, ret;
4072     gchar **options = NULL;
4073
4074     options = g_strsplit_set(opt, ",", 2);
4075
4076     if (options[0])
4077         freq = atoi(options[0]);
4078
4079     if (options[1]) {
4080         type = ws80211_str_to_chan_type(options[1]);
4081         if (type == -1) {
4082             ret = EINVAL;
4083             goto out;
4084         }
4085     }
4086     else
4087         type = -1;
4088
4089     ret = ws80211_init();
4090     if (ret) {
4091         cmdarg_err("%d: Failed to init ws80211: %s\n", abs(ret), g_strerror(abs(ret)));
4092         ret = 2;
4093         goto out;
4094     }
4095     ret = ws80211_set_freq(iface, freq, type);
4096
4097     if (ret) {
4098         cmdarg_err("%d: Failed to set channel: %s\n", abs(ret), g_strerror(abs(ret)));
4099         ret = 2;
4100         goto out;
4101     }
4102
4103     if (capture_child)
4104         pipe_write_block(2, SP_SUCCESS, NULL);
4105     ret = 0;
4106
4107 out:
4108     g_strfreev(options);
4109     return ret;
4110 }
4111
4112 /* And now our feature presentation... [ fade to music ] */
4113 int
4114 main(int argc, char *argv[])
4115 {
4116     GString          *comp_info_str;
4117     GString          *runtime_info_str;
4118     int               opt;
4119     gboolean          arg_error             = FALSE;
4120
4121 #ifdef _WIN32
4122     WSADATA           wsaData;
4123 #else
4124     struct sigaction  action, oldaction;
4125 #endif
4126
4127     gboolean          start_capture         = TRUE;
4128     gboolean          stats_known;
4129     struct pcap_stat  stats;
4130     GLogLevelFlags    log_flags;
4131     gboolean          list_interfaces       = FALSE;
4132     gboolean          list_link_layer_types = FALSE;
4133 #ifdef HAVE_BPF_IMAGE
4134     gboolean          print_bpf_code        = FALSE;
4135 #endif
4136     gboolean          set_chan              = FALSE;
4137     gchar            *set_chan_arg          = NULL;
4138     gboolean          machine_readable      = FALSE;
4139     gboolean          print_statistics      = FALSE;
4140     int               status, run_once_args = 0;
4141     gint              i;
4142     guint             j;
4143 #if defined(__APPLE__) && defined(__LP64__)
4144     struct utsname    osinfo;
4145 #endif
4146     GString          *str;
4147
4148     /* Assemble the compile-time version information string */
4149     comp_info_str = g_string_new("Compiled ");
4150     get_compiled_version_info(comp_info_str, NULL, NULL);
4151
4152     /* Assemble the run-time version information string */
4153     runtime_info_str = g_string_new("Running ");
4154     get_runtime_version_info(runtime_info_str, NULL);
4155
4156     /* Add it to the information to be reported on a crash. */
4157     ws_add_crash_info("Dumpcap " VERSION "%s\n"
4158            "\n"
4159            "%s"
4160            "\n"
4161            "%s",
4162         wireshark_svnversion, comp_info_str->str, runtime_info_str->str);
4163
4164 #ifdef _WIN32
4165     arg_list_utf_16to8(argc, argv);
4166     create_app_running_mutex();
4167
4168     /*
4169      * Initialize our DLL search path. MUST be called before LoadLibrary
4170      * or g_module_open.
4171      */
4172     ws_init_dll_search_path();
4173 #endif
4174
4175 #ifdef HAVE_PCAP_REMOTE
4176 #define OPTSTRING_A "A:"
4177 #define OPTSTRING_r "r"
4178 #define OPTSTRING_u "u"
4179 #else
4180 #define OPTSTRING_A ""
4181 #define OPTSTRING_r ""
4182 #define OPTSTRING_u ""
4183 #endif
4184
4185 #ifdef HAVE_PCAP_SETSAMPLING
4186 #define OPTSTRING_m "m:"
4187 #else
4188 #define OPTSTRING_m ""
4189 #endif
4190
4191 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4192 #define OPTSTRING_B "B:"
4193 #else
4194 #define OPTSTRING_B ""
4195 #endif  /* _WIN32 or HAVE_PCAP_CREATE */
4196
4197 #ifdef HAVE_PCAP_CREATE
4198 #define OPTSTRING_I "I"
4199 #else
4200 #define OPTSTRING_I ""
4201 #endif
4202
4203 #ifdef HAVE_BPF_IMAGE
4204 #define OPTSTRING_d "d"
4205 #else
4206 #define OPTSTRING_d ""
4207 #endif
4208
4209 #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:"
4210
4211 #ifdef DEBUG_CHILD_DUMPCAP
4212     if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
4213         fprintf (stderr, "Unable to open debug log file !\n");
4214         exit (1);
4215     }
4216 #endif
4217
4218 #if defined(__APPLE__) && defined(__LP64__)
4219     /*
4220      * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4?  If so, we need
4221      * a bug workaround - timeouts less than 1 second don't work with libpcap
4222      * in 64-bit code.  (The bug was introduced in 10.6, fixed in 10.6.2,
4223      * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
4224      * The problem is extremely unlikely to be reintroduced in a future
4225      * release.)
4226      */
4227     if (uname(&osinfo) == 0) {
4228         /*
4229          * Mac OS X 10.x uses Darwin {x+4}.0.0.  Mac OS X 10.x.y uses Darwin
4230          * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
4231          * number of 10.0.0, not 10.1.0 - go figure).
4232          */
4233         if (strcmp(osinfo.release, "10.0.0") == 0 ||    /* 10.6, 10.6.1 */
4234             strcmp(osinfo.release, "10.3.0") == 0 ||    /* 10.6.3 */
4235             strcmp(osinfo.release, "10.4.0") == 0)              /* 10.6.4 */
4236             need_timeout_workaround = TRUE;
4237     }
4238 #endif
4239
4240     /*
4241      * Determine if dumpcap is being requested to run in a special
4242      * capture_child mode by going thru the command line args to see if
4243      * a -Z is present. (-Z is a hidden option).
4244      *
4245      * The primary result of running in capture_child mode is that
4246      * all messages sent out on stderr are in a special type/len/string
4247      * format to allow message processing by type.  These messages include
4248      * error messages if dumpcap fails to start the operation it was
4249      * requested to do, as well as various "status" messages which are sent
4250      * when an actual capture is in progress, and a "success" message sent
4251      * if dumpcap was requested to perform an operation other than a
4252      * capture.
4253      *
4254      * Capture_child mode would normally be requested by a parent process
4255      * which invokes dumpcap and obtains dumpcap stderr output via a pipe
4256      * to which dumpcap stderr has been redirected.  It might also have
4257      * another pipe to obtain dumpcap stdout output; for operations other
4258      * than a capture, that information is formatted specially for easier
4259      * parsing by the parent process.
4260      *
4261      * Capture_child mode needs to be determined immediately upon
4262      * startup so that any messages generated by dumpcap in this mode
4263      * (eg: during initialization) will be formatted properly.
4264      */
4265
4266     for (i=1; i<argc; i++) {
4267         if (strcmp("-Z", argv[i]) == 0) {
4268             capture_child    = TRUE;
4269             machine_readable = TRUE;  /* request machine-readable output */
4270 #ifdef _WIN32
4271             /* set output pipe to binary mode, to avoid ugly text conversions */
4272             _setmode(2, O_BINARY);
4273 #endif
4274         }
4275     }
4276
4277     /* The default_log_handler will use stdout, which makes trouble in   */
4278     /* capture child mode, as it uses stdout for its sync_pipe.          */
4279     /* So: the filtering is done in the console_log_handler and not here.*/
4280     /* We set the log handlers right up front to make sure that any log  */
4281     /* messages when running as child will be sent back to the parent    */
4282     /* with the correct format.                                          */
4283
4284     log_flags =
4285         (GLogLevelFlags)(
4286         G_LOG_LEVEL_ERROR|
4287         G_LOG_LEVEL_CRITICAL|
4288         G_LOG_LEVEL_WARNING|
4289         G_LOG_LEVEL_MESSAGE|
4290         G_LOG_LEVEL_INFO|
4291         G_LOG_LEVEL_DEBUG|
4292         G_LOG_FLAG_FATAL|
4293         G_LOG_FLAG_RECURSION);
4294
4295     g_log_set_handler(NULL,
4296                       log_flags,
4297                       console_log_handler, NULL /* user_data */);
4298     g_log_set_handler(LOG_DOMAIN_MAIN,
4299                       log_flags,
4300                       console_log_handler, NULL /* user_data */);
4301     g_log_set_handler(LOG_DOMAIN_CAPTURE,
4302                       log_flags,
4303                       console_log_handler, NULL /* user_data */);
4304     g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
4305                       log_flags,
4306                       console_log_handler, NULL /* user_data */);
4307
4308     /* Initialize the pcaps list */
4309     global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
4310
4311 #if !GLIB_CHECK_VERSION(2,31,0)
4312     /* Initialize the thread system */
4313     g_thread_init(NULL);
4314 #endif
4315
4316 #ifdef _WIN32
4317     /* Load wpcap if possible. Do this before collecting the run-time version information */
4318     load_wpcap();
4319
4320     /* ... and also load the packet.dll from wpcap */
4321     /* XXX - currently not required, may change later. */
4322     /*wpcap_packet_load();*/
4323
4324     /* Start windows sockets */
4325     WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
4326
4327     /* Set handler for Ctrl+C key */
4328     SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
4329 #else
4330     /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
4331        and exit.  Do the same with SIGPIPE, in case, for example,
4332        we're writing to our standard output and it's a pipe.
4333        Do the same with SIGHUP if it's not being ignored (if we're
4334        being run under nohup, it might be ignored, in which case we
4335        should leave it ignored).
4336
4337        XXX - apparently, Coverity complained that part of action
4338        wasn't initialized.  Perhaps it's running on Linux, where
4339        struct sigaction has an ignored "sa_restorer" element and
4340        where "sa_handler" and "sa_sigaction" might not be two
4341        members of a union. */
4342     memset(&action, 0, sizeof(action));
4343     action.sa_handler = capture_cleanup_handler;
4344     /*
4345      * Arrange that system calls not get restarted, because when
4346      * our signal handler returns we don't want to restart
4347      * a call that was waiting for packets to arrive.
4348      */
4349     action.sa_flags = 0;
4350     sigemptyset(&action.sa_mask);
4351     sigaction(SIGTERM, &action, NULL);
4352     sigaction(SIGINT, &action, NULL);
4353     sigaction(SIGPIPE, &action, NULL);
4354     sigaction(SIGHUP, NULL, &oldaction);
4355     if (oldaction.sa_handler == SIG_DFL)
4356         sigaction(SIGHUP, &action, NULL);
4357
4358 #ifdef SIGINFO
4359     /* Catch SIGINFO and, if we get it and we're capturing in
4360        quiet mode, report the number of packets we've captured. */
4361     action.sa_handler = report_counts_siginfo;
4362     action.sa_flags = SA_RESTART;
4363     sigemptyset(&action.sa_mask);
4364     sigaction(SIGINFO, &action, NULL);
4365 #endif /* SIGINFO */
4366 #endif  /* _WIN32 */
4367
4368     /* ----------------------------------------------------------------- */
4369     /* Privilege and capability handling                                 */
4370     /* Cases:                                                            */
4371     /* 1. Running not as root or suid root; no special capabilities.     */
4372     /*    Action: none                                                   */
4373     /*                                                                   */
4374     /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap.  */
4375     /*    Action: none                                                   */
4376     /*                                                                   */
4377     /* 3. Running logged in as root (euid=0; ruid=0). Using libcap.      */
4378     /*    Action:                                                        */
4379     /*      - Near start of program: Enable NET_RAW and NET_ADMIN        */
4380     /*        capabilities; Drop all other capabilities;                 */
4381     /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
4382     /*        else: after  pcap_open_live() in capture_loop_open_input() */
4383     /*         drop all capabilities (NET_RAW and NET_ADMIN);            */
4384     /*         (Note: this means that the process, although logged in    */
4385     /*          as root, does not have various permissions such as the   */
4386     /*          ability to bypass file access permissions).              */
4387     /*      XXX: Should we just leave capabilities alone in this case    */
4388     /*          so that user gets expected effect that root can do       */
4389     /*          anything ??                                              */
4390     /*                                                                   */
4391     /* 4. Running as suid root (euid=0, ruid=n); Not using libcap.       */
4392     /*    Action:                                                        */
4393     /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
4394     /*        else: after  pcap_open_live() in capture_loop_open_input() */
4395     /*         drop suid root (set euid=ruid).(ie: keep suid until after */
4396     /*         pcap_open_live).                                          */
4397     /*                                                                   */
4398     /* 5. Running as suid root (euid=0, ruid=n); Using libcap.           */
4399     /*    Action:                                                        */
4400     /*      - Near start of program: Enable NET_RAW and NET_ADMIN        */
4401     /*        capabilities; Drop all other capabilities;                 */
4402     /*        Drop suid privileges (euid=ruid);                          */
4403     /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
4404     /*        else: after  pcap_open_live() in capture_loop_open_input() */
4405     /*         drop all capabilities (NET_RAW and NET_ADMIN).            */
4406     /*                                                                   */
4407     /*      XXX: For some Linux versions/distros with capabilities       */
4408     /*        a 'normal' process with any capabilities cannot be         */
4409     /*        'killed' (signaled) from another (same uid) non-privileged */
4410     /*        process.                                                   */
4411     /*        For example: If (non-suid) Wireshark forks a               */
4412     /*        child suid dumpcap which acts as described here (case 5),  */
4413     /*        Wireshark will be unable to kill (signal) the child        */
4414     /*        dumpcap process until the capabilities have been dropped   */
4415     /*        (after pcap_open_live()).                                  */
4416     /*        This behaviour will apparently be changed in the kernel    */
4417     /*        to allow the kill (signal) in this case.                   */
4418     /*        See the following for details:                             */
4419     /*           http://www.mail-archive.com/  [wrapped]                 */
4420     /*             linux-security-module@vger.kernel.org/msg02913.html   */
4421     /*                                                                   */
4422     /*        It is therefore conceivable that if dumpcap somehow hangs  */
4423     /*        in pcap_open_live or before that wireshark will not        */
4424     /*        be able to stop dumpcap using a signal (INT, TERM, etc).   */
4425     /*        In this case, exiting wireshark will kill the child        */
4426     /*        dumpcap process.                                           */
4427     /*                                                                   */
4428     /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN        */
4429     /*     capabilities; Using libcap.  Note: capset cmd (which see)     */
4430     /*     used to assign capabilities to file.                          */
4431     /*    Action:                                                        */
4432     /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
4433     /*        else: after  pcap_open_live() in capture_loop_open_input() */
4434     /*         drop all capabilities (NET_RAW and NET_ADMIN)             */
4435     /*                                                                   */
4436     /* ToDo: -S (stats) should drop privileges/capabilities when no      */
4437     /*       longer required (similar to capture).                       */
4438     /*                                                                   */
4439     /* ----------------------------------------------------------------- */
4440
4441     init_process_policies();
4442
4443 #ifdef HAVE_LIBCAP
4444     /* If 'started with special privileges' (and using libcap)  */
4445     /*   Set to keep only NET_RAW and NET_ADMIN capabilities;   */
4446     /*   Set euid/egid = ruid/rgid to remove suid privileges    */
4447     relinquish_privs_except_capture();
4448 #endif
4449
4450     /* Set the initial values in the capture options. This might be overwritten
4451        by the command line parameters. */
4452     capture_opts_init(&global_capture_opts, NULL);
4453
4454     /* We always save to a file - if no file was specified, we save to a
4455        temporary file. */
4456     global_capture_opts.saving_to_file      = TRUE;
4457     global_capture_opts.has_ring_num_files  = TRUE;
4458
4459     /* Now get our args */
4460     while ((opt = getopt(argc, argv, OPTSTRING)) != -1) {
4461         switch (opt) {
4462         case 'h':        /* Print help and exit */
4463             print_usage(TRUE);
4464             exit_main(0);
4465             break;
4466         case 'v':        /* Show version and exit */
4467         {
4468             show_version(comp_info_str, runtime_info_str);
4469             g_string_free(comp_info_str, TRUE);
4470             g_string_free(runtime_info_str, TRUE);
4471             exit_main(0);
4472             break;
4473         }
4474         /*** capture option specific ***/
4475         case 'a':        /* autostop criteria */
4476         case 'b':        /* Ringbuffer option */
4477         case 'c':        /* Capture x packets */
4478         case 'f':        /* capture filter */
4479         case 'g':        /* enable group read access on file(s) */
4480         case 'i':        /* Use interface x */
4481         case 'n':        /* Use pcapng format */
4482         case 'p':        /* Don't capture in promiscuous mode */
4483         case 'P':        /* Use pcap format */
4484         case 's':        /* Set the snapshot (capture) length */
4485         case 'w':        /* Write to capture file x */
4486         case 'y':        /* Set the pcap data link type */
4487 #ifdef HAVE_PCAP_REMOTE
4488         case 'u':        /* Use UDP for data transfer */
4489         case 'r':        /* Capture own RPCAP traffic too */
4490         case 'A':        /* Authentication */
4491 #endif
4492 #ifdef HAVE_PCAP_SETSAMPLING
4493         case 'm':        /* Sampling */
4494 #endif
4495 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4496         case 'B':        /* Buffer size */
4497 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4498 #ifdef HAVE_PCAP_CREATE
4499         case 'I':        /* Monitor mode */
4500 #endif
4501             status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4502             if (status != 0) {
4503                 exit_main(status);
4504             }
4505             break;
4506             /*** hidden option: Wireshark child mode (using binary output messages) ***/
4507         case 'Z':
4508             capture_child = TRUE;
4509 #ifdef _WIN32
4510             /* set output pipe to binary mode, to avoid ugly text conversions */
4511             _setmode(2, O_BINARY);
4512             /*
4513              * optarg = the control ID, aka the PPID, currently used for the
4514              * signal pipe name.
4515              */
4516             if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4517                 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4518                 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4519                                              GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4520
4521                 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4522                     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4523                           "Signal pipe: Unable to open %s.  Dead parent?",
4524                           sig_pipe_name);
4525                     exit_main(1);
4526                 }
4527             }
4528 #endif
4529             break;
4530
4531         case 'q':        /* Quiet */
4532             quiet = TRUE;
4533             break;
4534         case 't':
4535             use_threads = TRUE;
4536             break;
4537             /*** all non capture option specific ***/
4538         case 'D':        /* Print a list of capture devices and exit */
4539             list_interfaces = TRUE;
4540             run_once_args++;
4541             break;
4542         case 'L':        /* Print list of link-layer types and exit */
4543             list_link_layer_types = TRUE;
4544             run_once_args++;
4545             break;
4546 #ifdef HAVE_BPF_IMAGE
4547         case 'd':        /* Print BPF code for capture filter and exit */
4548             print_bpf_code = TRUE;
4549             run_once_args++;
4550             break;
4551 #endif
4552         case 'S':        /* Print interface statistics once a second */
4553             print_statistics = TRUE;
4554             run_once_args++;
4555             break;
4556         case 'k':        /* Set wireless channel */
4557             set_chan = TRUE;
4558             set_chan_arg = optarg;
4559             run_once_args++;
4560            break;
4561         case 'M':        /* For -D, -L, and -S, print machine-readable output */
4562             machine_readable = TRUE;
4563             break;
4564         case 'C':
4565             pcap_queue_byte_limit = get_positive_int(optarg, "byte_limit");
4566             break;
4567         case 'N':
4568             pcap_queue_packet_limit = get_positive_int(optarg, "packet_limit");
4569             break;
4570         default:
4571             cmdarg_err("Invalid Option: %s", argv[optind-1]);
4572             /* FALLTHROUGH */
4573         case '?':        /* Bad flag - print usage message */
4574             arg_error = TRUE;
4575             break;
4576         }
4577     }
4578     if (!arg_error) {
4579         argc -= optind;
4580         argv += optind;
4581         if (argc >= 1) {
4582             /* user specified file name as regular command-line argument */
4583             /* XXX - use it as the capture file name (or something else)? */
4584             argc--;
4585             argv++;
4586         }
4587         if (argc != 0) {
4588             /*
4589              * Extra command line arguments were specified; complain.
4590              * XXX - interpret as capture filter, as tcpdump and tshark do?
4591              */
4592             cmdarg_err("Invalid argument: %s", argv[0]);
4593             arg_error = TRUE;
4594         }
4595     }
4596
4597     if ((pcap_queue_byte_limit > 0) || (pcap_queue_packet_limit > 0)) {
4598         use_threads = TRUE;
4599     }
4600     if ((pcap_queue_byte_limit == 0) && (pcap_queue_packet_limit == 0)) {
4601         /* Use some default if the user hasn't specified some */
4602         /* XXX: Are these defaults good enough? */
4603         pcap_queue_byte_limit = 1000 * 1000;
4604         pcap_queue_packet_limit = 1000;
4605     }
4606     if (arg_error) {
4607         print_usage(FALSE);
4608         exit_main(1);
4609     }
4610
4611     if (run_once_args > 1) {
4612         cmdarg_err("Only one of -D, -L, or -S may be supplied.");
4613         exit_main(1);
4614     } else if (run_once_args == 1) {
4615         /* We're supposed to print some information, rather than
4616            to capture traffic; did they specify a ring buffer option? */
4617         if (global_capture_opts.multi_files_on) {
4618             cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4619             exit_main(1);
4620         }
4621     } else {
4622         /* We're supposed to capture traffic; */
4623         /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4624         if (global_capture_opts.ifaces->len > 1) {
4625             use_threads = TRUE;
4626             global_capture_opts.use_pcapng = TRUE;
4627         }
4628         /* Was the ring buffer option specified and, if so, does it make sense? */
4629         if (global_capture_opts.multi_files_on) {
4630             /* Ring buffer works only under certain conditions:
4631                a) ring buffer does not work with temporary files;
4632                b) it makes no sense to enable the ring buffer if the maximum
4633                file size is set to "infinite". */
4634             if (global_capture_opts.save_file == NULL) {
4635                 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4636                 global_capture_opts.multi_files_on = FALSE;
4637             }
4638             if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4639                 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4640 #if 0
4641                 /* XXX - this must be redesigned as the conditions changed */
4642                 global_capture_opts.multi_files_on = FALSE;
4643 #endif
4644             }
4645         }
4646     }
4647
4648     /*
4649      * "-D" requires no interface to be selected; it's supposed to list
4650      * all interfaces.
4651      */
4652     if (list_interfaces) {
4653         /* Get the list of interfaces */
4654         GList *if_list;
4655         int    err;
4656         gchar *err_str;
4657
4658         if_list = capture_interface_list(&err, &err_str);
4659         if (if_list == NULL) {
4660             switch (err) {
4661             case CANT_GET_INTERFACE_LIST:
4662             case DONT_HAVE_PCAP:
4663                 cmdarg_err("%s", err_str);
4664                 g_free(err_str);
4665                 exit_main(2);
4666                 break;
4667
4668             case NO_INTERFACES_FOUND:
4669                 /*
4670                  * If we're being run by another program, just give them
4671                  * an empty list of interfaces, don't report this as
4672                  * an error; that lets them decide whether to report
4673                  * this as an error or not.
4674                  */
4675                 if (!machine_readable) {
4676                     cmdarg_err("There are no interfaces on which a capture can be done");
4677                     exit_main(2);
4678                 }
4679                 break;
4680             }
4681         }
4682
4683         if (machine_readable)      /* tab-separated values to stdout */
4684             print_machine_readable_interfaces(if_list);
4685         else
4686             capture_opts_print_interfaces(if_list);
4687         free_interface_list(if_list);
4688         exit_main(0);
4689     }
4690
4691     /*
4692      * "-S" requires no interface to be selected; it gives statistics
4693      * for all interfaces.
4694      */
4695     if (print_statistics) {
4696         status = print_statistics_loop(machine_readable);
4697         exit_main(status);
4698     }
4699
4700     if (set_chan) {
4701         interface_options interface_opts;
4702
4703         if (global_capture_opts.ifaces->len != 1) {
4704             cmdarg_err("Need one interface");
4705             exit_main(2);
4706         }
4707
4708         interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, 0);
4709         status = set_80211_channel(interface_opts.name, set_chan_arg);
4710         exit_main(status);
4711     }
4712
4713     /*
4714      * "-L", "-d", and capturing act on a particular interface, so we have to
4715      * have an interface; if none was specified, pick a default.
4716      */
4717     status = capture_opts_trim_iface(&global_capture_opts, NULL);
4718     if (status != 0) {
4719         /* cmdarg_err() already called .... */
4720         exit_main(status);
4721     }
4722
4723     /* Let the user know what interfaces were chosen. */
4724     if (capture_child) {
4725         for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4726             interface_options interface_opts;
4727
4728             interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4729             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4730                   interface_opts.name);
4731         }
4732     } else {
4733         str = g_string_new("");
4734 #ifdef _WIN32
4735         if (global_capture_opts.ifaces->len < 2)
4736 #else
4737         if (global_capture_opts.ifaces->len < 4)
4738 #endif
4739         {
4740             for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4741                 interface_options interface_opts;
4742
4743                 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4744                 if (j > 0) {
4745                     if (global_capture_opts.ifaces->len > 2) {
4746                         g_string_append_printf(str, ",");
4747                     }
4748                     g_string_append_printf(str, " ");
4749                     if (j == global_capture_opts.ifaces->len - 1) {
4750                         g_string_append_printf(str, "and ");
4751                     }
4752                 }
4753                 g_string_append_printf(str, "'%s'", interface_opts.console_display_name);
4754             }
4755         } else {
4756             g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4757         }
4758         fprintf(stderr, "Capturing on %s\n", str->str);
4759         g_string_free(str, TRUE);
4760     }
4761
4762     if (list_link_layer_types) {
4763         /* Get the list of link-layer types for the capture device. */
4764         if_capabilities_t *caps;
4765         gchar *err_str;
4766         guint  ii;
4767
4768         for (ii = 0; ii < global_capture_opts.ifaces->len; ii++) {
4769             interface_options interface_opts;
4770
4771             interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, ii);
4772             caps = get_if_capabilities(interface_opts.name,
4773                                        interface_opts.monitor_mode, &err_str);
4774             if (caps == NULL) {
4775                 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4776                            "Please check to make sure you have sufficient permissions, and that\n"
4777                            "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4778                 g_free(err_str);
4779                 exit_main(2);
4780             }
4781             if (caps->data_link_types == NULL) {
4782                 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4783                 exit_main(2);
4784             }
4785             if (machine_readable)      /* tab-separated values to stdout */
4786                 /* XXX: We need to change the format and adopt consumers */
4787                 print_machine_readable_if_capabilities(caps);
4788             else
4789                 /* XXX: We might want to print also the interface name */
4790                 capture_opts_print_if_capabilities(caps, interface_opts.name,
4791                                                    interface_opts.monitor_mode);
4792             free_if_capabilities(caps);
4793         }
4794         exit_main(0);
4795     }
4796
4797     /* We're supposed to do a capture, or print the BPF code for a filter.
4798        Process the snapshot length, as that affects the generated BPF code. */
4799     capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4800
4801 #ifdef HAVE_BPF_IMAGE
4802     if (print_bpf_code) {
4803         show_filter_code(&global_capture_opts);
4804         exit_main(0);
4805     }
4806 #endif
4807
4808     /* We're supposed to do a capture.  Process the ring buffer arguments. */
4809     capture_opts_trim_ring_num_files(&global_capture_opts);
4810
4811     /* flush stderr prior to starting the main capture loop */
4812     fflush(stderr);
4813
4814     /* Now start the capture. */
4815
4816     if (capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4817         /* capture ok */
4818         exit_main(0);
4819     } else {
4820         /* capture failed */
4821         exit_main(1);
4822     }
4823     return 0; /* never here, make compiler happy */
4824 }
4825
4826
4827 static void
4828 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4829                     const char *message, gpointer user_data _U_)
4830 {
4831     time_t      curr;
4832     struct tm  *today;
4833     const char *level;
4834     gchar      *msg;
4835
4836     /* ignore log message, if log_level isn't interesting */
4837     if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4838 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4839         return;
4840 #endif
4841     }
4842
4843     /* create a "timestamp" */
4844     time(&curr);
4845     today = localtime(&curr);
4846
4847     switch(log_level & G_LOG_LEVEL_MASK) {
4848     case G_LOG_LEVEL_ERROR:
4849         level = "Err ";
4850         break;
4851     case G_LOG_LEVEL_CRITICAL:
4852         level = "Crit";
4853         break;
4854     case G_LOG_LEVEL_WARNING:
4855         level = "Warn";
4856         break;
4857     case G_LOG_LEVEL_MESSAGE:
4858         level = "Msg ";
4859         break;
4860     case G_LOG_LEVEL_INFO:
4861         level = "Info";
4862         break;
4863     case G_LOG_LEVEL_DEBUG:
4864         level = "Dbg ";
4865         break;
4866     default:
4867         fprintf(stderr, "unknown log_level %u\n", log_level);
4868         level = NULL;
4869         g_assert_not_reached();
4870     }
4871
4872     /* Generate the output message                                  */
4873     if (log_level & G_LOG_LEVEL_MESSAGE) {
4874         /* normal user messages without additional infos */
4875         msg =  g_strdup_printf("%s\n", message);
4876     } else {
4877         /* info/debug messages with additional infos */
4878         msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4879                               today->tm_hour, today->tm_min, today->tm_sec,
4880                               log_domain != NULL ? log_domain : "",
4881                               level, message);
4882     }
4883
4884     /* DEBUG & INFO msgs (if we're debugging today)                 */
4885 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4886     if ( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4887 #ifdef DEBUG_DUMPCAP
4888         fprintf(stderr, "%s", msg);
4889         fflush(stderr);
4890 #endif
4891 #ifdef DEBUG_CHILD_DUMPCAP
4892         fprintf(debug_log, "%s", msg);
4893         fflush(debug_log);
4894 #endif
4895         g_free(msg);
4896         return;
4897     }
4898 #endif
4899
4900     /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or    */
4901     /*  to parent especially formatted if dumpcap running as child. */
4902     if (capture_child) {
4903         sync_pipe_errmsg_to_parent(2, msg, "");
4904     } else {
4905         fprintf(stderr, "%s", msg);
4906         fflush(stderr);
4907     }
4908     g_free(msg);
4909 }
4910
4911
4912 /****************************************************************************************************************/
4913 /* indication report routines */
4914
4915
4916 static void
4917 report_packet_count(unsigned int packet_count)
4918 {
4919     char tmp[SP_DECISIZE+1+1];
4920     static unsigned int count = 0;
4921
4922     if (capture_child) {
4923         g_snprintf(tmp, sizeof(tmp), "%u", packet_count);
4924         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
4925         pipe_write_block(2, SP_PACKET_COUNT, tmp);
4926     } else {
4927         count += packet_count;
4928         fprintf(stderr, "\rPackets: %u ", count);
4929         /* stderr could be line buffered */
4930         fflush(stderr);
4931     }
4932 }
4933
4934 static void
4935 report_new_capture_file(const char *filename)
4936 {
4937     if (capture_child) {
4938         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
4939         pipe_write_block(2, SP_FILE, filename);
4940     } else {
4941 #ifdef SIGINFO
4942         /*
4943          * Prevent a SIGINFO handler from writing to the standard error
4944          * while we're doing so; instead, have it just set a flag telling
4945          * us to print that information when we're done.
4946          */
4947         infodelay = TRUE;
4948 #endif /* SIGINFO */
4949         fprintf(stderr, "File: %s\n", filename);
4950         /* stderr could be line buffered */
4951         fflush(stderr);
4952
4953 #ifdef SIGINFO
4954         /*
4955          * Allow SIGINFO handlers to write.
4956          */
4957         infodelay = FALSE;
4958
4959         /*
4960          * If a SIGINFO handler asked us to write out capture counts, do so.
4961          */
4962         if (infoprint)
4963           report_counts_for_siginfo();
4964 #endif /* SIGINFO */
4965     }
4966 }
4967
4968 static void
4969 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
4970 {
4971     interface_options interface_opts;
4972     char tmp[MSG_MAX_LENGTH+1+6];
4973
4974     if (i < capture_opts->ifaces->len) {
4975         if (capture_child) {
4976             g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
4977             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
4978             pipe_write_block(2, SP_BAD_FILTER, tmp);
4979         } else {
4980             /*
4981              * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
4982              * the error message below.
4983              */
4984             interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
4985             cmdarg_err(
4986               "Invalid capture filter \"%s\" for interface %s!\n"
4987               "\n"
4988               "That string isn't a valid capture filter (%s).\n"
4989               "See the User's Guide for a description of the capture filter syntax.",
4990               interface_opts.cfilter, interface_opts.name, errmsg);
4991         }
4992     }
4993 }
4994
4995 static void
4996 report_capture_error(const char *error_msg, const char *secondary_error_msg)
4997 {
4998     if (capture_child) {
4999         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5000             "Primary Error: %s", error_msg);
5001         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5002             "Secondary Error: %s", secondary_error_msg);
5003         sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
5004     } else {
5005         cmdarg_err("%s", error_msg);
5006         if (secondary_error_msg[0] != '\0')
5007           cmdarg_err_cont("%s", secondary_error_msg);
5008     }
5009 }
5010
5011 static void
5012 report_packet_drops(guint32 received, guint32 pcap_drops, guint32 drops, guint32 flushed, gchar *name)
5013 {
5014     char tmp[SP_DECISIZE+1+1];
5015     guint32 total_drops = pcap_drops + drops + flushed;
5016
5017     g_snprintf(tmp, sizeof(tmp), "%u", total_drops);
5018
5019     if (capture_child) {
5020         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5021             "Packets received/dropped on interface %s: %u/%u (pcap:%u/dumpcap:%u/flushed:%u)",
5022             name, received, total_drops, pcap_drops, drops, flushed);
5023         /* XXX: Need to provide interface id, changes to consumers required. */
5024         pipe_write_block(2, SP_DROPS, tmp);
5025     } else {
5026         fprintf(stderr,
5027             "Packets received/dropped on interface '%s': %u/%u (pcap:%u/dumpcap:%u/flushed:%u) (%.1f%%)\n",
5028             name, received, total_drops, pcap_drops, drops, flushed,
5029             received ? 100.0 * received / (received + total_drops) : 0.0);
5030         /* stderr could be line buffered */
5031         fflush(stderr);
5032     }
5033 }
5034
5035
5036 /************************************************************************************************/
5037 /* signal_pipe handling */
5038
5039
5040 #ifdef _WIN32
5041 static gboolean
5042 signal_pipe_check_running(void)
5043 {
5044     /* any news from our parent? -> just stop the capture */
5045     DWORD    avail = 0;
5046     gboolean result;
5047
5048     /* if we are running standalone, no check required */
5049     if (!capture_child) {
5050         return TRUE;
5051     }
5052
5053     if (!sig_pipe_name || !sig_pipe_handle) {
5054         /* This shouldn't happen */
5055         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5056             "Signal pipe: No name or handle");
5057         return FALSE;
5058     }
5059
5060     /*
5061      * XXX - We should have the process ID of the parent (from the "-Z" flag)
5062      * at this point.  Should we check to see if the parent is still alive,
5063      * e.g. by using OpenProcess?
5064      */
5065
5066     result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
5067
5068     if (!result || avail > 0) {
5069         /* peek failed or some bytes really available */
5070         /* (if not piping from stdin this would fail) */
5071         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
5072             "Signal pipe: Stop capture: %s", sig_pipe_name);
5073         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
5074             "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
5075             sig_pipe_handle, result, avail);
5076         return FALSE;
5077     } else {
5078         /* pipe ok and no bytes available */
5079         return TRUE;
5080     }
5081 }
5082 #endif
5083
5084 /*
5085  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
5086  *
5087  * Local variables:
5088  * c-basic-offset: 4
5089  * tab-width: 8
5090  * indent-tabs-mode: nil
5091  * End:
5092  *
5093  * vi: set shiftwidth=4 tabstop=8 expandtab:
5094  * :indentSize=4:tabSize=8:noTabs=true:
5095  */