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