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