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