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