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