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