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