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