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