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