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