Use Wireshark/GLib attribute specifiers instead of checking for __GNUC__ explicitly
[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 SIGUSR1 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 SIGUSR1 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 SIGUSR1 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(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(int signum)
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     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
549         "Console: Signal");
550     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
551         "Console: Signal, signal value: %u", signum);
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;
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", 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 static void
1985 capture_loop_stop_signal_handler(int signo _U_)
1986 {
1987   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Signal: Stop capture");
1988   capture_loop_stop();
1989 }
1990
1991 #ifdef _WIN32
1992 #define TIME_GET() GetTickCount()
1993 #else
1994 #define TIME_GET() time(NULL)
1995 #endif
1996
1997 /* Do the low-level work of a capture.
1998    Returns TRUE if it succeeds, FALSE otherwise. */
1999 static gboolean
2000 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
2001 {
2002 #ifndef _WIN32
2003   struct sigaction act;
2004 #endif
2005   time_t      upd_time, cur_time;
2006   time_t      start_time;
2007   int         err_close;
2008   int         inpkts;
2009   gint        inpkts_to_sync_pipe = 0;     /* packets not already send out to the sync_pipe */
2010   condition  *cnd_file_duration = NULL;
2011   condition  *cnd_autostop_files = NULL;
2012   condition  *cnd_autostop_size = NULL;
2013   condition  *cnd_autostop_duration = NULL;
2014   guint32     autostop_files = 0;
2015   gboolean    write_ok;
2016   gboolean    close_ok;
2017   gboolean    cfilter_error = FALSE;
2018 #define MSG_MAX_LENGTH 4096
2019   char        errmsg[MSG_MAX_LENGTH+1];
2020   char        secondary_errmsg[MSG_MAX_LENGTH+1];
2021   int         save_file_fd = -1;
2022
2023   *errmsg           = '\0';
2024   *secondary_errmsg = '\0';
2025
2026   /* init the loop data */
2027   global_ld.go                 = TRUE;
2028   global_ld.packet_count       = 0;
2029   if (capture_opts->has_autostop_packets)
2030     global_ld.packet_max       = capture_opts->autostop_packets;
2031   else
2032     global_ld.packet_max       = 0;     /* no limit */
2033   global_ld.err                = 0;     /* no error seen yet */
2034   global_ld.wtap_linktype      = WTAP_ENCAP_UNKNOWN;
2035   global_ld.pcap_err           = FALSE;
2036   global_ld.from_cap_pipe      = FALSE;
2037   global_ld.pdh                = NULL;
2038 #ifndef _WIN32
2039   global_ld.cap_pipe_fd        = -1;
2040 #else
2041   global_ld.cap_pipe_h         = INVALID_HANDLE_VALUE;
2042 #endif
2043 #ifdef MUST_DO_SELECT
2044   global_ld.pcap_fd            = 0;
2045 #endif
2046
2047   /* We haven't yet gotten the capture statistics. */
2048   *stats_known      = FALSE;
2049
2050 #ifndef _WIN32
2051   /*
2052    * Catch SIGUSR1, so that we exit cleanly if the parent process
2053    * kills us with it due to the user selecting "Capture->Stop".
2054    */
2055   act.sa_handler = capture_loop_stop_signal_handler;
2056   /*
2057    * Arrange that system calls not get restarted, because when
2058    * our signal handler returns we don't want to restart
2059    * a call that was waiting for packets to arrive.
2060    */
2061   act.sa_flags = 0;
2062   sigemptyset(&act.sa_mask);
2063   sigaction(SIGUSR1, &act, NULL);
2064 #endif /* _WIN32 */
2065
2066   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
2067   capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
2068
2069   /* open the "input file" from network interface or capture pipe */
2070   if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
2071                                secondary_errmsg, sizeof(secondary_errmsg))) {
2072     goto error;
2073   }
2074
2075   /* init the input filter from the network interface (capture pipe will do nothing) */
2076   switch (capture_loop_init_filter(global_ld.pcap_h, global_ld.from_cap_pipe,
2077                                    capture_opts->iface,
2078                                    capture_opts->cfilter)) {
2079
2080   case INITFILTER_NO_ERROR:
2081     break;
2082
2083   case INITFILTER_BAD_FILTER:
2084     cfilter_error = TRUE;
2085     g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(global_ld.pcap_h));
2086     goto error;
2087
2088   case INITFILTER_OTHER_ERROR:
2089     g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
2090                pcap_geterr(global_ld.pcap_h));
2091     g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
2092     goto error;
2093   }
2094
2095   /* If we're supposed to write to a capture file, open it for output
2096      (temporary/specified name/ringbuffer) */
2097   if (capture_opts->saving_to_file) {
2098     if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
2099       goto error;
2100     }
2101
2102     /* set up to write to the already-opened capture output file/files */
2103     if (!capture_loop_init_output(capture_opts, save_file_fd, &global_ld,
2104                                   errmsg, sizeof(errmsg))) {
2105       goto error;
2106     }
2107
2108   /* XXX - capture SIGTERM and close the capture, in case we're on a
2109      Linux 2.0[.x] system and you have to explicitly close the capture
2110      stream in order to turn promiscuous mode off?  We need to do that
2111      in other places as well - and I don't think that works all the
2112      time in any case, due to libpcap bugs. */
2113
2114     /* Well, we should be able to start capturing.
2115
2116        Sync out the capture file, so the header makes it to the file system,
2117        and send a "capture started successfully and capture file created"
2118        message to our parent so that they'll open the capture file and
2119        update its windows to indicate that we have a live capture in
2120        progress. */
2121     libpcap_dump_flush(global_ld.pdh, NULL);
2122     report_new_capture_file(capture_opts->save_file);
2123   }
2124
2125   /* initialize capture stop (and alike) conditions */
2126   init_capture_stop_conditions();
2127   /* create stop conditions */
2128   if (capture_opts->has_autostop_filesize)
2129     cnd_autostop_size =
2130         cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
2131   if (capture_opts->has_autostop_duration)
2132     cnd_autostop_duration =
2133         cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
2134
2135   if (capture_opts->multi_files_on) {
2136       if (capture_opts->has_file_duration)
2137         cnd_file_duration =
2138             cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
2139
2140       if (capture_opts->has_autostop_files)
2141         cnd_autostop_files =
2142             cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
2143   }
2144
2145   /* init the time values */
2146   start_time = TIME_GET();
2147   upd_time = TIME_GET();
2148
2149   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
2150
2151   /* WOW, everything is prepared! */
2152   /* please fasten your seat belts, we will enter now the actual capture loop */
2153   while (global_ld.go) {
2154     /* dispatch incoming packets */
2155     inpkts = capture_loop_dispatch(capture_opts, &global_ld, errmsg,
2156                                    sizeof(errmsg));
2157
2158 #ifdef _WIN32
2159     /* any news from our parent (signal pipe)? -> just stop the capture */
2160     if (!signal_pipe_check_running()) {
2161       global_ld.go = FALSE;
2162     }
2163 #endif
2164
2165     if (inpkts > 0) {
2166       inpkts_to_sync_pipe += inpkts;
2167
2168       /* check capture size condition */
2169       if (cnd_autostop_size != NULL &&
2170           cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)){
2171         /* Capture size limit reached, do we have another file? */
2172         if (capture_opts->multi_files_on) {
2173           if (cnd_autostop_files != NULL &&
2174               cnd_eval(cnd_autostop_files, ++autostop_files)) {
2175              /* no files left: stop here */
2176             global_ld.go = FALSE;
2177             continue;
2178           }
2179
2180           /* Switch to the next ringbuffer file */
2181           if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2182                                   &save_file_fd, &global_ld.err)) {
2183             gboolean successful;
2184
2185             /* File switch succeeded: reset the conditions */
2186             global_ld.bytes_written = 0;
2187             if (capture_opts->use_pcapng) {
2188               char appname[100];
2189
2190               g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2191               successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2192                            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);
2193             } else {
2194               successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2195                                                      &global_ld.bytes_written, &global_ld.err);
2196             }
2197             if (!successful) {
2198               fclose(global_ld.pdh);
2199               global_ld.pdh = NULL;
2200               global_ld.go = FALSE;
2201               continue;
2202             }
2203             cnd_reset(cnd_autostop_size);
2204             if (cnd_file_duration) {
2205               cnd_reset(cnd_file_duration);
2206             }
2207             libpcap_dump_flush(global_ld.pdh, NULL);
2208             report_packet_count(inpkts_to_sync_pipe);
2209             inpkts_to_sync_pipe = 0;
2210             report_new_capture_file(capture_opts->save_file);
2211           } else {
2212             /* File switch failed: stop here */
2213             global_ld.go = FALSE;
2214             continue;
2215           }
2216         } else {
2217           /* single file, stop now */
2218           global_ld.go = FALSE;
2219           continue;
2220         }
2221       } /* cnd_autostop_size */
2222       if (capture_opts->output_to_pipe) {
2223         libpcap_dump_flush(global_ld.pdh, NULL);
2224       }
2225     } /* inpkts */
2226
2227     /* Only update once a second (Win32: 500ms) so as not to overload slow
2228      * displays. This also prevents too much context-switching between the
2229      * dumpcap and wireshark processes */
2230     cur_time = TIME_GET();
2231 #ifdef _WIN32
2232     if ( (cur_time - upd_time) > 500) {
2233 #else
2234     if (cur_time - upd_time > 0) {
2235 #endif
2236         upd_time = cur_time;
2237
2238       /*if (pcap_stats(pch, stats) >= 0) {
2239         *stats_known = TRUE;
2240       }*/
2241
2242       /* Let the parent process know. */
2243       if (inpkts_to_sync_pipe) {
2244         /* do sync here */
2245         libpcap_dump_flush(global_ld.pdh, NULL);
2246
2247         /* Send our parent a message saying we've written out "inpkts_to_sync_pipe"
2248            packets to the capture file. */
2249         report_packet_count(inpkts_to_sync_pipe);
2250
2251         inpkts_to_sync_pipe = 0;
2252       }
2253
2254       /* check capture duration condition */
2255       if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
2256         /* The maximum capture time has elapsed; stop the capture. */
2257         global_ld.go = FALSE;
2258         continue;
2259       }
2260
2261       /* check capture file duration condition */
2262       if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
2263         /* duration limit reached, do we have another file? */
2264         if (capture_opts->multi_files_on) {
2265           if (cnd_autostop_files != NULL &&
2266               cnd_eval(cnd_autostop_files, ++autostop_files)) {
2267             /* no files left: stop here */
2268             global_ld.go = FALSE;
2269             continue;
2270           }
2271
2272           /* Switch to the next ringbuffer file */
2273           if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2274                                   &save_file_fd, &global_ld.err)) {
2275             gboolean successful;
2276
2277             /* file switch succeeded: reset the conditions */
2278             global_ld.bytes_written = 0;
2279             if (capture_opts->use_pcapng) {
2280               char appname[100];
2281
2282               g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2283               successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2284                            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);
2285             } else {
2286               successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2287                                                      &global_ld.bytes_written, &global_ld.err);
2288             }
2289             if (!successful) {
2290               fclose(global_ld.pdh);
2291               global_ld.pdh = NULL;
2292               global_ld.go = FALSE;
2293               continue;
2294             }
2295             cnd_reset(cnd_file_duration);
2296             if(cnd_autostop_size)
2297               cnd_reset(cnd_autostop_size);
2298             libpcap_dump_flush(global_ld.pdh, NULL);
2299             report_packet_count(inpkts_to_sync_pipe);
2300             inpkts_to_sync_pipe = 0;
2301             report_new_capture_file(capture_opts->save_file);
2302           } else {
2303             /* File switch failed: stop here */
2304             global_ld.go = FALSE;
2305             continue;
2306           }
2307         } else {
2308           /* single file, stop now */
2309           global_ld.go = FALSE;
2310           continue;
2311         }
2312       } /* cnd_file_duration */
2313     }
2314
2315   } /* while (global_ld.go) */
2316
2317   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
2318
2319   /* delete stop conditions */
2320   if (cnd_file_duration != NULL)
2321     cnd_delete(cnd_file_duration);
2322   if (cnd_autostop_files != NULL)
2323     cnd_delete(cnd_autostop_files);
2324   if (cnd_autostop_size != NULL)
2325     cnd_delete(cnd_autostop_size);
2326   if (cnd_autostop_duration != NULL)
2327     cnd_delete(cnd_autostop_duration);
2328
2329   /* did we had a pcap (input) error? */
2330   if (global_ld.pcap_err) {
2331     /* On Linux, if an interface goes down while you're capturing on it,
2332        you'll get a "recvfrom: Network is down" error (ENETDOWN).
2333        (At least you will if strerror() doesn't show a local translation
2334        of the error.)
2335
2336        On FreeBSD and OS X, if a network adapter disappears while
2337        you're capturing on it, you'll get a "read: Device not configured"
2338        error (ENXIO).  (See previous parenthetical note.)
2339
2340        On OpenBSD, you get "read: I/O error" (EIO) in the same case.
2341
2342        These should *not* be reported to the Wireshark developers. */
2343     char *cap_err_str;
2344
2345     cap_err_str = pcap_geterr(global_ld.pcap_h);
2346     if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
2347         strcmp(cap_err_str, "read: Device not configured") == 0 ||
2348         strcmp(cap_err_str, "read: I/O error") == 0) {
2349       report_capture_error("The network adapter on which the capture was being done "
2350                            "is no longer running; the capture has stopped.",
2351                            "");
2352     } else {
2353       g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
2354         cap_err_str);
2355       report_capture_error(errmsg, please_report);
2356     }
2357   }
2358   else if (global_ld.from_cap_pipe && global_ld.cap_pipe_err == PIPERR)
2359     report_capture_error(errmsg, "");
2360
2361   /* did we had an error while capturing? */
2362   if (global_ld.err == 0) {
2363     write_ok = TRUE;
2364   } else {
2365     capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
2366                             global_ld.err, FALSE);
2367     report_capture_error(errmsg, please_report);
2368     write_ok = FALSE;
2369   }
2370
2371   if (capture_opts->saving_to_file) {
2372     /* close the wiretap (output) file */
2373     close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
2374   } else
2375     close_ok = TRUE;
2376
2377   /* there might be packets not yet notified to the parent */
2378   /* (do this after closing the file, so all packets are already flushed) */
2379   if(inpkts_to_sync_pipe) {
2380     report_packet_count(inpkts_to_sync_pipe);
2381     inpkts_to_sync_pipe = 0;
2382   }
2383
2384   /* If we've displayed a message about a write error, there's no point
2385      in displaying another message about an error on close. */
2386   if (!close_ok && write_ok) {
2387     capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
2388                 TRUE);
2389     report_capture_error(errmsg, "");
2390   }
2391
2392   /*
2393    * XXX We exhibit different behaviour between normal mode and sync mode
2394    * when the pipe is stdin and not already at EOF.  If we're a child, the
2395    * parent's stdin isn't closed, so if the user starts another capture,
2396    * cap_pipe_open_live() will very likely not see the expected magic bytes and
2397    * will say "Unrecognized libpcap format".  On the other hand, in normal
2398    * mode, cap_pipe_open_live() will say "End of file on pipe during open".
2399    */
2400
2401   /* get packet drop statistics from pcap */
2402   if(global_ld.pcap_h != NULL) {
2403     g_assert(!global_ld.from_cap_pipe);
2404     /* Get the capture statistics, so we know how many packets were
2405        dropped. */
2406     if (pcap_stats(global_ld.pcap_h, stats) >= 0) {
2407       *stats_known = TRUE;
2408       /* Let the parent process know. */
2409       report_packet_drops(stats->ps_drop);
2410     } else {
2411       g_snprintf(errmsg, sizeof(errmsg),
2412                 "Can't get packet-drop statistics: %s",
2413                 pcap_geterr(global_ld.pcap_h));
2414       report_capture_error(errmsg, please_report);
2415     }
2416   }
2417
2418   /* close the input file (pcap or capture pipe) */
2419   capture_loop_close_input(&global_ld);
2420
2421   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
2422
2423   /* ok, if the write and the close were successful. */
2424   return write_ok && close_ok;
2425
2426 error:
2427   if (capture_opts->multi_files_on) {
2428     /* cleanup ringbuffer */
2429     ringbuf_error_cleanup();
2430   } else {
2431     /* We can't use the save file, and we have no FILE * for the stream
2432        to close in order to close it, so close the FD directly. */
2433     if(save_file_fd != -1) {
2434       ws_close(save_file_fd);
2435     }
2436
2437     /* We couldn't even start the capture, so get rid of the capture
2438        file. */
2439     if(capture_opts->save_file != NULL) {
2440       ws_unlink(capture_opts->save_file);
2441       g_free(capture_opts->save_file);
2442     }
2443   }
2444   capture_opts->save_file = NULL;
2445   if (cfilter_error)
2446     report_cfilter_error(capture_opts->cfilter, errmsg);
2447   else
2448     report_capture_error(errmsg, secondary_errmsg);
2449
2450   /* close the input file (pcap or cap_pipe) */
2451   capture_loop_close_input(&global_ld);
2452
2453   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
2454
2455   return FALSE;
2456 }
2457
2458
2459 static void capture_loop_stop(void)
2460 {
2461 #ifdef HAVE_PCAP_BREAKLOOP
2462   if(global_ld.pcap_h != NULL)
2463     pcap_breakloop(global_ld.pcap_h);
2464 #endif
2465   global_ld.go = FALSE;
2466 }
2467
2468
2469 static void
2470 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
2471                           int err, gboolean is_close)
2472 {
2473   switch (err) {
2474
2475   case ENOSPC:
2476     g_snprintf(errmsg, errmsglen,
2477                 "Not all the packets could be written to the file"
2478                 " to which the capture was being saved\n"
2479                 "(\"%s\") because there is no space left on the file system\n"
2480                 "on which that file resides.",
2481                 fname);
2482     break;
2483
2484 #ifdef EDQUOT
2485   case EDQUOT:
2486     g_snprintf(errmsg, errmsglen,
2487                 "Not all the packets could be written to the file"
2488                 " to which the capture was being saved\n"
2489                 "(\"%s\") because you are too close to, or over,"
2490                 " your disk quota\n"
2491                 "on the file system on which that file resides.",
2492                 fname);
2493   break;
2494 #endif
2495
2496   case WTAP_ERR_CANT_CLOSE:
2497     g_snprintf(errmsg, errmsglen,
2498                 "The file to which the capture was being saved"
2499                 " couldn't be closed for some unknown reason.");
2500     break;
2501
2502   case WTAP_ERR_SHORT_WRITE:
2503     g_snprintf(errmsg, errmsglen,
2504                 "Not all the packets could be written to the file"
2505                 " to which the capture was being saved\n"
2506                 "(\"%s\").",
2507                 fname);
2508     break;
2509
2510   default:
2511     if (is_close) {
2512       g_snprintf(errmsg, errmsglen,
2513                 "The file to which the capture was being saved\n"
2514                 "(\"%s\") could not be closed: %s.",
2515                 fname, wtap_strerror(err));
2516     } else {
2517       g_snprintf(errmsg, errmsglen,
2518                 "An error occurred while writing to the file"
2519                 " to which the capture was being saved\n"
2520                 "(\"%s\"): %s.",
2521                 fname, wtap_strerror(err));
2522     }
2523     break;
2524   }
2525 }
2526
2527
2528 /* one packet was captured, process it */
2529 static void
2530 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
2531   const u_char *pd)
2532 {
2533   loop_data *ld = (void *) user;
2534   int err;
2535
2536   /* We may be called multiple times from pcap_dispatch(); if we've set
2537      the "stop capturing" flag, ignore this packet, as we're not
2538      supposed to be saving any more packets. */
2539   if (!ld->go)
2540     return;
2541
2542   if (ld->pdh) {
2543     gboolean successful;
2544     /* We're supposed to write the packet to a file; do so.
2545        If this fails, set "ld->go" to FALSE, to stop the capture, and set
2546        "ld->err" to the error. */
2547     if (global_capture_opts.use_pcapng) {
2548       successful = libpcap_write_enhanced_packet_block(ld->pdh, phdr, 0, pd, &ld->bytes_written, &err);
2549     } else {
2550       successful = libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err);
2551     }
2552     if (!successful) {
2553       ld->go = FALSE;
2554       ld->err = err;
2555     } else {
2556       ld->packet_count++;
2557       /* if the user told us to stop after x packets, do we already have enough? */
2558       if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
2559       {
2560         ld->go = FALSE;
2561       }
2562     }
2563   }
2564 }
2565
2566
2567 /* And now our feature presentation... [ fade to music ] */
2568 int
2569 main(int argc, char *argv[])
2570 {
2571   int                  opt;
2572   extern char         *optarg;
2573   gboolean             arg_error = FALSE;
2574
2575 #ifdef _WIN32
2576   WSADATA              wsaData;
2577 #else
2578   struct sigaction action, oldaction;
2579 #endif
2580
2581   gboolean             start_capture = TRUE;
2582   gboolean             stats_known;
2583   struct pcap_stat     stats;
2584   GLogLevelFlags       log_flags;
2585   gboolean             list_interfaces = FALSE;
2586   gboolean             list_link_layer_types = FALSE;
2587   gboolean             machine_readable = FALSE;
2588   gboolean             print_statistics = FALSE;
2589   int                  status, run_once_args = 0;
2590   gint                 i;
2591
2592 #ifdef HAVE_PCAP_REMOTE
2593 #define OPTSTRING_INIT "a:A:b:c:Df:hi:Lm:MnprSs:uvw:y:Z:"
2594 #else
2595 #define OPTSTRING_INIT "a:b:c:Df:hi:LMnpSs:vw:y:Z:"
2596 #endif
2597
2598 #ifdef _WIN32
2599 #define OPTSTRING_WIN32 "B:"
2600 #else
2601 #define OPTSTRING_WIN32 ""
2602 #endif  /* _WIN32 */
2603
2604   char optstring[sizeof(OPTSTRING_INIT) + sizeof(OPTSTRING_WIN32) - 1] =
2605     OPTSTRING_INIT OPTSTRING_WIN32;
2606
2607 #ifdef DEBUG_CHILD_DUMPCAP
2608   if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
2609           fprintf (stderr, "Unable to open debug log file !\n");
2610           exit (1);
2611   }
2612 #endif
2613
2614   /* Determine if dumpcap is being requested to run in a special       */
2615   /* capture_child mode by going thru the command line args to see if  */
2616   /* a -Z is present. (-Z is a hidden option).                         */
2617   /* The primary result of running in capture_child mode is that       */
2618   /* all messages sent out on stderr are in a special type/len/string  */
2619   /* format to allow message processing by type.                       */
2620   /* These messages include various 'status' messages which are sent   */
2621   /* when an actual capture is in progress. Capture_child mode         */
2622   /* would normally be requested by a parent process which invokes     */
2623   /* dumpcap and obtains dumpcap stderr output via a pipe to which     */
2624   /* dumpcap stderr has been redirected.                               */
2625   /* Capture_child mode needs to be determined immediately upon        */
2626   /* startup so that any messages generated by dumpcap in this mode    */
2627   /* (eg: during initialization) will be formatted properly.           */
2628
2629   for (i=1; i<argc; i++) {
2630     if (strcmp("-Z", argv[i]) == 0) {
2631       capture_child = TRUE;
2632 #ifdef _WIN32
2633       /* set output pipe to binary mode, to avoid ugly text conversions */
2634       _setmode(2, O_BINARY);
2635 #endif
2636     }
2637   }
2638
2639   /* The default_log_handler will use stdout, which makes trouble in   */
2640   /* capture child mode, as it uses stdout for it's sync_pipe.         */
2641   /* So: the filtering is done in the console_log_handler and not here.*/
2642   /* We set the log handlers right up front to make sure that any log  */
2643   /* messages when running as child will be sent back to the parent    */
2644   /* with the correct format.                                          */
2645
2646   log_flags =
2647                     G_LOG_LEVEL_ERROR|
2648                     G_LOG_LEVEL_CRITICAL|
2649                     G_LOG_LEVEL_WARNING|
2650                     G_LOG_LEVEL_MESSAGE|
2651                     G_LOG_LEVEL_INFO|
2652                     G_LOG_LEVEL_DEBUG|
2653                     G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
2654
2655   g_log_set_handler(NULL,
2656                     log_flags,
2657                     console_log_handler, NULL /* user_data */);
2658   g_log_set_handler(LOG_DOMAIN_MAIN,
2659                     log_flags,
2660                     console_log_handler, NULL /* user_data */);
2661   g_log_set_handler(LOG_DOMAIN_CAPTURE,
2662                     log_flags,
2663                     console_log_handler, NULL /* user_data */);
2664   g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
2665                     log_flags,
2666                     console_log_handler, NULL /* user_data */);
2667
2668 #ifdef _WIN32
2669   /* Load wpcap if possible. Do this before collecting the run-time version information */
2670   load_wpcap();
2671
2672   /* ... and also load the packet.dll from wpcap */
2673   /* XXX - currently not required, may change later. */
2674   /*wpcap_packet_load();*/
2675
2676   /* Start windows sockets */
2677   WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
2678
2679   /* Set handler for Ctrl+C key */
2680   SetConsoleCtrlHandler(capture_cleanup, TRUE);
2681
2682   /* Prepare to read from a pipe */
2683   if (!g_thread_supported ())
2684     g_thread_init (NULL);
2685   cap_pipe_pending_q = g_async_queue_new();
2686   cap_pipe_done_q = g_async_queue_new();
2687   cap_pipe_read_mtx = g_mutex_new();
2688
2689 #else
2690   /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
2691      and exit. */
2692   action.sa_handler = capture_cleanup;
2693   action.sa_flags = 0;
2694   sigemptyset(&action.sa_mask);
2695   sigaction(SIGTERM, &action, NULL);
2696   sigaction(SIGINT, &action, NULL);
2697   sigaction(SIGPIPE, &action, NULL);
2698   sigaction(SIGHUP, NULL, &oldaction);
2699   if (oldaction.sa_handler == SIG_DFL)
2700     sigaction(SIGHUP, &action, NULL);
2701 #endif  /* _WIN32 */
2702
2703   /* ----------------------------------------------------------------- */
2704   /* Privilege and capability handling                                 */
2705   /* Cases:                                                            */
2706   /* 1. Running not as root or suid root; no special capabilities.     */
2707   /*    Action: none                                                   */
2708   /*                                                                   */
2709   /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap.  */
2710   /*    Action: none                                                   */
2711   /*                                                                   */
2712   /* 3. Running logged in as root (euid=0; ruid=0). Using libcap.      */
2713   /*    Action:                                                        */
2714   /*      - Near start of program: Enable NET_RAW and NET_ADMIN        */
2715   /*        capabilities; Drop all other capabilities;                 */
2716   /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
2717   /*        else: after  pcap_open_live() in capture_loop_open_input() */
2718   /*         drop all capabilities (NET_RAW and NET_ADMIN);            */
2719   /*         (Note: this means that the process, although logged in    */
2720   /*          as root, does not have various permissions such as the   */
2721   /*          ability to bypass file access permissions).              */
2722   /*      XXX: Should we just leave capabilities alone in this case    */
2723   /*          so that user gets expected effect that root can do       */
2724   /*          anything ??                                              */
2725   /*                                                                   */
2726   /* 4. Running as suid root (euid=0, ruid=n); Not using libcap.       */
2727   /*    Action:                                                        */
2728   /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
2729   /*        else: after  pcap_open_live() in capture_loop_open_input() */
2730   /*         drop suid root (set euid=ruid).(ie: keep suid until after */
2731   /*         pcap_open_live).                                          */
2732   /*                                                                   */
2733   /* 5. Running as suid root (euid=0, ruid=n); Using libcap.           */
2734   /*    Action:                                                        */
2735   /*      - Near start of program: Enable NET_RAW and NET_ADMIN        */
2736   /*        capabilities; Drop all other capabilities;                 */
2737   /*        Drop suid privileges (euid=ruid);                          */
2738   /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
2739   /*        else: after  pcap_open_live() in capture_loop_open_input() */
2740   /*         drop all capabilities (NET_RAW and NET_ADMIN).            */
2741   /*                                                                   */
2742   /*      XXX: For some Linux versions/distros with capabilities       */
2743   /*        a 'normal' process with any capabilities cannot be         */
2744   /*        'killed' (signaled) from another (same uid) non-privileged */
2745   /*        process.                                                   */
2746   /*        For example: If (non-suid) Wireshark forks a               */
2747   /*        child suid dumpcap which acts as described here (case 5),  */
2748   /*        Wireshark will be unable to kill (signal) the child        */
2749   /*        dumpcap process until the capabilities have been dropped   */
2750   /*        (after pcap_open_live()).                                  */
2751   /*        This behaviour will apparently be changed in the kernel    */
2752   /*        to allow the kill (signal) in this case.                   */
2753   /*        See the following for details:                             */
2754   /*           http://www.mail-archive.com/  [wrapped]                 */
2755   /*             linux-security-module@vger.kernel.org/msg02913.html   */
2756   /*                                                                   */
2757   /*        It is therefore conceivable that if dumpcap somehow hangs  */
2758   /*        in pcap_open_live or before that wireshark will not        */
2759   /*        be able to stop dumpcap using a signal (USR1, TERM, etc).  */
2760   /*        In this case, exiting wireshark will kill the child        */
2761   /*        dumpcap process.                                           */
2762   /*                                                                   */
2763   /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN        */
2764   /*     capabilities; Using libcap.  Note: capset cmd (which see)     */
2765   /*     used to assign capabilities to file.                          */
2766   /*    Action:                                                        */
2767   /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
2768   /*        else: after  pcap_open_live() in capture_loop_open_input() */
2769   /*         drop all capabilities (NET_RAW and NET_ADMIN)             */
2770   /*                                                                   */
2771   /* ToDo: -S (stats) should drop privileges/capabilities when no      */
2772   /*       longer required (similar to capture).                        */
2773   /*                                                                   */
2774   /* ----------------------------------------------------------------- */
2775
2776   get_credential_info();
2777
2778 #ifdef HAVE_LIBCAP
2779   /* If 'started with special privileges' (and using libcap)  */
2780   /*   Set to keep only NET_RAW and NET_ADMIN capabilities;   */
2781   /*   Set euid/egid = ruid/rgid to remove suid privileges    */
2782   relinquish_privs_except_capture();
2783 #endif
2784
2785   /* Set the initial values in the capture options. This might be overwritten
2786      by the command line parameters. */
2787   capture_opts_init(&global_capture_opts, NULL);
2788
2789   /* Default to capturing the entire packet. */
2790   global_capture_opts.snaplen             = WTAP_MAX_PACKET_SIZE;
2791
2792   /* We always save to a file - if no file was specified, we save to a
2793      temporary file. */
2794   global_capture_opts.saving_to_file      = TRUE;
2795   global_capture_opts.has_ring_num_files  = TRUE;
2796
2797   /* Now get our args */
2798   while ((opt = getopt(argc, argv, optstring)) != -1) {
2799     switch (opt) {
2800       case 'h':        /* Print help and exit */
2801         print_usage(TRUE);
2802         exit_main(0);
2803         break;
2804       case 'v':        /* Show version and exit */
2805       {
2806         GString             *comp_info_str;
2807         GString             *runtime_info_str;
2808         /* Assemble the compile-time version information string */
2809         comp_info_str = g_string_new("Compiled ");
2810         get_compiled_version_info(comp_info_str, NULL);
2811
2812         /* Assemble the run-time version information string */
2813         runtime_info_str = g_string_new("Running ");
2814         get_runtime_version_info(runtime_info_str, NULL);
2815         show_version(comp_info_str, runtime_info_str);
2816         g_string_free(comp_info_str, TRUE);
2817         g_string_free(runtime_info_str, TRUE);
2818         exit_main(0);
2819         break;
2820       }
2821       /*** capture option specific ***/
2822       case 'a':        /* autostop criteria */
2823       case 'b':        /* Ringbuffer option */
2824       case 'c':        /* Capture x packets */
2825       case 'f':        /* capture filter */
2826       case 'i':        /* Use interface x */
2827       case 'n':        /* Use pcapng format */
2828       case 'p':        /* Don't capture in promiscuous mode */
2829       case 's':        /* Set the snapshot (capture) length */
2830       case 'w':        /* Write to capture file x */
2831       case 'y':        /* Set the pcap data link type */
2832 #ifdef HAVE_PCAP_REMOTE
2833       case 'u':        /* Use UDP for data transfer */
2834       case 'r':        /* Capture own RPCAP traffic too */
2835       case 'A':        /* Authentication */
2836 #endif
2837 #ifdef HAVE_PCAP_SETSAMPLING
2838       case 'm':        /* Sampling */
2839 #endif
2840 #ifdef _WIN32
2841       case 'B':        /* Buffer size */
2842 #endif /* _WIN32 */
2843         status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
2844         if(status != 0) {
2845           exit_main(status);
2846         }
2847         break;
2848       /*** hidden option: Wireshark child mode (using binary output messages) ***/
2849       case 'Z':
2850         capture_child = TRUE;
2851 #ifdef _WIN32
2852         /* set output pipe to binary mode, to avoid ugly text conversions */
2853         _setmode(2, O_BINARY);
2854         /*
2855          * optarg = the control ID, aka the PPID, currently used for the
2856          * signal pipe name.
2857          */
2858         if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
2859           sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
2860           sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
2861               GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
2862
2863           if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
2864             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2865                   "Signal pipe: Unable to open %s.  Dead parent?",
2866                   sig_pipe_name);
2867             exit_main(1);
2868           }
2869         }
2870 #endif
2871         break;
2872
2873       /*** all non capture option specific ***/
2874       case 'D':        /* Print a list of capture devices and exit */
2875         list_interfaces = TRUE;
2876         run_once_args++;
2877         break;
2878       case 'L':        /* Print list of link-layer types and exit */
2879         list_link_layer_types = TRUE;
2880         run_once_args++;
2881         break;
2882       case 'S':        /* Print interface statistics once a second */
2883         print_statistics = TRUE;
2884         run_once_args++;
2885         break;
2886       case 'M':        /* For -D and -L, print machine-readable output */
2887         machine_readable = TRUE;
2888         break;
2889       default:
2890       case '?':        /* Bad flag - print usage message */
2891         cmdarg_err("Invalid Option: %s", argv[optind-1]);
2892         arg_error = TRUE;
2893         break;
2894     }
2895   }
2896   argc -= optind;
2897   argv += optind;
2898   if (argc >= 1) {
2899     /* user specified file name as regular command-line argument */
2900     /* XXX - use it as the capture file name (or something else)? */
2901     argc--;
2902     argv++;
2903   }
2904
2905   if (argc != 0) {
2906     /*
2907      * Extra command line arguments were specified; complain.
2908      * XXX - interpret as capture filter, as tcpdump and tshark do?
2909      */
2910     cmdarg_err("Invalid argument: %s", argv[0]);
2911     arg_error = TRUE;
2912   }
2913
2914   if (arg_error) {
2915     print_usage(FALSE);
2916     exit_main(1);
2917   }
2918
2919   if (run_once_args > 1) {
2920     cmdarg_err("Only one of -D, -L, or -S may be supplied.");
2921     exit_main(1);
2922   } else if (list_link_layer_types) {
2923     /* We're supposed to list the link-layer types for an interface;
2924        did the user also specify a capture file to be read? */
2925     /* No - did they specify a ring buffer option? */
2926     if (global_capture_opts.multi_files_on) {
2927       cmdarg_err("Ring buffer requested, but a capture isn't being done.");
2928       exit_main(1);
2929     }
2930   } else {
2931     /* No - was the ring buffer option specified and, if so, does it make
2932        sense? */
2933     if (global_capture_opts.multi_files_on) {
2934       /* Ring buffer works only under certain conditions:
2935          a) ring buffer does not work with temporary files;
2936          b) it makes no sense to enable the ring buffer if the maximum
2937             file size is set to "infinite". */
2938       if (global_capture_opts.save_file == NULL) {
2939         cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
2940         global_capture_opts.multi_files_on = FALSE;
2941       }
2942       if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
2943         cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
2944 /* XXX - this must be redesigned as the conditions changed */
2945 /*      global_capture_opts.multi_files_on = FALSE;*/
2946       }
2947     }
2948   }
2949
2950   if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
2951     /* cmdarg_err() already called .... */
2952     exit_main(1);
2953   }
2954
2955   /* Let the user know what interface was chosen. */
2956   /* get_interface_descriptive_name() is not available! */
2957   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", global_capture_opts.iface);
2958
2959   if (list_interfaces) {
2960     status = capture_opts_list_interfaces(machine_readable);
2961     exit_main(status);
2962   } else if (list_link_layer_types) {
2963     status = capture_opts_list_link_layer_types(&global_capture_opts, machine_readable);
2964     exit_main(status);
2965   } else if (print_statistics) {
2966     status = print_statistics_loop(machine_readable);
2967     exit_main(status);
2968   }
2969
2970   capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
2971   capture_opts_trim_ring_num_files(&global_capture_opts);
2972
2973   /* Now start the capture. */
2974
2975   if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
2976     /* capture ok */
2977     exit_main(0);
2978   } else {
2979     /* capture failed */
2980     exit_main(1);
2981   }
2982 }
2983
2984
2985 static void
2986 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
2987                     const char *message, gpointer user_data _U_)
2988 {
2989   time_t curr;
2990   struct tm  *today;
2991   const char *level;
2992   gchar      *msg;
2993
2994   /* ignore log message, if log_level isn't interesting */
2995   if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
2996 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
2997     return;
2998 #endif
2999   }
3000
3001   /* create a "timestamp" */
3002   time(&curr);
3003   today = localtime(&curr);
3004
3005   switch(log_level & G_LOG_LEVEL_MASK) {
3006   case G_LOG_LEVEL_ERROR:
3007     level = "Err ";
3008     break;
3009   case G_LOG_LEVEL_CRITICAL:
3010     level = "Crit";
3011     break;
3012   case G_LOG_LEVEL_WARNING:
3013     level = "Warn";
3014     break;
3015   case G_LOG_LEVEL_MESSAGE:
3016     level = "Msg ";
3017     break;
3018   case G_LOG_LEVEL_INFO:
3019     level = "Info";
3020     break;
3021   case G_LOG_LEVEL_DEBUG:
3022     level = "Dbg ";
3023     break;
3024   default:
3025     fprintf(stderr, "unknown log_level %u\n", log_level);
3026     level = NULL;
3027     g_assert_not_reached();
3028   }
3029
3030   /* Generate the output message                                  */
3031   if(log_level & G_LOG_LEVEL_MESSAGE) {
3032     /* normal user messages without additional infos */
3033     msg =  g_strdup_printf("%s\n", message);
3034   } else {
3035     /* info/debug messages with additional infos */
3036     msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
3037             today->tm_hour, today->tm_min, today->tm_sec,
3038             log_domain != NULL ? log_domain : "",
3039             level, message);
3040   }
3041
3042   /* DEBUG & INFO msgs (if we're debugging today)                 */
3043 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3044   if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3045 #ifdef DEBUG_DUMPCAP
3046     fprintf(stderr, "%s", msg);
3047     fflush(stderr);
3048 #endif
3049 #ifdef DEBUG_CHILD_DUMPCAP
3050     fprintf(debug_log, "%s", msg);
3051     fflush(debug_log);
3052 #endif
3053     g_free(msg);
3054     return;
3055   }
3056 #endif
3057
3058   /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or    */
3059   /*  to parent especially formatted if dumpcap running as child. */
3060   if (capture_child) {
3061     sync_pipe_errmsg_to_parent(2, msg, "");
3062   } else {
3063     fprintf(stderr, "%s", msg);
3064     fflush(stderr);
3065   }
3066   g_free(msg);
3067 }
3068
3069
3070 /****************************************************************************************************************/
3071 /* indication report routines */
3072
3073
3074 void
3075 report_packet_count(int packet_count)
3076 {
3077     char tmp[SP_DECISIZE+1+1];
3078     static int count = 0;
3079
3080     if(capture_child) {
3081         g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
3082         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
3083         pipe_write_block(2, SP_PACKET_COUNT, tmp);
3084     } else {
3085         count += packet_count;
3086         fprintf(stderr, "\rPackets: %u ", count);
3087         /* stderr could be line buffered */
3088         fflush(stderr);
3089     }
3090 }
3091
3092 void
3093 report_new_capture_file(const char *filename)
3094 {
3095     if(capture_child) {
3096         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
3097         pipe_write_block(2, SP_FILE, filename);
3098     } else {
3099         fprintf(stderr, "File: %s\n", filename);
3100         /* stderr could be line buffered */
3101         fflush(stderr);
3102     }
3103 }
3104
3105 void
3106 report_cfilter_error(const char *cfilter, const char *errmsg)
3107 {
3108     if (capture_child) {
3109         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
3110         pipe_write_block(2, SP_BAD_FILTER, errmsg);
3111     } else {
3112         fprintf(stderr,
3113           "Invalid capture filter: \"%s\"!\n"
3114           "\n"
3115           "That string isn't a valid capture filter (%s).\n"
3116           "See the User's Guide for a description of the capture filter syntax.\n",
3117           cfilter, errmsg);
3118     }
3119 }
3120
3121 void
3122 report_capture_error(const char *error_msg, const char *secondary_error_msg)
3123 {
3124     if(capture_child) {
3125         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3126             "Primary Error: %s", error_msg);
3127         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3128             "Secondary Error: %s", secondary_error_msg);
3129         sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
3130     } else {
3131         fprintf(stderr, "%s\n%s\n", error_msg, secondary_error_msg);
3132     }
3133 }
3134
3135 void
3136 report_packet_drops(guint32 drops)
3137 {
3138     char tmp[SP_DECISIZE+1+1];
3139
3140     g_snprintf(tmp, sizeof(tmp), "%u", drops);
3141
3142     if(capture_child) {
3143         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
3144         pipe_write_block(2, SP_DROPS, tmp);
3145     } else {
3146         fprintf(stderr, "Packets dropped: %s\n", tmp);
3147         /* stderr could be line buffered */
3148         fflush(stderr);
3149     }
3150 }
3151
3152
3153 /****************************************************************************************************************/
3154 /* signal_pipe handling */
3155
3156
3157 #ifdef _WIN32
3158 static gboolean
3159 signal_pipe_check_running(void)
3160 {
3161     /* any news from our parent? -> just stop the capture */
3162     DWORD avail = 0;
3163     gboolean result;
3164
3165     /* if we are running standalone, no check required */
3166     if(!capture_child) {
3167         return TRUE;
3168     }
3169
3170     if(!sig_pipe_name || !sig_pipe_handle) {
3171         /* This shouldn't happen */
3172         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3173             "Signal pipe: No name or handle");
3174         return FALSE;
3175     }
3176
3177     /*
3178      * XXX - We should have the process ID of the parent (from the "-Z" flag)
3179      * at this point.  Should we check to see if the parent is still alive,
3180      * e.g. by using OpenProcess?
3181      */
3182
3183     result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
3184
3185     if(!result || avail > 0) {
3186         /* peek failed or some bytes really available */
3187         /* (if not piping from stdin this would fail) */
3188         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3189             "Signal pipe: Stop capture: %s", sig_pipe_name);
3190         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3191             "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
3192             sig_pipe_handle, result, avail);
3193         return FALSE;
3194     } else {
3195         /* pipe ok and no bytes available */
3196         return TRUE;
3197     }
3198 }
3199 #endif
3200
3201 /*
3202  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
3203  *
3204  * Local variables:
3205  * c-basic-offset: 4
3206  * tab-width: 8
3207  * indent-tabs-mode: nil
3208  * End:
3209  *
3210  * vi: set shiftwidth=4 tabstop=8 expandtab
3211  * :indentSize=4:tabSize=8:noTabs=true:
3212  */