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