Pull capture_loop.c into dumpcap.c, as dumpcap is the only program that
[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 <stdlib.h> /* for exit() */
29 #include <glib.h>
30
31 #include <string.h>
32 #include <ctype.h>
33
34 #ifdef HAVE_SYS_TYPES_H
35 # include <sys/types.h>
36 #endif
37
38 #ifdef HAVE_SYS_STAT_H
39 # include <sys/stat.h>
40 #endif
41
42 #ifdef HAVE_FCNTL_H
43 #include <fcntl.h>
44 #endif
45
46 #ifdef HAVE_UNISTD_H
47 #include <unistd.h>
48 #endif
49
50 #include <signal.h>
51 #include <errno.h>
52
53 #ifdef NEED_GETOPT_H
54 #include "getopt.h"
55 #endif
56
57 #ifdef HAVE_NETDB_H
58 #include <netdb.h>
59 #endif
60
61 #ifdef HAVE_LIBCAP
62 # include <sys/prctl.h>
63 # include <sys/capability.h>
64 # include <stdio.h>
65 #endif
66
67 #include "ringbuffer.h"
68 #include "clopts_common.h"
69 #include "cmdarg_err.h"
70 #include "version_info.h"
71
72 #include <pcap.h>
73 #include "pcapio.h"
74
75 #include "capture-pcap-util.h"
76
77 #ifdef _WIN32
78 #include "capture-wpcap.h"
79 #endif
80
81 #ifdef _WIN32
82 #include "epan/unicode-utils.h"
83 #endif
84
85 #ifdef HAVE_LIBCAP
86 #include "epan/privileges.h"
87 #endif
88
89 #include "sync_pipe.h"
90
91 #include "capture.h"
92 #include "capture_sync.h"
93
94 #include "conditions.h"
95 #include "capture_stop_conditions.h"
96
97 #include "tempfile.h"
98 #include "log.h"
99 #include "file_util.h"
100
101 #include "epan/unicode-utils.h"
102
103 #ifdef NEED_G_ASCII_STRCASECMP_H
104 #include "epan/g_ascii_strcasecmp.h"
105 #endif
106
107 /*
108  * Get information about libpcap format from "wiretap/libpcap.h".
109  * XXX - can we just use pcap_open_offline() to read the pipe?
110  */
111 #include "wiretap/libpcap.h"
112
113 /*#define DEBUG_DUMPCAP*/
114
115 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
116 #ifdef _WIN32
117 static gchar *sig_pipe_name = NULL;
118 static HANDLE sig_pipe_handle = NULL;
119 #endif
120
121 /** Stop a low-level capture (stops the capture child). */
122 static void capture_loop_stop(void);
123
124 #if !defined (__linux__)
125 #ifndef HAVE_PCAP_BREAKLOOP
126 /*
127  * We don't have pcap_breakloop(), which is the only way to ensure that
128  * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
129  * won't, if the call to read the next packet or batch of packets is
130  * is interrupted by a signal on UN*X, just go back and try again to
131  * read again.
132  *
133  * On UN*X, we catch SIGUSR1 as a "stop capturing" signal, and, in
134  * the signal handler, set a flag to stop capturing; however, without
135  * a guarantee of that sort, we can't guarantee that we'll stop capturing
136  * if the read will be retried and won't time out if no packets arrive.
137  *
138  * Therefore, on at least some platforms, we work around the lack of
139  * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
140  * to wait for packets to arrive, so that we're probably going to be
141  * blocked in the select() when the signal arrives, and can just bail
142  * out of the loop at that point.
143  *
144  * However, we don't want to that on BSD (because "select()" doesn't work
145  * correctly on BPF devices on at least some releases of some flavors of
146  * BSD), and we don't want to do it on Windows (because "select()" is
147  * something for sockets, not for arbitrary handles).  (Note that "Windows"
148  * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
149  * using WinPcap, not a UNIX libpcap.)
150  *
151  * Fortunately, we don't need to do it on BSD, because the libpcap timeout
152  * on BSD times out even if no packets have arrived, so we'll eventually
153  * exit pcap_dispatch() with an indication that no packets have arrived,
154  * and will break out of the capture loop at that point.
155  *
156  * On Windows, we can't send a SIGUSR1 to stop capturing, so none of this
157  * applies in any case.
158  *
159  * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
160  * want to include it if it's not present on this platform, however.
161  */
162 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
163     !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
164     !defined(__CYGWIN__)
165 #  define MUST_DO_SELECT
166 # endif /* avoid select */
167 #endif /* HAVE_PCAP_BREAKLOOP */
168 #else /* linux */
169 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
170  * in pcap_dispatch(); on the other hand, select() works just fine there.
171  * Hence we use a select for that come what may.
172  */
173 #define MUST_DO_SELECT
174 #endif
175
176 typedef void (*capture_packet_cb_fct)(u_char *, const struct pcap_pkthdr *, const u_char *);
177
178 /** init the capture filter */
179 typedef enum {
180   INITFILTER_NO_ERROR,
181   INITFILTER_BAD_FILTER,
182   INITFILTER_OTHER_ERROR
183 } initfilter_status_t;
184
185 typedef struct _loop_data {
186   /* common */
187   gboolean       go;                    /* TRUE as long as we're supposed to keep capturing */
188   int            err;                   /* if non-zero, error seen while capturing */
189   gint           packet_count;          /* Number of packets we have already captured */
190   gint           packet_max;            /* Number of packets we're supposed to capture - 0 means infinite */
191
192   capture_packet_cb_fct  packet_cb;     /* callback for a single captured packet */
193
194   /* pcap "input file" */
195   pcap_t        *pcap_h;                /* pcap handle */
196   gboolean       pcap_err;              /* TRUE if error from pcap */
197 #ifdef MUST_DO_SELECT
198   int            pcap_fd;               /* pcap file descriptor */
199 #endif
200
201   /* capture pipe (unix only "input file") */
202   gboolean       from_cap_pipe;         /* TRUE if we are capturing data from a capture pipe */
203   struct pcap_hdr cap_pipe_hdr;         /* Pcap header when capturing from a pipe */
204   struct pcaprec_modified_hdr cap_pipe_rechdr;  /* Pcap record header when capturing from a pipe */
205   int            cap_pipe_fd;           /* the file descriptor of the capture pipe */
206   gboolean       cap_pipe_modified;     /* TRUE if data in the pipe uses modified pcap headers */
207   gboolean       cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
208   unsigned int   cap_pipe_bytes_to_read;/* Used by cap_pipe_dispatch */
209   unsigned int   cap_pipe_bytes_read;   /* Used by cap_pipe_dispatch */
210   enum {
211          STATE_EXPECT_REC_HDR,
212          STATE_READ_REC_HDR,
213          STATE_EXPECT_DATA,
214          STATE_READ_DATA
215        } cap_pipe_state;
216   enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
217
218   /* output file */
219   FILE          *pdh;
220   int            linktype;
221   gint           wtap_linktype;
222   long           bytes_written;
223
224 } loop_data;
225
226 /*
227  * Standard secondary message for unexpected errors.
228  */
229 static const char please_report[] =
230     "Please report this to the Wireshark developers.\n"
231     "(This is not a crash; please do not report it as such.)";
232
233 /*
234  * This needs to be static, so that the SIGUSR1 handler can clear the "go"
235  * flag.
236  */
237 static loop_data   ld;
238
239
240 /*
241  * Timeout, in milliseconds, for reads from the stream of captured packets.
242  */
243 #define CAP_READ_TIMEOUT        250
244 static char *cap_pipe_err_str;
245
246 static void
247 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
248                     const char *message, gpointer user_data _U_);
249
250 /* capture related options */
251 static capture_options global_capture_opts;
252 static capture_options *capture_opts = &global_capture_opts;
253
254 static void capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
255   const u_char *pd);
256 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
257                           int err, gboolean is_close);
258
259
260 #if __GNUC__ >= 2
261 static void exit_main(int err) __attribute__ ((noreturn));
262 #else
263 static void exit_main(int err);
264 #endif
265
266 static void report_new_capture_file(const char *filename);
267 static void report_packet_count(int packet_count);
268 static void report_packet_drops(int drops);
269 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
270 static void report_cfilter_error(const char *cfilter, const char *errmsg);
271
272 #ifdef _WIN32
273 static gboolean signal_pipe_check_running(void);
274 #endif
275
276 static void
277 print_usage(gboolean print_ver) {
278
279   FILE *output;
280
281
282   if (print_ver) {
283     output = stdout;
284     fprintf(output,
285         "Dumpcap " VERSION "%s\n"
286         "Capture network packets and dump them into a libpcap file.\n"
287         "See http://www.wireshark.org for more information.\n",
288         wireshark_svnversion);
289   } else {
290     output = stderr;
291   }
292   fprintf(output, "\nUsage: dumpcap [options] ...\n");
293   fprintf(output, "\n");
294   fprintf(output, "Capture interface:\n");
295   fprintf(output, "  -i <interface>           name or idx of interface (def: first non-loopback)\n");
296   fprintf(output, "  -f <capture filter>      packet filter in libpcap filter syntax\n");
297   fprintf(output, "  -s <snaplen>             packet snapshot length (def: 65535)\n");
298   fprintf(output, "  -p                       don't capture in promiscuous mode\n");
299 #ifdef _WIN32
300   fprintf(output, "  -B <buffer size>         size of kernel buffer (def: 1MB)\n");
301 #endif
302   fprintf(output, "  -y <link type>           link layer type (def: first appropriate)\n");
303   fprintf(output, "  -D                       print list of interfaces and exit\n");
304   fprintf(output, "  -L                       print list of link-layer types of iface and exit\n");
305   fprintf(output, "  -S                       print statistics for each interface once every second\n");
306   fprintf(output, "  -M                       for -D, -L, and -S produce machine-readable output\n");
307   fprintf(output, "\n");
308 #ifdef HAVE_PCAP_REMOTE
309   fprintf(output, "\nRPCAP options:\n");
310   fprintf(output, "  -r                       don't ignore own RPCAP traffic in capture\n");
311   fprintf(output, "  -u                       use UDP for RPCAP data transfer\n");
312   fprintf(output, "  -A <user>:<password>     use RPCAP password authentication\n");
313 #ifdef HAVE_PCAP_SETSAMPLING
314   fprintf(output, "  -m <sampling type>       use packet sampling\n");
315   fprintf(output, "                           count:NUM - capture one packet of every NUM\n");
316   fprintf(output, "                           timer:NUM - capture no more than 1 packet in NUM ms\n");
317 #endif
318 #endif
319   fprintf(output, "Stop conditions:\n");
320   fprintf(output, "  -c <packet count>        stop after n packets (def: infinite)\n");
321   fprintf(output, "  -a <autostop cond.> ...  duration:NUM - stop after NUM seconds\n");
322   fprintf(output, "                           filesize:NUM - stop this file after NUM KB\n");
323   fprintf(output, "                              files:NUM - stop after NUM files\n");
324   /*fprintf(output, "\n");*/
325   fprintf(output, "Output (files):\n");
326   fprintf(output, "  -w <filename>            name of file to save (def: tempfile)\n");
327   fprintf(output, "  -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
328   fprintf(output, "                           filesize:NUM - switch to next file after NUM KB\n");
329   fprintf(output, "                              files:NUM - ringbuffer: replace after NUM files\n");
330   /*fprintf(output, "\n");*/
331   fprintf(output, "Miscellaneous:\n");
332   fprintf(output, "  -v                       print version information and exit\n");
333   fprintf(output, "  -h                       display this help and exit\n");
334   fprintf(output, "\n");
335   fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcap\n");
336   fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcap\"\n");
337   fprintf(output, "\n");
338   fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
339 }
340
341 static void
342 show_version(GString *comp_info_str, GString *runtime_info_str)
343 {
344
345   printf(
346         "Dumpcap " VERSION "%s\n"
347         "\n"
348         "%s\n"
349         "%s\n"
350         "%s\n"
351         "See http://www.wireshark.org for more information.\n",
352         wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
353 }
354
355 /*
356  * Report an error in command-line arguments.
357  */
358 void
359 cmdarg_err(const char *fmt, ...)
360 {
361   va_list ap;
362
363   if(capture_child) {
364     /* Print a bare error */
365     va_start(ap, fmt);
366     vfprintf(stderr, fmt, ap);
367     va_end(ap);
368   } else {
369     va_start(ap, fmt);
370     fprintf(stderr, "dumpcap: ");
371     vfprintf(stderr, fmt, ap);
372     fprintf(stderr, "\n");
373     va_end(ap);
374   }
375 }
376
377 /*
378  * Report additional information for an error in command-line arguments.
379  */
380 void
381 cmdarg_err_cont(const char *fmt, ...)
382 {
383   va_list ap;
384
385   if(capture_child) {
386     /* XXX - convert to g_log */
387   } else {
388     va_start(ap, fmt);
389     vfprintf(stderr, fmt, ap);
390     fprintf(stderr, "\n");
391     va_end(ap);
392   }
393 }
394
395
396 #ifdef _WIN32
397 static BOOL WINAPI
398 capture_cleanup(DWORD dwCtrlType)
399 {
400     /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
401        Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
402        is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
403        like SIGTERM at least when the machine's shutting down.
404
405        For now, if we're running as a command rather than a capture child,
406        we handle all but CTRL_LOGOFF_EVENT as indications that we should
407        clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
408        in that way on UN*X.
409
410        If we're not running as a capture child, we might be running as
411        a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
412        user logs out.  (XXX - can we explicitly check whether we're
413        running as a service?) */
414
415     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
416         "Console: Control signal");
417     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
418         "Console: Control signal, CtrlType: %u", dwCtrlType);
419
420     /* Keep capture running if we're a service and a user logs off */
421     if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
422         capture_loop_stop();
423         return TRUE;
424     } else {
425         return FALSE;
426     }
427 }
428 #else
429 static void
430 capture_cleanup(int signum)
431 {
432     /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
433        SIGTERM.  We assume that if the user wanted it to keep running
434        after they logged out, they'd have nohupped it. */
435
436     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
437         "Console: Signal");
438     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
439         "Console: Signal, signal value: %u", signum);
440
441     capture_loop_stop();
442 }
443 #endif
444
445 static void exit_main(int status)
446 {
447 #ifdef _WIN32
448   /* Shutdown windows sockets */
449   WSACleanup();
450
451   /* can be helpful for debugging */
452 #ifdef DEBUG_DUMPCAP
453   printf("Press any key\n");
454   _getch();
455 #endif
456
457 #endif /* _WIN32 */
458
459   exit(status);
460 }
461
462 #ifdef HAVE_LIBCAP
463 /*
464  * If we were linked with libcap (not libpcap), make sure we have
465  * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
466  */
467
468 static void
469 #if 0 /* Set to enable capability debugging */
470 print_caps(char *pfx) {
471     cap_t caps = cap_get_proc();
472     fprintf(stderr, "%s: EUID: %d  Capabilities: %s\n", pfx,
473             geteuid(), cap_to_text(caps, NULL));
474     cap_free(caps);
475 #else
476 print_caps(char *pfx _U_) {
477 #endif
478 }
479
480 static void
481 relinquish_privs_except_capture(void)
482 {
483     /* CAP_NET_ADMIN: Promiscuous mode and a truckload of other
484      *                stuff we don't need (and shouldn't have).
485      * CAP_NET_RAW:   Packet capture (raw sockets).
486      */
487     cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
488     cap_t caps = cap_init();
489     int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
490
491     if (started_with_special_privs()) {
492         print_caps("Pre drop, pre set");
493         if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
494             perror("prctl()");
495         }
496
497         cap_set_flag(caps, CAP_PERMITTED,   cl_len, cap_list, CAP_SET);
498         cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
499
500         if (cap_set_proc(caps)) {
501             perror("capset()");
502         }
503         print_caps("Pre drop, post set");
504     }
505
506     relinquish_special_privs_perm();
507
508     print_caps("Post drop, pre set");
509     cap_set_flag(caps, CAP_EFFECTIVE,   cl_len, cap_list, CAP_SET);
510     if (cap_set_proc(caps)) {
511         perror("capset()");
512     }
513     print_caps("Post drop, post set");
514     cap_free(caps);
515 }
516 #endif /* HAVE_LIBCAP */
517
518 /* Take care of byte order in the libpcap headers read from pipes.
519  * (function taken from wiretap/libpcap.c) */
520 static void
521 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
522 {
523   if (byte_swapped) {
524     /* Byte-swap the record header fields. */
525     rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
526     rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
527     rechdr->incl_len = BSWAP32(rechdr->incl_len);
528     rechdr->orig_len = BSWAP32(rechdr->orig_len);
529   }
530
531   /* In file format version 2.3, the "incl_len" and "orig_len" fields were
532      swapped, in order to match the BPF header layout.
533
534      Unfortunately, some files were, according to a comment in the "libpcap"
535      source, written with version 2.3 in their headers but without the
536      interchanged fields, so if "incl_len" is greater than "orig_len" - which
537      would make no sense - we assume that we need to swap them.  */
538   if (hdr->version_major == 2 &&
539       (hdr->version_minor < 3 ||
540        (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
541     guint32 temp;
542
543     temp = rechdr->orig_len;
544     rechdr->orig_len = rechdr->incl_len;
545     rechdr->incl_len = temp;
546   }
547 }
548
549 /* Provide select() functionality for a single file descriptor
550  * on both UNIX/POSIX and Windows.
551  *
552  * The Windows version calls WaitForSingleObject instead of
553  * select().
554  *
555  * Returns the same values as select.  If an error is returned,
556  * the string cap_pipe_err_str should be used instead of errno.
557  */
558 static int
559 cap_pipe_select(int pipe_fd) {
560 #ifndef _WIN32
561   fd_set      rfds;
562   struct timeval timeout, *pto;
563   int sel_ret;
564
565   cap_pipe_err_str = "Unknown error";
566
567   FD_ZERO(&rfds);
568   FD_SET(pipe_fd, &rfds);
569
570   timeout.tv_sec = 0;
571   timeout.tv_usec = CAP_READ_TIMEOUT * 1000;
572   pto = &timeout;
573
574   sel_ret = select(pipe_fd+1, &rfds, NULL, NULL, pto);
575   if (sel_ret < 0)
576     cap_pipe_err_str = strerror(errno);
577   return sel_ret;
578 }
579 #else
580   /* XXX - Should we just use file handles exclusively under Windows?
581    * Otherwise we have to convert between file handles and file descriptors
582    * here and when we open a named pipe.
583    */
584   HANDLE hPipe = (HANDLE) _get_osfhandle(pipe_fd);
585   wchar_t *err_str;
586   DWORD wait_ret;
587
588   if (hPipe == INVALID_HANDLE_VALUE) {
589     cap_pipe_err_str = "Could not open standard input";
590     return -1;
591   }
592
593   cap_pipe_err_str = "Unknown error";
594
595   wait_ret = WaitForSingleObject(hPipe, CAP_READ_TIMEOUT);
596   switch (wait_ret) {
597     /* XXX - This probably isn't correct */
598     case WAIT_ABANDONED:
599       errno = EINTR;
600       return -1;
601     case WAIT_OBJECT_0:
602       return 1;
603     case WAIT_TIMEOUT:
604       return 0;
605     case WAIT_FAILED:
606       FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
607         NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
608       cap_pipe_err_str = utf_16to8(err_str);
609       LocalFree(err_str);
610       return -1;
611     default:
612       g_assert_not_reached();
613       return -1;
614   }
615 }
616 #endif
617
618
619 /* Mimic pcap_open_live() for pipe captures
620  * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
621  * header.
622  * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
623  * because we can't seek on pipes (see wiretap/libpcap.c for details) */
624 static int
625 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
626                  char *errmsg, int errmsgl)
627 {
628 #ifndef _WIN32
629   struct stat pipe_stat;
630 #else
631 #if 1
632   char *pncopy, *pos;
633   wchar_t *err_str;
634 #endif
635   HANDLE hPipe = NULL;
636 #endif
637   int          sel_ret;
638   int          fd;
639   int          b;
640   guint32       magic;
641   unsigned int bytes_read;
642
643   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
644
645   /*
646    * XXX (T)Wireshark blocks until we return
647    */
648   if (strcmp(pipename, "-") == 0) {
649     fd = 0; /* read from stdin */
650 #ifdef _WIN32
651     /*
652      * This is needed to set the stdin pipe into binary mode, otherwise
653      * CR/LF are mangled...
654      */
655     _setmode(0, _O_BINARY);
656 #endif  /* _WIN32 */
657   } else {
658 #ifndef _WIN32
659     if (eth_stat(pipename, &pipe_stat) < 0) {
660       if (errno == ENOENT || errno == ENOTDIR)
661         ld->cap_pipe_err = PIPNEXIST;
662       else {
663         g_snprintf(errmsg, errmsgl,
664           "The capture session could not be initiated "
665           "due to error on pipe: %s", strerror(errno));
666         ld->cap_pipe_err = PIPERR;
667       }
668       return -1;
669     }
670     if (! S_ISFIFO(pipe_stat.st_mode)) {
671       if (S_ISCHR(pipe_stat.st_mode)) {
672         /*
673          * Assume the user specified an interface on a system where
674          * interfaces are in /dev.  Pretend we haven't seen it.
675          */
676          ld->cap_pipe_err = PIPNEXIST;
677       } else
678       {
679         g_snprintf(errmsg, errmsgl,
680             "The capture session could not be initiated because\n"
681             "\"%s\" is neither an interface nor a pipe", pipename);
682         ld->cap_pipe_err = PIPERR;
683       }
684       return -1;
685     }
686     fd = eth_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
687     if (fd == -1) {
688       g_snprintf(errmsg, errmsgl,
689           "The capture session could not be initiated "
690           "due to error on pipe open: %s", strerror(errno));
691       ld->cap_pipe_err = PIPERR;
692       return -1;
693     }
694 #else /* _WIN32 */
695 #define PIPE_STR "\\pipe\\"
696     /* Under Windows, named pipes _must_ have the form
697      * "\\<server>\pipe\<pipename>".  <server> may be "." for localhost.
698      */
699     pncopy = g_strdup(pipename);
700     if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
701       pos = strchr(pncopy + 3, '\\');
702       if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
703         pos = NULL;
704     }
705
706     g_free(pncopy);
707
708     if (!pos) {
709       g_snprintf(errmsg, errmsgl,
710           "The capture session could not be initiated because\n"
711           "\"%s\" is neither an interface nor a pipe", pipename);
712       ld->cap_pipe_err = PIPNEXIST;
713       return -1;
714     }
715
716     /* Wait for the pipe to appear */
717     while (1) {
718       hPipe = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
719           OPEN_EXISTING, 0, NULL);
720
721       if (hPipe != INVALID_HANDLE_VALUE)
722         break;
723
724       if (GetLastError() != ERROR_PIPE_BUSY) {
725         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
726           NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
727         g_snprintf(errmsg, errmsgl,
728             "The capture session on \"%s\" could not be initiated "
729             "due to error on pipe open: pipe busy: %s (error %d)",
730             pipename, utf_16to8(err_str), GetLastError());
731         LocalFree(err_str);
732         ld->cap_pipe_err = PIPERR;
733         return -1;
734       }
735
736       if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
737         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
738           NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
739         g_snprintf(errmsg, errmsgl,
740             "The capture session could not be initiated "
741             "due to error on named pipe open: %s (error %d)",
742             utf_16to8(err_str), GetLastError());
743         LocalFree(err_str);
744         ld->cap_pipe_err = PIPERR;
745         return -1;
746       }
747     }
748
749     fd = _open_osfhandle((long) hPipe, _O_RDONLY);
750     if (fd == -1) {
751       g_snprintf(errmsg, errmsgl,
752           "The capture session could not be initiated "
753           "due to error on pipe open: %s", strerror(errno));
754       ld->cap_pipe_err = PIPERR;
755       return -1;
756     }
757 #endif /* _WIN32 */
758   }
759
760   ld->from_cap_pipe = TRUE;
761
762   /* read the pcap header */
763   bytes_read = 0;
764   while (bytes_read < sizeof magic) {
765     sel_ret = cap_pipe_select(fd);
766     if (sel_ret < 0) {
767       g_snprintf(errmsg, errmsgl,
768         "Unexpected error from select: %s", strerror(errno));
769       goto error;
770     } else if (sel_ret > 0) {
771       b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
772       if (b <= 0) {
773         if (b == 0)
774           g_snprintf(errmsg, errmsgl, "End of file on pipe during open");
775         else
776           g_snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
777             strerror(errno));
778         goto error;
779       }
780       bytes_read += b;
781     }
782   }
783
784   switch (magic) {
785   case PCAP_MAGIC:
786     /* Host that wrote it has our byte order, and was running
787        a program using either standard or ss990417 libpcap. */
788     ld->cap_pipe_byte_swapped = FALSE;
789     ld->cap_pipe_modified = FALSE;
790     break;
791   case PCAP_MODIFIED_MAGIC:
792     /* Host that wrote it has our byte order, but was running
793        a program using either ss990915 or ss991029 libpcap. */
794     ld->cap_pipe_byte_swapped = FALSE;
795     ld->cap_pipe_modified = TRUE;
796     break;
797   case PCAP_SWAPPED_MAGIC:
798     /* Host that wrote it has a byte order opposite to ours,
799        and was running a program using either standard or
800        ss990417 libpcap. */
801     ld->cap_pipe_byte_swapped = TRUE;
802     ld->cap_pipe_modified = FALSE;
803     break;
804   case PCAP_SWAPPED_MODIFIED_MAGIC:
805     /* Host that wrote it out has a byte order opposite to
806        ours, and was running a program using either ss990915
807        or ss991029 libpcap. */
808     ld->cap_pipe_byte_swapped = TRUE;
809     ld->cap_pipe_modified = TRUE;
810     break;
811   default:
812     /* Not a "libpcap" type we know about. */
813     g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
814     goto error;
815   }
816
817   /* Read the rest of the header */
818   bytes_read = 0;
819   while (bytes_read < sizeof(struct pcap_hdr)) {
820     sel_ret = cap_pipe_select(fd);
821     if (sel_ret < 0) {
822       g_snprintf(errmsg, errmsgl,
823         "Unexpected error from select: %s", strerror(errno));
824       goto error;
825     } else if (sel_ret > 0) {
826       b = read(fd, ((char *)hdr)+bytes_read,
827             sizeof(struct pcap_hdr) - bytes_read);
828       if (b <= 0) {
829         if (b == 0)
830           g_snprintf(errmsg, errmsgl, "End of file on pipe during open");
831         else
832           g_snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
833             strerror(errno));
834         goto error;
835       }
836       bytes_read += b;
837     }
838   }
839
840   if (ld->cap_pipe_byte_swapped) {
841     /* Byte-swap the header fields about which we care. */
842     hdr->version_major = BSWAP16(hdr->version_major);
843     hdr->version_minor = BSWAP16(hdr->version_minor);
844     hdr->snaplen = BSWAP32(hdr->snaplen);
845     hdr->network = BSWAP32(hdr->network);
846   }
847   ld->linktype = hdr->network;
848
849   if (hdr->version_major < 2) {
850     g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
851     goto error;
852   }
853
854   ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
855   ld->cap_pipe_err = PIPOK;
856   return fd;
857
858 error:
859   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
860   ld->cap_pipe_err = PIPERR;
861   eth_close(fd);
862   return -1;
863
864 }
865
866
867 /* We read one record from the pipe, take care of byte order in the record
868  * header, write the record to the capture file, and update capture statistics. */
869 static int
870 cap_pipe_dispatch(loop_data *ld, guchar *data, char *errmsg, int errmsgl)
871 {
872   struct pcap_pkthdr phdr;
873   int b;
874   enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
875           PD_ERR } result;
876
877
878 #ifdef LOG_CAPTURE_VERBOSE
879   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
880 #endif
881
882   switch (ld->cap_pipe_state) {
883
884   case STATE_EXPECT_REC_HDR:
885     ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
886       sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
887     ld->cap_pipe_bytes_read = 0;
888     ld->cap_pipe_state = STATE_READ_REC_HDR;
889     /* Fall through */
890
891   case STATE_READ_REC_HDR:
892     b = read(ld->cap_pipe_fd, ((char *)&ld->cap_pipe_rechdr)+ld->cap_pipe_bytes_read,
893              ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
894     if (b <= 0) {
895       if (b == 0)
896         result = PD_PIPE_EOF;
897       else
898         result = PD_PIPE_ERR;
899       break;
900     }
901     if ((ld->cap_pipe_bytes_read += b) < ld->cap_pipe_bytes_to_read)
902         return 0;
903     result = PD_REC_HDR_READ;
904     break;
905
906   case STATE_EXPECT_DATA:
907     ld->cap_pipe_bytes_read = 0;
908     ld->cap_pipe_state = STATE_READ_DATA;
909     /* Fall through */
910
911   case STATE_READ_DATA:
912     b = read(ld->cap_pipe_fd, data+ld->cap_pipe_bytes_read,
913              ld->cap_pipe_rechdr.hdr.incl_len - ld->cap_pipe_bytes_read);
914     if (b <= 0) {
915       if (b == 0)
916         result = PD_PIPE_EOF;
917       else
918         result = PD_PIPE_ERR;
919       break;
920     }
921     if ((ld->cap_pipe_bytes_read += b) < ld->cap_pipe_rechdr.hdr.incl_len)
922       return 0;
923     result = PD_DATA_READ;
924     break;
925
926   default:
927     g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
928     result = PD_ERR;
929
930   } /* switch (ld->cap_pipe_state) */
931
932   /*
933    * We've now read as much data as we were expecting, so process it.
934    */
935   switch (result) {
936
937   case PD_REC_HDR_READ:
938     /* We've read the header. Take care of byte order. */
939     cap_pipe_adjust_header(ld->cap_pipe_byte_swapped, &ld->cap_pipe_hdr,
940                            &ld->cap_pipe_rechdr.hdr);
941     if (ld->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
942       g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
943         ld->packet_count+1, ld->cap_pipe_rechdr.hdr.incl_len);
944       break;
945     }
946     ld->cap_pipe_state = STATE_EXPECT_DATA;
947     return 0;
948
949   case PD_DATA_READ:
950     /* Fill in a "struct pcap_pkthdr", and process the packet. */
951     phdr.ts.tv_sec = ld->cap_pipe_rechdr.hdr.ts_sec;
952     phdr.ts.tv_usec = ld->cap_pipe_rechdr.hdr.ts_usec;
953     phdr.caplen = ld->cap_pipe_rechdr.hdr.incl_len;
954     phdr.len = ld->cap_pipe_rechdr.hdr.orig_len;
955
956     ld->packet_cb((u_char *)ld, &phdr, data);
957
958     ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
959     return 1;
960
961   case PD_PIPE_EOF:
962     ld->cap_pipe_err = PIPEOF;
963     return -1;
964
965   case PD_PIPE_ERR:
966     g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
967       strerror(errno));
968     /* Fall through */
969   case PD_ERR:
970     break;
971   }
972
973   ld->cap_pipe_err = PIPERR;
974   /* Return here rather than inside the switch to prevent GCC warning */
975   return -1;
976 }
977
978
979 /** Open the capture input file (pcap or capture pipe).
980  *  Returns TRUE if it succeeds, FALSE otherwise. */
981 static gboolean
982 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
983                         char *errmsg, size_t errmsg_len,
984                         char *secondary_errmsg, size_t secondary_errmsg_len)
985 {
986   gchar       open_err_str[PCAP_ERRBUF_SIZE];
987   gchar      *sync_msg_str;
988   static const char ppamsg[] = "can't find PPA for ";
989   const char *set_linktype_err_str;
990   const char  *libpcap_warn;
991 #ifdef _WIN32
992   gchar      *sync_secondary_msg_str;
993   int         err;
994   WORD        wVersionRequested;
995   WSADATA     wsaData;
996 #endif
997 #ifdef HAVE_PCAP_REMOTE
998   struct pcap_rmtauth auth;
999 #endif
1000
1001
1002   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
1003
1004
1005 /* XXX - opening Winsock on tshark? */
1006
1007   /* Initialize Windows Socket if we are in a WIN32 OS
1008      This needs to be done before querying the interface for network/netmask */
1009 #ifdef _WIN32
1010   /* XXX - do we really require 1.1 or earlier?
1011      Are there any versions that support only 2.0 or higher? */
1012   wVersionRequested = MAKEWORD(1, 1);
1013   err = WSAStartup(wVersionRequested, &wsaData);
1014   if (err != 0) {
1015     switch (err) {
1016
1017     case WSASYSNOTREADY:
1018       g_snprintf(errmsg, errmsg_len,
1019         "Couldn't initialize Windows Sockets: Network system not ready for network communication");
1020       break;
1021
1022     case WSAVERNOTSUPPORTED:
1023       g_snprintf(errmsg, errmsg_len,
1024         "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
1025         LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
1026       break;
1027
1028     case WSAEINPROGRESS:
1029       g_snprintf(errmsg, errmsg_len,
1030         "Couldn't initialize Windows Sockets: Blocking operation is in progress");
1031       break;
1032
1033     case WSAEPROCLIM:
1034       g_snprintf(errmsg, errmsg_len,
1035         "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
1036       break;
1037
1038     case WSAEFAULT:
1039       g_snprintf(errmsg, errmsg_len,
1040         "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
1041       break;
1042
1043     default:
1044       g_snprintf(errmsg, errmsg_len,
1045         "Couldn't initialize Windows Sockets: error %d", err);
1046       break;
1047     }
1048     g_snprintf(secondary_errmsg, secondary_errmsg_len, please_report);
1049     return FALSE;
1050   }
1051 #endif
1052
1053   /* Open the network interface to capture from it.
1054      Some versions of libpcap may put warnings into the error buffer
1055      if they succeed; to tell if that's happened, we have to clear
1056      the error buffer, and check if it's still a null string.  */
1057   open_err_str[0] = '\0';
1058 #ifdef HAVE_PCAP_OPEN
1059   auth.type = capture_opts->auth_type == CAPTURE_AUTH_PWD ?
1060                     RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
1061   auth.username = capture_opts->auth_username;
1062   auth.password = capture_opts->auth_password;
1063
1064   ld->pcap_h = pcap_open(capture_opts->iface,
1065                capture_opts->has_snaplen ? capture_opts->snaplen :
1066                           WTAP_MAX_PACKET_SIZE,
1067                /* flags */
1068                (capture_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
1069                (capture_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
1070                (capture_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
1071                CAP_READ_TIMEOUT, &auth, open_err_str);
1072 #else
1073   ld->pcap_h = pcap_open_live(capture_opts->iface,
1074                        capture_opts->has_snaplen ? capture_opts->snaplen :
1075                                                   WTAP_MAX_PACKET_SIZE,
1076                        capture_opts->promisc_mode, CAP_READ_TIMEOUT,
1077                        open_err_str);
1078 #endif
1079
1080   if (ld->pcap_h != NULL) {
1081     /* we've opened "iface" as a network device */
1082 #ifdef _WIN32
1083     /* try to set the capture buffer size */
1084     if (pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
1085         sync_secondary_msg_str = g_strdup_printf(
1086           "The capture buffer size of %luMB seems to be too high for your machine,\n"
1087           "the default of 1MB will be used.\n"
1088           "\n"
1089           "Nonetheless, the capture is started.\n",
1090           capture_opts->buffer_size);
1091         report_capture_error("Couldn't set the capture buffer size!",
1092                                    sync_secondary_msg_str);
1093         g_free(sync_secondary_msg_str);
1094     }
1095 #endif
1096
1097 #if defined(HAVE_PCAP_REMOTE) && defined(HAVE_PCAP_SETSAMPLING)
1098     if (capture_opts->sampling_method != CAPTURE_SAMP_NONE)
1099     {
1100         struct pcap_samp *samp;
1101
1102         if ((samp = pcap_setsampling(ld->pcap_h)) != NULL)
1103         {
1104             switch (capture_opts->sampling_method)
1105             {
1106                 case CAPTURE_SAMP_BY_COUNT:
1107                     samp->method = PCAP_SAMP_1_EVERY_N;
1108                     break;
1109
1110                 case CAPTURE_SAMP_BY_TIMER:
1111                     samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
1112                     break;
1113
1114                 default:
1115                     sync_msg_str = g_strdup_printf(
1116                             "Unknown sampling method %d specified,\n"
1117                             "continue without packet sampling",
1118                             capture_opts->sampling_method);
1119                     report_capture_error("Couldn't set the capture "
1120                             "sampling", sync_msg_str);
1121                     g_free(sync_msg_str);
1122             }
1123             samp->value = capture_opts->sampling_param;
1124         }
1125         else
1126         {
1127             report_capture_error("Couldn't set the capture sampling",
1128                     "Cannot get packet sampling data structure");
1129         }
1130
1131     }
1132 #endif
1133
1134     /* setting the data link type only works on real interfaces */
1135     if (capture_opts->linktype != -1) {
1136       set_linktype_err_str = set_pcap_linktype(ld->pcap_h, capture_opts->iface,
1137         capture_opts->linktype);
1138       if (set_linktype_err_str != NULL) {
1139         g_snprintf(errmsg, errmsg_len, "Unable to set data link type (%s).",
1140                    set_linktype_err_str);
1141         g_snprintf(secondary_errmsg, secondary_errmsg_len, please_report);
1142         return FALSE;
1143       }
1144     }
1145     ld->linktype = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
1146   } else {
1147     /* We couldn't open "iface" as a network device. */
1148     /* Try to open it as a pipe */
1149     ld->cap_pipe_fd = cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, errmsg_len);
1150
1151     if (ld->cap_pipe_fd == -1) {
1152
1153       if (ld->cap_pipe_err == PIPNEXIST) {
1154         /* Pipe doesn't exist, so output message for interface */
1155
1156         /* If we got a "can't find PPA for X" message, warn the user (who
1157            is running (T)Wireshark on HP-UX) that they don't have a version
1158            of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1159            versions, which properly handle HP-UX, say "can't find /dev/dlpi
1160            PPA for X" rather than "can't find PPA for X"). */
1161         if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1162           libpcap_warn =
1163             "\n\n"
1164             "You are running (T)Wireshark with a version of the libpcap library\n"
1165             "that doesn't handle HP-UX network devices well; this means that\n"
1166             "(T)Wireshark may not be able to capture packets.\n"
1167             "\n"
1168             "To fix this, you should install libpcap 0.6.2, or a later version\n"
1169             "of libpcap, rather than libpcap 0.4 or 0.5.x.  It is available in\n"
1170             "packaged binary form from the Software Porting And Archive Centre\n"
1171             "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1172             "at the URL lists a number of mirror sites.";
1173         else
1174           libpcap_warn = "";
1175         g_snprintf(errmsg, errmsg_len,
1176           "The capture session could not be initiated (%s).", open_err_str);
1177 #ifndef _WIN32
1178         g_snprintf(secondary_errmsg, secondary_errmsg_len,
1179 "Please check to make sure you have sufficient permissions, and that you have "
1180 "the proper interface or pipe specified.%s", libpcap_warn);
1181 #else
1182     g_snprintf(secondary_errmsg, secondary_errmsg_len,
1183 "\n"
1184 "Please check that \"%s\" is the proper interface.\n"
1185 "\n"
1186 "\n"
1187 "Help can be found at:\n"
1188 "\n"
1189 "       http://wiki.wireshark.org/CaptureSetup\n"
1190 "\n"
1191 "64-bit Windows:\n"
1192 "WinPcap does not support 64-bit Windows; you will have to use some other\n"
1193 "tool to capture traffic, such as netcap.\n"
1194 "For netcap details see: http://support.microsoft.com/?id=310875\n"
1195 "\n"
1196 "Modem (PPP/WAN):\n"
1197 "Note that version 3.0 of WinPcap, and earlier versions of WinPcap, don't\n"
1198 "support capturing on PPP/WAN interfaces on Windows NT 4.0 / 2000 / XP /\n"
1199 "Server 2003.\n"
1200 "WinPcap 3.1 has support for it on Windows 2000 / XP / Server 2003, but has no\n"
1201 "support for it on Windows NT 4.0 or Windows Vista (Beta 1).",
1202     capture_opts->iface);
1203 #endif /* _WIN32 */
1204       }
1205       /*
1206        * Else pipe (or file) does exist and cap_pipe_open_live() has
1207        * filled in errmsg
1208        */
1209       return FALSE;
1210     } else
1211       /* cap_pipe_open_live() succeeded; don't want
1212          error message from pcap_open_live() */
1213       open_err_str[0] = '\0';
1214   }
1215
1216 /* XXX - will this work for tshark? */
1217 #ifdef MUST_DO_SELECT
1218   if (!ld->from_cap_pipe) {
1219 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
1220     ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
1221 #else
1222     ld->pcap_fd = pcap_fileno(ld->pcap_h);
1223 #endif
1224   }
1225 #endif
1226
1227   /* Does "open_err_str" contain a non-empty string?  If so, "pcap_open_live()"
1228      returned a warning; print it, but keep capturing. */
1229   if (open_err_str[0] != '\0') {
1230     sync_msg_str = g_strdup_printf("%s.", open_err_str);
1231     report_capture_error(sync_msg_str, "");
1232     g_free(sync_msg_str);
1233   }
1234
1235   return TRUE;
1236 }
1237
1238
1239 /* close the capture input file (pcap or capture pipe) */
1240 static void capture_loop_close_input(loop_data *ld) {
1241
1242   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
1243
1244   /* if open, close the capture pipe "input file" */
1245   if (ld->cap_pipe_fd >= 0) {
1246     g_assert(ld->from_cap_pipe);
1247     eth_close(ld->cap_pipe_fd);
1248     ld->cap_pipe_fd = 0;
1249   }
1250
1251   /* if open, close the pcap "input file" */
1252   if(ld->pcap_h != NULL) {
1253     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", ld->pcap_h);
1254     g_assert(!ld->from_cap_pipe);
1255     pcap_close(ld->pcap_h);
1256     ld->pcap_h = NULL;
1257   }
1258
1259   ld->go = FALSE;
1260
1261 #ifdef _WIN32
1262   /* Shut down windows sockets */
1263   WSACleanup();
1264 #endif
1265 }
1266
1267
1268 /* init the capture filter */
1269 static initfilter_status_t
1270 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe, gchar * iface, gchar * cfilter) {
1271   bpf_u_int32 netnum, netmask;
1272   gchar       lookup_net_err_str[PCAP_ERRBUF_SIZE];
1273   struct bpf_program fcode;
1274
1275
1276   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
1277
1278   /* capture filters only work on real interfaces */
1279   if (cfilter && !from_cap_pipe) {
1280     /* A capture filter was specified; set it up. */
1281     if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1282       /*
1283        * Well, we can't get the netmask for this interface; it's used
1284        * only for filters that check for broadcast IP addresses, so
1285        * we just punt and use 0.  It might be nice to warn the user,
1286        * but that's a pain in a GUI application, as it'd involve popping
1287        * up a message box, and it's not clear how often this would make
1288        * a difference (only filters that check for IP broadcast addresses
1289        * use the netmask).
1290        */
1291       /*cmdarg_err(
1292         "Warning:  Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
1293       netmask = 0;
1294     }
1295     if (pcap_compile(pcap_h, &fcode, cfilter, 1, netmask) < 0) {
1296       /* Treat this specially - our caller might try to compile this
1297          as a display filter and, if that succeeds, warn the user that
1298          the display and capture filter syntaxes are different. */
1299       return INITFILTER_BAD_FILTER;
1300     }
1301     if (pcap_setfilter(pcap_h, &fcode) < 0) {
1302 #ifdef HAVE_PCAP_FREECODE
1303       pcap_freecode(&fcode);
1304 #endif
1305       return INITFILTER_OTHER_ERROR;
1306     }
1307 #ifdef HAVE_PCAP_FREECODE
1308     pcap_freecode(&fcode);
1309 #endif
1310   }
1311
1312   return INITFILTER_NO_ERROR;
1313 }
1314
1315
1316 /* set up to write to the already-opened capture output file/files */
1317 static gboolean
1318 capture_loop_init_output(capture_options *capture_opts, int save_file_fd, loop_data *ld, char *errmsg, int errmsg_len) {
1319   int         file_snaplen;
1320   int         err;
1321
1322
1323   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
1324
1325   /* get snaplen */
1326   if (ld->from_cap_pipe) {
1327     file_snaplen = ld->cap_pipe_hdr.snaplen;
1328   } else
1329   {
1330     file_snaplen = pcap_snapshot(ld->pcap_h);
1331   }
1332
1333   /* Set up to write to the capture file. */
1334   if (capture_opts->multi_files_on) {
1335     ld->pdh = ringbuf_init_libpcap_fdopen(ld->linktype, file_snaplen,
1336                                           &ld->bytes_written, &err);
1337   } else {
1338     ld->pdh = libpcap_fdopen(save_file_fd, ld->linktype, file_snaplen,
1339                              &ld->bytes_written, &err);
1340   }
1341
1342   if (ld->pdh == NULL) {
1343     /* We couldn't set up to write to the capture file. */
1344     /* XXX - use cf_open_error_message from tshark instead? */
1345     switch (err) {
1346
1347     case WTAP_ERR_CANT_OPEN:
1348       g_snprintf(errmsg, errmsg_len, "The file to which the capture would be saved"
1349                " couldn't be created for some unknown reason.");
1350       break;
1351
1352     case WTAP_ERR_SHORT_WRITE:
1353       g_snprintf(errmsg, errmsg_len, "A full header couldn't be written to the file"
1354                " to which the capture would be saved.");
1355       break;
1356
1357     default:
1358       if (err < 0) {
1359         g_snprintf(errmsg, errmsg_len,
1360                      "The file to which the capture would be"
1361                      " saved (\"%s\") could not be opened: Error %d.",
1362                         capture_opts->save_file, err);
1363       } else {
1364         g_snprintf(errmsg, errmsg_len,
1365                      "The file to which the capture would be"
1366                      " saved (\"%s\") could not be opened: %s.",
1367                         capture_opts->save_file, strerror(err));
1368       }
1369       break;
1370     }
1371
1372     return FALSE;
1373   }
1374
1375   return TRUE;
1376 }
1377
1378 static gboolean
1379 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
1380
1381   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
1382
1383   if (capture_opts->multi_files_on) {
1384     return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
1385   } else {
1386     return libpcap_dump_close(ld->pdh, err_close);
1387   }
1388 }
1389
1390 /* dispatch incoming packets (pcap or capture pipe)
1391  *
1392  * Waits for incoming packets to be available, and calls pcap_dispatch()
1393  * to cause them to be processed.
1394  *
1395  * Returns the number of packets which were processed.
1396  *
1397  * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
1398  * packet-batching behaviour does not cause packets to get held back
1399  * indefinitely.
1400  */
1401 static int
1402 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
1403                       char *errmsg, int errmsg_len)
1404 {
1405   int       inpkts;
1406   int       sel_ret;
1407   gint      packet_count_before;
1408   guchar    pcap_data[WTAP_MAX_PACKET_SIZE];
1409
1410   packet_count_before = ld->packet_count;
1411   if (ld->from_cap_pipe) {
1412     /* dispatch from capture pipe */
1413 #ifdef LOG_CAPTURE_VERBOSE
1414     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
1415 #endif
1416     sel_ret = cap_pipe_select(ld->cap_pipe_fd);
1417     if (sel_ret <= 0) {
1418       inpkts = 0;
1419       if (sel_ret < 0 && errno != EINTR) {
1420         g_snprintf(errmsg, errmsg_len,
1421           "Unexpected error from select: %s", strerror(errno));
1422         report_capture_error(errmsg, please_report);
1423         ld->go = FALSE;
1424       }
1425     } else {
1426       /*
1427        * "select()" says we can read from the pipe without blocking
1428        */
1429       inpkts = cap_pipe_dispatch(ld, pcap_data, errmsg, errmsg_len);
1430       if (inpkts < 0) {
1431         ld->go = FALSE;
1432       }
1433     }
1434   }
1435   else
1436   {
1437     /* dispatch from pcap */
1438 #ifdef MUST_DO_SELECT
1439     /*
1440      * If we have "pcap_get_selectable_fd()", we use it to get the
1441      * descriptor on which to select; if that's -1, it means there
1442      * is no descriptor on which you can do a "select()" (perhaps
1443      * because you're capturing on a special device, and that device's
1444      * driver unfortunately doesn't support "select()", in which case
1445      * we don't do the select - which means it might not be possible
1446      * to stop a capture until a packet arrives.  If that's unacceptable,
1447      * plead with whoever supplies the software for that device to add
1448      * "select()" support, or upgrade to libpcap 0.8.1 or later, and
1449      * rebuild Wireshark or get a version built with libpcap 0.8.1 or
1450      * later, so it can use pcap_breakloop().
1451      */
1452 #ifdef LOG_CAPTURE_VERBOSE
1453     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
1454 #endif
1455     if (ld->pcap_fd != -1) {
1456       sel_ret = cap_pipe_select(ld->pcap_fd);
1457       if (sel_ret > 0) {
1458         /*
1459          * "select()" says we can read from it without blocking; go for
1460          * it.
1461          *
1462          * We don't have pcap_breakloop(), so we only process one packet
1463          * per pcap_dispatch() call, to allow a signal to stop the
1464          * processing immediately, rather than processing all packets
1465          * in a batch before quitting.
1466          */
1467         inpkts = pcap_dispatch(ld->pcap_h, 1, ld->packet_cb, (u_char *)ld);
1468         if (inpkts < 0) {
1469           ld->pcap_err = TRUE;
1470           ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1471         }
1472       } else {
1473         if (sel_ret < 0 && errno != EINTR) {
1474           g_snprintf(errmsg, errmsg_len,
1475             "Unexpected error from select: %s", strerror(errno));
1476           report_capture_error(errmsg, please_report);
1477           ld->go = FALSE;
1478         }
1479       }
1480     }
1481     else
1482 #endif /* MUST_DO_SELECT */
1483     {
1484       /* dispatch from pcap without select */
1485 #if 1
1486 #ifdef LOG_CAPTURE_VERBOSE
1487       g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
1488 #endif
1489 #ifdef _WIN32
1490       /*
1491        * On Windows, we don't support asynchronously telling a process to
1492        * stop capturing; instead, we check for an indication on a pipe
1493        * after processing packets.  We therefore process only one packet
1494        * at a time, so that we can check the pipe after every packet.
1495        */
1496       inpkts = pcap_dispatch(ld->pcap_h, 1, ld->packet_cb, (u_char *) ld);
1497 #else
1498       inpkts = pcap_dispatch(ld->pcap_h, -1, ld->packet_cb, (u_char *) ld);
1499 #endif
1500       if (inpkts < 0) {
1501         if (inpkts == -1) {
1502           /* Error, rather than pcap_breakloop(). */
1503           ld->pcap_err = TRUE;
1504         }
1505         ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1506       }
1507 #else /* pcap_next_ex */
1508 #ifdef LOG_CAPTURE_VERBOSE
1509       g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
1510 #endif
1511       /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
1512
1513       /*
1514        * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
1515        * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
1516        * This should be fixed in the WinPcap 4.0 alpha release.
1517        *
1518        * For reference, an example remote interface:
1519        * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
1520        */
1521
1522       /* emulate dispatch from pcap */
1523       {
1524         int in;
1525         struct pcap_pkthdr *pkt_header;
1526         u_char *pkt_data;
1527
1528         in = 0;
1529         while(ld->go &&
1530               (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1)
1531           ld->packet_cb( (u_char *) ld, pkt_header, pkt_data);
1532
1533         if(in < 0) {
1534           ld->pcap_err = TRUE;
1535           ld->go = FALSE;
1536         }
1537       }
1538 #endif /* pcap_next_ex */
1539     }
1540   }
1541
1542 #ifdef LOG_CAPTURE_VERBOSE
1543   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
1544 #endif
1545
1546   return ld->packet_count - packet_count_before;
1547 }
1548
1549
1550 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
1551 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
1552 static gboolean
1553 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
1554                       char *errmsg, int errmsg_len) {
1555
1556   char tmpname[128+1];
1557   gchar *capfile_name;
1558   gboolean is_tempfile;
1559
1560
1561   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
1562       (capture_opts->save_file) ? capture_opts->save_file : "");
1563
1564   if (capture_opts->save_file != NULL) {
1565     /* We return to the caller while the capture is in progress.
1566      * Therefore we need to take a copy of save_file in
1567      * case the caller destroys it after we return.
1568      */
1569     capfile_name = g_strdup(capture_opts->save_file);
1570
1571     if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
1572       if (capture_opts->multi_files_on) {
1573         /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
1574         g_snprintf(errmsg, errmsg_len,
1575             "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
1576         g_free(capfile_name);
1577         return FALSE;
1578       }
1579       if (strcmp(capfile_name, "-") == 0) {
1580         /* write to stdout */
1581         *save_file_fd = 1;
1582 #ifdef _WIN32
1583         /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF)  */
1584         _setmode(1, O_BINARY);
1585 #endif
1586       }
1587     } /* if (...output_to_pipe ... */
1588
1589     else {
1590       if (capture_opts->multi_files_on) {
1591         /* ringbuffer is enabled */
1592         *save_file_fd = ringbuf_init(capfile_name,
1593             (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
1594
1595         /* we need the ringbuf name */
1596         if(*save_file_fd != -1) {
1597             g_free(capfile_name);
1598             capfile_name = g_strdup(ringbuf_current_filename());
1599         }
1600       } else {
1601         /* Try to open/create the specified file for use as a capture buffer. */
1602         *save_file_fd = eth_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
1603                              0600);
1604       }
1605     }
1606     is_tempfile = FALSE;
1607   } else {
1608     /* Choose a random name for the temporary capture buffer */
1609     *save_file_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
1610     capfile_name = g_strdup(tmpname);
1611     is_tempfile = TRUE;
1612   }
1613
1614   /* did we fail to open the output file? */
1615   if (*save_file_fd == -1) {
1616     if (is_tempfile) {
1617       g_snprintf(errmsg, errmsg_len,
1618         "The temporary file to which the capture would be saved (\"%s\") "
1619         "could not be opened: %s.", capfile_name, strerror(errno));
1620     } else {
1621       if (capture_opts->multi_files_on) {
1622         ringbuf_error_cleanup();
1623       }
1624
1625       g_snprintf(errmsg, errmsg_len,
1626             "The file to which the capture would be saved (\"%s\") "
1627         "could not be opened: %s.", capfile_name,
1628         strerror(errno));
1629     }
1630     g_free(capfile_name);
1631     return FALSE;
1632   }
1633
1634   if(capture_opts->save_file != NULL) {
1635     g_free(capture_opts->save_file);
1636   }
1637   capture_opts->save_file = capfile_name;
1638   /* capture_opts.save_file is "g_free"ed later, which is equivalent to
1639      "g_free(capfile_name)". */
1640 #ifndef _WIN32
1641   fchown(*save_file_fd, capture_opts->owner, capture_opts->group);
1642 #endif
1643
1644   return TRUE;
1645 }
1646
1647
1648 static void
1649 capture_loop_stop_signal_handler(int signo _U_)
1650 {
1651   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Signal: Stop capture");
1652   capture_loop_stop();
1653 }
1654
1655 #ifdef _WIN32
1656 #define TIME_GET() GetTickCount()
1657 #else
1658 #define TIME_GET() time(NULL)
1659 #endif
1660
1661 /* Do the low-level work of a capture.
1662    Returns TRUE if it succeeds, FALSE otherwise. */
1663 static gboolean
1664 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
1665 {
1666 #ifndef _WIN32
1667   struct sigaction act;
1668 #endif
1669   time_t      upd_time, cur_time;
1670   time_t      start_time;
1671   int         err_close;
1672   int         inpkts;
1673   gint        inpkts_to_sync_pipe = 0;     /* packets not already send out to the sync_pipe */
1674   condition  *cnd_file_duration = NULL;
1675   condition  *cnd_autostop_files = NULL;
1676   condition  *cnd_autostop_size = NULL;
1677   condition  *cnd_autostop_duration = NULL;
1678   guint32     autostop_files = 0;
1679   gboolean    write_ok;
1680   gboolean    close_ok;
1681   gboolean    cfilter_error = FALSE;
1682 #define MSG_MAX_LENGTH 4096
1683   char        errmsg[MSG_MAX_LENGTH+1];
1684   char        secondary_errmsg[MSG_MAX_LENGTH+1];
1685   int         save_file_fd = -1;
1686
1687   *errmsg           = '\0';
1688   *secondary_errmsg = '\0';
1689
1690   /* init the loop data */
1691   ld.go                 = TRUE;
1692   ld.packet_count       = 0;
1693   if (capture_opts->has_autostop_packets)
1694     ld.packet_max       = capture_opts->autostop_packets;
1695   else
1696     ld.packet_max       = 0;    /* no limit */
1697   ld.err                = 0;    /* no error seen yet */
1698   ld.wtap_linktype      = WTAP_ENCAP_UNKNOWN;
1699   ld.pcap_err           = FALSE;
1700   ld.from_cap_pipe      = FALSE;
1701   ld.pdh                = NULL;
1702   ld.cap_pipe_fd        = -1;
1703 #ifdef MUST_DO_SELECT
1704   ld.pcap_fd            = 0;
1705 #endif
1706   ld.packet_cb          = capture_loop_packet_cb;
1707
1708
1709   /* We haven't yet gotten the capture statistics. */
1710   *stats_known      = FALSE;
1711
1712 #ifndef _WIN32
1713   /*
1714    * Catch SIGUSR1, so that we exit cleanly if the parent process
1715    * kills us with it due to the user selecting "Capture->Stop".
1716    */
1717   act.sa_handler = capture_loop_stop_signal_handler;
1718   /*
1719    * Arrange that system calls not get restarted, because when
1720    * our signal handler returns we don't want to restart
1721    * a call that was waiting for packets to arrive.
1722    */
1723   act.sa_flags = 0;
1724   sigemptyset(&act.sa_mask);
1725   sigaction(SIGUSR1, &act, NULL);
1726 #endif /* _WIN32 */
1727
1728   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
1729   capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
1730
1731   /* open the "input file" from network interface or capture pipe */
1732   if (!capture_loop_open_input(capture_opts, &ld, errmsg, sizeof(errmsg),
1733                                secondary_errmsg, sizeof(secondary_errmsg))) {
1734     goto error;
1735   }
1736
1737   /* init the input filter from the network interface (capture pipe will do nothing) */
1738   switch (capture_loop_init_filter(ld.pcap_h, ld.from_cap_pipe, capture_opts->iface, capture_opts->cfilter)) {
1739
1740   case INITFILTER_NO_ERROR:
1741     break;
1742
1743   case INITFILTER_BAD_FILTER:
1744     cfilter_error = TRUE;
1745     g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(ld.pcap_h));
1746     goto error;
1747
1748   case INITFILTER_OTHER_ERROR:
1749     g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
1750                pcap_geterr(ld.pcap_h));
1751     g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
1752     goto error;
1753   }
1754
1755   /* If we're supposed to write to a capture file, open it for output
1756      (temporary/specified name/ringbuffer) */
1757   if (capture_opts->saving_to_file) {
1758     if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
1759       goto error;
1760     }
1761
1762     /* set up to write to the already-opened capture output file/files */
1763     if (!capture_loop_init_output(capture_opts, save_file_fd, &ld, errmsg, sizeof(errmsg))) {
1764       goto error;
1765     }
1766
1767   /* XXX - capture SIGTERM and close the capture, in case we're on a
1768      Linux 2.0[.x] system and you have to explicitly close the capture
1769      stream in order to turn promiscuous mode off?  We need to do that
1770      in other places as well - and I don't think that works all the
1771      time in any case, due to libpcap bugs. */
1772
1773     /* Well, we should be able to start capturing.
1774
1775        Sync out the capture file, so the header makes it to the file system,
1776        and send a "capture started successfully and capture file created"
1777        message to our parent so that they'll open the capture file and
1778        update its windows to indicate that we have a live capture in
1779        progress. */
1780     libpcap_dump_flush(ld.pdh, NULL);
1781     report_new_capture_file(capture_opts->save_file);
1782   }
1783
1784   /* initialize capture stop (and alike) conditions */
1785   init_capture_stop_conditions();
1786   /* create stop conditions */
1787   if (capture_opts->has_autostop_filesize)
1788     cnd_autostop_size =
1789         cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
1790   if (capture_opts->has_autostop_duration)
1791     cnd_autostop_duration =
1792         cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
1793
1794   if (capture_opts->multi_files_on) {
1795       if (capture_opts->has_file_duration)
1796         cnd_file_duration =
1797             cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
1798
1799       if (capture_opts->has_autostop_files)
1800         cnd_autostop_files =
1801             cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
1802   }
1803
1804   /* init the time values */
1805   start_time = TIME_GET();
1806   upd_time = TIME_GET();
1807
1808   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
1809
1810   /* WOW, everything is prepared! */
1811   /* please fasten your seat belts, we will enter now the actual capture loop */
1812   while (ld.go) {
1813     /* dispatch incoming packets */
1814     inpkts = capture_loop_dispatch(capture_opts, &ld, errmsg, sizeof(errmsg));
1815
1816 #ifdef _WIN32
1817     /* any news from our parent (signal pipe)? -> just stop the capture */
1818     if (!signal_pipe_check_running()) {
1819       ld.go = FALSE;
1820     }
1821 #endif
1822
1823     if (inpkts > 0) {
1824       inpkts_to_sync_pipe += inpkts;
1825
1826       /* check capture size condition */
1827       if (cnd_autostop_size != NULL &&
1828           cnd_eval(cnd_autostop_size, (guint32)ld.bytes_written)){
1829         /* Capture size limit reached, do we have another file? */
1830         if (capture_opts->multi_files_on) {
1831           if (cnd_autostop_files != NULL &&
1832               cnd_eval(cnd_autostop_files, ++autostop_files)) {
1833              /* no files left: stop here */
1834             ld.go = FALSE;
1835             continue;
1836           }
1837
1838           /* Switch to the next ringbuffer file */
1839           if (ringbuf_switch_file(&ld.pdh, &capture_opts->save_file,
1840               &save_file_fd, &ld.bytes_written, &ld.err)) {
1841             /* File switch succeeded: reset the conditions */
1842             cnd_reset(cnd_autostop_size);
1843             if (cnd_file_duration) {
1844               cnd_reset(cnd_file_duration);
1845             }
1846             libpcap_dump_flush(ld.pdh, NULL);
1847             report_packet_count(inpkts_to_sync_pipe);
1848             inpkts_to_sync_pipe = 0;
1849             report_new_capture_file(capture_opts->save_file);
1850           } else {
1851             /* File switch failed: stop here */
1852             ld.go = FALSE;
1853             continue;
1854           }
1855         } else {
1856           /* single file, stop now */
1857           ld.go = FALSE;
1858           continue;
1859         }
1860       } /* cnd_autostop_size */
1861       if (capture_opts->output_to_pipe) {
1862         libpcap_dump_flush(ld.pdh, NULL);
1863       }
1864     } /* inpkts */
1865
1866     /* Only update once a second (Win32: 500ms) so as not to overload slow
1867      * displays. This also prevents too much context-switching between the
1868      * dumpcap and wireshark processes */
1869     cur_time = TIME_GET();
1870 #ifdef _WIN32
1871     if ( (cur_time - upd_time) > 500) {
1872 #else
1873     if (cur_time - upd_time > 0) {
1874 #endif
1875         upd_time = cur_time;
1876
1877       /*if (pcap_stats(pch, stats) >= 0) {
1878         *stats_known = TRUE;
1879       }*/
1880
1881       /* Let the parent process know. */
1882       if (inpkts_to_sync_pipe) {
1883         /* do sync here */
1884         libpcap_dump_flush(ld.pdh, NULL);
1885
1886         /* Send our parent a message saying we've written out "inpkts_to_sync_pipe"
1887            packets to the capture file. */
1888         report_packet_count(inpkts_to_sync_pipe);
1889
1890         inpkts_to_sync_pipe = 0;
1891       }
1892
1893       /* check capture duration condition */
1894       if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
1895         /* The maximum capture time has elapsed; stop the capture. */
1896         ld.go = FALSE;
1897         continue;
1898       }
1899
1900       /* check capture file duration condition */
1901       if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
1902         /* duration limit reached, do we have another file? */
1903         if (capture_opts->multi_files_on) {
1904           if (cnd_autostop_files != NULL &&
1905               cnd_eval(cnd_autostop_files, ++autostop_files)) {
1906             /* no files left: stop here */
1907             ld.go = FALSE;
1908             continue;
1909           }
1910
1911           /* Switch to the next ringbuffer file */
1912           if (ringbuf_switch_file(&ld.pdh, &capture_opts->save_file,
1913                                   &save_file_fd, &ld.bytes_written, &ld.err)) {
1914             /* file switch succeeded: reset the conditions */
1915             cnd_reset(cnd_file_duration);
1916             if(cnd_autostop_size)
1917               cnd_reset(cnd_autostop_size);
1918             libpcap_dump_flush(ld.pdh, NULL);
1919             report_packet_count(inpkts_to_sync_pipe);
1920             inpkts_to_sync_pipe = 0;
1921             report_new_capture_file(capture_opts->save_file);
1922           } else {
1923             /* File switch failed: stop here */
1924             ld.go = FALSE;
1925             continue;
1926           }
1927         } else {
1928           /* single file, stop now */
1929           ld.go = FALSE;
1930           continue;
1931         }
1932       } /* cnd_file_duration */
1933     }
1934
1935   } /* while (ld.go) */
1936
1937   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
1938
1939   /* delete stop conditions */
1940   if (cnd_file_duration != NULL)
1941     cnd_delete(cnd_file_duration);
1942   if (cnd_autostop_files != NULL)
1943     cnd_delete(cnd_autostop_files);
1944   if (cnd_autostop_size != NULL)
1945     cnd_delete(cnd_autostop_size);
1946   if (cnd_autostop_duration != NULL)
1947     cnd_delete(cnd_autostop_duration);
1948
1949   /* did we had a pcap (input) error? */
1950   if (ld.pcap_err) {
1951     /* On Linux, if an interface goes down while you're capturing on it,
1952        you'll get a "recvfrom: Network is down" error (ENETDOWN).
1953        (At least you will if strerror() doesn't show a local translation
1954        of the error.)
1955
1956        On FreeBSD and OS X, if a network adapter disappears while
1957        you're capturing on it, you'll get a "read: Device not configured"
1958        error (ENXIO).  (See previous parenthetical note.)
1959
1960        On OpenBSD, you get "read: I/O error" (EIO) in the same case.
1961
1962        These should *not* be reported to the Wireshark developers. */
1963     char *cap_err_str;
1964
1965     cap_err_str = pcap_geterr(ld.pcap_h);
1966     if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
1967         strcmp(cap_err_str, "read: Device not configured") == 0 ||
1968         strcmp(cap_err_str, "read: I/O error") == 0) {
1969       report_capture_error("The network adapter on which the capture was being done "
1970                            "is no longer running; the capture has stopped.",
1971                            "");
1972     } else {
1973       g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
1974         cap_err_str);
1975       report_capture_error(errmsg, please_report);
1976     }
1977   }
1978   else if (ld.from_cap_pipe && ld.cap_pipe_err == PIPERR)
1979     report_capture_error(errmsg, "");
1980
1981   /* did we had an error while capturing? */
1982   if (ld.err == 0) {
1983     write_ok = TRUE;
1984   } else {
1985     capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, ld.err,
1986                               FALSE);
1987     report_capture_error(errmsg, please_report);
1988     write_ok = FALSE;
1989   }
1990
1991   if (capture_opts->saving_to_file) {
1992     /* close the wiretap (output) file */
1993     close_ok = capture_loop_close_output(capture_opts, &ld, &err_close);
1994   } else
1995     close_ok = TRUE;
1996
1997   /* there might be packets not yet notified to the parent */
1998   /* (do this after closing the file, so all packets are already flushed) */
1999   if(inpkts_to_sync_pipe) {
2000     report_packet_count(inpkts_to_sync_pipe);
2001     inpkts_to_sync_pipe = 0;
2002   }
2003
2004   /* If we've displayed a message about a write error, there's no point
2005      in displaying another message about an error on close. */
2006   if (!close_ok && write_ok) {
2007     capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
2008                 TRUE);
2009     report_capture_error(errmsg, "");
2010   }
2011
2012   /*
2013    * XXX We exhibit different behaviour between normal mode and sync mode
2014    * when the pipe is stdin and not already at EOF.  If we're a child, the
2015    * parent's stdin isn't closed, so if the user starts another capture,
2016    * cap_pipe_open_live() will very likely not see the expected magic bytes and
2017    * will say "Unrecognized libpcap format".  On the other hand, in normal
2018    * mode, cap_pipe_open_live() will say "End of file on pipe during open".
2019    */
2020
2021   /* get packet drop statistics from pcap */
2022   if(ld.pcap_h != NULL) {
2023     g_assert(!ld.from_cap_pipe);
2024     /* Get the capture statistics, so we know how many packets were
2025        dropped. */
2026     if (pcap_stats(ld.pcap_h, stats) >= 0) {
2027       *stats_known = TRUE;
2028       /* Let the parent process know. */
2029       report_packet_drops(stats->ps_drop);
2030     } else {
2031       g_snprintf(errmsg, sizeof(errmsg),
2032                 "Can't get packet-drop statistics: %s",
2033                 pcap_geterr(ld.pcap_h));
2034       report_capture_error(errmsg, please_report);
2035     }
2036   }
2037
2038   /* close the input file (pcap or capture pipe) */
2039   capture_loop_close_input(&ld);
2040
2041   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
2042
2043   /* ok, if the write and the close were successful. */
2044   return write_ok && close_ok;
2045
2046 error:
2047   if (capture_opts->multi_files_on) {
2048     /* cleanup ringbuffer */
2049     ringbuf_error_cleanup();
2050   } else {
2051     /* We can't use the save file, and we have no FILE * for the stream
2052        to close in order to close it, so close the FD directly. */
2053     if(save_file_fd != -1) {
2054       eth_close(save_file_fd);
2055     }
2056
2057     /* We couldn't even start the capture, so get rid of the capture
2058        file. */
2059     if(capture_opts->save_file != NULL) {
2060       eth_unlink(capture_opts->save_file);
2061       g_free(capture_opts->save_file);
2062     }
2063   }
2064   capture_opts->save_file = NULL;
2065   if (cfilter_error)
2066     report_cfilter_error(capture_opts->cfilter, errmsg);
2067   else
2068     report_capture_error(errmsg, secondary_errmsg);
2069
2070   /* close the input file (pcap or cap_pipe) */
2071   capture_loop_close_input(&ld);
2072
2073   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
2074
2075   return FALSE;
2076 }
2077
2078
2079 static void capture_loop_stop(void)
2080 {
2081 #ifdef HAVE_PCAP_BREAKLOOP
2082   if(ld.pcap_h != NULL)
2083     pcap_breakloop(ld.pcap_h);
2084 #endif
2085   ld.go = FALSE;
2086 }
2087
2088
2089 static void
2090 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
2091                           int err, gboolean is_close)
2092 {
2093   switch (err) {
2094
2095   case ENOSPC:
2096     g_snprintf(errmsg, errmsglen,
2097                 "Not all the packets could be written to the file"
2098                 " to which the capture was being saved\n"
2099                 "(\"%s\") because there is no space left on the file system\n"
2100                 "on which that file resides.",
2101                 fname);
2102     break;
2103
2104 #ifdef EDQUOT
2105   case EDQUOT:
2106     g_snprintf(errmsg, errmsglen,
2107                 "Not all the packets could be written to the file"
2108                 " to which the capture was being saved\n"
2109                 "(\"%s\") because you are too close to, or over,"
2110                 " your disk quota\n"
2111                 "on the file system on which that file resides.",
2112                 fname);
2113   break;
2114 #endif
2115
2116   case WTAP_ERR_CANT_CLOSE:
2117     g_snprintf(errmsg, errmsglen,
2118                 "The file to which the capture was being saved"
2119                 " couldn't be closed for some unknown reason.");
2120     break;
2121
2122   case WTAP_ERR_SHORT_WRITE:
2123     g_snprintf(errmsg, errmsglen,
2124                 "Not all the packets could be written to the file"
2125                 " to which the capture was being saved\n"
2126                 "(\"%s\").",
2127                 fname);
2128     break;
2129
2130   default:
2131     if (is_close) {
2132       g_snprintf(errmsg, errmsglen,
2133                 "The file to which the capture was being saved\n"
2134                 "(\"%s\") could not be closed: %s.",
2135                 fname, wtap_strerror(err));
2136     } else {
2137       g_snprintf(errmsg, errmsglen,
2138                 "An error occurred while writing to the file"
2139                 " to which the capture was being saved\n"
2140                 "(\"%s\"): %s.",
2141                 fname, wtap_strerror(err));
2142     }
2143     break;
2144   }
2145 }
2146
2147
2148 /* one packet was captured, process it */
2149 static void
2150 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
2151   const u_char *pd)
2152 {
2153   loop_data *ld = (void *) user;
2154   int err;
2155
2156   /* if the user told us to stop after x packets, do we already have enough? */
2157   if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
2158   {
2159      ld->go = FALSE;
2160      return;
2161   }
2162
2163   /* We may be called multiple times from pcap_dispatch(); if we've set
2164      the "stop capturing" flag, ignore this packet, as we're not
2165      supposed to be saving any more packets. */
2166   if (!ld->go)
2167     return;
2168
2169   if (ld->pdh) {
2170     /* We're supposed to write the packet to a file; do so.
2171        If this fails, set "ld->go" to FALSE, to stop the capture, and set
2172        "ld->err" to the error. */
2173     if (!libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err)) {
2174       ld->go = FALSE;
2175       ld->err = err;
2176     } else
2177       ld->packet_count++;
2178   }
2179 }
2180
2181
2182 /* And now our feature presentation... [ fade to music ] */
2183 int
2184 main(int argc, char *argv[])
2185 {
2186   int                  opt;
2187   extern char         *optarg;
2188   gboolean             arg_error = FALSE;
2189
2190 #ifdef _WIN32
2191   WSADATA              wsaData;
2192 #endif  /* _WIN32 */
2193 #ifndef _WIN32
2194   struct sigaction action, oldaction;
2195 #endif
2196
2197   gboolean             start_capture = TRUE;
2198   gboolean             stats_known;
2199   struct pcap_stat     stats;
2200   GLogLevelFlags       log_flags;
2201   gboolean             list_interfaces = FALSE;
2202   gboolean             list_link_layer_types = FALSE;
2203   gboolean             machine_readable = FALSE;
2204   gboolean             print_statistics = FALSE;
2205   int                  status, run_once_args = 0;
2206
2207 #ifdef HAVE_PCAP_REMOTE
2208 #define OPTSTRING_INIT "a:A:b:c:Df:hi:Lm:MprSs:uvw:y:Z:"
2209 #else
2210 #define OPTSTRING_INIT "a:b:c:Df:hi:LMpSs:vw:y:Z:"
2211 #endif
2212
2213 #ifdef _WIN32
2214 #define OPTSTRING_WIN32 "B:"
2215 #else
2216 #define OPTSTRING_WIN32 ""
2217 #endif  /* _WIN32 */
2218
2219   char optstring[sizeof(OPTSTRING_INIT) + sizeof(OPTSTRING_WIN32) - 1] =
2220     OPTSTRING_INIT OPTSTRING_WIN32;
2221
2222 #ifdef _WIN32
2223   /* Load wpcap if possible. Do this before collecting the run-time version information */
2224   load_wpcap();
2225
2226   /* ... and also load the packet.dll from wpcap */
2227   /* XXX - currently not required, may change later. */
2228   /*wpcap_packet_load();*/
2229
2230   /* Start windows sockets */
2231   WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
2232
2233   /* Set handler for Ctrl+C key */
2234   SetConsoleCtrlHandler(capture_cleanup, TRUE);
2235 #else
2236   /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
2237      and exit. */
2238   action.sa_handler = capture_cleanup;
2239   action.sa_flags = 0;
2240   sigemptyset(&action.sa_mask);
2241   sigaction(SIGTERM, &action, NULL);
2242   sigaction(SIGINT, &action, NULL);
2243   sigaction(SIGHUP, NULL, &oldaction);
2244   if (oldaction.sa_handler == SIG_DFL)
2245     sigaction(SIGHUP, &action, NULL);
2246 #endif  /* _WIN32 */
2247
2248 #ifdef HAVE_LIBCAP
2249   get_credential_info();
2250   relinquish_privs_except_capture();
2251 #endif
2252
2253   /* the default_log_handler will use stdout, which makes trouble in */
2254   /* capture child mode, as it uses stdout for it's sync_pipe */
2255   /* so do the filtering in the console_log_handler and not here */
2256   log_flags =
2257                     G_LOG_LEVEL_ERROR|
2258                     G_LOG_LEVEL_CRITICAL|
2259                     G_LOG_LEVEL_WARNING|
2260                     G_LOG_LEVEL_MESSAGE|
2261                     G_LOG_LEVEL_INFO|
2262                     G_LOG_LEVEL_DEBUG|
2263                     G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
2264
2265   g_log_set_handler(NULL,
2266                     log_flags,
2267                     console_log_handler, NULL /* user_data */);
2268   g_log_set_handler(LOG_DOMAIN_MAIN,
2269                     log_flags,
2270                     console_log_handler, NULL /* user_data */);
2271   g_log_set_handler(LOG_DOMAIN_CAPTURE,
2272                     log_flags,
2273             console_log_handler, NULL /* user_data */);
2274   g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
2275                     log_flags,
2276             console_log_handler, NULL /* user_data */);
2277
2278   /* Set the initial values in the capture_opts. This might be overwritten
2279      by the command line parameters. */
2280   capture_opts_init(capture_opts, NULL);
2281
2282   /* Default to capturing the entire packet. */
2283   capture_opts->snaplen             = WTAP_MAX_PACKET_SIZE;
2284
2285   /* We always save to a file - if no file was specified, we save to a
2286      temporary file. */
2287   capture_opts->saving_to_file      = TRUE;
2288   capture_opts->has_ring_num_files  = TRUE;
2289
2290   /* Now get our args */
2291   while ((opt = getopt(argc, argv, optstring)) != -1) {
2292     switch (opt) {
2293       case 'h':        /* Print help and exit */
2294         print_usage(TRUE);
2295         exit_main(0);
2296         break;
2297       case 'v':        /* Show version and exit */
2298       {
2299         GString             *comp_info_str;
2300         GString             *runtime_info_str;
2301         /* Assemble the compile-time version information string */
2302         comp_info_str = g_string_new("Compiled ");
2303         get_compiled_version_info(comp_info_str, NULL);
2304
2305         /* Assemble the run-time version information string */
2306         runtime_info_str = g_string_new("Running ");
2307         get_runtime_version_info(runtime_info_str, NULL);
2308         show_version(comp_info_str, runtime_info_str);
2309         g_string_free(comp_info_str, TRUE);
2310         g_string_free(runtime_info_str, TRUE);
2311         exit_main(0);
2312         break;
2313       }
2314       /*** capture option specific ***/
2315       case 'a':        /* autostop criteria */
2316       case 'b':        /* Ringbuffer option */
2317       case 'c':        /* Capture x packets */
2318       case 'f':        /* capture filter */
2319       case 'i':        /* Use interface x */
2320       case 'p':        /* Don't capture in promiscuous mode */
2321       case 's':        /* Set the snapshot (capture) length */
2322       case 'w':        /* Write to capture file x */
2323       case 'y':        /* Set the pcap data link type */
2324 #ifdef HAVE_PCAP_REMOTE
2325       case 'u':        /* Use UDP for data transfer */
2326       case 'r':        /* Capture own RPCAP traffic too */
2327       case 'A':        /* Authentication */
2328 #endif
2329 #ifdef HAVE_PCAP_SETSAMPLING
2330       case 'm':        /* Sampling */
2331 #endif
2332 #ifdef _WIN32
2333       case 'B':        /* Buffer size */
2334 #endif /* _WIN32 */
2335         status = capture_opts_add_opt(capture_opts, opt, optarg, &start_capture);
2336         if(status != 0) {
2337             exit_main(status);
2338         }
2339         break;
2340       /*** hidden option: Wireshark child mode (using binary output messages) ***/
2341       case 'Z':
2342           capture_child = TRUE;
2343 #ifdef _WIN32
2344           /* set output pipe to binary mode, to avoid ugly text conversions */
2345           _setmode(2, O_BINARY);
2346           /*
2347            * optarg = the control ID, aka the PPID, currently used for the
2348            * signal pipe name.
2349            */
2350           if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
2351               sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT,
2352                   optarg);
2353               sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
2354                   GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
2355
2356               if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
2357                   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2358                       "Signal pipe: Unable to open %s.  Dead parent?",
2359                       sig_pipe_name);
2360                   exit_main(1);
2361               }
2362           }
2363 #endif
2364           break;
2365
2366       /*** all non capture option specific ***/
2367       case 'D':        /* Print a list of capture devices and exit */
2368         list_interfaces = TRUE;
2369         run_once_args++;
2370         break;
2371       case 'L':        /* Print list of link-layer types and exit */
2372         list_link_layer_types = TRUE;
2373         run_once_args++;
2374         break;
2375       case 'S':        /* Print interface statistics once a second */
2376         print_statistics = TRUE;
2377         run_once_args++;
2378         break;
2379       case 'M':        /* For -D and -L, print machine-readable output */
2380         machine_readable = TRUE;
2381         break;
2382       default:
2383       case '?':        /* Bad flag - print usage message */
2384         cmdarg_err("Invalid Option: %s", argv[optind-1]);
2385         arg_error = TRUE;
2386         break;
2387     }
2388   }
2389   argc -= optind;
2390   argv += optind;
2391   if (argc >= 1) {
2392       /* user specified file name as regular command-line argument */
2393       /* XXX - use it as the capture file name (or something else)? */
2394     argc--;
2395     argv++;
2396   }
2397
2398   if (argc != 0) {
2399     /*
2400      * Extra command line arguments were specified; complain.
2401      * XXX - interpret as capture filter, as tcpdump and tshark do?
2402      */
2403     cmdarg_err("Invalid argument: %s", argv[0]);
2404     arg_error = TRUE;
2405   }
2406
2407   if (arg_error) {
2408     print_usage(FALSE);
2409     exit_main(1);
2410   }
2411
2412   if (run_once_args > 1) {
2413     cmdarg_err("Only one of -D, -L, or -S may be supplied.");
2414     exit_main(1);
2415   } else if (list_link_layer_types) {
2416     /* We're supposed to list the link-layer types for an interface;
2417        did the user also specify a capture file to be read? */
2418     /* No - did they specify a ring buffer option? */
2419     if (capture_opts->multi_files_on) {
2420       cmdarg_err("Ring buffer requested, but a capture isn't being done.");
2421       exit_main(1);
2422     }
2423   } else {
2424     /* No - was the ring buffer option specified and, if so, does it make
2425        sense? */
2426     if (capture_opts->multi_files_on) {
2427       /* Ring buffer works only under certain conditions:
2428          a) ring buffer does not work with temporary files;
2429          b) it makes no sense to enable the ring buffer if the maximum
2430             file size is set to "infinite". */
2431       if (capture_opts->save_file == NULL) {
2432         cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
2433         capture_opts->multi_files_on = FALSE;
2434       }
2435       if (!capture_opts->has_autostop_filesize && !capture_opts->has_file_duration) {
2436         cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
2437 /* XXX - this must be redesigned as the conditions changed */
2438 /*      capture_opts->multi_files_on = FALSE;*/
2439       }
2440     }
2441   }
2442
2443   if (capture_opts_trim_iface(capture_opts, NULL) == FALSE) {
2444         cmdarg_err("No capture interfaces available (maybe lack of privileges?).");
2445     exit_main(1);
2446   }
2447
2448   /* Let the user know what interface was chosen. */
2449   /* get_interface_descriptive_name() is not available! */
2450   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", capture_opts->iface);
2451
2452   if (list_interfaces) {
2453     status = capture_opts_list_interfaces(machine_readable);
2454     exit_main(status);
2455   } else if (list_link_layer_types) {
2456     status = capture_opts_list_link_layer_types(capture_opts, machine_readable);
2457     exit_main(status);
2458   } else if (print_statistics) {
2459     status = capture_opts_print_statistics(machine_readable);
2460     exit_main(status);
2461   }
2462
2463   capture_opts_trim_snaplen(capture_opts, MIN_PACKET_SIZE);
2464   capture_opts_trim_ring_num_files(capture_opts);
2465
2466   /* Now start the capture. */
2467
2468   if(capture_loop_start(capture_opts, &stats_known, &stats) == TRUE) {
2469       /* capture ok */
2470       exit_main(0);
2471   } else {
2472       /* capture failed */
2473       exit_main(1);
2474   }
2475 }
2476
2477
2478 static void
2479 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
2480                     const char *message, gpointer user_data _U_)
2481 {
2482   time_t curr;
2483   struct tm *today;
2484   const char *level;
2485
2486
2487   /* ignore log message, if log_level isn't interesting */
2488   if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
2489 #ifndef DEBUG_DUMPCAP
2490     return;
2491 #endif
2492   }
2493
2494   /* create a "timestamp" */
2495   time(&curr);
2496   today = localtime(&curr);
2497
2498   switch(log_level & G_LOG_LEVEL_MASK) {
2499   case G_LOG_LEVEL_ERROR:
2500     level = "Err ";
2501     break;
2502   case G_LOG_LEVEL_CRITICAL:
2503     level = "Crit";
2504     break;
2505   case G_LOG_LEVEL_WARNING:
2506     level = "Warn";
2507     break;
2508   case G_LOG_LEVEL_MESSAGE:
2509     level = "Msg ";
2510     break;
2511   case G_LOG_LEVEL_INFO:
2512     level = "Info";
2513     break;
2514   case G_LOG_LEVEL_DEBUG:
2515     level = "Dbg ";
2516     break;
2517   default:
2518     fprintf(stderr, "unknown log_level %u\n", log_level);
2519     level = NULL;
2520     g_assert_not_reached();
2521   }
2522
2523   /* don't use printf (stdout), in child mode we're using stdout for the sync_pipe */
2524   if(log_level & G_LOG_LEVEL_MESSAGE) {
2525     /* normal user messages without additional infos */
2526     fprintf(stderr, "%s\n", message);
2527     fflush(stderr);
2528   } else {
2529     /* info/debug messages with additional infos */
2530     fprintf(stderr, "%02u:%02u:%02u %8s %s %s\n",
2531             today->tm_hour, today->tm_min, today->tm_sec,
2532             log_domain != NULL ? log_domain : "",
2533             level, message);
2534     fflush(stderr);
2535   }
2536 }
2537
2538
2539 /****************************************************************************************************************/
2540 /* indication report routines */
2541
2542
2543 void
2544 report_packet_count(int packet_count)
2545 {
2546     char tmp[SP_DECISIZE+1+1];
2547     static int count = 0;
2548
2549     if(capture_child) {
2550         g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
2551         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
2552         pipe_write_block(2, SP_PACKET_COUNT, tmp);
2553     } else {
2554         count += packet_count;
2555         fprintf(stderr, "\rPackets: %u ", count);
2556         /* stderr could be line buffered */
2557         fflush(stderr);
2558     }
2559 }
2560
2561 void
2562 report_new_capture_file(const char *filename)
2563 {
2564     if(capture_child) {
2565         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
2566         pipe_write_block(2, SP_FILE, filename);
2567     } else {
2568         fprintf(stderr, "File: %s\n", filename);
2569         /* stderr could be line buffered */
2570         fflush(stderr);
2571     }
2572 }
2573
2574 void
2575 report_cfilter_error(const char *cfilter, const char *errmsg)
2576 {
2577     if (capture_child) {
2578         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
2579         pipe_write_block(2, SP_BAD_FILTER, errmsg);
2580     } else {
2581         fprintf(stderr,
2582           "Invalid capture filter: \"%s\"!\n"
2583           "\n"
2584           "That string isn't a valid capture filter (%s).\n"
2585           "See the User's Guide for a description of the capture filter syntax.\n",
2586           cfilter, errmsg);
2587     }
2588 }
2589
2590 void
2591 report_capture_error(const char *error_msg, const char *secondary_error_msg)
2592 {
2593     if(capture_child) {
2594         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
2595             "Primary Error: %s", error_msg);
2596         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
2597             "Secondary Error: %s", secondary_error_msg);
2598         sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
2599     } else {
2600         fprintf(stderr, "%s\n%s\n", error_msg, secondary_error_msg);
2601     }
2602 }
2603
2604 void
2605 report_packet_drops(int drops)
2606 {
2607     char tmp[SP_DECISIZE+1+1];
2608
2609     g_snprintf(tmp, sizeof(tmp), "%d", drops);
2610
2611     if(capture_child) {
2612         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
2613         pipe_write_block(2, SP_DROPS, tmp);
2614     } else {
2615         fprintf(stderr, "Packets dropped: %s\n", tmp);
2616         /* stderr could be line buffered */
2617         fflush(stderr);
2618     }
2619 }
2620
2621
2622 /****************************************************************************************************************/
2623 /* signal_pipe handling */
2624
2625
2626 #ifdef _WIN32
2627 static gboolean
2628 signal_pipe_check_running(void)
2629 {
2630     /* any news from our parent? -> just stop the capture */
2631     DWORD avail = 0;
2632     gboolean result;
2633
2634     /* if we are running standalone, no check required */
2635     if(!capture_child) {
2636         return TRUE;
2637     }
2638
2639     if(!sig_pipe_name || !sig_pipe_handle) {
2640         /* This shouldn't happen */
2641         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2642             "Signal pipe: No name or handle");
2643         return FALSE;
2644     }
2645
2646     /*
2647      * XXX - We should have the process ID of the parent (from the "-Z" flag)
2648      * at this point.  Should we check to see if the parent is still alive,
2649      * e.g. by using OpenProcess?
2650      */
2651
2652     result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
2653
2654     if(!result || avail > 0) {
2655         /* peek failed or some bytes really available */
2656         /* (if not piping from stdin this would fail) */
2657         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2658             "Signal pipe: Stop capture: %s", sig_pipe_name);
2659         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
2660             "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
2661             sig_pipe_handle, result, avail);
2662         return FALSE;
2663     } else {
2664         /* pipe ok and no bytes available */
2665         return TRUE;
2666     }
2667 }
2668 #endif