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