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