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