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