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