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