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