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