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