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