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