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