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