Minor fix: highlight a command argument as part of the command.
[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
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 #ifndef _WIN32
829   struct stat pipe_stat;
830   int          sel_ret;
831   int          b;
832   unsigned int bytes_read;
833   int          fd;
834 #else /* _WIN32 */
835 #if 1
836   char *pncopy, *pos;
837   wchar_t *err_str;
838 #endif
839 #endif
840   guint32       magic = 0;
841
842 #ifndef _WIN32
843   ld->cap_pipe_fd = -1;
844 #else
845   ld->cap_pipe_h = INVALID_HANDLE_VALUE;
846 #endif
847   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
848
849   /*
850    * XXX (T)Wireshark blocks until we return
851    */
852   if (strcmp(pipename, "-") == 0) {
853 #ifndef _WIN32
854     fd = 0; /* read from stdin */
855 #else /* _WIN32 */
856     ld->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
857 #endif  /* _WIN32 */
858   } else {
859 #ifndef _WIN32
860     if (ws_stat(pipename, &pipe_stat) < 0) {
861       if (errno == ENOENT || errno == ENOTDIR)
862         ld->cap_pipe_err = PIPNEXIST;
863       else {
864         g_snprintf(errmsg, errmsgl,
865           "The capture session could not be initiated "
866           "due to error on pipe: %s", strerror(errno));
867         ld->cap_pipe_err = PIPERR;
868       }
869       return;
870     }
871     if (! S_ISFIFO(pipe_stat.st_mode)) {
872       if (S_ISCHR(pipe_stat.st_mode)) {
873         /*
874          * Assume the user specified an interface on a system where
875          * interfaces are in /dev.  Pretend we haven't seen it.
876          */
877          ld->cap_pipe_err = PIPNEXIST;
878       } else
879       {
880         g_snprintf(errmsg, errmsgl,
881             "The capture session could not be initiated because\n"
882             "\"%s\" is neither an interface nor a pipe", pipename);
883         ld->cap_pipe_err = PIPERR;
884       }
885       return;
886     }
887     fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
888     if (fd == -1) {
889       g_snprintf(errmsg, errmsgl,
890           "The capture session could not be initiated "
891           "due to error on pipe open: %s", strerror(errno));
892       ld->cap_pipe_err = PIPERR;
893       return;
894     }
895 #else /* _WIN32 */
896 #define PIPE_STR "\\pipe\\"
897     /* Under Windows, named pipes _must_ have the form
898      * "\\<server>\pipe\<pipename>".  <server> may be "." for localhost.
899      */
900     pncopy = g_strdup(pipename);
901     if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
902       pos = strchr(pncopy + 3, '\\');
903       if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
904         pos = NULL;
905     }
906
907     g_free(pncopy);
908
909     if (!pos) {
910       g_snprintf(errmsg, errmsgl,
911           "The capture session could not be initiated because\n"
912           "\"%s\" is neither an interface nor a pipe", pipename);
913       ld->cap_pipe_err = PIPNEXIST;
914       return;
915     }
916
917     /* Wait for the pipe to appear */
918     while (1) {
919       ld->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
920           OPEN_EXISTING, 0, NULL);
921
922       if (ld->cap_pipe_h != INVALID_HANDLE_VALUE)
923         break;
924
925       if (GetLastError() != ERROR_PIPE_BUSY) {
926         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
927           NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
928         g_snprintf(errmsg, errmsgl,
929             "The capture session on \"%s\" could not be started "
930             "due to error on pipe open: %s (error %d)",
931             pipename, utf_16to8(err_str), GetLastError());
932         LocalFree(err_str);
933         ld->cap_pipe_err = PIPERR;
934         return;
935       }
936
937       if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
938         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
939           NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
940         g_snprintf(errmsg, errmsgl,
941             "The capture session on \"%s\" timed out during "
942             "pipe open: %s (error %d)",
943             pipename, utf_16to8(err_str), GetLastError());
944         LocalFree(err_str);
945         ld->cap_pipe_err = PIPERR;
946         return;
947       }
948     }
949
950 #endif /* _WIN32 */
951   }
952
953   ld->from_cap_pipe = TRUE;
954
955 #ifndef USE_THREADS
956   /* read the pcap header */
957   bytes_read = 0;
958   while (bytes_read < sizeof magic) {
959     sel_ret = cap_pipe_select(fd);
960     if (sel_ret < 0) {
961       g_snprintf(errmsg, errmsgl,
962         "Unexpected error from select: %s", strerror(errno));
963       goto error;
964     } else if (sel_ret > 0) {
965       b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
966       if (b <= 0) {
967         if (b == 0)
968           g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
969         else
970           g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
971             strerror(errno));
972         goto error;
973       }
974       bytes_read += b;
975     }
976   }
977 #else /* USE_THREADS */
978   g_thread_create(&cap_pipe_read, ld, FALSE, NULL);
979
980   ld->cap_pipe_buf = (char *) &magic;
981   ld->cap_pipe_bytes_read = 0;
982   ld->cap_pipe_bytes_to_read = sizeof(magic);
983   /* We don't have to worry about cap_pipe_read_mtx here */
984   g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
985   g_async_queue_pop(cap_pipe_done_q);
986   if (ld->cap_pipe_bytes_read <= 0) {
987     if (ld->cap_pipe_bytes_read == 0)
988       g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
989     else
990       g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
991                  strerror(errno));
992     goto error;
993   }
994 #endif /* USE_THREADS */
995
996   switch (magic) {
997   case PCAP_MAGIC:
998     /* Host that wrote it has our byte order, and was running
999        a program using either standard or ss990417 libpcap. */
1000     ld->cap_pipe_byte_swapped = FALSE;
1001     ld->cap_pipe_modified = FALSE;
1002     break;
1003   case PCAP_MODIFIED_MAGIC:
1004     /* Host that wrote it has our byte order, but was running
1005        a program using either ss990915 or ss991029 libpcap. */
1006     ld->cap_pipe_byte_swapped = FALSE;
1007     ld->cap_pipe_modified = TRUE;
1008     break;
1009   case PCAP_SWAPPED_MAGIC:
1010     /* Host that wrote it has a byte order opposite to ours,
1011        and was running a program using either standard or
1012        ss990417 libpcap. */
1013     ld->cap_pipe_byte_swapped = TRUE;
1014     ld->cap_pipe_modified = FALSE;
1015     break;
1016   case PCAP_SWAPPED_MODIFIED_MAGIC:
1017     /* Host that wrote it out has a byte order opposite to
1018        ours, and was running a program using either ss990915
1019        or ss991029 libpcap. */
1020     ld->cap_pipe_byte_swapped = TRUE;
1021     ld->cap_pipe_modified = TRUE;
1022     break;
1023   default:
1024     /* Not a "libpcap" type we know about. */
1025     g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
1026     goto error;
1027   }
1028
1029 #ifndef USE_THREADS
1030   /* Read the rest of the header */
1031   bytes_read = 0;
1032   while (bytes_read < sizeof(struct pcap_hdr)) {
1033     sel_ret = cap_pipe_select(fd);
1034     if (sel_ret < 0) {
1035       g_snprintf(errmsg, errmsgl,
1036         "Unexpected error from select: %s", strerror(errno));
1037       goto error;
1038     } else if (sel_ret > 0) {
1039       b = read(fd, ((char *)hdr)+bytes_read,
1040             sizeof(struct pcap_hdr) - bytes_read);
1041       if (b <= 0) {
1042         if (b == 0)
1043           g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1044         else
1045           g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
1046             strerror(errno));
1047         goto error;
1048       }
1049       bytes_read += b;
1050     }
1051   }
1052 #else /* USE_THREADS */
1053   ld->cap_pipe_buf = (char *) hdr;
1054   ld->cap_pipe_bytes_read = 0;
1055   ld->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1056   g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1057   g_async_queue_pop(cap_pipe_done_q);
1058   if (ld->cap_pipe_bytes_read <= 0) {
1059     if (ld->cap_pipe_bytes_read == 0)
1060       g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1061     else
1062       g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
1063             strerror(errno));
1064     goto error;
1065   }
1066 #endif /* USE_THREADS */
1067
1068   if (ld->cap_pipe_byte_swapped) {
1069     /* Byte-swap the header fields about which we care. */
1070     hdr->version_major = BSWAP16(hdr->version_major);
1071     hdr->version_minor = BSWAP16(hdr->version_minor);
1072     hdr->snaplen = BSWAP32(hdr->snaplen);
1073     hdr->network = BSWAP32(hdr->network);
1074   }
1075   ld->linktype = hdr->network;
1076
1077   if (hdr->version_major < 2) {
1078     g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1079     goto error;
1080   }
1081
1082   ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1083   ld->cap_pipe_err = PIPOK;
1084 #ifndef _WIN32
1085   ld->cap_pipe_fd = fd;
1086 #endif
1087   return;
1088
1089 error:
1090   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1091   ld->cap_pipe_err = PIPERR;
1092 #ifndef _WIN32
1093   ws_close(fd);
1094   ld->cap_pipe_fd = -1;
1095 #endif
1096   return;
1097
1098 }
1099
1100
1101 /* We read one record from the pipe, take care of byte order in the record
1102  * header, write the record to the capture file, and update capture statistics. */
1103 static int
1104 cap_pipe_dispatch(loop_data *ld, guchar *data, char *errmsg, int errmsgl)
1105 {
1106   struct pcap_pkthdr phdr;
1107   enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1108          PD_ERR } result;
1109 #ifdef USE_THREADS
1110   GTimeVal wait_time;
1111   gpointer q_status;
1112 #else
1113   int b;
1114 #endif
1115 #ifdef _WIN32
1116   wchar_t *err_str;
1117 #endif
1118
1119 #ifdef LOG_CAPTURE_VERBOSE
1120   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1121 #endif
1122
1123   switch (ld->cap_pipe_state) {
1124
1125   case STATE_EXPECT_REC_HDR:
1126 #ifdef USE_THREADS
1127     if (g_mutex_trylock(cap_pipe_read_mtx)) {
1128 #endif
1129
1130     ld->cap_pipe_state = STATE_READ_REC_HDR;
1131     ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
1132       sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1133     ld->cap_pipe_bytes_read = 0;
1134
1135 #ifdef USE_THREADS
1136       ld->cap_pipe_buf = (char *) &ld->cap_pipe_rechdr;
1137       g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1138       g_mutex_unlock(cap_pipe_read_mtx);
1139     }
1140 #endif
1141     /* Fall through */
1142
1143   case STATE_READ_REC_HDR:
1144 #ifndef USE_THREADS
1145     b = read(ld->cap_pipe_fd, ((char *)&ld->cap_pipe_rechdr)+ld->cap_pipe_bytes_read,
1146              ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1147     if (b <= 0) {
1148       if (b == 0)
1149         result = PD_PIPE_EOF;
1150       else
1151         result = PD_PIPE_ERR;
1152       break;
1153     }
1154     ld->cap_pipe_bytes_read += b;
1155 #else /* USE_THREADS */
1156     g_get_current_time(&wait_time);
1157     g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1158     q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1159     if (ld->cap_pipe_err == PIPEOF) {
1160       result = PD_PIPE_EOF;
1161       break;
1162     } else if (ld->cap_pipe_err == PIPERR) {
1163       result = PD_PIPE_ERR;
1164       break;
1165     }
1166     if (!q_status) {
1167       return 0;
1168     }
1169 #endif /* USE_THREADS */
1170     if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1171         return 0;
1172     result = PD_REC_HDR_READ;
1173     break;
1174
1175   case STATE_EXPECT_DATA:
1176 #ifdef USE_THREADS
1177     if (g_mutex_trylock(cap_pipe_read_mtx)) {
1178 #endif
1179
1180     ld->cap_pipe_state = STATE_READ_DATA;
1181     ld->cap_pipe_bytes_to_read = ld->cap_pipe_rechdr.hdr.incl_len;
1182     ld->cap_pipe_bytes_read = 0;
1183
1184 #ifdef USE_THREADS
1185       ld->cap_pipe_buf = (char *) data;
1186       g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1187       g_mutex_unlock(cap_pipe_read_mtx);
1188     }
1189 #endif
1190     /* Fall through */
1191
1192   case STATE_READ_DATA:
1193 #ifndef USE_THREADS
1194     b = read(ld->cap_pipe_fd, data+ld->cap_pipe_bytes_read,
1195              ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1196     if (b <= 0) {
1197       if (b == 0)
1198         result = PD_PIPE_EOF;
1199       else
1200         result = PD_PIPE_ERR;
1201       break;
1202     }
1203     ld->cap_pipe_bytes_read += b;
1204 #else /* USE_THREADS */
1205     g_get_current_time(&wait_time);
1206     g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1207     q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1208     if (ld->cap_pipe_err == PIPEOF) {
1209       result = PD_PIPE_EOF;
1210       break;
1211     } else if (ld->cap_pipe_err == PIPERR) {
1212       result = PD_PIPE_ERR;
1213       break;
1214     }
1215     if (!q_status) {
1216       return 0;
1217     }
1218 #endif /* USE_THREADS */
1219     if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1220         return 0;
1221     result = PD_DATA_READ;
1222     break;
1223
1224   default:
1225     g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
1226     result = PD_ERR;
1227
1228   } /* switch (ld->cap_pipe_state) */
1229
1230   /*
1231    * We've now read as much data as we were expecting, so process it.
1232    */
1233   switch (result) {
1234
1235   case PD_REC_HDR_READ:
1236     /* We've read the header. Take care of byte order. */
1237     cap_pipe_adjust_header(ld->cap_pipe_byte_swapped, &ld->cap_pipe_hdr,
1238                            &ld->cap_pipe_rechdr.hdr);
1239     if (ld->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1240       g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
1241         ld->packet_count+1, ld->cap_pipe_rechdr.hdr.incl_len);
1242       break;
1243     }
1244     ld->cap_pipe_state = STATE_EXPECT_DATA;
1245     return 0;
1246
1247   case PD_DATA_READ:
1248     /* Fill in a "struct pcap_pkthdr", and process the packet. */
1249     phdr.ts.tv_sec = ld->cap_pipe_rechdr.hdr.ts_sec;
1250     phdr.ts.tv_usec = ld->cap_pipe_rechdr.hdr.ts_usec;
1251     phdr.caplen = ld->cap_pipe_rechdr.hdr.incl_len;
1252     phdr.len = ld->cap_pipe_rechdr.hdr.orig_len;
1253
1254     capture_loop_packet_cb((u_char *)ld, &phdr, data);
1255
1256     ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1257     return 1;
1258
1259   case PD_PIPE_EOF:
1260     ld->cap_pipe_err = PIPEOF;
1261     return -1;
1262
1263   case PD_PIPE_ERR:
1264 #ifdef _WIN32
1265     FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1266       NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1267     g_snprintf(errmsg, errmsgl,
1268         "Error reading from pipe: %s (error %d)",
1269         utf_16to8(err_str), GetLastError());
1270     LocalFree(err_str);
1271 #else
1272     g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
1273       strerror(errno));
1274 #endif
1275     /* Fall through */
1276   case PD_ERR:
1277     break;
1278   }
1279
1280   ld->cap_pipe_err = PIPERR;
1281   /* Return here rather than inside the switch to prevent GCC warning */
1282   return -1;
1283 }
1284
1285
1286 /** Open the capture input file (pcap or capture pipe).
1287  *  Returns TRUE if it succeeds, FALSE otherwise. */
1288 static gboolean
1289 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
1290                         char *errmsg, size_t errmsg_len,
1291                         char *secondary_errmsg, size_t secondary_errmsg_len)
1292 {
1293   gchar       open_err_str[PCAP_ERRBUF_SIZE];
1294   gchar      *sync_msg_str;
1295   static const char ppamsg[] = "can't find PPA for ";
1296   const char *set_linktype_err_str;
1297   const char  *libpcap_warn;
1298 #ifdef _WIN32
1299   gchar      *sync_secondary_msg_str;
1300   int         err;
1301   WORD        wVersionRequested;
1302   WSADATA     wsaData;
1303 #endif
1304 #ifdef HAVE_PCAP_REMOTE
1305   struct pcap_rmtauth auth;
1306 #endif
1307
1308
1309   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
1310
1311
1312 /* XXX - opening Winsock on tshark? */
1313
1314   /* Initialize Windows Socket if we are in a WIN32 OS
1315      This needs to be done before querying the interface for network/netmask */
1316 #ifdef _WIN32
1317   /* XXX - do we really require 1.1 or earlier?
1318      Are there any versions that support only 2.0 or higher? */
1319   wVersionRequested = MAKEWORD(1, 1);
1320   err = WSAStartup(wVersionRequested, &wsaData);
1321   if (err != 0) {
1322     switch (err) {
1323
1324     case WSASYSNOTREADY:
1325       g_snprintf(errmsg, (gulong) errmsg_len,
1326         "Couldn't initialize Windows Sockets: Network system not ready for network communication");
1327       break;
1328
1329     case WSAVERNOTSUPPORTED:
1330       g_snprintf(errmsg, (gulong) errmsg_len,
1331         "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
1332         LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
1333       break;
1334
1335     case WSAEINPROGRESS:
1336       g_snprintf(errmsg, (gulong) errmsg_len,
1337         "Couldn't initialize Windows Sockets: Blocking operation is in progress");
1338       break;
1339
1340     case WSAEPROCLIM:
1341       g_snprintf(errmsg, (gulong) errmsg_len,
1342         "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
1343       break;
1344
1345     case WSAEFAULT:
1346       g_snprintf(errmsg, (gulong) errmsg_len,
1347         "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
1348       break;
1349
1350     default:
1351       g_snprintf(errmsg, (gulong) errmsg_len,
1352         "Couldn't initialize Windows Sockets: error %d", err);
1353       break;
1354     }
1355     g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
1356     return FALSE;
1357   }
1358 #endif
1359
1360   /* Open the network interface to capture from it.
1361      Some versions of libpcap may put warnings into the error buffer
1362      if they succeed; to tell if that's happened, we have to clear
1363      the error buffer, and check if it's still a null string.  */
1364   open_err_str[0] = '\0';
1365 #ifdef HAVE_PCAP_OPEN
1366   auth.type = capture_opts->auth_type == CAPTURE_AUTH_PWD ?
1367                     RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
1368   auth.username = capture_opts->auth_username;
1369   auth.password = capture_opts->auth_password;
1370
1371   ld->pcap_h = pcap_open(capture_opts->iface,
1372                capture_opts->has_snaplen ? capture_opts->snaplen :
1373                           WTAP_MAX_PACKET_SIZE,
1374                /* flags */
1375                (capture_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
1376                (capture_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
1377                (capture_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
1378                CAP_READ_TIMEOUT, &auth, open_err_str);
1379 #else
1380   ld->pcap_h = pcap_open_live(capture_opts->iface,
1381                               capture_opts->has_snaplen ? capture_opts->snaplen :
1382                                                           WTAP_MAX_PACKET_SIZE,
1383                               capture_opts->promisc_mode, CAP_READ_TIMEOUT,
1384                               open_err_str);
1385 #endif
1386
1387 /* If not using libcap: we now can now set euid/egid to ruid/rgid         */
1388 /*  to remove any suid privileges.                                        */
1389 /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities  */
1390 /*  (euid/egid have already previously been set to ruid/rgid.             */
1391 /* (See comment in main() for details)                                    */
1392 #ifndef HAVE_LIBCAP
1393   relinquish_special_privs_perm();
1394 #else
1395   relinquish_all_capabilities();
1396 #endif
1397
1398   if (ld->pcap_h != NULL) {
1399     /* we've opened "iface" as a network device */
1400 #ifdef _WIN32
1401     /* try to set the capture buffer size */
1402     if (capture_opts->buffer_size > 1 &&
1403         pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
1404         sync_secondary_msg_str = g_strdup_printf(
1405           "The capture buffer size of %luMB seems to be too high for your machine,\n"
1406           "the default of 1MB will be used.\n"
1407           "\n"
1408           "Nonetheless, the capture is started.\n",
1409           capture_opts->buffer_size);
1410         report_capture_error("Couldn't set the capture buffer size!",
1411                                    sync_secondary_msg_str);
1412         g_free(sync_secondary_msg_str);
1413     }
1414 #endif
1415
1416 #if defined(HAVE_PCAP_REMOTE) && defined(HAVE_PCAP_SETSAMPLING)
1417     if (capture_opts->sampling_method != CAPTURE_SAMP_NONE)
1418     {
1419         struct pcap_samp *samp;
1420
1421         if ((samp = pcap_setsampling(ld->pcap_h)) != NULL)
1422         {
1423             switch (capture_opts->sampling_method)
1424             {
1425                 case CAPTURE_SAMP_BY_COUNT:
1426                     samp->method = PCAP_SAMP_1_EVERY_N;
1427                     break;
1428
1429                 case CAPTURE_SAMP_BY_TIMER:
1430                     samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
1431                     break;
1432
1433                 default:
1434                     sync_msg_str = g_strdup_printf(
1435                             "Unknown sampling method %d specified,\n"
1436                             "continue without packet sampling",
1437                             capture_opts->sampling_method);
1438                     report_capture_error("Couldn't set the capture "
1439                             "sampling", sync_msg_str);
1440                     g_free(sync_msg_str);
1441             }
1442             samp->value = capture_opts->sampling_param;
1443         }
1444         else
1445         {
1446             report_capture_error("Couldn't set the capture sampling",
1447                     "Cannot get packet sampling data structure");
1448         }
1449
1450     }
1451 #endif
1452
1453     /* setting the data link type only works on real interfaces */
1454     if (capture_opts->linktype != -1) {
1455       set_linktype_err_str = set_pcap_linktype(ld->pcap_h, capture_opts->iface,
1456         capture_opts->linktype);
1457       if (set_linktype_err_str != NULL) {
1458         g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
1459                 set_linktype_err_str);
1460         g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
1461         return FALSE;
1462       }
1463     }
1464     ld->linktype = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
1465   } else {
1466     /* We couldn't open "iface" as a network device. */
1467     /* Try to open it as a pipe */
1468     cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, (int) errmsg_len);
1469
1470 #ifndef _WIN32
1471     if (ld->cap_pipe_fd == -1) {
1472 #else
1473     if (ld->cap_pipe_h == INVALID_HANDLE_VALUE) {
1474 #endif
1475
1476       if (ld->cap_pipe_err == PIPNEXIST) {
1477         /* Pipe doesn't exist, so output message for interface */
1478
1479         /* If we got a "can't find PPA for X" message, warn the user (who
1480            is running (T)Wireshark on HP-UX) that they don't have a version
1481            of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1482            versions, which properly handle HP-UX, say "can't find /dev/dlpi
1483            PPA for X" rather than "can't find PPA for X"). */
1484         if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1485           libpcap_warn =
1486             "\n\n"
1487             "You are running (T)Wireshark with a version of the libpcap library\n"
1488             "that doesn't handle HP-UX network devices well; this means that\n"
1489             "(T)Wireshark may not be able to capture packets.\n"
1490             "\n"
1491             "To fix this, you should install libpcap 0.6.2, or a later version\n"
1492             "of libpcap, rather than libpcap 0.4 or 0.5.x.  It is available in\n"
1493             "packaged binary form from the Software Porting And Archive Centre\n"
1494             "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1495             "at the URL lists a number of mirror sites.";
1496         else
1497           libpcap_warn = "";
1498         g_snprintf(errmsg, (gulong) errmsg_len,
1499           "The capture session could not be initiated (%s).", open_err_str);
1500 #ifndef _WIN32
1501         g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
1502 "Please check to make sure you have sufficient permissions, and that you have "
1503 "the proper interface or pipe specified.%s", libpcap_warn);
1504 #else
1505     g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
1506 "\n"
1507 "Please check that \"%s\" is the proper interface.\n"
1508 "\n"
1509 "\n"
1510 "Help can be found at:\n"
1511 "\n"
1512 "       http://wiki.wireshark.org/WinPcap\n"
1513 "       http://wiki.wireshark.org/CaptureSetup\n",
1514     capture_opts->iface);
1515 #endif /* _WIN32 */
1516       }
1517       /*
1518        * Else pipe (or file) does exist and cap_pipe_open_live() has
1519        * filled in errmsg
1520        */
1521       return FALSE;
1522     } else
1523       /* cap_pipe_open_live() succeeded; don't want
1524          error message from pcap_open_live() */
1525       open_err_str[0] = '\0';
1526   }
1527
1528 /* XXX - will this work for tshark? */
1529 #ifdef MUST_DO_SELECT
1530   if (!ld->from_cap_pipe) {
1531 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
1532     ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
1533 #else
1534     ld->pcap_fd = pcap_fileno(ld->pcap_h);
1535 #endif
1536   }
1537 #endif
1538
1539   /* Does "open_err_str" contain a non-empty string?  If so, "pcap_open_live()"
1540      returned a warning; print it, but keep capturing. */
1541   if (open_err_str[0] != '\0') {
1542     sync_msg_str = g_strdup_printf("%s.", open_err_str);
1543     report_capture_error(sync_msg_str, "");
1544     g_free(sync_msg_str);
1545   }
1546
1547   return TRUE;
1548 }
1549
1550
1551 /* close the capture input file (pcap or capture pipe) */
1552 static void capture_loop_close_input(loop_data *ld) {
1553
1554   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
1555
1556   /* if open, close the capture pipe "input file" */
1557 #ifndef _WIN32
1558   if (ld->cap_pipe_fd >= 0) {
1559     g_assert(ld->from_cap_pipe);
1560     ws_close(ld->cap_pipe_fd);
1561     ld->cap_pipe_fd = 0;
1562   }
1563 #else
1564   if (ld->cap_pipe_h != INVALID_HANDLE_VALUE) {
1565     CloseHandle(ld->cap_pipe_h);
1566     ld->cap_pipe_h = INVALID_HANDLE_VALUE;
1567   }
1568 #endif
1569
1570   /* if open, close the pcap "input file" */
1571   if(ld->pcap_h != NULL) {
1572     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)ld->pcap_h);
1573     g_assert(!ld->from_cap_pipe);
1574     pcap_close(ld->pcap_h);
1575     ld->pcap_h = NULL;
1576   }
1577
1578   ld->go = FALSE;
1579
1580 #ifdef _WIN32
1581   /* Shut down windows sockets */
1582   WSACleanup();
1583 #endif
1584 }
1585
1586
1587 /* init the capture filter */
1588 static initfilter_status_t
1589 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe, gchar * iface, gchar * cfilter) {
1590   bpf_u_int32 netnum, netmask;
1591   gchar       lookup_net_err_str[PCAP_ERRBUF_SIZE];
1592   struct bpf_program fcode;
1593
1594
1595   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
1596
1597   /* capture filters only work on real interfaces */
1598   if (cfilter && !from_cap_pipe) {
1599     /* A capture filter was specified; set it up. */
1600     if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1601       /*
1602        * Well, we can't get the netmask for this interface; it's used
1603        * only for filters that check for broadcast IP addresses, so
1604        * we just punt and use 0.  It might be nice to warn the user,
1605        * but that's a pain in a GUI application, as it'd involve popping
1606        * up a message box, and it's not clear how often this would make
1607        * a difference (only filters that check for IP broadcast addresses
1608        * use the netmask).
1609        */
1610       /*cmdarg_err(
1611         "Warning:  Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
1612       netmask = 0;
1613     }
1614     if (pcap_compile(pcap_h, &fcode, cfilter, 1, netmask) < 0) {
1615       /* Treat this specially - our caller might try to compile this
1616          as a display filter and, if that succeeds, warn the user that
1617          the display and capture filter syntaxes are different. */
1618       return INITFILTER_BAD_FILTER;
1619     }
1620     if (pcap_setfilter(pcap_h, &fcode) < 0) {
1621 #ifdef HAVE_PCAP_FREECODE
1622       pcap_freecode(&fcode);
1623 #endif
1624       return INITFILTER_OTHER_ERROR;
1625     }
1626 #ifdef HAVE_PCAP_FREECODE
1627     pcap_freecode(&fcode);
1628 #endif
1629   }
1630
1631   return INITFILTER_NO_ERROR;
1632 }
1633
1634
1635 /* set up to write to the already-opened capture output file/files */
1636 static gboolean
1637 capture_loop_init_output(capture_options *capture_opts, int save_file_fd, loop_data *ld, char *errmsg, int errmsg_len) {
1638   int         err;
1639
1640
1641   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
1642
1643   /* get snaplen */
1644   if (ld->from_cap_pipe) {
1645     ld->file_snaplen = ld->cap_pipe_hdr.snaplen;
1646   } else
1647   {
1648     ld->file_snaplen = pcap_snapshot(ld->pcap_h);
1649   }
1650
1651   /* Set up to write to the capture file. */
1652   if (capture_opts->multi_files_on) {
1653     ld->pdh = ringbuf_init_libpcap_fdopen(&err);
1654   } else {
1655     ld->pdh = libpcap_fdopen(save_file_fd, &err);
1656   }
1657   if (ld->pdh) {
1658     gboolean successful;
1659
1660     ld->bytes_written = 0;
1661     if (capture_opts->use_pcapng) {
1662       char appname[100];
1663
1664       g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
1665       successful = libpcap_write_session_header_block(ld->pdh, appname, &ld->bytes_written, &err) &&
1666                    libpcap_write_interface_description_block(ld->pdh, capture_opts->iface, capture_opts->cfilter, ld->linktype, ld->file_snaplen, &ld->bytes_written, &err);
1667     } else {
1668       successful = libpcap_write_file_header(ld->pdh, ld->linktype, ld->file_snaplen,
1669                                              &ld->bytes_written, &err);
1670     }
1671     if (!successful) {
1672       fclose(ld->pdh);
1673       ld->pdh = NULL;
1674     }
1675   }
1676
1677   if (ld->pdh == NULL) {
1678     /* We couldn't set up to write to the capture file. */
1679     /* XXX - use cf_open_error_message from tshark instead? */
1680     switch (err) {
1681
1682     case WTAP_ERR_CANT_OPEN:
1683       g_snprintf(errmsg, errmsg_len, "The file to which the capture would be saved"
1684                " couldn't be created for some unknown reason.");
1685       break;
1686
1687     case WTAP_ERR_SHORT_WRITE:
1688       g_snprintf(errmsg, errmsg_len, "A full header couldn't be written to the file"
1689                " to which the capture would be saved.");
1690       break;
1691
1692     default:
1693       if (err < 0) {
1694         g_snprintf(errmsg, errmsg_len,
1695                    "The file to which the capture would be"
1696                    " saved (\"%s\") could not be opened: Error %d.",
1697                    capture_opts->save_file, err);
1698       } else {
1699         g_snprintf(errmsg, errmsg_len,
1700                     "The file to which the capture would be"
1701                     " saved (\"%s\") could not be opened: %s.",
1702                     capture_opts->save_file, strerror(err));
1703       }
1704       break;
1705     }
1706
1707     return FALSE;
1708   }
1709
1710   return TRUE;
1711 }
1712
1713 static gboolean
1714 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
1715
1716   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
1717
1718   if (capture_opts->multi_files_on) {
1719     return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
1720   } else {
1721     if (capture_opts->use_pcapng) {
1722       libpcap_write_interface_statistics_block(ld->pdh, 0, ld->pcap_h, &ld->bytes_written, err_close);
1723     }
1724     return libpcap_dump_close(ld->pdh, err_close);
1725   }
1726 }
1727
1728 /* dispatch incoming packets (pcap or capture pipe)
1729  *
1730  * Waits for incoming packets to be available, and calls pcap_dispatch()
1731  * to cause them to be processed.
1732  *
1733  * Returns the number of packets which were processed.
1734  *
1735  * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
1736  * packet-batching behaviour does not cause packets to get held back
1737  * indefinitely.
1738  */
1739 static int
1740 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
1741                       char *errmsg, int errmsg_len)
1742 {
1743   int       inpkts;
1744   gint      packet_count_before;
1745   guchar    pcap_data[WTAP_MAX_PACKET_SIZE];
1746 #ifndef USE_THREADS
1747   int       sel_ret;
1748 #endif
1749
1750   packet_count_before = ld->packet_count;
1751   if (ld->from_cap_pipe) {
1752     /* dispatch from capture pipe */
1753 #ifdef LOG_CAPTURE_VERBOSE
1754     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
1755 #endif
1756 #ifndef USE_THREADS
1757     sel_ret = cap_pipe_select(ld->cap_pipe_fd);
1758     if (sel_ret <= 0) {
1759       inpkts = 0;
1760       if (sel_ret < 0 && errno != EINTR) {
1761         g_snprintf(errmsg, errmsg_len,
1762           "Unexpected error from select: %s", strerror(errno));
1763         report_capture_error(errmsg, please_report);
1764         ld->go = FALSE;
1765       }
1766     } else {
1767       /*
1768        * "select()" says we can read from the pipe without blocking
1769        */
1770 #endif /* USE_THREADS */
1771       inpkts = cap_pipe_dispatch(ld, pcap_data, errmsg, errmsg_len);
1772       if (inpkts < 0) {
1773         ld->go = FALSE;
1774       }
1775 #ifndef USE_THREADS
1776     }
1777 #endif
1778   }
1779   else
1780   {
1781     /* dispatch from pcap */
1782 #ifdef MUST_DO_SELECT
1783     /*
1784      * If we have "pcap_get_selectable_fd()", we use it to get the
1785      * descriptor on which to select; if that's -1, it means there
1786      * is no descriptor on which you can do a "select()" (perhaps
1787      * because you're capturing on a special device, and that device's
1788      * driver unfortunately doesn't support "select()", in which case
1789      * we don't do the select - which means it might not be possible
1790      * to stop a capture until a packet arrives.  If that's unacceptable,
1791      * plead with whoever supplies the software for that device to add
1792      * "select()" support, or upgrade to libpcap 0.8.1 or later, and
1793      * rebuild Wireshark or get a version built with libpcap 0.8.1 or
1794      * later, so it can use pcap_breakloop().
1795      */
1796 #ifdef LOG_CAPTURE_VERBOSE
1797     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
1798 #endif
1799     if (ld->pcap_fd != -1) {
1800       sel_ret = cap_pipe_select(ld->pcap_fd);
1801       if (sel_ret > 0) {
1802         /*
1803          * "select()" says we can read from it without blocking; go for
1804          * it.
1805          *
1806          * We don't have pcap_breakloop(), so we only process one packet
1807          * per pcap_dispatch() call, to allow a signal to stop the
1808          * processing immediately, rather than processing all packets
1809          * in a batch before quitting.
1810          */
1811         inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb,
1812                                (u_char *)ld);
1813         if (inpkts < 0) {
1814             if (inpkts == -1) {
1815                 /* Error, rather than pcap_breakloop(). */
1816                 ld->pcap_err = TRUE;
1817             }
1818           ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1819         }
1820       } else {
1821         if (sel_ret < 0 && errno != EINTR) {
1822           g_snprintf(errmsg, errmsg_len,
1823             "Unexpected error from select: %s", strerror(errno));
1824           report_capture_error(errmsg, please_report);
1825           ld->go = FALSE;
1826         }
1827       }
1828     }
1829     else
1830 #endif /* MUST_DO_SELECT */
1831     {
1832       /* dispatch from pcap without select */
1833 #if 1
1834 #ifdef LOG_CAPTURE_VERBOSE
1835       g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
1836 #endif
1837 #ifdef _WIN32
1838       /*
1839        * On Windows, we don't support asynchronously telling a process to
1840        * stop capturing; instead, we check for an indication on a pipe
1841        * after processing packets.  We therefore process only one packet
1842        * at a time, so that we can check the pipe after every packet.
1843        */
1844       inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb, (u_char *) ld);
1845 #else
1846       inpkts = pcap_dispatch(ld->pcap_h, -1, capture_loop_packet_cb, (u_char *) ld);
1847 #endif
1848       if (inpkts < 0) {
1849         if (inpkts == -1) {
1850           /* Error, rather than pcap_breakloop(). */
1851           ld->pcap_err = TRUE;
1852         }
1853         ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
1854       }
1855 #else /* pcap_next_ex */
1856 #ifdef LOG_CAPTURE_VERBOSE
1857       g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
1858 #endif
1859       /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
1860
1861       /*
1862        * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
1863        * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
1864        * This should be fixed in the WinPcap 4.0 alpha release.
1865        *
1866        * For reference, an example remote interface:
1867        * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
1868        */
1869
1870       /* emulate dispatch from pcap */
1871       {
1872         int in;
1873         struct pcap_pkthdr *pkt_header;
1874         u_char *pkt_data;
1875
1876         in = 0;
1877         while(ld->go &&
1878               (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1)
1879           capture_loop_packet_cb( (u_char *) ld, pkt_header, pkt_data);
1880
1881         if(in < 0) {
1882           ld->pcap_err = TRUE;
1883           ld->go = FALSE;
1884         }
1885       }
1886 #endif /* pcap_next_ex */
1887     }
1888   }
1889
1890 #ifdef LOG_CAPTURE_VERBOSE
1891   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
1892 #endif
1893
1894   return ld->packet_count - packet_count_before;
1895 }
1896
1897
1898 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
1899 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
1900 static gboolean
1901 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
1902                       char *errmsg, int errmsg_len) {
1903
1904   char *tmpname;
1905   gchar *capfile_name;
1906   gboolean is_tempfile;
1907 #ifndef _WIN32
1908   int ret;
1909 #endif
1910
1911   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
1912       (capture_opts->save_file) ? capture_opts->save_file : "");
1913
1914   if (capture_opts->save_file != NULL) {
1915     /* We return to the caller while the capture is in progress.
1916      * Therefore we need to take a copy of save_file in
1917      * case the caller destroys it after we return.
1918      */
1919     capfile_name = g_strdup(capture_opts->save_file);
1920
1921     if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
1922       if (capture_opts->multi_files_on) {
1923         /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
1924         g_snprintf(errmsg, errmsg_len,
1925             "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
1926         g_free(capfile_name);
1927         return FALSE;
1928       }
1929       if (strcmp(capfile_name, "-") == 0) {
1930         /* write to stdout */
1931         *save_file_fd = 1;
1932 #ifdef _WIN32
1933         /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF)  */
1934         _setmode(1, O_BINARY);
1935 #endif
1936       }
1937     } /* if (...output_to_pipe ... */
1938
1939     else {
1940       if (capture_opts->multi_files_on) {
1941         /* ringbuffer is enabled */
1942         *save_file_fd = ringbuf_init(capfile_name,
1943             (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
1944
1945         /* we need the ringbuf name */
1946         if(*save_file_fd != -1) {
1947             g_free(capfile_name);
1948             capfile_name = g_strdup(ringbuf_current_filename());
1949         }
1950       } else {
1951         /* Try to open/create the specified file for use as a capture buffer. */
1952         *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
1953                              0600);
1954       }
1955     }
1956     is_tempfile = FALSE;
1957   } else {
1958     /* Choose a random name for the temporary capture buffer */
1959     *save_file_fd = create_tempfile(&tmpname, "wireshark");
1960     capfile_name = g_strdup(tmpname);
1961     is_tempfile = TRUE;
1962   }
1963
1964   /* did we fail to open the output file? */
1965   if (*save_file_fd == -1) {
1966     if (is_tempfile) {
1967       g_snprintf(errmsg, errmsg_len,
1968         "The temporary file to which the capture would be saved (\"%s\") "
1969         "could not be opened: %s.", capfile_name, strerror(errno));
1970     } else {
1971       if (capture_opts->multi_files_on) {
1972         ringbuf_error_cleanup();
1973       }
1974
1975       g_snprintf(errmsg, errmsg_len,
1976             "The file to which the capture would be saved (\"%s\") "
1977         "could not be opened: %s.", capfile_name,
1978         strerror(errno));
1979     }
1980     g_free(capfile_name);
1981     return FALSE;
1982   }
1983
1984   if(capture_opts->save_file != NULL) {
1985     g_free(capture_opts->save_file);
1986   }
1987   capture_opts->save_file = capfile_name;
1988   /* capture_opts.save_file is "g_free"ed later, which is equivalent to
1989      "g_free(capfile_name)". */
1990 #ifndef _WIN32
1991   ret = fchown(*save_file_fd, capture_opts->owner, capture_opts->group);
1992 #endif
1993
1994   return TRUE;
1995 }
1996
1997
1998 #ifdef _WIN32
1999 #define TIME_GET() GetTickCount()
2000 #else
2001 #define TIME_GET() time(NULL)
2002 #endif
2003
2004 /* Do the low-level work of a capture.
2005    Returns TRUE if it succeeds, FALSE otherwise. */
2006 static gboolean
2007 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
2008 {
2009   time_t      upd_time, cur_time;
2010   time_t      start_time;
2011   int         err_close;
2012   int         inpkts;
2013   gint        inpkts_to_sync_pipe = 0;     /* packets not already send out to the sync_pipe */
2014   condition  *cnd_file_duration = NULL;
2015   condition  *cnd_autostop_files = NULL;
2016   condition  *cnd_autostop_size = NULL;
2017   condition  *cnd_autostop_duration = NULL;
2018   guint32     autostop_files = 0;
2019   gboolean    write_ok;
2020   gboolean    close_ok;
2021   gboolean    cfilter_error = FALSE;
2022 #define MSG_MAX_LENGTH 4096
2023   char        errmsg[MSG_MAX_LENGTH+1];
2024   char        secondary_errmsg[MSG_MAX_LENGTH+1];
2025   int         save_file_fd = -1;
2026
2027   *errmsg           = '\0';
2028   *secondary_errmsg = '\0';
2029
2030   /* init the loop data */
2031   global_ld.go                 = TRUE;
2032   global_ld.packet_count       = 0;
2033   if (capture_opts->has_autostop_packets)
2034     global_ld.packet_max       = capture_opts->autostop_packets;
2035   else
2036     global_ld.packet_max       = 0;     /* no limit */
2037   global_ld.err                = 0;     /* no error seen yet */
2038   global_ld.wtap_linktype      = WTAP_ENCAP_UNKNOWN;
2039   global_ld.pcap_err           = FALSE;
2040   global_ld.from_cap_pipe      = FALSE;
2041   global_ld.pdh                = NULL;
2042 #ifndef _WIN32
2043   global_ld.cap_pipe_fd        = -1;
2044 #else
2045   global_ld.cap_pipe_h         = INVALID_HANDLE_VALUE;
2046 #endif
2047 #ifdef MUST_DO_SELECT
2048   global_ld.pcap_fd            = 0;
2049 #endif
2050
2051   /* We haven't yet gotten the capture statistics. */
2052   *stats_known      = FALSE;
2053
2054   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
2055   capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
2056
2057   /* open the "input file" from network interface or capture pipe */
2058   if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
2059                                secondary_errmsg, sizeof(secondary_errmsg))) {
2060     goto error;
2061   }
2062
2063   /* init the input filter from the network interface (capture pipe will do nothing) */
2064   switch (capture_loop_init_filter(global_ld.pcap_h, global_ld.from_cap_pipe,
2065                                    capture_opts->iface,
2066                                    capture_opts->cfilter)) {
2067
2068   case INITFILTER_NO_ERROR:
2069     break;
2070
2071   case INITFILTER_BAD_FILTER:
2072     cfilter_error = TRUE;
2073     g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(global_ld.pcap_h));
2074     goto error;
2075
2076   case INITFILTER_OTHER_ERROR:
2077     g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
2078                pcap_geterr(global_ld.pcap_h));
2079     g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
2080     goto error;
2081   }
2082
2083   /* If we're supposed to write to a capture file, open it for output
2084      (temporary/specified name/ringbuffer) */
2085   if (capture_opts->saving_to_file) {
2086     if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
2087       goto error;
2088     }
2089
2090     /* set up to write to the already-opened capture output file/files */
2091     if (!capture_loop_init_output(capture_opts, save_file_fd, &global_ld,
2092                                   errmsg, sizeof(errmsg))) {
2093       goto error;
2094     }
2095
2096   /* XXX - capture SIGTERM and close the capture, in case we're on a
2097      Linux 2.0[.x] system and you have to explicitly close the capture
2098      stream in order to turn promiscuous mode off?  We need to do that
2099      in other places as well - and I don't think that works all the
2100      time in any case, due to libpcap bugs. */
2101
2102     /* Well, we should be able to start capturing.
2103
2104        Sync out the capture file, so the header makes it to the file system,
2105        and send a "capture started successfully and capture file created"
2106        message to our parent so that they'll open the capture file and
2107        update its windows to indicate that we have a live capture in
2108        progress. */
2109     libpcap_dump_flush(global_ld.pdh, NULL);
2110     report_new_capture_file(capture_opts->save_file);
2111   }
2112
2113   /* initialize capture stop (and alike) conditions */
2114   init_capture_stop_conditions();
2115   /* create stop conditions */
2116   if (capture_opts->has_autostop_filesize)
2117     cnd_autostop_size =
2118         cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
2119   if (capture_opts->has_autostop_duration)
2120     cnd_autostop_duration =
2121         cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
2122
2123   if (capture_opts->multi_files_on) {
2124       if (capture_opts->has_file_duration)
2125         cnd_file_duration =
2126             cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
2127
2128       if (capture_opts->has_autostop_files)
2129         cnd_autostop_files =
2130             cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
2131   }
2132
2133   /* init the time values */
2134   start_time = TIME_GET();
2135   upd_time = TIME_GET();
2136
2137   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
2138
2139   /* WOW, everything is prepared! */
2140   /* please fasten your seat belts, we will enter now the actual capture loop */
2141   while (global_ld.go) {
2142     /* dispatch incoming packets */
2143     inpkts = capture_loop_dispatch(capture_opts, &global_ld, errmsg,
2144                                    sizeof(errmsg));
2145
2146 #ifdef _WIN32
2147     /* any news from our parent (signal pipe)? -> just stop the capture */
2148     if (!signal_pipe_check_running()) {
2149       global_ld.go = FALSE;
2150     }
2151 #endif
2152
2153     if (inpkts > 0) {
2154       inpkts_to_sync_pipe += inpkts;
2155
2156       /* check capture size condition */
2157       if (cnd_autostop_size != NULL &&
2158           cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)){
2159         /* Capture size limit reached, do we have another file? */
2160         if (capture_opts->multi_files_on) {
2161           if (cnd_autostop_files != NULL &&
2162               cnd_eval(cnd_autostop_files, ++autostop_files)) {
2163              /* no files left: stop here */
2164             global_ld.go = FALSE;
2165             continue;
2166           }
2167
2168           /* Switch to the next ringbuffer file */
2169           if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2170                                   &save_file_fd, &global_ld.err)) {
2171             gboolean successful;
2172
2173             /* File switch succeeded: reset the conditions */
2174             global_ld.bytes_written = 0;
2175             if (capture_opts->use_pcapng) {
2176               char appname[100];
2177
2178               g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2179               successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2180                            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);
2181             } else {
2182               successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2183                                                      &global_ld.bytes_written, &global_ld.err);
2184             }
2185             if (!successful) {
2186               fclose(global_ld.pdh);
2187               global_ld.pdh = NULL;
2188               global_ld.go = FALSE;
2189               continue;
2190             }
2191             cnd_reset(cnd_autostop_size);
2192             if (cnd_file_duration) {
2193               cnd_reset(cnd_file_duration);
2194             }
2195             libpcap_dump_flush(global_ld.pdh, NULL);
2196             report_packet_count(inpkts_to_sync_pipe);
2197             inpkts_to_sync_pipe = 0;
2198             report_new_capture_file(capture_opts->save_file);
2199           } else {
2200             /* File switch failed: stop here */
2201             global_ld.go = FALSE;
2202             continue;
2203           }
2204         } else {
2205           /* single file, stop now */
2206           global_ld.go = FALSE;
2207           continue;
2208         }
2209       } /* cnd_autostop_size */
2210       if (capture_opts->output_to_pipe) {
2211         libpcap_dump_flush(global_ld.pdh, NULL);
2212       }
2213     } /* inpkts */
2214
2215     /* Only update once a second (Win32: 500ms) so as not to overload slow
2216      * displays. This also prevents too much context-switching between the
2217      * dumpcap and wireshark processes */
2218     cur_time = TIME_GET();
2219 #ifdef _WIN32
2220     if ( (cur_time - upd_time) > 500) {
2221 #else
2222     if (cur_time - upd_time > 0) {
2223 #endif
2224         upd_time = cur_time;
2225
2226       /*if (pcap_stats(pch, stats) >= 0) {
2227         *stats_known = TRUE;
2228       }*/
2229
2230       /* Let the parent process know. */
2231       if (inpkts_to_sync_pipe) {
2232         /* do sync here */
2233         libpcap_dump_flush(global_ld.pdh, NULL);
2234
2235         /* Send our parent a message saying we've written out "inpkts_to_sync_pipe"
2236            packets to the capture file. */
2237         report_packet_count(inpkts_to_sync_pipe);
2238
2239         inpkts_to_sync_pipe = 0;
2240       }
2241
2242       /* check capture duration condition */
2243       if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
2244         /* The maximum capture time has elapsed; stop the capture. */
2245         global_ld.go = FALSE;
2246         continue;
2247       }
2248
2249       /* check capture file duration condition */
2250       if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
2251         /* duration limit reached, do we have another file? */
2252         if (capture_opts->multi_files_on) {
2253           if (cnd_autostop_files != NULL &&
2254               cnd_eval(cnd_autostop_files, ++autostop_files)) {
2255             /* no files left: stop here */
2256             global_ld.go = FALSE;
2257             continue;
2258           }
2259
2260           /* Switch to the next ringbuffer file */
2261           if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2262                                   &save_file_fd, &global_ld.err)) {
2263             gboolean successful;
2264
2265             /* file switch succeeded: reset the conditions */
2266             global_ld.bytes_written = 0;
2267             if (capture_opts->use_pcapng) {
2268               char appname[100];
2269
2270               g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2271               successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2272                            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);
2273             } else {
2274               successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2275                                                      &global_ld.bytes_written, &global_ld.err);
2276             }
2277             if (!successful) {
2278               fclose(global_ld.pdh);
2279               global_ld.pdh = NULL;
2280               global_ld.go = FALSE;
2281               continue;
2282             }
2283             cnd_reset(cnd_file_duration);
2284             if(cnd_autostop_size)
2285               cnd_reset(cnd_autostop_size);
2286             libpcap_dump_flush(global_ld.pdh, NULL);
2287             report_packet_count(inpkts_to_sync_pipe);
2288             inpkts_to_sync_pipe = 0;
2289             report_new_capture_file(capture_opts->save_file);
2290           } else {
2291             /* File switch failed: stop here */
2292             global_ld.go = FALSE;
2293             continue;
2294           }
2295         } else {
2296           /* single file, stop now */
2297           global_ld.go = FALSE;
2298           continue;
2299         }
2300       } /* cnd_file_duration */
2301     }
2302
2303   } /* while (global_ld.go) */
2304
2305   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
2306
2307   /* delete stop conditions */
2308   if (cnd_file_duration != NULL)
2309     cnd_delete(cnd_file_duration);
2310   if (cnd_autostop_files != NULL)
2311     cnd_delete(cnd_autostop_files);
2312   if (cnd_autostop_size != NULL)
2313     cnd_delete(cnd_autostop_size);
2314   if (cnd_autostop_duration != NULL)
2315     cnd_delete(cnd_autostop_duration);
2316
2317   /* did we had a pcap (input) error? */
2318   if (global_ld.pcap_err) {
2319     /* On Linux, if an interface goes down while you're capturing on it,
2320        you'll get a "recvfrom: Network is down" error (ENETDOWN).
2321        (At least you will if strerror() doesn't show a local translation
2322        of the error.)
2323
2324        On FreeBSD and OS X, if a network adapter disappears while
2325        you're capturing on it, you'll get a "read: Device not configured"
2326        error (ENXIO).  (See previous parenthetical note.)
2327
2328        On OpenBSD, you get "read: I/O error" (EIO) in the same case.
2329
2330        These should *not* be reported to the Wireshark developers. */
2331     char *cap_err_str;
2332
2333     cap_err_str = pcap_geterr(global_ld.pcap_h);
2334     if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
2335         strcmp(cap_err_str, "read: Device not configured") == 0 ||
2336         strcmp(cap_err_str, "read: I/O error") == 0) {
2337       report_capture_error("The network adapter on which the capture was being done "
2338                            "is no longer running; the capture has stopped.",
2339                            "");
2340     } else {
2341       g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
2342         cap_err_str);
2343       report_capture_error(errmsg, please_report);
2344     }
2345   }
2346   else if (global_ld.from_cap_pipe && global_ld.cap_pipe_err == PIPERR)
2347     report_capture_error(errmsg, "");
2348
2349   /* did we had an error while capturing? */
2350   if (global_ld.err == 0) {
2351     write_ok = TRUE;
2352   } else {
2353     capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
2354                             global_ld.err, FALSE);
2355     report_capture_error(errmsg, please_report);
2356     write_ok = FALSE;
2357   }
2358
2359   if (capture_opts->saving_to_file) {
2360     /* close the wiretap (output) file */
2361     close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
2362   } else
2363     close_ok = TRUE;
2364
2365   /* there might be packets not yet notified to the parent */
2366   /* (do this after closing the file, so all packets are already flushed) */
2367   if(inpkts_to_sync_pipe) {
2368     report_packet_count(inpkts_to_sync_pipe);
2369     inpkts_to_sync_pipe = 0;
2370   }
2371
2372   /* If we've displayed a message about a write error, there's no point
2373      in displaying another message about an error on close. */
2374   if (!close_ok && write_ok) {
2375     capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
2376                 TRUE);
2377     report_capture_error(errmsg, "");
2378   }
2379
2380   /*
2381    * XXX We exhibit different behaviour between normal mode and sync mode
2382    * when the pipe is stdin and not already at EOF.  If we're a child, the
2383    * parent's stdin isn't closed, so if the user starts another capture,
2384    * cap_pipe_open_live() will very likely not see the expected magic bytes and
2385    * will say "Unrecognized libpcap format".  On the other hand, in normal
2386    * mode, cap_pipe_open_live() will say "End of file on pipe during open".
2387    */
2388
2389   /* get packet drop statistics from pcap */
2390   if(global_ld.pcap_h != NULL) {
2391     g_assert(!global_ld.from_cap_pipe);
2392     /* Get the capture statistics, so we know how many packets were
2393        dropped. */
2394     if (pcap_stats(global_ld.pcap_h, stats) >= 0) {
2395       *stats_known = TRUE;
2396       /* Let the parent process know. */
2397       report_packet_drops(stats->ps_drop);
2398     } else {
2399       g_snprintf(errmsg, sizeof(errmsg),
2400                 "Can't get packet-drop statistics: %s",
2401                 pcap_geterr(global_ld.pcap_h));
2402       report_capture_error(errmsg, please_report);
2403     }
2404   }
2405
2406   /* close the input file (pcap or capture pipe) */
2407   capture_loop_close_input(&global_ld);
2408
2409   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
2410
2411   /* ok, if the write and the close were successful. */
2412   return write_ok && close_ok;
2413
2414 error:
2415   if (capture_opts->multi_files_on) {
2416     /* cleanup ringbuffer */
2417     ringbuf_error_cleanup();
2418   } else {
2419     /* We can't use the save file, and we have no FILE * for the stream
2420        to close in order to close it, so close the FD directly. */
2421     if(save_file_fd != -1) {
2422       ws_close(save_file_fd);
2423     }
2424
2425     /* We couldn't even start the capture, so get rid of the capture
2426        file. */
2427     if(capture_opts->save_file != NULL) {
2428       ws_unlink(capture_opts->save_file);
2429       g_free(capture_opts->save_file);
2430     }
2431   }
2432   capture_opts->save_file = NULL;
2433   if (cfilter_error)
2434     report_cfilter_error(capture_opts->cfilter, errmsg);
2435   else
2436     report_capture_error(errmsg, secondary_errmsg);
2437
2438   /* close the input file (pcap or cap_pipe) */
2439   capture_loop_close_input(&global_ld);
2440
2441   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
2442
2443   return FALSE;
2444 }
2445
2446
2447 static void capture_loop_stop(void)
2448 {
2449 #ifdef HAVE_PCAP_BREAKLOOP
2450   if(global_ld.pcap_h != NULL)
2451     pcap_breakloop(global_ld.pcap_h);
2452 #endif
2453   global_ld.go = FALSE;
2454 }
2455
2456
2457 static void
2458 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
2459                           int err, gboolean is_close)
2460 {
2461   switch (err) {
2462
2463   case ENOSPC:
2464     g_snprintf(errmsg, errmsglen,
2465                 "Not all the packets could be written to the file"
2466                 " to which the capture was being saved\n"
2467                 "(\"%s\") because there is no space left on the file system\n"
2468                 "on which that file resides.",
2469                 fname);
2470     break;
2471
2472 #ifdef EDQUOT
2473   case EDQUOT:
2474     g_snprintf(errmsg, errmsglen,
2475                 "Not all the packets could be written to the file"
2476                 " to which the capture was being saved\n"
2477                 "(\"%s\") because you are too close to, or over,"
2478                 " your disk quota\n"
2479                 "on the file system on which that file resides.",
2480                 fname);
2481   break;
2482 #endif
2483
2484   case WTAP_ERR_CANT_CLOSE:
2485     g_snprintf(errmsg, errmsglen,
2486                 "The file to which the capture was being saved"
2487                 " couldn't be closed for some unknown reason.");
2488     break;
2489
2490   case WTAP_ERR_SHORT_WRITE:
2491     g_snprintf(errmsg, errmsglen,
2492                 "Not all the packets could be written to the file"
2493                 " to which the capture was being saved\n"
2494                 "(\"%s\").",
2495                 fname);
2496     break;
2497
2498   default:
2499     if (is_close) {
2500       g_snprintf(errmsg, errmsglen,
2501                 "The file to which the capture was being saved\n"
2502                 "(\"%s\") could not be closed: %s.",
2503                 fname, wtap_strerror(err));
2504     } else {
2505       g_snprintf(errmsg, errmsglen,
2506                 "An error occurred while writing to the file"
2507                 " to which the capture was being saved\n"
2508                 "(\"%s\"): %s.",
2509                 fname, wtap_strerror(err));
2510     }
2511     break;
2512   }
2513 }
2514
2515
2516 /* one packet was captured, process it */
2517 static void
2518 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
2519   const u_char *pd)
2520 {
2521   loop_data *ld = (void *) user;
2522   int err;
2523
2524   /* We may be called multiple times from pcap_dispatch(); if we've set
2525      the "stop capturing" flag, ignore this packet, as we're not
2526      supposed to be saving any more packets. */
2527   if (!ld->go)
2528     return;
2529
2530   if (ld->pdh) {
2531     gboolean successful;
2532     /* We're supposed to write the packet to a file; do so.
2533        If this fails, set "ld->go" to FALSE, to stop the capture, and set
2534        "ld->err" to the error. */
2535     if (global_capture_opts.use_pcapng) {
2536       successful = libpcap_write_enhanced_packet_block(ld->pdh, phdr, 0, pd, &ld->bytes_written, &err);
2537     } else {
2538       successful = libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err);
2539     }
2540     if (!successful) {
2541       ld->go = FALSE;
2542       ld->err = err;
2543     } else {
2544       ld->packet_count++;
2545       /* if the user told us to stop after x packets, do we already have enough? */
2546       if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
2547       {
2548         ld->go = FALSE;
2549       }
2550     }
2551   }
2552 }
2553
2554
2555 /* And now our feature presentation... [ fade to music ] */
2556 int
2557 main(int argc, char *argv[])
2558 {
2559   int                  opt;
2560   gboolean             arg_error = FALSE;
2561
2562 #ifdef _WIN32
2563   WSADATA              wsaData;
2564 #else
2565   struct sigaction action, oldaction;
2566 #endif
2567
2568   gboolean             start_capture = TRUE;
2569   gboolean             stats_known;
2570   struct pcap_stat     stats;
2571   GLogLevelFlags       log_flags;
2572   gboolean             list_interfaces = FALSE;
2573   gboolean             list_link_layer_types = FALSE;
2574   gboolean             machine_readable = FALSE;
2575   gboolean             print_statistics = FALSE;
2576   int                  status, run_once_args = 0;
2577   gint                 i;
2578 #if defined(__APPLE__) && defined(__LP64__)
2579   struct utsname       osinfo;
2580 #endif
2581
2582 #ifdef HAVE_PCAP_REMOTE
2583 #define OPTSTRING_INIT "a:A:b:c:Df:hi:Lm:MnprSs:uvw:y:Z:"
2584 #else
2585 #define OPTSTRING_INIT "a:b:c:Df:hi:LMnpSs:vw:y:Z:"
2586 #endif
2587
2588 #ifdef _WIN32
2589 #define OPTSTRING_WIN32 "B:"
2590 #else
2591 #define OPTSTRING_WIN32 ""
2592 #endif  /* _WIN32 */
2593
2594   char optstring[sizeof(OPTSTRING_INIT) + sizeof(OPTSTRING_WIN32) - 1] =
2595     OPTSTRING_INIT OPTSTRING_WIN32;
2596
2597 #ifdef DEBUG_CHILD_DUMPCAP
2598   if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
2599           fprintf (stderr, "Unable to open debug log file !\n");
2600           exit (1);
2601   }
2602 #endif
2603
2604 #if defined(__APPLE__) && defined(__LP64__)
2605   /*
2606    * Is this Mac OS X 10.6 or 10.6.1?  If so, we need a bug workaround.
2607    */
2608   if (uname(&osinfo) == 0) {
2609     /*
2610      * Mac OS X 10.x uses Darwin x.0.0.  Mac OS X 10.x.y uses Darwin
2611      * x.y.0 (except that 10.6.1 appears to have a uname version
2612      * number of 10.0.0, not 10.1.0 - go figure).
2613      */
2614     if (strcmp(osinfo.release, "10.0.0") == 0 ||
2615         strcmp(osinfo.release, "10.1.0") == 0)
2616       need_timeout_workaround = 1;
2617   }
2618 #endif
2619
2620   /* Determine if dumpcap is being requested to run in a special       */
2621   /* capture_child mode by going thru the command line args to see if  */
2622   /* a -Z is present. (-Z is a hidden option).                         */
2623   /* The primary result of running in capture_child mode is that       */
2624   /* all messages sent out on stderr are in a special type/len/string  */
2625   /* format to allow message processing by type.                       */
2626   /* These messages include various 'status' messages which are sent   */
2627   /* when an actual capture is in progress. Capture_child mode         */
2628   /* would normally be requested by a parent process which invokes     */
2629   /* dumpcap and obtains dumpcap stderr output via a pipe to which     */
2630   /* dumpcap stderr has been redirected.                               */
2631   /* Capture_child mode needs to be determined immediately upon        */
2632   /* startup so that any messages generated by dumpcap in this mode    */
2633   /* (eg: during initialization) will be formatted properly.           */
2634
2635   for (i=1; i<argc; i++) {
2636     if (strcmp("-Z", argv[i]) == 0) {
2637       capture_child = TRUE;
2638 #ifdef _WIN32
2639       /* set output pipe to binary mode, to avoid ugly text conversions */
2640       _setmode(2, O_BINARY);
2641 #endif
2642     }
2643   }
2644
2645   /* The default_log_handler will use stdout, which makes trouble in   */
2646   /* capture child mode, as it uses stdout for it's sync_pipe.         */
2647   /* So: the filtering is done in the console_log_handler and not here.*/
2648   /* We set the log handlers right up front to make sure that any log  */
2649   /* messages when running as child will be sent back to the parent    */
2650   /* with the correct format.                                          */
2651
2652   log_flags =
2653                     G_LOG_LEVEL_ERROR|
2654                     G_LOG_LEVEL_CRITICAL|
2655                     G_LOG_LEVEL_WARNING|
2656                     G_LOG_LEVEL_MESSAGE|
2657                     G_LOG_LEVEL_INFO|
2658                     G_LOG_LEVEL_DEBUG|
2659                     G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
2660
2661   g_log_set_handler(NULL,
2662                     log_flags,
2663                     console_log_handler, NULL /* user_data */);
2664   g_log_set_handler(LOG_DOMAIN_MAIN,
2665                     log_flags,
2666                     console_log_handler, NULL /* user_data */);
2667   g_log_set_handler(LOG_DOMAIN_CAPTURE,
2668                     log_flags,
2669                     console_log_handler, NULL /* user_data */);
2670   g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
2671                     log_flags,
2672                     console_log_handler, NULL /* user_data */);
2673
2674 #ifdef _WIN32
2675   /* Load wpcap if possible. Do this before collecting the run-time version information */
2676   load_wpcap();
2677
2678   /* ... and also load the packet.dll from wpcap */
2679   /* XXX - currently not required, may change later. */
2680   /*wpcap_packet_load();*/
2681
2682   /* Start windows sockets */
2683   WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
2684
2685   /* Set handler for Ctrl+C key */
2686   SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
2687
2688   /* Prepare to read from a pipe */
2689   if (!g_thread_supported ())
2690     g_thread_init (NULL);
2691   cap_pipe_pending_q = g_async_queue_new();
2692   cap_pipe_done_q = g_async_queue_new();
2693   cap_pipe_read_mtx = g_mutex_new();
2694
2695 #else
2696   /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
2697      and exit. */
2698   action.sa_handler = capture_cleanup_handler;
2699   /*
2700    * Arrange that system calls not get restarted, because when
2701    * our signal handler returns we don't want to restart
2702    * a call that was waiting for packets to arrive.
2703    */
2704   action.sa_flags = 0;
2705   sigemptyset(&action.sa_mask);
2706   sigaction(SIGTERM, &action, NULL);
2707   sigaction(SIGINT, &action, NULL);
2708   sigaction(SIGPIPE, &action, NULL);
2709   sigaction(SIGHUP, NULL, &oldaction);
2710   if (oldaction.sa_handler == SIG_DFL)
2711     sigaction(SIGHUP, &action, NULL);
2712 #endif  /* _WIN32 */
2713
2714   /* ----------------------------------------------------------------- */
2715   /* Privilege and capability handling                                 */
2716   /* Cases:                                                            */
2717   /* 1. Running not as root or suid root; no special capabilities.     */
2718   /*    Action: none                                                   */
2719   /*                                                                   */
2720   /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap.  */
2721   /*    Action: none                                                   */
2722   /*                                                                   */
2723   /* 3. Running logged in as root (euid=0; ruid=0). Using libcap.      */
2724   /*    Action:                                                        */
2725   /*      - Near start of program: Enable NET_RAW and NET_ADMIN        */
2726   /*        capabilities; Drop all other capabilities;                 */
2727   /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
2728   /*        else: after  pcap_open_live() in capture_loop_open_input() */
2729   /*         drop all capabilities (NET_RAW and NET_ADMIN);            */
2730   /*         (Note: this means that the process, although logged in    */
2731   /*          as root, does not have various permissions such as the   */
2732   /*          ability to bypass file access permissions).              */
2733   /*      XXX: Should we just leave capabilities alone in this case    */
2734   /*          so that user gets expected effect that root can do       */
2735   /*          anything ??                                              */
2736   /*                                                                   */
2737   /* 4. Running as suid root (euid=0, ruid=n); Not using libcap.       */
2738   /*    Action:                                                        */
2739   /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
2740   /*        else: after  pcap_open_live() in capture_loop_open_input() */
2741   /*         drop suid root (set euid=ruid).(ie: keep suid until after */
2742   /*         pcap_open_live).                                          */
2743   /*                                                                   */
2744   /* 5. Running as suid root (euid=0, ruid=n); Using libcap.           */
2745   /*    Action:                                                        */
2746   /*      - Near start of program: Enable NET_RAW and NET_ADMIN        */
2747   /*        capabilities; Drop all other capabilities;                 */
2748   /*        Drop suid privileges (euid=ruid);                          */
2749   /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
2750   /*        else: after  pcap_open_live() in capture_loop_open_input() */
2751   /*         drop all capabilities (NET_RAW and NET_ADMIN).            */
2752   /*                                                                   */
2753   /*      XXX: For some Linux versions/distros with capabilities       */
2754   /*        a 'normal' process with any capabilities cannot be         */
2755   /*        'killed' (signaled) from another (same uid) non-privileged */
2756   /*        process.                                                   */
2757   /*        For example: If (non-suid) Wireshark forks a               */
2758   /*        child suid dumpcap which acts as described here (case 5),  */
2759   /*        Wireshark will be unable to kill (signal) the child        */
2760   /*        dumpcap process until the capabilities have been dropped   */
2761   /*        (after pcap_open_live()).                                  */
2762   /*        This behaviour will apparently be changed in the kernel    */
2763   /*        to allow the kill (signal) in this case.                   */
2764   /*        See the following for details:                             */
2765   /*           http://www.mail-archive.com/  [wrapped]                 */
2766   /*             linux-security-module@vger.kernel.org/msg02913.html   */
2767   /*                                                                   */
2768   /*        It is therefore conceivable that if dumpcap somehow hangs  */
2769   /*        in pcap_open_live or before that wireshark will not        */
2770   /*        be able to stop dumpcap using a signal (INT, TERM, etc).  */
2771   /*        In this case, exiting wireshark will kill the child        */
2772   /*        dumpcap process.                                           */
2773   /*                                                                   */
2774   /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN        */
2775   /*     capabilities; Using libcap.  Note: capset cmd (which see)     */
2776   /*     used to assign capabilities to file.                          */
2777   /*    Action:                                                        */
2778   /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
2779   /*        else: after  pcap_open_live() in capture_loop_open_input() */
2780   /*         drop all capabilities (NET_RAW and NET_ADMIN)             */
2781   /*                                                                   */
2782   /* ToDo: -S (stats) should drop privileges/capabilities when no      */
2783   /*       longer required (similar to capture).                        */
2784   /*                                                                   */
2785   /* ----------------------------------------------------------------- */
2786
2787   get_credential_info();
2788
2789 #ifdef HAVE_LIBCAP
2790   /* If 'started with special privileges' (and using libcap)  */
2791   /*   Set to keep only NET_RAW and NET_ADMIN capabilities;   */
2792   /*   Set euid/egid = ruid/rgid to remove suid privileges    */
2793   relinquish_privs_except_capture();
2794 #endif
2795
2796   /* Set the initial values in the capture options. This might be overwritten
2797      by the command line parameters. */
2798   capture_opts_init(&global_capture_opts, NULL);
2799
2800   /* Default to capturing the entire packet. */
2801   global_capture_opts.snaplen             = WTAP_MAX_PACKET_SIZE;
2802
2803   /* We always save to a file - if no file was specified, we save to a
2804      temporary file. */
2805   global_capture_opts.saving_to_file      = TRUE;
2806   global_capture_opts.has_ring_num_files  = TRUE;
2807
2808   /* Now get our args */
2809   while ((opt = getopt(argc, argv, optstring)) != -1) {
2810     switch (opt) {
2811       case 'h':        /* Print help and exit */
2812         print_usage(TRUE);
2813         exit_main(0);
2814         break;
2815       case 'v':        /* Show version and exit */
2816       {
2817         GString             *comp_info_str;
2818         GString             *runtime_info_str;
2819         /* Assemble the compile-time version information string */
2820         comp_info_str = g_string_new("Compiled ");
2821         get_compiled_version_info(comp_info_str, NULL);
2822
2823         /* Assemble the run-time version information string */
2824         runtime_info_str = g_string_new("Running ");
2825         get_runtime_version_info(runtime_info_str, NULL);
2826         show_version(comp_info_str, runtime_info_str);
2827         g_string_free(comp_info_str, TRUE);
2828         g_string_free(runtime_info_str, TRUE);
2829         exit_main(0);
2830         break;
2831       }
2832       /*** capture option specific ***/
2833       case 'a':        /* autostop criteria */
2834       case 'b':        /* Ringbuffer option */
2835       case 'c':        /* Capture x packets */
2836       case 'f':        /* capture filter */
2837       case 'i':        /* Use interface x */
2838       case 'n':        /* Use pcapng format */
2839       case 'p':        /* Don't capture in promiscuous mode */
2840       case 's':        /* Set the snapshot (capture) length */
2841       case 'w':        /* Write to capture file x */
2842       case 'y':        /* Set the pcap data link type */
2843 #ifdef HAVE_PCAP_REMOTE
2844       case 'u':        /* Use UDP for data transfer */
2845       case 'r':        /* Capture own RPCAP traffic too */
2846       case 'A':        /* Authentication */
2847 #endif
2848 #ifdef HAVE_PCAP_SETSAMPLING
2849       case 'm':        /* Sampling */
2850 #endif
2851 #ifdef _WIN32
2852       case 'B':        /* Buffer size */
2853 #endif /* _WIN32 */
2854         status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
2855         if(status != 0) {
2856           exit_main(status);
2857         }
2858         break;
2859       /*** hidden option: Wireshark child mode (using binary output messages) ***/
2860       case 'Z':
2861         capture_child = TRUE;
2862 #ifdef _WIN32
2863         /* set output pipe to binary mode, to avoid ugly text conversions */
2864         _setmode(2, O_BINARY);
2865         /*
2866          * optarg = the control ID, aka the PPID, currently used for the
2867          * signal pipe name.
2868          */
2869         if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
2870           sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
2871           sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
2872               GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
2873
2874           if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
2875             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
2876                   "Signal pipe: Unable to open %s.  Dead parent?",
2877                   sig_pipe_name);
2878             exit_main(1);
2879           }
2880         }
2881 #endif
2882         break;
2883
2884       /*** all non capture option specific ***/
2885       case 'D':        /* Print a list of capture devices and exit */
2886         list_interfaces = TRUE;
2887         run_once_args++;
2888         break;
2889       case 'L':        /* Print list of link-layer types and exit */
2890         list_link_layer_types = TRUE;
2891         run_once_args++;
2892         break;
2893       case 'S':        /* Print interface statistics once a second */
2894         print_statistics = TRUE;
2895         run_once_args++;
2896         break;
2897       case 'M':        /* For -D and -L, print machine-readable output */
2898         machine_readable = TRUE;
2899         break;
2900       default:
2901       case '?':        /* Bad flag - print usage message */
2902         cmdarg_err("Invalid Option: %s", argv[optind-1]);
2903         arg_error = TRUE;
2904         break;
2905     }
2906   }
2907   argc -= optind;
2908   argv += optind;
2909   if (argc >= 1) {
2910     /* user specified file name as regular command-line argument */
2911     /* XXX - use it as the capture file name (or something else)? */
2912     argc--;
2913     argv++;
2914   }
2915
2916   if (argc != 0) {
2917     /*
2918      * Extra command line arguments were specified; complain.
2919      * XXX - interpret as capture filter, as tcpdump and tshark do?
2920      */
2921     cmdarg_err("Invalid argument: %s", argv[0]);
2922     arg_error = TRUE;
2923   }
2924
2925   if (arg_error) {
2926     print_usage(FALSE);
2927     exit_main(1);
2928   }
2929
2930   if (run_once_args > 1) {
2931     cmdarg_err("Only one of -D, -L, or -S may be supplied.");
2932     exit_main(1);
2933   } else if (list_link_layer_types) {
2934     /* We're supposed to list the link-layer types for an interface;
2935        did the user also specify a capture file to be read? */
2936     /* No - did they specify a ring buffer option? */
2937     if (global_capture_opts.multi_files_on) {
2938       cmdarg_err("Ring buffer requested, but a capture isn't being done.");
2939       exit_main(1);
2940     }
2941   } else {
2942     /* No - was the ring buffer option specified and, if so, does it make
2943        sense? */
2944     if (global_capture_opts.multi_files_on) {
2945       /* Ring buffer works only under certain conditions:
2946          a) ring buffer does not work with temporary files;
2947          b) it makes no sense to enable the ring buffer if the maximum
2948             file size is set to "infinite". */
2949       if (global_capture_opts.save_file == NULL) {
2950         cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
2951         global_capture_opts.multi_files_on = FALSE;
2952       }
2953       if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
2954         cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
2955 /* XXX - this must be redesigned as the conditions changed */
2956 /*      global_capture_opts.multi_files_on = FALSE;*/
2957       }
2958     }
2959   }
2960
2961   if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
2962     /* cmdarg_err() already called .... */
2963     exit_main(1);
2964   }
2965
2966   /* Let the user know what interface was chosen. */
2967   /* get_interface_descriptive_name() is not available! */
2968   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", global_capture_opts.iface);
2969
2970   if (list_interfaces) {
2971     status = capture_opts_list_interfaces(machine_readable);
2972     exit_main(status);
2973   } else if (list_link_layer_types) {
2974     status = capture_opts_list_link_layer_types(&global_capture_opts, machine_readable);
2975     exit_main(status);
2976   } else if (print_statistics) {
2977     status = print_statistics_loop(machine_readable);
2978     exit_main(status);
2979   }
2980
2981   capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
2982   capture_opts_trim_ring_num_files(&global_capture_opts);
2983
2984   /* Now start the capture. */
2985
2986   if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
2987     /* capture ok */
2988     exit_main(0);
2989   } else {
2990     /* capture failed */
2991     exit_main(1);
2992   }
2993 }
2994
2995
2996 static void
2997 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
2998                     const char *message, gpointer user_data _U_)
2999 {
3000   time_t curr;
3001   struct tm  *today;
3002   const char *level;
3003   gchar      *msg;
3004
3005   /* ignore log message, if log_level isn't interesting */
3006   if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3007 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
3008     return;
3009 #endif
3010   }
3011
3012   /* create a "timestamp" */
3013   time(&curr);
3014   today = localtime(&curr);
3015
3016   switch(log_level & G_LOG_LEVEL_MASK) {
3017   case G_LOG_LEVEL_ERROR:
3018     level = "Err ";
3019     break;
3020   case G_LOG_LEVEL_CRITICAL:
3021     level = "Crit";
3022     break;
3023   case G_LOG_LEVEL_WARNING:
3024     level = "Warn";
3025     break;
3026   case G_LOG_LEVEL_MESSAGE:
3027     level = "Msg ";
3028     break;
3029   case G_LOG_LEVEL_INFO:
3030     level = "Info";
3031     break;
3032   case G_LOG_LEVEL_DEBUG:
3033     level = "Dbg ";
3034     break;
3035   default:
3036     fprintf(stderr, "unknown log_level %u\n", log_level);
3037     level = NULL;
3038     g_assert_not_reached();
3039   }
3040
3041   /* Generate the output message                                  */
3042   if(log_level & G_LOG_LEVEL_MESSAGE) {
3043     /* normal user messages without additional infos */
3044     msg =  g_strdup_printf("%s\n", message);
3045   } else {
3046     /* info/debug messages with additional infos */
3047     msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
3048             today->tm_hour, today->tm_min, today->tm_sec,
3049             log_domain != NULL ? log_domain : "",
3050             level, message);
3051   }
3052
3053   /* DEBUG & INFO msgs (if we're debugging today)                 */
3054 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3055   if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3056 #ifdef DEBUG_DUMPCAP
3057     fprintf(stderr, "%s", msg);
3058     fflush(stderr);
3059 #endif
3060 #ifdef DEBUG_CHILD_DUMPCAP
3061     fprintf(debug_log, "%s", msg);
3062     fflush(debug_log);
3063 #endif
3064     g_free(msg);
3065     return;
3066   }
3067 #endif
3068
3069   /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or    */
3070   /*  to parent especially formatted if dumpcap running as child. */
3071   if (capture_child) {
3072     sync_pipe_errmsg_to_parent(2, msg, "");
3073   } else {
3074     fprintf(stderr, "%s", msg);
3075     fflush(stderr);
3076   }
3077   g_free(msg);
3078 }
3079
3080
3081 /****************************************************************************************************************/
3082 /* indication report routines */
3083
3084
3085 void
3086 report_packet_count(int packet_count)
3087 {
3088     char tmp[SP_DECISIZE+1+1];
3089     static int count = 0;
3090
3091     if(capture_child) {
3092         g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
3093         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
3094         pipe_write_block(2, SP_PACKET_COUNT, tmp);
3095     } else {
3096         count += packet_count;
3097         fprintf(stderr, "\rPackets: %u ", count);
3098         /* stderr could be line buffered */
3099         fflush(stderr);
3100     }
3101 }
3102
3103 void
3104 report_new_capture_file(const char *filename)
3105 {
3106     if(capture_child) {
3107         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
3108         pipe_write_block(2, SP_FILE, filename);
3109     } else {
3110         fprintf(stderr, "File: %s\n", filename);
3111         /* stderr could be line buffered */
3112         fflush(stderr);
3113     }
3114 }
3115
3116 void
3117 report_cfilter_error(const char *cfilter, const char *errmsg)
3118 {
3119     if (capture_child) {
3120         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
3121         pipe_write_block(2, SP_BAD_FILTER, errmsg);
3122     } else {
3123         fprintf(stderr,
3124           "Invalid capture filter: \"%s\"!\n"
3125           "\n"
3126           "That string isn't a valid capture filter (%s).\n"
3127           "See the User's Guide for a description of the capture filter syntax.\n",
3128           cfilter, errmsg);
3129     }
3130 }
3131
3132 void
3133 report_capture_error(const char *error_msg, const char *secondary_error_msg)
3134 {
3135     if(capture_child) {
3136         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3137             "Primary Error: %s", error_msg);
3138         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3139             "Secondary Error: %s", secondary_error_msg);
3140         sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
3141     } else {
3142         fprintf(stderr, "%s\n%s\n", error_msg, secondary_error_msg);
3143     }
3144 }
3145
3146 void
3147 report_packet_drops(guint32 drops)
3148 {
3149     char tmp[SP_DECISIZE+1+1];
3150
3151     g_snprintf(tmp, sizeof(tmp), "%u", drops);
3152
3153     if(capture_child) {
3154         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
3155         pipe_write_block(2, SP_DROPS, tmp);
3156     } else {
3157         fprintf(stderr, "Packets dropped: %s\n", tmp);
3158         /* stderr could be line buffered */
3159         fflush(stderr);
3160     }
3161 }
3162
3163
3164 /****************************************************************************************************************/
3165 /* signal_pipe handling */
3166
3167
3168 #ifdef _WIN32
3169 static gboolean
3170 signal_pipe_check_running(void)
3171 {
3172     /* any news from our parent? -> just stop the capture */
3173     DWORD avail = 0;
3174     gboolean result;
3175
3176     /* if we are running standalone, no check required */
3177     if(!capture_child) {
3178         return TRUE;
3179     }
3180
3181     if(!sig_pipe_name || !sig_pipe_handle) {
3182         /* This shouldn't happen */
3183         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3184             "Signal pipe: No name or handle");
3185         return FALSE;
3186     }
3187
3188     /*
3189      * XXX - We should have the process ID of the parent (from the "-Z" flag)
3190      * at this point.  Should we check to see if the parent is still alive,
3191      * e.g. by using OpenProcess?
3192      */
3193
3194     result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
3195
3196     if(!result || avail > 0) {
3197         /* peek failed or some bytes really available */
3198         /* (if not piping from stdin this would fail) */
3199         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3200             "Signal pipe: Stop capture: %s", sig_pipe_name);
3201         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
3202             "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
3203             sig_pipe_handle, result, avail);
3204         return FALSE;
3205     } else {
3206         /* pipe ok and no bytes available */
3207         return TRUE;
3208     }
3209 }
3210 #endif
3211
3212 /*
3213  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
3214  *
3215  * Local variables:
3216  * c-basic-offset: 4
3217  * tab-width: 8
3218  * indent-tabs-mode: nil
3219  * End:
3220  *
3221  * vi: set shiftwidth=4 tabstop=8 expandtab
3222  * :indentSize=4:tabSize=8:noTabs=true:
3223  */