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