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