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