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