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