Free the buffer
[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             GString             *os_info_str;
2563
2564             os_info_str = g_string_new("");
2565             get_os_version_info(os_info_str);
2566
2567             g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2568             successful = libpcap_write_session_header_block(ld->pdh, 
2569                                 NULL,                        /* Comment*/
2570                                 NULL,                        /* HW*/
2571                                 os_info_str->str,            /* OS*/
2572                                 appname,
2573                                                                 -1,                          /* section_length */
2574                                 &ld->bytes_written, 
2575                                 &err);
2576
2577             g_string_free(os_info_str, TRUE);
2578
2579             for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
2580                 interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
2581                 pcap_opts = g_array_index(ld->pcaps, pcap_options *, i);
2582                 if (pcap_opts->from_cap_pipe) {
2583                     pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2584                 } else {
2585                     pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2586                 }
2587                 successful = libpcap_write_interface_description_block(ld->pdh,
2588                                                                        interface_opts.name,
2589                                                                        interface_opts.cfilter?interface_opts.cfilter:"",
2590                                                                        pcap_opts->linktype,
2591                                                                        pcap_opts->snaplen,
2592                                                                        &ld->bytes_written,
2593                                                                        &err);
2594             }
2595         } else {
2596             pcap_opts = g_array_index(ld->pcaps, pcap_options *, 0);
2597             if (pcap_opts->from_cap_pipe) {
2598                 pcap_opts->snaplen = pcap_opts->cap_pipe_hdr.snaplen;
2599             } else {
2600                 pcap_opts->snaplen = pcap_snapshot(pcap_opts->pcap_h);
2601             }
2602             successful = libpcap_write_file_header(ld->pdh, pcap_opts->linktype, pcap_opts->snaplen,
2603                                                    &ld->bytes_written, &err);
2604         }
2605         if (!successful) {
2606             fclose(ld->pdh);
2607             ld->pdh = NULL;
2608         }
2609     }
2610
2611     if (ld->pdh == NULL) {
2612         /* We couldn't set up to write to the capture file. */
2613         /* XXX - use cf_open_error_message from tshark instead? */
2614         switch (err) {
2615
2616         default:
2617             if (err < 0) {
2618                 g_snprintf(errmsg, errmsg_len,
2619                            "The file to which the capture would be"
2620                            " saved (\"%s\") could not be opened: Error %d.",
2621                            capture_opts->save_file, err);
2622             } else {
2623                 g_snprintf(errmsg, errmsg_len,
2624                            "The file to which the capture would be"
2625                            " saved (\"%s\") could not be opened: %s.",
2626                            capture_opts->save_file, g_strerror(err));
2627             }
2628             break;
2629         }
2630
2631         return FALSE;
2632     }
2633
2634     return TRUE;
2635 }
2636
2637 static gboolean
2638 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close)
2639 {
2640
2641     unsigned int i;
2642     pcap_options *pcap_opts;
2643
2644     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2645
2646     if (capture_opts->multi_files_on) {
2647         return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2648     } else {
2649         if (capture_opts->use_pcapng) {
2650             for (i = 0; i < global_ld.pcaps->len; i++) {
2651                 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
2652                 if (!pcap_opts->from_cap_pipe) {
2653                     libpcap_write_interface_statistics_block(ld->pdh, i, pcap_opts->pcap_h, &ld->bytes_written, err_close);
2654                 }
2655             }
2656         }
2657         return libpcap_dump_close(ld->pdh, err_close);
2658     }
2659 }
2660
2661 /* dispatch incoming packets (pcap or capture pipe)
2662  *
2663  * Waits for incoming packets to be available, and calls pcap_dispatch()
2664  * to cause them to be processed.
2665  *
2666  * Returns the number of packets which were processed.
2667  *
2668  * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2669  * packet-batching behaviour does not cause packets to get held back
2670  * indefinitely.
2671  */
2672 static int
2673 capture_loop_dispatch(loop_data *ld,
2674                       char *errmsg, int errmsg_len, pcap_options *pcap_opts)
2675 {
2676     int       inpkts;
2677     gint      packet_count_before;
2678     guchar    pcap_data[WTAP_MAX_PACKET_SIZE];
2679 #ifndef _WIN32
2680     int       sel_ret;
2681 #endif
2682
2683     packet_count_before = ld->packet_count;
2684     if (pcap_opts->from_cap_pipe) {
2685         /* dispatch from capture pipe */
2686 #ifdef LOG_CAPTURE_VERBOSE
2687         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2688 #endif
2689 #ifndef _WIN32
2690         sel_ret = cap_pipe_select(pcap_opts->cap_pipe_fd);
2691         if (sel_ret <= 0) {
2692             if (sel_ret < 0 && errno != EINTR) {
2693                 g_snprintf(errmsg, errmsg_len,
2694                            "Unexpected error from select: %s", g_strerror(errno));
2695                 report_capture_error(errmsg, please_report);
2696                 ld->go = FALSE;
2697             }
2698         } else {
2699             /*
2700              * "select()" says we can read from the pipe without blocking
2701              */
2702 #endif
2703             inpkts = cap_pipe_dispatch(ld, pcap_opts, pcap_data, errmsg, errmsg_len);
2704             if (inpkts < 0) {
2705                 ld->go = FALSE;
2706             }
2707 #ifndef _WIN32
2708         }
2709 #endif
2710     }
2711     else
2712     {
2713         /* dispatch from pcap */
2714 #ifdef MUST_DO_SELECT
2715         /*
2716          * If we have "pcap_get_selectable_fd()", we use it to get the
2717          * descriptor on which to select; if that's -1, it means there
2718          * is no descriptor on which you can do a "select()" (perhaps
2719          * because you're capturing on a special device, and that device's
2720          * driver unfortunately doesn't support "select()", in which case
2721          * we don't do the select - which means it might not be possible
2722          * to stop a capture until a packet arrives.  If that's unacceptable,
2723          * plead with whoever supplies the software for that device to add
2724          * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2725          * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2726          * later, so it can use pcap_breakloop().
2727          */
2728 #ifdef LOG_CAPTURE_VERBOSE
2729         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2730 #endif
2731         if (pcap_opts->pcap_fd != -1) {
2732             sel_ret = cap_pipe_select(pcap_opts->pcap_fd);
2733             if (sel_ret > 0) {
2734                 /*
2735                  * "select()" says we can read from it without blocking; go for
2736                  * it.
2737                  *
2738                  * We don't have pcap_breakloop(), so we only process one packet
2739                  * per pcap_dispatch() call, to allow a signal to stop the
2740                  * processing immediately, rather than processing all packets
2741                  * in a batch before quitting.
2742                  */
2743                 if (use_threads) {
2744                     inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2745                 } else {
2746                     inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2747                 }
2748                 if (inpkts < 0) {
2749                     if (inpkts == -1) {
2750                         /* Error, rather than pcap_breakloop(). */
2751                         pcap_opts->pcap_err = TRUE;
2752                     }
2753                     ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2754                 }
2755             } else {
2756                 if (sel_ret < 0 && errno != EINTR) {
2757                     g_snprintf(errmsg, errmsg_len,
2758                                "Unexpected error from select: %s", g_strerror(errno));
2759                     report_capture_error(errmsg, please_report);
2760                     ld->go = FALSE;
2761                 }
2762             }
2763         }
2764         else
2765 #endif /* MUST_DO_SELECT */
2766         {
2767             /* dispatch from pcap without select */
2768 #if 1
2769 #ifdef LOG_CAPTURE_VERBOSE
2770             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2771 #endif
2772 #ifdef _WIN32
2773             /*
2774              * On Windows, we don't support asynchronously telling a process to
2775              * stop capturing; instead, we check for an indication on a pipe
2776              * after processing packets.  We therefore process only one packet
2777              * at a time, so that we can check the pipe after every packet.
2778              */
2779             if (use_threads) {
2780                 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2781             } else {
2782                 inpkts = pcap_dispatch(pcap_opts->pcap_h, 1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2783             }
2784 #else
2785             if (use_threads) {
2786                 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_queue_packet_cb, (u_char *)pcap_opts);
2787             } else {
2788                 inpkts = pcap_dispatch(pcap_opts->pcap_h, -1, capture_loop_write_packet_cb, (u_char *)pcap_opts);
2789             }
2790 #endif
2791             if (inpkts < 0) {
2792                 if (inpkts == -1) {
2793                     /* Error, rather than pcap_breakloop(). */
2794                     pcap_opts->pcap_err = TRUE;
2795                 }
2796                 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2797             }
2798 #else /* pcap_next_ex */
2799 #ifdef LOG_CAPTURE_VERBOSE
2800             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2801 #endif
2802             /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2803
2804             /*
2805              * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2806              * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
2807              * This should be fixed in the WinPcap 4.0 alpha release.
2808              *
2809              * For reference, an example remote interface:
2810              * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2811              */
2812
2813             /* emulate dispatch from pcap */
2814             {
2815                 int in;
2816                 struct pcap_pkthdr *pkt_header;
2817                 u_char *pkt_data;
2818
2819                 in = 0;
2820                 while(ld->go &&
2821                       (in = pcap_next_ex(pcap_opts->pcap_h, &pkt_header, &pkt_data)) == 1) {
2822                     if (use_threads) {
2823                         capture_loop_queue_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
2824                     } else {
2825                         capture_loop_write_packet_cb((u_char *)pcap_opts, pkt_header, pkt_data);
2826                     }
2827                 }
2828
2829                 if(in < 0) {
2830                     pcap_opts->pcap_err = TRUE;
2831                     ld->go = FALSE;
2832                 }
2833             }
2834 #endif /* pcap_next_ex */
2835         }
2836     }
2837
2838 #ifdef LOG_CAPTURE_VERBOSE
2839     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2840 #endif
2841
2842     return ld->packet_count - packet_count_before;
2843 }
2844
2845 #ifdef _WIN32
2846 /* Isolate the Universally Unique Identifier from the interface.  Basically, we
2847  * want to grab only the characters between the '{' and '}' delimiters.
2848  *
2849  * Returns a GString that must be freed with g_string_free(). */
2850 static GString *
2851 isolate_uuid(const char *iface)
2852 {
2853     gchar *ptr;
2854     GString *gstr;
2855
2856     ptr = strchr(iface, '{');
2857     if (ptr == NULL)
2858         return g_string_new(iface);
2859     gstr = g_string_new(ptr + 1);
2860
2861     ptr = strchr(gstr->str, '}');
2862     if (ptr == NULL)
2863         return gstr;
2864
2865     gstr = g_string_truncate(gstr, ptr - gstr->str);
2866     return gstr;
2867 }
2868 #endif
2869
2870 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2871 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2872 static gboolean
2873 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2874                          char *errmsg, int errmsg_len)
2875 {
2876     char *tmpname;
2877     gchar *capfile_name;
2878     gchar *prefix;
2879     gboolean is_tempfile;
2880
2881     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2882           (capture_opts->save_file) ? capture_opts->save_file : "(not specified)");
2883
2884     if (capture_opts->save_file != NULL) {
2885         /* We return to the caller while the capture is in progress.
2886          * Therefore we need to take a copy of save_file in
2887          * case the caller destroys it after we return.
2888          */
2889         capfile_name = g_strdup(capture_opts->save_file);
2890
2891         if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2892             if (capture_opts->multi_files_on) {
2893                 /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2894                 g_snprintf(errmsg, errmsg_len,
2895                            "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2896                 g_free(capfile_name);
2897                 return FALSE;
2898             }
2899             if (strcmp(capfile_name, "-") == 0) {
2900                 /* write to stdout */
2901                 *save_file_fd = 1;
2902 #ifdef _WIN32
2903                 /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF)  */
2904                 _setmode(1, O_BINARY);
2905 #endif
2906             }
2907         } /* if (...output_to_pipe ... */
2908
2909         else {
2910             if (capture_opts->multi_files_on) {
2911                 /* ringbuffer is enabled */
2912                 *save_file_fd = ringbuf_init(capfile_name,
2913                                              (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0,
2914                                              capture_opts->group_read_access);
2915
2916                 /* we need the ringbuf name */
2917                 if(*save_file_fd != -1) {
2918                     g_free(capfile_name);
2919                     capfile_name = g_strdup(ringbuf_current_filename());
2920                 }
2921             } else {
2922                 /* Try to open/create the specified file for use as a capture buffer. */
2923                 *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
2924                                         (capture_opts->group_read_access) ? 0640 : 0600);
2925             }
2926         }
2927         is_tempfile = FALSE;
2928     } else {
2929         /* Choose a random name for the temporary capture buffer */
2930         if (global_capture_opts.ifaces->len > 1) {
2931             prefix = g_strdup_printf("wireshark_%d_interfaces", global_capture_opts.ifaces->len);
2932         } else {
2933             gchar *basename;
2934 #ifdef _WIN32
2935             GString *iface;
2936             iface = isolate_uuid(g_array_index(global_capture_opts.ifaces, interface_options, 0).name);
2937             basename = g_path_get_basename(iface->str);
2938             g_string_free(iface, TRUE);
2939 #else
2940             basename = g_path_get_basename(g_array_index(global_capture_opts.ifaces, interface_options, 0).name);
2941 #endif
2942             prefix = g_strconcat("wireshark_", basename, NULL);
2943             g_free(basename);
2944         }
2945         *save_file_fd = create_tempfile(&tmpname, prefix);
2946         g_free(prefix);
2947         capfile_name = g_strdup(tmpname);
2948         is_tempfile = TRUE;
2949     }
2950
2951     /* did we fail to open the output file? */
2952     if (*save_file_fd == -1) {
2953         if (is_tempfile) {
2954             g_snprintf(errmsg, errmsg_len,
2955                        "The temporary file to which the capture would be saved (\"%s\") "
2956                        "could not be opened: %s.", capfile_name, g_strerror(errno));
2957         } else {
2958             if (capture_opts->multi_files_on) {
2959                 ringbuf_error_cleanup();
2960             }
2961
2962             g_snprintf(errmsg, errmsg_len,
2963                        "The file to which the capture would be saved (\"%s\") "
2964                        "could not be opened: %s.", capfile_name,
2965                        g_strerror(errno));
2966         }
2967         g_free(capfile_name);
2968         return FALSE;
2969     }
2970
2971     if(capture_opts->save_file != NULL) {
2972         g_free(capture_opts->save_file);
2973     }
2974     capture_opts->save_file = capfile_name;
2975     /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2976        "g_free(capfile_name)". */
2977
2978     return TRUE;
2979 }
2980
2981
2982 /* Do the work of handling either the file size or file duration capture
2983    conditions being reached, and switching files or stopping. */
2984 static gboolean
2985 do_file_switch_or_stop(capture_options *capture_opts,
2986                        condition *cnd_autostop_files,
2987                        condition *cnd_autostop_size,
2988                        condition *cnd_file_duration)
2989 {
2990     guint i;
2991     pcap_options *pcap_opts;
2992     interface_options interface_opts;
2993     gboolean successful;
2994
2995     if (capture_opts->multi_files_on) {
2996         if (cnd_autostop_files != NULL &&
2997             cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
2998             /* no files left: stop here */
2999             global_ld.go = FALSE;
3000             return FALSE;
3001         }
3002
3003         /* Switch to the next ringbuffer file */
3004         if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
3005                                 &global_ld.save_file_fd, &global_ld.err)) {
3006
3007             /* File switch succeeded: reset the conditions */
3008             global_ld.bytes_written = 0;
3009             if (capture_opts->use_pcapng) {
3010                 char appname[100];
3011                 GString             *os_info_str;
3012
3013                 os_info_str = g_string_new("");
3014                 get_os_version_info(os_info_str);
3015
3016                 g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
3017                 successful = libpcap_write_session_header_block(global_ld.pdh, 
3018                                 NULL,                        /* Comment */
3019                                 NULL,                        /* HW */
3020                                 os_info_str->str,            /* OS */
3021                                 appname,
3022                                                                 -1,                          /* section_length */
3023                                 &(global_ld.bytes_written), 
3024                                 &global_ld.err);
3025
3026                 g_string_free(os_info_str, TRUE);
3027
3028                 for (i = 0; successful && (i < capture_opts->ifaces->len); i++) {
3029                     interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3030                     pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3031                     successful = libpcap_write_interface_description_block(global_ld.pdh,
3032                                                                            interface_opts.name,
3033                                                                            interface_opts.cfilter?interface_opts.cfilter:"",
3034                                                                            pcap_opts->linktype,
3035                                                                            pcap_opts->snaplen,
3036                                                                            &(global_ld.bytes_written),
3037                                                                            &global_ld.err);
3038                 }
3039             } else {
3040                 pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3041                 successful = libpcap_write_file_header(global_ld.pdh, pcap_opts->linktype, pcap_opts->snaplen,
3042                                                        &global_ld.bytes_written, &global_ld.err);
3043             }
3044             if (!successful) {
3045                 fclose(global_ld.pdh);
3046                 global_ld.pdh = NULL;
3047                 global_ld.go = FALSE;
3048                 return FALSE;
3049             }
3050             if (cnd_autostop_size)
3051                 cnd_reset(cnd_autostop_size);
3052             if (cnd_file_duration)
3053                 cnd_reset(cnd_file_duration);
3054             libpcap_dump_flush(global_ld.pdh, NULL);
3055             if (!quiet)
3056                 report_packet_count(global_ld.inpkts_to_sync_pipe);
3057             global_ld.inpkts_to_sync_pipe = 0;
3058             report_new_capture_file(capture_opts->save_file);
3059         } else {
3060             /* File switch failed: stop here */
3061             global_ld.go = FALSE;
3062             return FALSE;
3063         }
3064     } else {
3065         /* single file, stop now */
3066         global_ld.go = FALSE;
3067         return FALSE;
3068     }
3069     return TRUE;
3070 }
3071
3072 static void *
3073 pcap_read_handler(void* arg)
3074 {
3075     pcap_options *pcap_opts;
3076     char errmsg[MSG_MAX_LENGTH+1];
3077
3078     pcap_opts = (pcap_options *)arg;
3079
3080     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Started thread for interface %d.",
3081           pcap_opts->interface_id);
3082
3083     while (global_ld.go) {
3084         /* dispatch incoming packets */
3085         capture_loop_dispatch(&global_ld, errmsg, sizeof(errmsg), pcap_opts);
3086     }
3087     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Stopped thread for interface %d.",
3088           pcap_opts->interface_id);
3089     g_thread_exit(NULL);
3090     return (NULL);
3091 }
3092
3093 /* Do the low-level work of a capture.
3094    Returns TRUE if it succeeds, FALSE otherwise. */
3095 static gboolean
3096 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
3097 {
3098 #ifdef WIN32
3099     DWORD upd_time, cur_time;   /* GetTickCount() returns a "DWORD" (which is 'unsigned long') */
3100 #else
3101     struct timeval upd_time, cur_time;
3102 #endif
3103     int         err_close;
3104     int         inpkts;
3105     condition  *cnd_file_duration = NULL;
3106     condition  *cnd_autostop_files = NULL;
3107     condition  *cnd_autostop_size = NULL;
3108     condition  *cnd_autostop_duration = NULL;
3109     gboolean    write_ok;
3110     gboolean    close_ok;
3111     gboolean    cfilter_error = FALSE;
3112     char        errmsg[MSG_MAX_LENGTH+1];
3113     char        secondary_errmsg[MSG_MAX_LENGTH+1];
3114     pcap_options *pcap_opts;
3115     interface_options interface_opts;
3116     guint i, error_index = 0;
3117
3118     *errmsg           = '\0';
3119     *secondary_errmsg = '\0';
3120
3121     /* init the loop data */
3122     global_ld.go                  = TRUE;
3123     global_ld.packet_count        = 0;
3124 #ifdef SIGINFO
3125     global_ld.report_packet_count = FALSE;
3126 #endif
3127     if (capture_opts->has_autostop_packets)
3128         global_ld.packet_max      = capture_opts->autostop_packets;
3129     else
3130         global_ld.packet_max      = 0;        /* no limit */
3131     global_ld.inpkts_to_sync_pipe = 0;
3132     global_ld.err                 = 0;  /* no error seen yet */
3133     global_ld.pdh                 = NULL;
3134     global_ld.autostop_files      = 0;
3135     global_ld.save_file_fd        = -1;
3136
3137     /* We haven't yet gotten the capture statistics. */
3138     *stats_known      = FALSE;
3139
3140     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
3141     capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
3142
3143     /* open the "input file" from network interface or capture pipe */
3144     if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
3145                                  secondary_errmsg, sizeof(secondary_errmsg))) {
3146         goto error;
3147     }
3148     for (i = 0; i < capture_opts->ifaces->len; i++) {
3149         pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3150         interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3151         /* init the input filter from the network interface (capture pipe will do nothing) */
3152         /*
3153          * When remote capturing WinPCap crashes when the capture filter
3154          * is NULL. This might be a bug in WPCap. Therefore we provide an emtpy
3155          * string.
3156          */
3157         switch (capture_loop_init_filter(pcap_opts->pcap_h, pcap_opts->from_cap_pipe,
3158                                          interface_opts.name,
3159                                          interface_opts.cfilter?interface_opts.cfilter:"")) {
3160
3161         case INITFILTER_NO_ERROR:
3162             break;
3163
3164         case INITFILTER_BAD_FILTER:
3165             cfilter_error = TRUE;
3166             error_index = i;
3167             g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(pcap_opts->pcap_h));
3168             goto error;
3169
3170         case INITFILTER_OTHER_ERROR:
3171             g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
3172                        pcap_geterr(pcap_opts->pcap_h));
3173             g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
3174             goto error;
3175         }
3176     }
3177
3178     /* If we're supposed to write to a capture file, open it for output
3179        (temporary/specified name/ringbuffer) */
3180     if (capture_opts->saving_to_file) {
3181         if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
3182                                       errmsg, sizeof(errmsg))) {
3183             goto error;
3184         }
3185
3186         /* set up to write to the already-opened capture output file/files */
3187         if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
3188                                       sizeof(errmsg))) {
3189             goto error;
3190         }
3191
3192         /* XXX - capture SIGTERM and close the capture, in case we're on a
3193            Linux 2.0[.x] system and you have to explicitly close the capture
3194            stream in order to turn promiscuous mode off?  We need to do that
3195            in other places as well - and I don't think that works all the
3196            time in any case, due to libpcap bugs. */
3197
3198         /* Well, we should be able to start capturing.
3199
3200            Sync out the capture file, so the header makes it to the file system,
3201            and send a "capture started successfully and capture file created"
3202            message to our parent so that they'll open the capture file and
3203            update its windows to indicate that we have a live capture in
3204            progress. */
3205         libpcap_dump_flush(global_ld.pdh, NULL);
3206         report_new_capture_file(capture_opts->save_file);
3207     }
3208
3209     /* initialize capture stop (and alike) conditions */
3210     init_capture_stop_conditions();
3211     /* create stop conditions */
3212     if (capture_opts->has_autostop_filesize)
3213         cnd_autostop_size =
3214             cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
3215     if (capture_opts->has_autostop_duration)
3216         cnd_autostop_duration =
3217             cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
3218
3219     if (capture_opts->multi_files_on) {
3220         if (capture_opts->has_file_duration)
3221             cnd_file_duration =
3222                 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
3223
3224         if (capture_opts->has_autostop_files)
3225             cnd_autostop_files =
3226                 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
3227     }
3228
3229     /* init the time values */
3230 #ifdef WIN32
3231     upd_time = GetTickCount();
3232 #else
3233     gettimeofday(&upd_time, NULL);
3234 #endif
3235
3236     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
3237
3238     /* WOW, everything is prepared! */
3239     /* please fasten your seat belts, we will enter now the actual capture loop */
3240     if (use_threads) {
3241         pcap_queue = g_async_queue_new();
3242         pcap_queue_bytes = 0;
3243         pcap_queue_packets = 0;
3244         for (i = 0; i < global_ld.pcaps->len; i++) {
3245             pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3246 #if GLIB_CHECK_VERSION(2,31,0)
3247             /* XXX - Add an interface name here? */
3248             pcap_opts->tid = g_thread_new("Capture read", pcap_read_handler, pcap_opts);
3249 #else
3250             pcap_opts->tid = g_thread_create(pcap_read_handler, pcap_opts, TRUE, NULL);
3251 #endif
3252         }
3253     }
3254     while (global_ld.go) {
3255         /* dispatch incoming packets */
3256         if (use_threads) {
3257             GTimeVal write_thread_time;
3258             pcap_queue_element *queue_element;
3259
3260             g_get_current_time(&write_thread_time);
3261             g_time_val_add(&write_thread_time, WRITER_THREAD_TIMEOUT);
3262             g_async_queue_lock(pcap_queue);
3263             queue_element = g_async_queue_timed_pop_unlocked(pcap_queue, &write_thread_time);
3264             if (queue_element) {
3265                 pcap_queue_bytes -= queue_element->phdr.caplen;
3266                 pcap_queue_packets -= 1;
3267             }
3268             g_async_queue_unlock(pcap_queue);
3269             if (queue_element) {
3270                 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3271                       "Dequeued a packet of length %d captured on interface %d.",
3272                       queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3273
3274                 capture_loop_write_packet_cb((u_char *) queue_element->pcap_opts,
3275                                              &queue_element->phdr,
3276                                              queue_element->pd);
3277                 g_free(queue_element->pd);
3278                 g_free(queue_element);
3279                 inpkts = 1;
3280             } else {
3281                 inpkts = 0;
3282             }
3283         } else {
3284             pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, 0);
3285             inpkts = capture_loop_dispatch(&global_ld, errmsg,
3286                                            sizeof(errmsg), pcap_opts);
3287         }
3288 #ifdef SIGINFO
3289         /* Were we asked to print packet counts by the SIGINFO handler? */
3290         if (global_ld.report_packet_count) {
3291             fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
3292                     plurality(global_ld.packet_count, "", "s"));
3293             global_ld.report_packet_count = FALSE;
3294         }
3295 #endif
3296
3297 #ifdef _WIN32
3298         /* any news from our parent (signal pipe)? -> just stop the capture */
3299         if (!signal_pipe_check_running()) {
3300             global_ld.go = FALSE;
3301         }
3302 #endif
3303
3304         if (inpkts > 0) {
3305             global_ld.inpkts_to_sync_pipe += inpkts;
3306
3307             /* check capture size condition */
3308             if (cnd_autostop_size != NULL &&
3309                 cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)) {
3310                 /* Capture size limit reached, do we have another file? */
3311                 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3312                                             cnd_autostop_size, cnd_file_duration))
3313                     continue;
3314             } /* cnd_autostop_size */
3315             if (capture_opts->output_to_pipe) {
3316                 libpcap_dump_flush(global_ld.pdh, NULL);
3317             }
3318         } /* inpkts */
3319
3320         /* Only update once every 500ms so as not to overload slow displays.
3321          * This also prevents too much context-switching between the dumpcap
3322          * and wireshark processes.
3323          */
3324 #define DUMPCAP_UPD_TIME 500
3325
3326 #ifdef WIN32
3327         cur_time = GetTickCount();  /* Note: wraps to 0 if sys runs for 49.7 days */
3328         if ((cur_time - upd_time) > DUMPCAP_UPD_TIME) { /* wrap just causes an extra update */
3329 #else
3330         gettimeofday(&cur_time, NULL);
3331         if ((cur_time.tv_sec * 1000000 + cur_time.tv_usec) >
3332             (upd_time.tv_sec * 1000000 + upd_time.tv_usec + DUMPCAP_UPD_TIME*1000)) {
3333 #endif
3334
3335             upd_time = cur_time;
3336
3337 #if 0
3338             if (pcap_stats(pch, stats) >= 0) {
3339                 *stats_known = TRUE;
3340             }
3341 #endif
3342             /* Let the parent process know. */
3343             if (global_ld.inpkts_to_sync_pipe) {
3344                 /* do sync here */
3345                 libpcap_dump_flush(global_ld.pdh, NULL);
3346
3347                 /* Send our parent a message saying we've written out
3348                    "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
3349                 if (!quiet)
3350                     report_packet_count(global_ld.inpkts_to_sync_pipe);
3351
3352                 global_ld.inpkts_to_sync_pipe = 0;
3353             }
3354
3355             /* check capture duration condition */
3356             if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3357                 /* The maximum capture time has elapsed; stop the capture. */
3358                 global_ld.go = FALSE;
3359                 continue;
3360             }
3361
3362             /* check capture file duration condition */
3363             if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3364                 /* duration limit reached, do we have another file? */
3365                 if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3366                                             cnd_autostop_size, cnd_file_duration))
3367                     continue;
3368             } /* cnd_file_duration */
3369         }
3370     }
3371
3372     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3373     if (use_threads) {
3374         pcap_queue_element *queue_element;
3375
3376         for (i = 0; i < global_ld.pcaps->len; i++) {
3377             pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3378             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Waiting for thread of interface %u...",
3379                   pcap_opts->interface_id);
3380             g_thread_join(pcap_opts->tid);
3381             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Thread of interface %u terminated.",
3382                   pcap_opts->interface_id);
3383         }
3384         while (1) {
3385             g_async_queue_lock(pcap_queue);
3386             queue_element = g_async_queue_try_pop_unlocked(pcap_queue);
3387             if (queue_element) {
3388                 pcap_queue_bytes -= queue_element->phdr.caplen;
3389                 pcap_queue_packets -= 1;
3390             }
3391             g_async_queue_unlock(pcap_queue);
3392             if (queue_element == NULL) {
3393                 break;
3394             }
3395             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3396                   "Dequeued a packet of length %d captured on interface %d.",
3397                   queue_element->phdr.caplen, queue_element->pcap_opts->interface_id);
3398             capture_loop_write_packet_cb((u_char *)queue_element->pcap_opts,
3399                                          &queue_element->phdr,
3400                                          queue_element->pd);
3401             g_free(queue_element->pd);
3402             g_free(queue_element);
3403             global_ld.inpkts_to_sync_pipe += 1;
3404             if (capture_opts->output_to_pipe) {
3405                 libpcap_dump_flush(global_ld.pdh, NULL);
3406             }
3407         }
3408     }
3409
3410
3411     /* delete stop conditions */
3412     if (cnd_file_duration != NULL)
3413         cnd_delete(cnd_file_duration);
3414     if (cnd_autostop_files != NULL)
3415         cnd_delete(cnd_autostop_files);
3416     if (cnd_autostop_size != NULL)
3417         cnd_delete(cnd_autostop_size);
3418     if (cnd_autostop_duration != NULL)
3419         cnd_delete(cnd_autostop_duration);
3420
3421     /* did we have a pcap (input) error? */
3422     for (i = 0; i < capture_opts->ifaces->len; i++) {
3423         pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3424         if (pcap_opts->pcap_err) {
3425             /* On Linux, if an interface goes down while you're capturing on it,
3426                you'll get a "recvfrom: Network is down" or
3427                "The interface went down" error (ENETDOWN).
3428                (At least you will if g_strerror() doesn't show a local translation
3429                of the error.)
3430
3431                On FreeBSD and OS X, if a network adapter disappears while
3432                you're capturing on it, you'll get a "read: Device not configured"
3433                error (ENXIO).  (See previous parenthetical note.)
3434
3435                On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3436
3437                These should *not* be reported to the Wireshark developers. */
3438             char *cap_err_str;
3439
3440             cap_err_str = pcap_geterr(pcap_opts->pcap_h);
3441             if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3442                 strcmp(cap_err_str, "The interface went down") == 0 ||
3443                 strcmp(cap_err_str, "read: Device not configured") == 0 ||
3444                 strcmp(cap_err_str, "read: I/O error") == 0 ||
3445                 strcmp(cap_err_str, "read error: PacketReceivePacket failed") == 0) {
3446                 report_capture_error("The network adapter on which the capture was being done "
3447                                      "is no longer running; the capture has stopped.",
3448                                      "");
3449             } else {
3450                 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3451                            cap_err_str);
3452                 report_capture_error(errmsg, please_report);
3453             }
3454             break;
3455         } else if (pcap_opts->from_cap_pipe && pcap_opts->cap_pipe_err == PIPERR) {
3456             report_capture_error(errmsg, "");
3457             break;
3458         }
3459     }
3460     /* did we have an output error while capturing? */
3461     if (global_ld.err == 0) {
3462         write_ok = TRUE;
3463     } else {
3464         capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3465                                 global_ld.err, FALSE);
3466         report_capture_error(errmsg, please_report);
3467         write_ok = FALSE;
3468     }
3469
3470     if (capture_opts->saving_to_file) {
3471         /* close the output file */
3472         close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3473     } else
3474         close_ok = TRUE;
3475
3476     /* there might be packets not yet notified to the parent */
3477     /* (do this after closing the file, so all packets are already flushed) */
3478     if(global_ld.inpkts_to_sync_pipe) {
3479         if (!quiet)
3480             report_packet_count(global_ld.inpkts_to_sync_pipe);
3481         global_ld.inpkts_to_sync_pipe = 0;
3482     }
3483
3484     /* If we've displayed a message about a write error, there's no point
3485        in displaying another message about an error on close. */
3486     if (!close_ok && write_ok) {
3487         capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3488                                 TRUE);
3489         report_capture_error(errmsg, "");
3490     }
3491
3492     /*
3493      * XXX We exhibit different behaviour between normal mode and sync mode
3494      * when the pipe is stdin and not already at EOF.  If we're a child, the
3495      * parent's stdin isn't closed, so if the user starts another capture,
3496      * cap_pipe_open_live() will very likely not see the expected magic bytes and
3497      * will say "Unrecognized libpcap format".  On the other hand, in normal
3498      * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3499      */
3500
3501     report_capture_count(TRUE);
3502
3503     /* get packet drop statistics from pcap */
3504     for (i = 0; i < capture_opts->ifaces->len; i++) {
3505         guint32 received;
3506         guint32 dropped;
3507
3508         pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3509         interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
3510         received = pcap_opts->received;
3511         dropped = pcap_opts->dropped;
3512         if (pcap_opts->pcap_h != NULL) {
3513             g_assert(!pcap_opts->from_cap_pipe);
3514             /* Get the capture statistics, so we know how many packets were dropped. */
3515             if (pcap_stats(pcap_opts->pcap_h, stats) >= 0) {
3516                 *stats_known = TRUE;
3517                 /* Let the parent process know. */
3518                 dropped += stats->ps_drop;
3519             } else {
3520                 g_snprintf(errmsg, sizeof(errmsg),
3521                            "Can't get packet-drop statistics: %s",
3522                            pcap_geterr(pcap_opts->pcap_h));
3523                 report_capture_error(errmsg, please_report);
3524             }
3525         }
3526         report_packet_drops(received, dropped, interface_opts.name);
3527     }
3528
3529     /* close the input file (pcap or capture pipe) */
3530     capture_loop_close_input(&global_ld);
3531
3532     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
3533
3534     /* ok, if the write and the close were successful. */
3535     return write_ok && close_ok;
3536
3537 error:
3538     if (capture_opts->multi_files_on) {
3539         /* cleanup ringbuffer */
3540         ringbuf_error_cleanup();
3541     } else {
3542         /* We can't use the save file, and we have no FILE * for the stream
3543            to close in order to close it, so close the FD directly. */
3544         if (global_ld.save_file_fd != -1) {
3545             ws_close(global_ld.save_file_fd);
3546         }
3547
3548         /* We couldn't even start the capture, so get rid of the capture
3549            file. */
3550         if (capture_opts->save_file != NULL) {
3551             ws_unlink(capture_opts->save_file);
3552             g_free(capture_opts->save_file);
3553         }
3554     }
3555     capture_opts->save_file = NULL;
3556     if (cfilter_error)
3557         report_cfilter_error(capture_opts, error_index, errmsg);
3558     else
3559         report_capture_error(errmsg, secondary_errmsg);
3560
3561     /* close the input file (pcap or cap_pipe) */
3562     capture_loop_close_input(&global_ld);
3563
3564     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3565
3566     return FALSE;
3567 }
3568
3569
3570 static void capture_loop_stop(void)
3571 {
3572 #ifdef HAVE_PCAP_BREAKLOOP
3573     guint i;
3574     pcap_options *pcap_opts;
3575
3576     for (i = 0; i < global_ld.pcaps->len; i++) {
3577         pcap_opts = g_array_index(global_ld.pcaps, pcap_options *, i);
3578         if (pcap_opts->pcap_h != NULL)
3579             pcap_breakloop(pcap_opts->pcap_h);
3580     }
3581 #endif
3582     global_ld.go = FALSE;
3583 }
3584
3585
3586 static void
3587 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3588                         int err, gboolean is_close)
3589 {
3590     switch (err) {
3591
3592     case ENOSPC:
3593         g_snprintf(errmsg, errmsglen,
3594                    "Not all the packets could be written to the file"
3595                    " to which the capture was being saved\n"
3596                    "(\"%s\") because there is no space left on the file system\n"
3597                    "on which that file resides.",
3598                    fname);
3599         break;
3600
3601 #ifdef EDQUOT
3602     case EDQUOT:
3603         g_snprintf(errmsg, errmsglen,
3604                    "Not all the packets could be written to the file"
3605                    " to which the capture was being saved\n"
3606                    "(\"%s\") because you are too close to, or over,"
3607                    " your disk quota\n"
3608                    "on the file system on which that file resides.",
3609                    fname);
3610         break;
3611 #endif
3612
3613     default:
3614         if (is_close) {
3615             g_snprintf(errmsg, errmsglen,
3616                        "The file to which the capture was being saved\n"
3617                        "(\"%s\") could not be closed: %s.",
3618                        fname, g_strerror(err));
3619         } else {
3620             g_snprintf(errmsg, errmsglen,
3621                        "An error occurred while writing to the file"
3622                        " to which the capture was being saved\n"
3623                        "(\"%s\"): %s.",
3624                        fname, g_strerror(err));
3625         }
3626         break;
3627     }
3628 }
3629
3630
3631 /* one packet was captured, process it */
3632 static void
3633 capture_loop_write_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3634                              const u_char *pd)
3635 {
3636     pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3637     int err;
3638
3639     /* We may be called multiple times from pcap_dispatch(); if we've set
3640        the "stop capturing" flag, ignore this packet, as we're not
3641        supposed to be saving any more packets. */
3642     if (!global_ld.go)
3643         return;
3644
3645     if (global_ld.pdh) {
3646         gboolean successful;
3647
3648         /* We're supposed to write the packet to a file; do so.
3649            If this fails, set "ld->go" to FALSE, to stop the capture, and set
3650            "ld->err" to the error. */
3651         if (global_capture_opts.use_pcapng) {
3652             successful = libpcap_write_enhanced_packet_block(global_ld.pdh, phdr, pcap_opts->interface_id, pd, &global_ld.bytes_written, &err);
3653         } else {
3654             successful = libpcap_write_packet(global_ld.pdh, phdr, pd, &global_ld.bytes_written, &err);
3655         }
3656         if (!successful) {
3657             global_ld.go = FALSE;
3658             global_ld.err = err;
3659         } else {
3660             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3661                   "Wrote a packet of length %d captured on interface %u.",
3662                    phdr->caplen, pcap_opts->interface_id);
3663             global_ld.packet_count++;
3664             pcap_opts->received++;
3665             /* if the user told us to stop after x packets, do we already have enough? */
3666             if ((global_ld.packet_max > 0) && (global_ld.packet_count >= global_ld.packet_max)) {
3667                 global_ld.go = FALSE;
3668             }
3669         }
3670     }
3671 }
3672
3673 /* one packet was captured, queue it */
3674 static void
3675 capture_loop_queue_packet_cb(u_char *pcap_opts_p, const struct pcap_pkthdr *phdr,
3676                              const u_char *pd)
3677 {
3678     pcap_options *pcap_opts = (pcap_options *) (void *) pcap_opts_p;
3679     pcap_queue_element *queue_element;
3680     gboolean limit_reached;
3681
3682     /* We may be called multiple times from pcap_dispatch(); if we've set
3683        the "stop capturing" flag, ignore this packet, as we're not
3684        supposed to be saving any more packets. */
3685     if (!global_ld.go)
3686         return;
3687
3688     queue_element = (pcap_queue_element *)g_malloc(sizeof(pcap_queue_element));
3689     if (queue_element == NULL) {
3690        pcap_opts->dropped++;
3691        return;
3692     }
3693     queue_element->pcap_opts = pcap_opts;
3694     queue_element->phdr = *phdr;
3695     queue_element->pd = (u_char *)g_malloc(phdr->caplen);
3696     if (queue_element->pd == NULL) {
3697         pcap_opts->dropped++;
3698         g_free(queue_element);
3699         return;
3700     }
3701     memcpy(queue_element->pd, pd, phdr->caplen);
3702     g_async_queue_lock(pcap_queue);
3703     if (((pcap_queue_byte_limit > 0) && (pcap_queue_bytes < pcap_queue_byte_limit)) &&
3704         ((pcap_queue_packet_limit > 0) && (pcap_queue_packets < pcap_queue_packet_limit))) {
3705         limit_reached = FALSE;
3706         g_async_queue_push_unlocked(pcap_queue, queue_element);
3707         pcap_queue_bytes += phdr->caplen;
3708         pcap_queue_packets += 1;
3709     } else {
3710         limit_reached = TRUE;
3711     }
3712     g_async_queue_unlock(pcap_queue);
3713     if (limit_reached) {
3714         pcap_opts->dropped++;
3715         g_free(queue_element->pd);
3716         g_free(queue_element);
3717         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3718               "Dropped a packet of length %d captured on interface %u.",
3719               phdr->caplen, pcap_opts->interface_id);
3720     } else {
3721         pcap_opts->received++;
3722         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3723               "Queued a packet of length %d captured on interface %u.",
3724               phdr->caplen, pcap_opts->interface_id);
3725     }
3726     /* I don't want to hold the mutex over the debug output. So the
3727        output may be wrong */
3728     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3729           "Queue size is now %" G_GINT64_MODIFIER "d bytes (%" G_GINT64_MODIFIER "d packets)",
3730           pcap_queue_bytes, pcap_queue_packets);
3731 }
3732
3733 /* And now our feature presentation... [ fade to music ] */
3734 int
3735 main(int argc, char *argv[])
3736 {
3737     int                  opt;
3738     gboolean             arg_error = FALSE;
3739
3740 #ifdef _WIN32
3741     WSADATA              wsaData;
3742 #else
3743     struct sigaction action, oldaction;
3744 #endif
3745
3746     gboolean             start_capture = TRUE;
3747     gboolean             stats_known;
3748     struct pcap_stat     stats;
3749     GLogLevelFlags       log_flags;
3750     gboolean             list_interfaces = FALSE;
3751     gboolean             list_link_layer_types = FALSE;
3752 #ifdef HAVE_BPF_IMAGE
3753     gboolean             print_bpf_code = FALSE;
3754 #endif
3755     gboolean             machine_readable = FALSE;
3756     gboolean             print_statistics = FALSE;
3757     int                  status, run_once_args = 0;
3758     gint                 i;
3759     guint                j;
3760 #if defined(__APPLE__) && defined(__LP64__)
3761     struct utsname       osinfo;
3762 #endif
3763     GString             *str;
3764
3765 #ifdef _WIN32
3766     arg_list_utf_16to8(argc, argv);
3767 #endif /* _WIN32 */
3768
3769 #ifdef _WIN32
3770     /*
3771      * Initialize our DLL search path. MUST be called before LoadLibrary
3772      * or g_module_open.
3773      */
3774     ws_init_dll_search_path();
3775 #endif
3776
3777 #ifdef HAVE_PCAP_REMOTE
3778 #define OPTSTRING_A "A:"
3779 #define OPTSTRING_r "r"
3780 #define OPTSTRING_u "u"
3781 #else
3782 #define OPTSTRING_A ""
3783 #define OPTSTRING_r ""
3784 #define OPTSTRING_u ""
3785 #endif
3786
3787 #ifdef HAVE_PCAP_SETSAMPLING
3788 #define OPTSTRING_m "m:"
3789 #else
3790 #define OPTSTRING_m ""
3791 #endif
3792
3793 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
3794 #define OPTSTRING_B "B:"
3795 #else
3796 #define OPTSTRING_B ""
3797 #endif  /* _WIN32 or HAVE_PCAP_CREATE */
3798
3799 #ifdef HAVE_PCAP_CREATE
3800 #define OPTSTRING_I "I"
3801 #else
3802 #define OPTSTRING_I ""
3803 #endif
3804
3805 #ifdef HAVE_BPF_IMAGE
3806 #define OPTSTRING_d "d"
3807 #else
3808 #define OPTSTRING_d ""
3809 #endif
3810
3811 #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:"
3812
3813 #ifdef DEBUG_CHILD_DUMPCAP
3814     if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
3815         fprintf (stderr, "Unable to open debug log file !\n");
3816         exit (1);
3817     }
3818 #endif
3819
3820 #if defined(__APPLE__) && defined(__LP64__)
3821     /*
3822      * Is this Mac OS X 10.6.0, 10.6.1, 10.6.3, or 10.6.4?  If so, we need
3823      * a bug workaround - timeouts less than 1 second don't work with libpcap
3824      * in 64-bit code.  (The bug was introduced in 10.6, fixed in 10.6.2,
3825      * re-introduced in 10.6.3, not fixed in 10.6.4, and fixed in 10.6.5.
3826      * The problem is extremely unlikely to be reintroduced in a future
3827      * release.)
3828      */
3829     if (uname(&osinfo) == 0) {
3830         /*
3831          * Mac OS X 10.x uses Darwin {x+4}.0.0.  Mac OS X 10.x.y uses Darwin
3832          * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
3833          * number of 10.0.0, not 10.1.0 - go figure).
3834          */
3835         if (strcmp(osinfo.release, "10.0.0") == 0 ||    /* 10.6, 10.6.1 */
3836             strcmp(osinfo.release, "10.3.0") == 0 ||    /* 10.6.3 */
3837             strcmp(osinfo.release, "10.4.0") == 0)              /* 10.6.4 */
3838             need_timeout_workaround = TRUE;
3839     }
3840 #endif
3841
3842     /*
3843      * Determine if dumpcap is being requested to run in a special
3844      * capture_child mode by going thru the command line args to see if
3845      * a -Z is present. (-Z is a hidden option).
3846      *
3847      * The primary result of running in capture_child mode is that
3848      * all messages sent out on stderr are in a special type/len/string
3849      * format to allow message processing by type.  These messages include
3850      * error messages if dumpcap fails to start the operation it was
3851      * requested to do, as well as various "status" messages which are sent
3852      * when an actual capture is in progress, and a "success" message sent
3853      * if dumpcap was requested to perform an operation other than a
3854      * capture.
3855      *
3856      * Capture_child mode would normally be requested by a parent process
3857      * which invokes dumpcap and obtains dumpcap stderr output via a pipe
3858      * to which dumpcap stderr has been redirected.  It might also have
3859      * another pipe to obtain dumpcap stdout output; for operations other
3860      * than a capture, that information is formatted specially for easier
3861      * parsing by the parent process.
3862      *
3863      * Capture_child mode needs to be determined immediately upon
3864      * startup so that any messages generated by dumpcap in this mode
3865      * (eg: during initialization) will be formatted properly.
3866      */
3867
3868     for (i=1; i<argc; i++) {
3869         if (strcmp("-Z", argv[i]) == 0) {
3870             capture_child = TRUE;
3871             machine_readable = TRUE;  /* request machine-readable output */
3872 #ifdef _WIN32
3873             /* set output pipe to binary mode, to avoid ugly text conversions */
3874             _setmode(2, O_BINARY);
3875 #endif
3876         }
3877     }
3878
3879     /* The default_log_handler will use stdout, which makes trouble in   */
3880     /* capture child mode, as it uses stdout for it's sync_pipe.         */
3881     /* So: the filtering is done in the console_log_handler and not here.*/
3882     /* We set the log handlers right up front to make sure that any log  */
3883     /* messages when running as child will be sent back to the parent    */
3884     /* with the correct format.                                          */
3885
3886     log_flags =
3887         G_LOG_LEVEL_ERROR|
3888         G_LOG_LEVEL_CRITICAL|
3889         G_LOG_LEVEL_WARNING|
3890         G_LOG_LEVEL_MESSAGE|
3891         G_LOG_LEVEL_INFO|
3892         G_LOG_LEVEL_DEBUG|
3893         G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
3894
3895     g_log_set_handler(NULL,
3896                       log_flags,
3897                       console_log_handler, NULL /* user_data */);
3898     g_log_set_handler(LOG_DOMAIN_MAIN,
3899                       log_flags,
3900                       console_log_handler, NULL /* user_data */);
3901     g_log_set_handler(LOG_DOMAIN_CAPTURE,
3902                       log_flags,
3903                       console_log_handler, NULL /* user_data */);
3904     g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
3905                       log_flags,
3906                       console_log_handler, NULL /* user_data */);
3907
3908     /* Initialize the pcaps list */
3909     global_ld.pcaps = g_array_new(FALSE, FALSE, sizeof(pcap_options *));
3910
3911 #if !GLIB_CHECK_VERSION(2,31,0)
3912     /* Initialize the thread system */
3913     g_thread_init(NULL);
3914 #endif
3915
3916 #ifdef _WIN32
3917     /* Load wpcap if possible. Do this before collecting the run-time version information */
3918     load_wpcap();
3919
3920     /* ... and also load the packet.dll from wpcap */
3921     /* XXX - currently not required, may change later. */
3922     /*wpcap_packet_load();*/
3923
3924     /* Start windows sockets */
3925     WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
3926
3927     /* Set handler for Ctrl+C key */
3928     SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
3929 #else
3930     /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
3931        and exit. */
3932     action.sa_handler = capture_cleanup_handler;
3933     /*
3934      * Arrange that system calls not get restarted, because when
3935      * our signal handler returns we don't want to restart
3936      * a call that was waiting for packets to arrive.
3937      */
3938     action.sa_flags = 0;
3939     sigemptyset(&action.sa_mask);
3940     sigaction(SIGTERM, &action, NULL);
3941     sigaction(SIGINT, &action, NULL);
3942     sigaction(SIGPIPE, &action, NULL);
3943     sigaction(SIGHUP, NULL, &oldaction);
3944     if (oldaction.sa_handler == SIG_DFL)
3945         sigaction(SIGHUP, &action, NULL);
3946
3947 #ifdef SIGINFO
3948     /* Catch SIGINFO and, if we get it and we're capturing in
3949        quiet mode, report the number of packets we've captured. */
3950     action.sa_handler = report_counts_siginfo;
3951     action.sa_flags = SA_RESTART;
3952     sigemptyset(&action.sa_mask);
3953     sigaction(SIGINFO, &action, NULL);
3954 #endif /* SIGINFO */
3955 #endif  /* _WIN32 */
3956
3957     /* ----------------------------------------------------------------- */
3958     /* Privilege and capability handling                                 */
3959     /* Cases:                                                            */
3960     /* 1. Running not as root or suid root; no special capabilities.     */
3961     /*    Action: none                                                   */
3962     /*                                                                   */
3963     /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap.  */
3964     /*    Action: none                                                   */
3965     /*                                                                   */
3966     /* 3. Running logged in as root (euid=0; ruid=0). Using libcap.      */
3967     /*    Action:                                                        */
3968     /*      - Near start of program: Enable NET_RAW and NET_ADMIN        */
3969     /*        capabilities; Drop all other capabilities;                 */
3970     /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
3971     /*        else: after  pcap_open_live() in capture_loop_open_input() */
3972     /*         drop all capabilities (NET_RAW and NET_ADMIN);            */
3973     /*         (Note: this means that the process, although logged in    */
3974     /*          as root, does not have various permissions such as the   */
3975     /*          ability to bypass file access permissions).              */
3976     /*      XXX: Should we just leave capabilities alone in this case    */
3977     /*          so that user gets expected effect that root can do       */
3978     /*          anything ??                                              */
3979     /*                                                                   */
3980     /* 4. Running as suid root (euid=0, ruid=n); Not using libcap.       */
3981     /*    Action:                                                        */
3982     /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
3983     /*        else: after  pcap_open_live() in capture_loop_open_input() */
3984     /*         drop suid root (set euid=ruid).(ie: keep suid until after */
3985     /*         pcap_open_live).                                          */
3986     /*                                                                   */
3987     /* 5. Running as suid root (euid=0, ruid=n); Using libcap.           */
3988     /*    Action:                                                        */
3989     /*      - Near start of program: Enable NET_RAW and NET_ADMIN        */
3990     /*        capabilities; Drop all other capabilities;                 */
3991     /*        Drop suid privileges (euid=ruid);                          */
3992     /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
3993     /*        else: after  pcap_open_live() in capture_loop_open_input() */
3994     /*         drop all capabilities (NET_RAW and NET_ADMIN).            */
3995     /*                                                                   */
3996     /*      XXX: For some Linux versions/distros with capabilities       */
3997     /*        a 'normal' process with any capabilities cannot be         */
3998     /*        'killed' (signaled) from another (same uid) non-privileged */
3999     /*        process.                                                   */
4000     /*        For example: If (non-suid) Wireshark forks a               */
4001     /*        child suid dumpcap which acts as described here (case 5),  */
4002     /*        Wireshark will be unable to kill (signal) the child        */
4003     /*        dumpcap process until the capabilities have been dropped   */
4004     /*        (after pcap_open_live()).                                  */
4005     /*        This behaviour will apparently be changed in the kernel    */
4006     /*        to allow the kill (signal) in this case.                   */
4007     /*        See the following for details:                             */
4008     /*           http://www.mail-archive.com/  [wrapped]                 */
4009     /*             linux-security-module@vger.kernel.org/msg02913.html   */
4010     /*                                                                   */
4011     /*        It is therefore conceivable that if dumpcap somehow hangs  */
4012     /*        in pcap_open_live or before that wireshark will not        */
4013     /*        be able to stop dumpcap using a signal (INT, TERM, etc).   */
4014     /*        In this case, exiting wireshark will kill the child        */
4015     /*        dumpcap process.                                           */
4016     /*                                                                   */
4017     /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN        */
4018     /*     capabilities; Using libcap.  Note: capset cmd (which see)     */
4019     /*     used to assign capabilities to file.                          */
4020     /*    Action:                                                        */
4021     /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
4022     /*        else: after  pcap_open_live() in capture_loop_open_input() */
4023     /*         drop all capabilities (NET_RAW and NET_ADMIN)             */
4024     /*                                                                   */
4025     /* ToDo: -S (stats) should drop privileges/capabilities when no      */
4026     /*       longer required (similar to capture).                       */
4027     /*                                                                   */
4028     /* ----------------------------------------------------------------- */
4029
4030     init_process_policies();
4031
4032 #ifdef HAVE_LIBCAP
4033     /* If 'started with special privileges' (and using libcap)  */
4034     /*   Set to keep only NET_RAW and NET_ADMIN capabilities;   */
4035     /*   Set euid/egid = ruid/rgid to remove suid privileges    */
4036     relinquish_privs_except_capture();
4037 #endif
4038
4039     /* Set the initial values in the capture options. This might be overwritten
4040        by the command line parameters. */
4041     capture_opts_init(&global_capture_opts, NULL);
4042
4043     /* We always save to a file - if no file was specified, we save to a
4044        temporary file. */
4045     global_capture_opts.saving_to_file      = TRUE;
4046     global_capture_opts.has_ring_num_files  = TRUE;
4047
4048     /* Now get our args */
4049     while ((opt = getopt(argc, argv, OPTSTRING)) != -1) {
4050         switch (opt) {
4051         case 'h':        /* Print help and exit */
4052             print_usage(TRUE);
4053             exit_main(0);
4054             break;
4055         case 'v':        /* Show version and exit */
4056         {
4057             GString             *comp_info_str;
4058             GString             *runtime_info_str;
4059             /* Assemble the compile-time version information string */
4060             comp_info_str = g_string_new("Compiled ");
4061             get_compiled_version_info(comp_info_str, NULL, NULL);
4062
4063             /* Assemble the run-time version information string */
4064             runtime_info_str = g_string_new("Running ");
4065             get_runtime_version_info(runtime_info_str, NULL);
4066             show_version(comp_info_str, runtime_info_str);
4067             g_string_free(comp_info_str, TRUE);
4068             g_string_free(runtime_info_str, TRUE);
4069             exit_main(0);
4070             break;
4071         }
4072         /*** capture option specific ***/
4073         case 'a':        /* autostop criteria */
4074         case 'b':        /* Ringbuffer option */
4075         case 'c':        /* Capture x packets */
4076         case 'f':        /* capture filter */
4077         case 'i':        /* Use interface x */
4078         case 'n':        /* Use pcapng format */
4079         case 'p':        /* Don't capture in promiscuous mode */
4080         case 'P':        /* Use pcap format */
4081         case 's':        /* Set the snapshot (capture) length */
4082         case 'w':        /* Write to capture file x */
4083         case 'g':        /* enable group read accesson file(s) */
4084         case 'y':        /* Set the pcap data link type */
4085 #ifdef HAVE_PCAP_REMOTE
4086         case 'u':        /* Use UDP for data transfer */
4087         case 'r':        /* Capture own RPCAP traffic too */
4088         case 'A':        /* Authentication */
4089 #endif
4090 #ifdef HAVE_PCAP_SETSAMPLING
4091         case 'm':        /* Sampling */
4092 #endif
4093 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
4094         case 'B':        /* Buffer size */
4095 #endif /* _WIN32 or HAVE_PCAP_CREATE */
4096 #ifdef HAVE_PCAP_CREATE
4097         case 'I':        /* Monitor mode */
4098 #endif
4099             status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
4100             if(status != 0) {
4101                 exit_main(status);
4102             }
4103             break;
4104             /*** hidden option: Wireshark child mode (using binary output messages) ***/
4105         case 'Z':
4106             capture_child = TRUE;
4107 #ifdef _WIN32
4108             /* set output pipe to binary mode, to avoid ugly text conversions */
4109             _setmode(2, O_BINARY);
4110             /*
4111              * optarg = the control ID, aka the PPID, currently used for the
4112              * signal pipe name.
4113              */
4114             if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
4115                 sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
4116                 sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
4117                                              GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
4118
4119                 if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
4120                     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4121                           "Signal pipe: Unable to open %s.  Dead parent?",
4122                           sig_pipe_name);
4123                     exit_main(1);
4124                 }
4125             }
4126 #endif
4127             break;
4128
4129         case 'q':        /* Quiet */
4130             quiet = TRUE;
4131             break;
4132         case 't':
4133             use_threads = TRUE;
4134             break;
4135             /*** all non capture option specific ***/
4136         case 'D':        /* Print a list of capture devices and exit */
4137             list_interfaces = TRUE;
4138             run_once_args++;
4139             break;
4140         case 'L':        /* Print list of link-layer types and exit */
4141             list_link_layer_types = TRUE;
4142             run_once_args++;
4143             break;
4144 #ifdef HAVE_BPF_IMAGE
4145         case 'd':        /* Print BPF code for capture filter and exit */
4146             print_bpf_code = TRUE;
4147             run_once_args++;
4148             break;
4149 #endif
4150         case 'S':        /* Print interface statistics once a second */
4151             print_statistics = TRUE;
4152             run_once_args++;
4153             break;
4154         case 'M':        /* For -D, -L, and -S, print machine-readable output */
4155             machine_readable = TRUE;
4156             break;
4157         default:
4158             cmdarg_err("Invalid Option: %s", argv[optind-1]);
4159             /* FALLTHROUGH */
4160         case '?':        /* Bad flag - print usage message */
4161             arg_error = TRUE;
4162             break;
4163         }
4164     }
4165     if (!arg_error) {
4166         argc -= optind;
4167         argv += optind;
4168         if (argc >= 1) {
4169             /* user specified file name as regular command-line argument */
4170             /* XXX - use it as the capture file name (or something else)? */
4171             argc--;
4172             argv++;
4173         }
4174         if (argc != 0) {
4175             /*
4176              * Extra command line arguments were specified; complain.
4177              * XXX - interpret as capture filter, as tcpdump and tshark do?
4178              */
4179             cmdarg_err("Invalid argument: %s", argv[0]);
4180             arg_error = TRUE;
4181         }
4182     }
4183
4184     if (arg_error) {
4185         print_usage(FALSE);
4186         exit_main(1);
4187     }
4188
4189     if (run_once_args > 1) {
4190         cmdarg_err("Only one of -D, -L, or -S may be supplied.");
4191         exit_main(1);
4192     } else if (run_once_args == 1) {
4193         /* We're supposed to print some information, rather than
4194            to capture traffic; did they specify a ring buffer option? */
4195         if (global_capture_opts.multi_files_on) {
4196             cmdarg_err("Ring buffer requested, but a capture isn't being done.");
4197             exit_main(1);
4198         }
4199     } else {
4200         /* We're supposed to capture traffic; */
4201         /* Are we capturing on multiple interface? If so, use threads and pcapng. */
4202         if (global_capture_opts.ifaces->len > 1) {
4203             use_threads = TRUE;
4204             global_capture_opts.use_pcapng = TRUE;
4205         }
4206         /* Was the ring buffer option specified and, if so, does it make sense? */
4207         if (global_capture_opts.multi_files_on) {
4208             /* Ring buffer works only under certain conditions:
4209                a) ring buffer does not work with temporary files;
4210                b) it makes no sense to enable the ring buffer if the maximum
4211                file size is set to "infinite". */
4212             if (global_capture_opts.save_file == NULL) {
4213                 cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
4214                 global_capture_opts.multi_files_on = FALSE;
4215             }
4216             if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
4217                 cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
4218 #if 0
4219                 /* XXX - this must be redesigned as the conditions changed */
4220                 global_capture_opts.multi_files_on = FALSE;
4221 #endif
4222             }
4223         }
4224     }
4225
4226     /*
4227      * "-D" requires no interface to be selected; it's supposed to list
4228      * all interfaces.
4229      */
4230     if (list_interfaces) {
4231         /* Get the list of interfaces */
4232         GList       *if_list;
4233         int         err;
4234         gchar       *err_str;
4235
4236         if_list = capture_interface_list(&err, &err_str);
4237         if (if_list == NULL) {
4238             switch (err) {
4239             case CANT_GET_INTERFACE_LIST:
4240             case DONT_HAVE_PCAP:
4241                 cmdarg_err("%s", err_str);
4242                 g_free(err_str);
4243                 exit_main(2);
4244                 break;
4245
4246             case NO_INTERFACES_FOUND:
4247                 /*
4248                  * If we're being run by another program, just give them
4249                  * an empty list of interfaces, don't report this as
4250                  * an error; that lets them decide whether to report
4251                  * this as an error or not.
4252                  */
4253                 if (!machine_readable) {
4254                     cmdarg_err("There are no interfaces on which a capture can be done");
4255                     exit_main(2);
4256                 }
4257                 break;
4258             }
4259         }
4260
4261         if (machine_readable)      /* tab-separated values to stdout */
4262             print_machine_readable_interfaces(if_list);
4263         else
4264             capture_opts_print_interfaces(if_list);
4265         free_interface_list(if_list);
4266         exit_main(0);
4267     }
4268
4269     /*
4270      * "-S" requires no interface to be selected; it gives statistics
4271      * for all interfaces.
4272      */
4273     if (print_statistics) {
4274         status = print_statistics_loop(machine_readable);
4275         exit_main(status);
4276     }
4277
4278     /*
4279      * "-L", "-d", and capturing act on a particular interface, so we have to
4280      * have an interface; if none was specified, pick a default.
4281      */
4282     if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
4283         /* cmdarg_err() already called .... */
4284         exit_main(1);
4285     }
4286
4287     /* Let the user know what interfaces were chosen. */
4288     /* get_interface_descriptive_name() is not available! */
4289     if (capture_child) {
4290         for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4291             interface_options interface_opts;
4292
4293             interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4294             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n",
4295                   interface_opts.name);
4296         }
4297     } else {
4298         str = g_string_new("");
4299 #ifdef _WIN32
4300         if (global_capture_opts.ifaces->len < 2) {
4301 #else
4302         if (global_capture_opts.ifaces->len < 4) {
4303 #endif
4304             for (j = 0; j < global_capture_opts.ifaces->len; j++) {
4305                 interface_options interface_opts;
4306
4307                 interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, j);
4308                 if (j > 0) {
4309                     if (global_capture_opts.ifaces->len > 2) {
4310                         g_string_append_printf(str, ",");
4311                     }
4312                     g_string_append_printf(str, " ");
4313                     if (j == global_capture_opts.ifaces->len - 1) {
4314                         g_string_append_printf(str, "and ");
4315                     }
4316                 }
4317                 g_string_append_printf(str, "%s", interface_opts.name);
4318             }
4319         } else {
4320             g_string_append_printf(str, "%u interfaces", global_capture_opts.ifaces->len);
4321         }
4322         fprintf(stderr, "Capturing on %s\n", str->str);
4323         g_string_free(str, TRUE);
4324     }
4325
4326     if (list_link_layer_types) {
4327         /* Get the list of link-layer types for the capture device. */
4328         if_capabilities_t *caps;
4329         gchar *err_str;
4330         guint i;
4331
4332         for (i = 0; i < global_capture_opts.ifaces->len; i++) {
4333             interface_options interface_opts;
4334
4335             interface_opts = g_array_index(global_capture_opts.ifaces, interface_options, i);
4336             caps = get_if_capabilities(interface_opts.name,
4337                                        interface_opts.monitor_mode, &err_str);
4338             if (caps == NULL) {
4339                 cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
4340                            "Please check to make sure you have sufficient permissions, and that\n"
4341                            "you have the proper interface or pipe specified.", interface_opts.name, err_str);
4342                 g_free(err_str);
4343                 exit_main(2);
4344             }
4345             if (caps->data_link_types == NULL) {
4346                 cmdarg_err("The capture device \"%s\" has no data link types.", interface_opts.name);
4347                 exit_main(2);
4348             }
4349             if (machine_readable)      /* tab-separated values to stdout */
4350                 /* XXX: We need to change the format and adopt consumers */
4351                 print_machine_readable_if_capabilities(caps);
4352             else
4353                 /* XXX: We might want to print also the interface name */
4354                 capture_opts_print_if_capabilities(caps, interface_opts.name,
4355                                                    interface_opts.monitor_mode);
4356             free_if_capabilities(caps);
4357         }
4358         exit_main(0);
4359     }
4360
4361     /* We're supposed to do a capture, or print the BPF code for a filter.
4362        Process the snapshot length, as that affects the generated BPF code. */
4363     capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
4364
4365 #ifdef HAVE_BPF_IMAGE
4366     if (print_bpf_code) {
4367         show_filter_code(&global_capture_opts);
4368         exit_main(0);
4369     }
4370 #endif
4371
4372     /* We're supposed to do a capture.  Process the ring buffer arguments. */
4373     capture_opts_trim_ring_num_files(&global_capture_opts);
4374
4375     /* Now start the capture. */
4376
4377     if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
4378         /* capture ok */
4379         exit_main(0);
4380     } else {
4381         /* capture failed */
4382         exit_main(1);
4383     }
4384     return 0; /* never here, make compiler happy */
4385 }
4386
4387
4388 static void
4389 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
4390                     const char *message, gpointer user_data _U_)
4391 {
4392     time_t curr;
4393     struct tm  *today;
4394     const char *level;
4395     gchar      *msg;
4396
4397     /* ignore log message, if log_level isn't interesting */
4398     if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4399 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
4400         return;
4401 #endif
4402     }
4403
4404     /* create a "timestamp" */
4405     time(&curr);
4406     today = localtime(&curr);
4407
4408     switch(log_level & G_LOG_LEVEL_MASK) {
4409     case G_LOG_LEVEL_ERROR:
4410         level = "Err ";
4411         break;
4412     case G_LOG_LEVEL_CRITICAL:
4413         level = "Crit";
4414         break;
4415     case G_LOG_LEVEL_WARNING:
4416         level = "Warn";
4417         break;
4418     case G_LOG_LEVEL_MESSAGE:
4419         level = "Msg ";
4420         break;
4421     case G_LOG_LEVEL_INFO:
4422         level = "Info";
4423         break;
4424     case G_LOG_LEVEL_DEBUG:
4425         level = "Dbg ";
4426         break;
4427     default:
4428         fprintf(stderr, "unknown log_level %u\n", log_level);
4429         level = NULL;
4430         g_assert_not_reached();
4431     }
4432
4433     /* Generate the output message                                  */
4434     if(log_level & G_LOG_LEVEL_MESSAGE) {
4435         /* normal user messages without additional infos */
4436         msg =  g_strdup_printf("%s\n", message);
4437     } else {
4438         /* info/debug messages with additional infos */
4439         msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
4440                               today->tm_hour, today->tm_min, today->tm_sec,
4441                               log_domain != NULL ? log_domain : "",
4442                               level, message);
4443     }
4444
4445     /* DEBUG & INFO msgs (if we're debugging today)                 */
4446 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
4447     if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
4448 #ifdef DEBUG_DUMPCAP
4449         fprintf(stderr, "%s", msg);
4450         fflush(stderr);
4451 #endif
4452 #ifdef DEBUG_CHILD_DUMPCAP
4453         fprintf(debug_log, "%s", msg);
4454         fflush(debug_log);
4455 #endif
4456         g_free(msg);
4457         return;
4458     }
4459 #endif
4460
4461     /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or    */
4462     /*  to parent especially formatted if dumpcap running as child. */
4463     if (capture_child) {
4464         sync_pipe_errmsg_to_parent(2, msg, "");
4465     } else {
4466         fprintf(stderr, "%s", msg);
4467         fflush(stderr);
4468     }
4469     g_free(msg);
4470 }
4471
4472
4473 /****************************************************************************************************************/
4474 /* indication report routines */
4475
4476
4477 static void
4478 report_packet_count(int packet_count)
4479 {
4480     char tmp[SP_DECISIZE+1+1];
4481     static int count = 0;
4482
4483     if(capture_child) {
4484         g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
4485         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
4486         pipe_write_block(2, SP_PACKET_COUNT, tmp);
4487     } else {
4488         count += packet_count;
4489         fprintf(stderr, "\rPackets: %u ", count);
4490         /* stderr could be line buffered */
4491         fflush(stderr);
4492     }
4493 }
4494
4495 static void
4496 report_new_capture_file(const char *filename)
4497 {
4498     if(capture_child) {
4499         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
4500         pipe_write_block(2, SP_FILE, filename);
4501     } else {
4502 #ifdef SIGINFO
4503         /*
4504          * Prevent a SIGINFO handler from writing to the standard error
4505          * while we're doing so; instead, have it just set a flag telling
4506          * us to print that information when we're done.
4507          */
4508         infodelay = TRUE;
4509 #endif /* SIGINFO */
4510         fprintf(stderr, "File: %s\n", filename);
4511         /* stderr could be line buffered */
4512         fflush(stderr);
4513
4514 #ifdef SIGINFO
4515         /*
4516          * Allow SIGINFO handlers to write.
4517          */
4518         infodelay = FALSE;
4519
4520         /*
4521          * If a SIGINFO handler asked us to write out capture counts, do so.
4522          */
4523         if (infoprint)
4524           report_counts_for_siginfo();
4525 #endif /* SIGINFO */
4526     }
4527 }
4528
4529 static void
4530 report_cfilter_error(capture_options *capture_opts, guint i, const char *errmsg)
4531 {
4532     interface_options interface_opts;
4533     char tmp[MSG_MAX_LENGTH+1+6];
4534
4535     if (i < capture_opts->ifaces->len) {
4536         if (capture_child) {
4537             g_snprintf(tmp, sizeof(tmp), "%u:%s", i, errmsg);
4538             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
4539             pipe_write_block(2, SP_BAD_FILTER, tmp);
4540         } else {
4541             /*
4542              * clopts_step_invalid_capfilter in test/suite-clopts.sh MUST match
4543              * the error message below.
4544              */
4545             interface_opts = g_array_index(capture_opts->ifaces, interface_options, i);
4546             cmdarg_err(
4547               "Invalid capture filter: \"%s\" for interface %s!\n"
4548               "\n"
4549               "That string isn't a valid capture filter (%s).\n"
4550               "See the User's Guide for a description of the capture filter syntax.",
4551               interface_opts.cfilter, interface_opts.name, errmsg);
4552         }
4553     }
4554 }
4555
4556 static void
4557 report_capture_error(const char *error_msg, const char *secondary_error_msg)
4558 {
4559     if(capture_child) {
4560         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4561             "Primary Error: %s", error_msg);
4562         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4563             "Secondary Error: %s", secondary_error_msg);
4564         sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
4565     } else {
4566         cmdarg_err("%s", error_msg);
4567         if (secondary_error_msg[0] != '\0')
4568           cmdarg_err_cont("%s", secondary_error_msg);
4569     }
4570 }
4571
4572 static void
4573 report_packet_drops(guint32 received, guint32 drops, gchar *name)
4574 {
4575     char tmp[SP_DECISIZE+1+1];
4576
4577     g_snprintf(tmp, sizeof(tmp), "%u", drops);
4578
4579     if(capture_child) {
4580         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4581             "Packets received/dropped on interface %s: %u/%u",
4582             name, received, drops);
4583         /* XXX: Need to provide interface id, changes to consumers required. */
4584         pipe_write_block(2, SP_DROPS, tmp);
4585     } else {
4586         fprintf(stderr,
4587             "Packets received/dropped on interface %s: %u/%u (%.1f%%)\n",
4588             name, received, drops,
4589             received ? 100.0 * received / (received + drops) : 0.0);
4590         /* stderr could be line buffered */
4591         fflush(stderr);
4592     }
4593 }
4594
4595
4596 /****************************************************************************************************************/
4597 /* signal_pipe handling */
4598
4599
4600 #ifdef _WIN32
4601 static gboolean
4602 signal_pipe_check_running(void)
4603 {
4604     /* any news from our parent? -> just stop the capture */
4605     DWORD avail = 0;
4606     gboolean result;
4607
4608     /* if we are running standalone, no check required */
4609     if(!capture_child) {
4610         return TRUE;
4611     }
4612
4613     if(!sig_pipe_name || !sig_pipe_handle) {
4614         /* This shouldn't happen */
4615         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4616             "Signal pipe: No name or handle");
4617         return FALSE;
4618     }
4619
4620     /*
4621      * XXX - We should have the process ID of the parent (from the "-Z" flag)
4622      * at this point.  Should we check to see if the parent is still alive,
4623      * e.g. by using OpenProcess?
4624      */
4625
4626     result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
4627
4628     if(!result || avail > 0) {
4629         /* peek failed or some bytes really available */
4630         /* (if not piping from stdin this would fail) */
4631         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4632             "Signal pipe: Stop capture: %s", sig_pipe_name);
4633         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4634             "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
4635             sig_pipe_handle, result, avail);
4636         return FALSE;
4637     } else {
4638         /* pipe ok and no bytes available */
4639         return TRUE;
4640     }
4641 }
4642 #endif
4643
4644 /*
4645  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
4646  *
4647  * Local variables:
4648  * c-basic-offset: 4
4649  * tab-width: 8
4650  * indent-tabs-mode: nil
4651  * End:
4652  *
4653  * vi: set shiftwidth=4 tabstop=8 expandtab:
4654  * :indentSize=4:tabSize=8:noTabs=true:
4655  */