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