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