Make frames containing Malformed expert items match with "malformed" display filter.
[obnox/wireshark/wip.git] / dumpcap.c
1 /* dumpcap.c
2  *
3  * $Id$
4  *
5  * Wireshark - Network traffic analyzer
6  * By Gerald Combs <gerald@wireshark.org>
7  * Copyright 1998 Gerald Combs
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License
11  * as published by the Free Software Foundation; either version 2
12  * of the License, or (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  */
23
24 #ifdef HAVE_CONFIG_H
25 # include "config.h"
26 #endif
27
28 #include <stdio.h>
29 #include <stdlib.h> /* for exit() */
30 #include <glib.h>
31
32 #include <string.h>
33 #include <ctype.h>
34
35 #ifdef HAVE_SYS_TYPES_H
36 # include <sys/types.h>
37 #endif
38
39 #ifdef HAVE_SYS_STAT_H
40 # include <sys/stat.h>
41 #endif
42
43 #ifdef HAVE_FCNTL_H
44 #include <fcntl.h>
45 #endif
46
47 #ifdef HAVE_UNISTD_H
48 #include <unistd.h>
49 #endif
50
51 #ifdef HAVE_ARPA_INET_H
52 #include <arpa/inet.h>
53 #endif
54
55 #if defined(__APPLE__) && defined(__LP64__)
56 #include <sys/utsname.h>
57 #endif
58
59 #include <signal.h>
60 #include <errno.h>
61
62 #ifdef HAVE_GETOPT_H
63 #include <getopt.h>
64 #else
65 #include "wsutil/wsgetopt.h"
66 #endif
67
68 #ifdef HAVE_NETDB_H
69 #include <netdb.h>
70 #endif
71
72 #ifdef HAVE_LIBCAP
73 # include <sys/prctl.h>
74 # include <sys/capability.h>
75 #endif
76
77 #include "ringbuffer.h"
78 #include "clopts_common.h"
79 #include "console_io.h"
80 #include "cmdarg_err.h"
81 #include "version_info.h"
82
83 #include "capture-pcap-util.h"
84
85 #include "pcapio.h"
86
87 #ifdef _WIN32
88 #include "capture-wpcap.h"
89 #include <wsutil/unicode-utils.h>
90 #endif
91
92 #ifndef _WIN32
93 #include <sys/socket.h>
94 #include <sys/un.h>
95 #endif
96
97 #ifdef NEED_INET_V6DEFS_H
98 # include "wsutil/inet_v6defs.h"
99 #endif
100
101 #include <wsutil/privileges.h>
102
103 #include "sync_pipe.h"
104
105 #include "capture_opts.h"
106 #include "capture_ifinfo.h"
107 #include "capture_sync.h"
108
109 #include "conditions.h"
110 #include "capture_stop_conditions.h"
111
112 #include "tempfile.h"
113 #include "log.h"
114 #include "wsutil/file_util.h"
115
116 /*
117  * Get information about libpcap format from "wiretap/libpcap.h".
118  * XXX - can we just use pcap_open_offline() to read the pipe?
119  */
120 #include "wiretap/libpcap.h"
121
122 /**#define DEBUG_DUMPCAP**/
123 /**#define DEBUG_CHILD_DUMPCAP**/
124
125 #ifdef DEBUG_CHILD_DUMPCAP
126 FILE *debug_log;   /* for logging debug messages to  */
127                    /*  a file if DEBUG_CHILD_DUMPCAP */
128                    /*  is defined                    */
129 #endif
130
131 #ifdef _WIN32
132 #define USE_THREADS
133 #endif
134
135 static gboolean capture_child = FALSE; /* FALSE: standalone call, TRUE: this is an Wireshark capture child */
136 #ifdef _WIN32
137 static gchar *sig_pipe_name = NULL;
138 static HANDLE sig_pipe_handle = NULL;
139 static gboolean signal_pipe_check_running(void);
140 #endif
141
142 #ifdef USE_THREADS
143 static GAsyncQueue *cap_pipe_pending_q, *cap_pipe_done_q;
144 static GMutex *cap_pipe_read_mtx;
145 #endif
146
147 #ifdef SIGINFO
148 static gboolean infodelay;      /* if TRUE, don't print capture info in SIGINFO handler */
149 static gboolean infoprint;      /* if TRUE, print capture info after clearing infodelay */
150 #endif /* SIGINFO */
151
152 /** Stop a low-level capture (stops the capture child). */
153 static void capture_loop_stop(void);
154
155 #if !defined (__linux__)
156 #ifndef HAVE_PCAP_BREAKLOOP
157 /*
158  * We don't have pcap_breakloop(), which is the only way to ensure that
159  * pcap_dispatch(), pcap_loop(), or even pcap_next() or pcap_next_ex()
160  * won't, if the call to read the next packet or batch of packets is
161  * is interrupted by a signal on UN*X, just go back and try again to
162  * read again.
163  *
164  * On UN*X, we catch SIGINT as a "stop capturing" signal, and, in
165  * the signal handler, set a flag to stop capturing; however, without
166  * a guarantee of that sort, we can't guarantee that we'll stop capturing
167  * if the read will be retried and won't time out if no packets arrive.
168  *
169  * Therefore, on at least some platforms, we work around the lack of
170  * pcap_breakloop() by doing a select() on the pcap_t's file descriptor
171  * to wait for packets to arrive, so that we're probably going to be
172  * blocked in the select() when the signal arrives, and can just bail
173  * out of the loop at that point.
174  *
175  * However, we don't want to that on BSD (because "select()" doesn't work
176  * correctly on BPF devices on at least some releases of some flavors of
177  * BSD), and we don't want to do it on Windows (because "select()" is
178  * something for sockets, not for arbitrary handles).  (Note that "Windows"
179  * here includes Cygwin; even in its pretend-it's-UNIX environment, we're
180  * using WinPcap, not a UNIX libpcap.)
181  *
182  * Fortunately, we don't need to do it on BSD, because the libpcap timeout
183  * on BSD times out even if no packets have arrived, so we'll eventually
184  * exit pcap_dispatch() with an indication that no packets have arrived,
185  * and will break out of the capture loop at that point.
186  *
187  * On Windows, we can't send a SIGINT to stop capturing, so none of this
188  * applies in any case.
189  *
190  * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
191  * want to include it if it's not present on this platform, however.
192  */
193 # if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
194     !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
195     !defined(__CYGWIN__)
196 #  define MUST_DO_SELECT
197 # endif /* avoid select */
198 #endif /* HAVE_PCAP_BREAKLOOP */
199 #else /* linux */
200 /* whatever the deal with pcap_breakloop, linux doesn't support timeouts
201  * in pcap_dispatch(); on the other hand, select() works just fine there.
202  * Hence we use a select for that come what may.
203  */
204 #define MUST_DO_SELECT
205 #endif
206
207 /** init the capture filter */
208 typedef enum {
209   INITFILTER_NO_ERROR,
210   INITFILTER_BAD_FILTER,
211   INITFILTER_OTHER_ERROR
212 } initfilter_status_t;
213
214 typedef struct _loop_data {
215   /* common */
216   gboolean       go;                    /* TRUE as long as we're supposed to keep capturing */
217   int            err;                   /* if non-zero, error seen while capturing */
218   gint           packet_count;          /* Number of packets we have already captured */
219   gint           packet_max;            /* Number of packets we're supposed to capture - 0 means infinite */
220   gint           inpkts_to_sync_pipe;   /* Packets not already send out to the sync_pipe */
221 #ifdef SIGINFO
222   gboolean       report_packet_count;   /* Set by SIGINFO handler; print packet count */
223 #endif
224
225   /* pcap "input file" */
226   pcap_t        *pcap_h;                /* pcap handle */
227   gboolean       pcap_err;              /* TRUE if error from pcap */
228 #ifdef MUST_DO_SELECT
229   int            pcap_fd;               /* pcap file descriptor */
230 #endif
231
232   /* capture pipe (unix only "input file") */
233   gboolean       from_cap_pipe;         /* TRUE if we are capturing data from a capture pipe */
234   struct pcap_hdr cap_pipe_hdr;         /* Pcap header when capturing from a pipe */
235   struct pcaprec_modified_hdr cap_pipe_rechdr;  /* Pcap record header when capturing from a pipe */
236 #ifdef _WIN32
237   HANDLE         cap_pipe_h;            /* The handle of the capture pipe */
238 #else
239   int            cap_pipe_fd;           /* the file descriptor of the capture pipe */
240 #endif
241   gboolean       cap_pipe_modified;     /* TRUE if data in the pipe uses modified pcap headers */
242   gboolean       cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
243 #ifdef USE_THREADS
244   char *         cap_pipe_buf;          /* Pointer to the data buffer we read into */
245 #endif /* USE_THREADS */
246   int   cap_pipe_bytes_to_read;/* Used by cap_pipe_dispatch */
247   int   cap_pipe_bytes_read;   /* Used by cap_pipe_dispatch */
248   enum {
249          STATE_EXPECT_REC_HDR,
250          STATE_READ_REC_HDR,
251          STATE_EXPECT_DATA,
252          STATE_READ_DATA
253        } cap_pipe_state;
254   enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
255
256   /* output file(s) */
257   FILE          *pdh;
258   int            save_file_fd;
259   int            linktype;
260   int            file_snaplen;
261   gint           wtap_linktype;
262   long           bytes_written;
263   guint32        autostop_files;
264 } loop_data;
265
266 /*
267  * Standard secondary message for unexpected errors.
268  */
269 static const char please_report[] =
270     "Please report this to the Wireshark developers.\n"
271     "(This is not a crash; please do not report it as such.)";
272
273 /*
274  * This needs to be static, so that the SIGINT handler can clear the "go"
275  * flag.
276  */
277 static loop_data   global_ld;
278
279
280 /*
281  * Timeout, in milliseconds, for reads from the stream of captured packets.
282  *
283  * A bug in Mac OS X 10.6 and 10.6.1 causes calls to pcap_open_live(), in
284  * 64-bit applications, with sub-second timeouts not to work.  The bug is
285  * fixed in 10.6.2.
286  */
287 #if defined(__APPLE__) && defined(__LP64__)
288 static gboolean need_timeout_workaround;
289
290 #define CAP_READ_TIMEOUT        (need_timeout_workaround ? 1000 : 250)
291 #else
292 #define CAP_READ_TIMEOUT        250
293 #endif
294
295 /*
296  * Timeout, in microseconds, for threaded reads from a pipe.
297  */
298 #define THREAD_READ_TIMEOUT   100
299 static const char *cap_pipe_err_str;
300
301 static void
302 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
303                     const char *message, gpointer user_data _U_);
304
305 /* capture related options */
306 static capture_options global_capture_opts;
307 static gboolean quiet;
308
309 static void capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
310   const u_char *pd);
311 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
312                           int err, gboolean is_close);
313
314 static void exit_main(int err) G_GNUC_NORETURN;
315
316 static void report_new_capture_file(const char *filename);
317 static void report_packet_count(int packet_count);
318 static void report_packet_drops(guint32 drops);
319 static void report_capture_error(const char *error_msg, const char *secondary_error_msg);
320 static void report_cfilter_error(const char *cfilter, const char *errmsg);
321
322 #define MSG_MAX_LENGTH 4096
323
324 static void
325 print_usage(gboolean print_ver) {
326
327   FILE *output;
328
329
330   if (print_ver) {
331     output = stdout;
332     fprintf(output,
333         "Dumpcap " VERSION "%s\n"
334         "Capture network packets and dump them into a libpcap file.\n"
335         "See http://www.wireshark.org for more information.\n",
336         wireshark_svnversion);
337   } else {
338     output = stderr;
339   }
340   fprintf(output, "\nUsage: dumpcap [options] ...\n");
341   fprintf(output, "\n");
342   fprintf(output, "Capture interface:\n");
343   fprintf(output, "  -i <interface>           name or idx of interface (def: first non-loopback)\n");
344   fprintf(output, "  -f <capture filter>      packet filter in libpcap filter syntax\n");
345   fprintf(output, "  -s <snaplen>             packet snapshot length (def: 65535)\n");
346   fprintf(output, "  -p                       don't capture in promiscuous mode\n");
347 #ifdef HAVE_PCAP_CREATE
348   fprintf(output, "  -I                       capture in monitor mode, if available\n");
349 #endif
350 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
351   fprintf(output, "  -B <buffer size>         size of kernel buffer (def: 1MB)\n");
352 #endif
353   fprintf(output, "  -y <link type>           link layer type (def: first appropriate)\n");
354   fprintf(output, "  -D                       print list of interfaces and exit\n");
355   fprintf(output, "  -L                       print list of link-layer types of iface and exit\n");
356 #ifdef HAVE_BPF_IMAGE
357   fprintf(output, "  -d                       print generated BPF code for capture filter\n");
358 #endif
359   fprintf(output, "  -S                       print statistics for each interface once every second\n");
360   fprintf(output, "  -M                       for -D, -L, and -S, produce machine-readable output\n");
361   fprintf(output, "\n");
362 #ifdef HAVE_PCAP_REMOTE
363   fprintf(output, "\nRPCAP options:\n");
364   fprintf(output, "  -r                       don't ignore own RPCAP traffic in capture\n");
365   fprintf(output, "  -u                       use UDP for RPCAP data transfer\n");
366   fprintf(output, "  -A <user>:<password>     use RPCAP password authentication\n");
367 #ifdef HAVE_PCAP_SETSAMPLING
368   fprintf(output, "  -m <sampling type>       use packet sampling\n");
369   fprintf(output, "                           count:NUM - capture one packet of every NUM\n");
370   fprintf(output, "                           timer:NUM - capture no more than 1 packet in NUM ms\n");
371 #endif
372 #endif
373   fprintf(output, "Stop conditions:\n");
374   fprintf(output, "  -c <packet count>        stop after n packets (def: infinite)\n");
375   fprintf(output, "  -a <autostop cond.> ...  duration:NUM - stop after NUM seconds\n");
376   fprintf(output, "                           filesize:NUM - stop this file after NUM KB\n");
377   fprintf(output, "                              files:NUM - stop after NUM files\n");
378   /*fprintf(output, "\n");*/
379   fprintf(output, "Output (files):\n");
380   fprintf(output, "  -w <filename>            name of file to save (def: tempfile)\n");
381   fprintf(output, "  -b <ringbuffer opt.> ... duration:NUM - switch to next file after NUM secs\n");
382   fprintf(output, "                           filesize:NUM - switch to next file after NUM KB\n");
383   fprintf(output, "                              files:NUM - ringbuffer: replace after NUM files\n");
384   fprintf(output, "  -n                       use pcapng format instead of pcap\n");
385   /*fprintf(output, "\n");*/
386   fprintf(output, "Miscellaneous:\n");
387   fprintf(output, "  -q                       don't report packet capture counts\n");
388   fprintf(output, "  -v                       print version information and exit\n");
389   fprintf(output, "  -h                       display this help and exit\n");
390   fprintf(output, "\n");
391   fprintf(output, "Example: dumpcap -i eth0 -a duration:60 -w output.pcap\n");
392   fprintf(output, "\"Capture network packets from interface eth0 until 60s passed into output.pcap\"\n");
393   fprintf(output, "\n");
394   fprintf(output, "Use Ctrl-C to stop capturing at any time.\n");
395 }
396
397 static void
398 show_version(GString *comp_info_str, GString *runtime_info_str)
399 {
400
401   printf(
402         "Dumpcap " VERSION "%s\n"
403         "\n"
404         "%s\n"
405         "%s\n"
406         "%s\n"
407         "See http://www.wireshark.org for more information.\n",
408         wireshark_svnversion, get_copyright_info() ,comp_info_str->str, runtime_info_str->str);
409 }
410
411 /*
412  * Print to the standard error.  This is a command-line tool, so there's
413  * no need to pop up a console.
414  */
415 void
416 vfprintf_stderr(const char *fmt, va_list ap)
417 {
418   vfprintf(stderr, fmt, ap);
419 }
420
421 void
422 fprintf_stderr(const char *fmt, ...)
423 {
424   va_list ap;
425
426   va_start(ap, fmt);
427   vfprintf_stderr(fmt, ap);
428   va_end(ap);
429 }
430
431 /*
432  * Report an error in command-line arguments.
433  */
434 void
435 cmdarg_err(const char *fmt, ...)
436 {
437   va_list ap;
438
439   if(capture_child) {
440     gchar *msg;
441     /* Generate a 'special format' message back to parent */
442     va_start(ap, fmt);
443     msg = g_strdup_vprintf(fmt, ap);
444     sync_pipe_errmsg_to_parent(2, msg, "");
445     g_free(msg);
446     va_end(ap);
447   } else {
448     va_start(ap, fmt);
449     fprintf(stderr, "dumpcap: ");
450     vfprintf(stderr, fmt, ap);
451     fprintf(stderr, "\n");
452     va_end(ap);
453   }
454 }
455
456 /*
457  * Report additional information for an error in command-line arguments.
458  */
459 void
460 cmdarg_err_cont(const char *fmt, ...)
461 {
462   va_list ap;
463
464   if(capture_child) {
465     gchar *msg;
466     va_start(ap, fmt);
467     msg = g_strdup_vprintf(fmt, ap);
468     sync_pipe_errmsg_to_parent(2, msg, "");
469     g_free(msg);
470     va_end(ap);
471   } else {
472     va_start(ap, fmt);
473     vfprintf(stderr, fmt, ap);
474     fprintf(stderr, "\n");
475     va_end(ap);
476   }
477 }
478
479 #ifdef HAVE_LIBCAP
480 static void
481 #if 0 /* Set to enable capability debugging */
482 /* see 'man cap_to_text()' for explanation of output                         */
483 /* '='   means 'all= '  ie: no capabilities                                  */
484 /* '=ip' means 'all=ip' ie: all capabilities are permissible and inheritable */
485 /* ....                                                                      */
486 print_caps(const char *pfx) {
487     cap_t caps = cap_get_proc();
488     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
489           "%s: EUID: %d  Capabilities: %s", pfx,
490           geteuid(), cap_to_text(caps, NULL));
491     cap_free(caps);
492 #else
493 print_caps(const char *pfx _U_) {
494 #endif
495 }
496
497 static void
498 relinquish_all_capabilities(void)
499 {
500     /* Drop any and all capabilities this process may have.            */
501     /* Allowed whether or not process has any privileges.              */
502     cap_t caps = cap_init();    /* all capabilities initialized to off */
503     print_caps("Pre-clear");
504     if (cap_set_proc(caps)) {
505         cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
506     }
507     print_caps("Post-clear");
508     cap_free(caps);
509 }
510 #endif
511
512 static pcap_t *
513 open_capture_device(capture_options *capture_opts,
514                     char (*open_err_str)[PCAP_ERRBUF_SIZE])
515 {
516   pcap_t *pcap_h;
517 #ifdef HAVE_PCAP_CREATE
518   int         err;
519 #endif
520 #ifdef HAVE_PCAP_REMOTE
521   struct pcap_rmtauth auth;
522 #endif
523
524   /* Open the network interface to capture from it.
525      Some versions of libpcap may put warnings into the error buffer
526      if they succeed; to tell if that's happened, we have to clear
527      the error buffer, and check if it's still a null string.  */
528   (*open_err_str)[0] = '\0';
529 #ifdef HAVE_PCAP_OPEN
530   /*
531    * If we're opening a remote device, use pcap_open(); that's currently
532    * the only open routine that supports remote devices.
533    */
534   if (strncmp (capture_opts->iface, "rpcap://", 8) == 0) {
535     auth.type = capture_opts->auth_type == CAPTURE_AUTH_PWD ?
536       RPCAP_RMTAUTH_PWD : RPCAP_RMTAUTH_NULL;
537     auth.username = capture_opts->auth_username;
538     auth.password = capture_opts->auth_password;
539
540     pcap_h = pcap_open(capture_opts->iface,
541                        capture_opts->has_snaplen ? capture_opts->snaplen :
542                                                    WTAP_MAX_PACKET_SIZE,
543                        /* flags */
544                        (capture_opts->promisc_mode ? PCAP_OPENFLAG_PROMISCUOUS : 0) |
545                        (capture_opts->datatx_udp ? PCAP_OPENFLAG_DATATX_UDP : 0) |
546                        (capture_opts->nocap_rpcap ? PCAP_OPENFLAG_NOCAPTURE_RPCAP : 0),
547                        CAP_READ_TIMEOUT, &auth, *open_err_str);
548   } else
549 #endif /* HAVE_PCAP_OPEN */
550   {
551     /*
552      * If we're not opening a remote device, use pcap_create() and
553      * pcap_activate() if we have them, so that we can set the buffer
554      * size, otherwise use pcap_open_live().
555      */
556 #ifdef HAVE_PCAP_CREATE
557     pcap_h = pcap_create(capture_opts->iface, *open_err_str);
558     if (pcap_h != NULL) {
559       pcap_set_snaplen(pcap_h, capture_opts->has_snaplen ? capture_opts->snaplen : WTAP_MAX_PACKET_SIZE);
560       pcap_set_promisc(pcap_h, capture_opts->promisc_mode);
561       pcap_set_timeout(pcap_h, CAP_READ_TIMEOUT);
562
563       if (capture_opts->buffer_size > 1) {
564         pcap_set_buffer_size(pcap_h, capture_opts->buffer_size * 1024 * 1024);
565       }
566       if (capture_opts->monitor_mode)
567         pcap_set_rfmon(pcap_h, 1);
568       err = pcap_activate(pcap_h);
569       if (err < 0) {
570         /* Failed to activate, set to NULL */
571         if (err == PCAP_ERROR)
572           g_strlcpy(*open_err_str, pcap_geterr(pcap_h), sizeof *open_err_str);
573         else
574           g_strlcpy(*open_err_str, pcap_statustostr(err), sizeof *open_err_str);
575         pcap_close(pcap_h);
576         pcap_h = NULL;
577       }
578     }
579 #else
580     pcap_h = pcap_open_live(capture_opts->iface,
581                             capture_opts->has_snaplen ? capture_opts->snaplen :
582                                                         WTAP_MAX_PACKET_SIZE,
583                             capture_opts->promisc_mode, CAP_READ_TIMEOUT,
584                             *open_err_str);
585 #endif
586   }
587
588   /* If not using libcap: we now can now set euid/egid to ruid/rgid         */
589   /*  to remove any suid privileges.                                        */
590   /* If using libcap: we can now remove NET_RAW and NET_ADMIN capabilities  */
591   /*  (euid/egid have already previously been set to ruid/rgid.             */
592   /* (See comment in main() for details)                                    */
593 #ifndef HAVE_LIBCAP
594   relinquish_special_privs_perm();
595 #else
596   relinquish_all_capabilities();
597 #endif
598
599   return pcap_h;
600 }
601
602 static void
603 get_capture_device_open_failure_messages(const char *open_err_str,
604                                          const char *iface
605 #ifndef _WIN32
606                                                            _U_
607 #endif
608                                          ,
609                                          char *errmsg, size_t errmsg_len,
610                                          char *secondary_errmsg,
611                                          size_t secondary_errmsg_len)
612 {
613   const char *libpcap_warn;
614   static const char ppamsg[] = "can't find PPA for ";
615
616   /* If we got a "can't find PPA for X" message, warn the user (who
617      is running dumcap on HP-UX) that they don't have a version of
618      libpcap that properly handles HP-UX (libpcap 0.6.x and later
619      versions, which properly handle HP-UX, say "can't find /dev/dlpi
620      PPA for X" rather than "can't find PPA for X"). */
621   if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
622     libpcap_warn =
623       "\n\n"
624       "You are running (T)Wireshark with a version of the libpcap library\n"
625       "that doesn't handle HP-UX network devices well; this means that\n"
626       "(T)Wireshark may not be able to capture packets.\n"
627       "\n"
628       "To fix this, you should install libpcap 0.6.2, or a later version\n"
629       "of libpcap, rather than libpcap 0.4 or 0.5.x.  It is available in\n"
630       "packaged binary form from the Software Porting And Archive Centre\n"
631       "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
632       "at the URL lists a number of mirror sites.";
633   else
634     libpcap_warn = "";
635   g_snprintf(errmsg, (gulong) errmsg_len,
636              "The capture session could not be initiated (%s).", open_err_str);
637 #ifndef _WIN32
638   g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
639 "Please check to make sure you have sufficient permissions, and that you have "
640 "the proper interface or pipe specified.%s", libpcap_warn);
641 #else
642   g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len,
643 "\n"
644 "Please check that \"%s\" is the proper interface.\n"
645 "\n"
646 "\n"
647 "Help can be found at:\n"
648 "\n"
649 "       http://wiki.wireshark.org/WinPcap\n"
650 "       http://wiki.wireshark.org/CaptureSetup\n",
651              iface);
652 #endif /* _WIN32 */
653 }
654
655 /* Set the data link type on a pcap. */
656 static gboolean
657 set_pcap_linktype(pcap_t *pcap_h, capture_options *capture_opts,
658                   char *errmsg, size_t errmsg_len,
659                   char *secondary_errmsg, size_t secondary_errmsg_len)
660 {
661   char *set_linktype_err_str;
662
663   if (capture_opts->linktype == -1)
664     return TRUE; /* just use the default */ 
665 #ifdef HAVE_PCAP_SET_DATALINK
666   if (pcap_set_datalink(pcap_h, capture_opts->linktype) == 0)
667     return TRUE; /* no error */
668   set_linktype_err_str = pcap_geterr(pcap_h);
669 #else
670   /* Let them set it to the type it is; reject any other request. */
671   if (get_pcap_linktype(pcap_h, capture_opts->iface) == capture_opts->linktype)
672     return TRUE; /* no error */
673   set_linktype_err_str =
674     "That DLT isn't one of the DLTs supported by this device";
675 #endif
676   g_snprintf(errmsg, (gulong) errmsg_len, "Unable to set data link type (%s).",
677              set_linktype_err_str);
678   /*
679    * If the error isn't "XXX is not one of the DLTs supported by this device",
680    * tell the user to tell the Wireshark developers about it.
681    */
682   if (strstr(set_linktype_err_str, "is not one of the DLTs supported by this device") == NULL)
683     g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
684   else
685     secondary_errmsg[0] = '\0';
686   return FALSE;
687 }
688
689 static gboolean
690 compile_capture_filter(const char *iface, pcap_t *pcap_h,
691                        struct bpf_program *fcode, char *cfilter)
692 {
693   bpf_u_int32 netnum, netmask;
694   gchar       lookup_net_err_str[PCAP_ERRBUF_SIZE];
695
696   if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
697     /*
698      * Well, we can't get the netmask for this interface; it's used
699      * only for filters that check for broadcast IP addresses, so
700      * we just punt and use 0.  It might be nice to warn the user,
701      * but that's a pain in a GUI application, as it'd involve popping
702      * up a message box, and it's not clear how often this would make
703      * a difference (only filters that check for IP broadcast addresses
704      * use the netmask).
705      */
706     /*cmdarg_err(
707       "Warning:  Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
708     netmask = 0;
709   }
710   if (pcap_compile(pcap_h, fcode, cfilter, 1, netmask) < 0)
711     return FALSE;
712   return TRUE;
713 }
714
715 #ifdef HAVE_BPF_IMAGE
716 static gboolean
717 show_filter_code(capture_options *capture_opts)
718 {
719   pcap_t *pcap_h;
720   gchar open_err_str[PCAP_ERRBUF_SIZE];
721   char errmsg[MSG_MAX_LENGTH+1];
722   char secondary_errmsg[MSG_MAX_LENGTH+1];
723   struct bpf_program fcode;
724   struct bpf_insn *insn;
725   u_int i;
726
727   pcap_h = open_capture_device(capture_opts, &open_err_str);
728   if (pcap_h == NULL) {
729     /* Open failed; get messages */
730     get_capture_device_open_failure_messages(open_err_str,
731                                              capture_opts->iface,
732                                              errmsg, sizeof errmsg,
733                                              secondary_errmsg,
734                                              sizeof secondary_errmsg);
735     /* And report them */
736     report_capture_error(errmsg, secondary_errmsg);
737     return FALSE;
738   }
739
740   /* Set the link-layer type. */
741   if (!set_pcap_linktype(pcap_h, capture_opts, errmsg, sizeof errmsg,
742                          secondary_errmsg, sizeof secondary_errmsg)) {
743     pcap_close(pcap_h);
744     report_capture_error(errmsg, secondary_errmsg);
745     return FALSE;
746   }
747
748   /* OK, try to compile the capture filter. */
749   if (!compile_capture_filter(capture_opts->iface, pcap_h, &fcode,
750                               capture_opts->cfilter)) {
751     pcap_close(pcap_h);
752     report_cfilter_error(capture_opts->cfilter, errmsg);
753     return FALSE;
754   }
755   pcap_close(pcap_h);
756
757   if (capture_child) {
758     /* Let our parent know we succeeded. */
759     pipe_write_block(2, SP_SUCCESS, NULL);
760  }
761
762   /* Now print the filter code. */
763   insn = fcode.bf_insns;
764
765   for (i = 0; i < fcode.bf_len; insn++, i++)
766     printf("%s\n", bpf_image(insn, i));
767   return TRUE;
768 }
769 #endif
770
771 /*
772  * capture_interface_list() is expected to do the right thing to get
773  * a list of interfaces.
774  *
775  * In most of the programs in the Wireshark suite, "the right thing"
776  * is to run dumpcap and ask it for the list, because dumpcap may
777  * be the only program in the suite with enough privileges to get
778  * the list.
779  *
780  * In dumpcap itself, however, we obviously can't run dumpcap to
781  * ask for the list.  Therefore, our capture_interface_list() should
782  * just call get_interface_list().
783  */
784 GList *
785 capture_interface_list(int *err, char **err_str)
786 {
787   return get_interface_list(err, err_str);
788 }
789
790 /*
791  * Get the data-link type for a libpcap device.
792  * This works around AIX 5.x's non-standard and incompatible-with-the-
793  * rest-of-the-universe libpcap.
794  */
795 static int
796 get_pcap_linktype(pcap_t *pch, const char *devname
797 #ifndef _AIX
798         _U_
799 #endif
800 )
801 {
802   int linktype;
803 #ifdef _AIX
804   const char *ifacename;
805 #endif
806
807   linktype = pcap_datalink(pch);
808 #ifdef _AIX
809
810   /*
811    * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
812    * rather than DLT_ values for link-layer types; the ifType values
813    * for LAN devices are:
814    *
815    *    Ethernet        6
816    *    802.3           7
817    *    Token Ring      9
818    *    FDDI            15
819    *
820    * and the ifType value for a loopback device is 24.
821    *
822    * The AIX names for LAN devices begin with:
823    *
824    *    Ethernet                en
825    *    802.3                   et
826    *    Token Ring              tr
827    *    FDDI                    fi
828    *
829    * and the AIX names for loopback devices begin with "lo".
830    *
831    * (The difference between "Ethernet" and "802.3" is presumably
832    * whether packets have an Ethernet header, with a packet type,
833    * or an 802.3 header, with a packet length, followed by an 802.2
834    * header and possibly a SNAP header.)
835    *
836    * If the device name matches "linktype" interpreted as an ifType
837    * value, rather than as a DLT_ value, we will assume this is AIX's
838    * non-standard, incompatible libpcap, rather than a standard libpcap,
839    * and will map the link-layer type to the standard DLT_ value for
840    * that link-layer type, as that's what the rest of Wireshark expects.
841    *
842    * (This means the capture files won't be readable by a tcpdump
843    * linked with AIX's non-standard libpcap, but so it goes.  They
844    * *will* be readable by standard versions of tcpdump, Wireshark,
845    * and so on.)
846    *
847    * XXX - if we conclude we're using AIX libpcap, should we also
848    * set a flag to cause us to assume the time stamps are in
849    * seconds-and-nanoseconds form, and to convert them to
850    * seconds-and-microseconds form before processing them and
851    * writing them out?
852    */
853
854   /*
855    * Find the last component of the device name, which is the
856    * interface name.
857    */
858   ifacename = strchr(devname, '/');
859   if (ifacename == NULL)
860     ifacename = devname;
861
862   /* See if it matches any of the LAN device names. */
863   if (strncmp(ifacename, "en", 2) == 0) {
864     if (linktype == 6) {
865       /*
866        * That's the RFC 1573 value for Ethernet; map it to DLT_EN10MB.
867        */
868       linktype = 1;
869     }
870   } else if (strncmp(ifacename, "et", 2) == 0) {
871     if (linktype == 7) {
872       /*
873        * That's the RFC 1573 value for 802.3; map it to DLT_EN10MB.
874        * (libpcap, tcpdump, Wireshark, etc. don't care if it's Ethernet
875        * or 802.3.)
876        */
877       linktype = 1;
878     }
879   } else if (strncmp(ifacename, "tr", 2) == 0) {
880     if (linktype == 9) {
881       /*
882        * That's the RFC 1573 value for 802.5 (Token Ring); map it to
883        * DLT_IEEE802, which is what's used for Token Ring.
884        */
885       linktype = 6;
886     }
887   } else if (strncmp(ifacename, "fi", 2) == 0) {
888     if (linktype == 15) {
889       /*
890        * That's the RFC 1573 value for FDDI; map it to DLT_FDDI.
891        */
892       linktype = 10;
893     }
894   } else if (strncmp(ifacename, "lo", 2) == 0) {
895     if (linktype == 24) {
896       /*
897        * That's the RFC 1573 value for "software loopback" devices; map it
898        * to DLT_NULL, which is what's used for loopback devices on BSD.
899        */
900       linktype = 0;
901     }
902   }
903 #endif
904
905   return linktype;
906 }
907
908 static data_link_info_t *
909 create_data_link_info(int dlt)
910 {
911   data_link_info_t *data_link_info;
912   const char *text;
913
914   data_link_info = (data_link_info_t *)g_malloc(sizeof (data_link_info_t));
915   data_link_info->dlt = dlt;
916   text = pcap_datalink_val_to_name(dlt);
917   if (text != NULL)
918     data_link_info->name = g_strdup(text);
919   else
920     data_link_info->name = g_strdup_printf("DLT %d", dlt);
921   text = pcap_datalink_val_to_description(dlt);
922   if (text != NULL)
923     data_link_info->description = g_strdup(text);
924   else
925     data_link_info->description = NULL;
926   return data_link_info;
927 }
928
929 /*
930  * Get the capabilities of a network device.
931  */
932 static if_capabilities_t *
933 get_if_capabilities(const char *devname, gboolean monitor_mode
934 #ifndef HAVE_PCAP_CREATE
935         _U_
936 #endif
937 , char **err_str)
938 {
939     if_capabilities_t *caps;
940     char errbuf[PCAP_ERRBUF_SIZE];
941     pcap_t *pch;
942 #ifdef HAVE_PCAP_CREATE
943     int status;
944 #endif
945     int deflt;
946 #ifdef HAVE_PCAP_LIST_DATALINKS
947     int *linktypes;
948     int i, nlt;
949 #endif
950     data_link_info_t *data_link_info;
951
952     /*
953      * Allocate the interface capabilities structure.
954      */
955     caps = g_malloc(sizeof *caps);
956
957 #ifdef HAVE_PCAP_OPEN
958     pch = pcap_open(devname, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
959     caps->can_set_rfmon = FALSE;
960     if (pch == NULL) {
961         if (err_str != NULL)
962             *err_str = g_strdup(errbuf);
963         g_free(caps);
964         return NULL;
965     }
966 #elif defined(HAVE_PCAP_CREATE)
967     pch = pcap_create(devname, errbuf);
968     if (pch == NULL) {
969         if (err_str != NULL)
970             *err_str = g_strdup(errbuf);
971         g_free(caps);
972         return NULL;
973     }
974     status = pcap_can_set_rfmon(pch);
975     if (status < 0) {
976         /* Error. */
977         if (status == PCAP_ERROR)
978             *err_str = g_strdup_printf("pcap_can_set_rfmon() failed: %s",
979                                        pcap_geterr(pch));
980         else
981             *err_str = g_strdup(pcap_statustostr(status));
982         pcap_close(pch);
983         g_free(caps);
984         return NULL;
985     }
986     if (status == 0)
987         caps->can_set_rfmon = FALSE;
988     else if (status == 1) {
989         caps->can_set_rfmon = TRUE;
990         if (monitor_mode)
991             pcap_set_rfmon(pch, 1);
992     } else {
993         if (err_str != NULL) {
994             *err_str = g_strdup_printf("pcap_can_set_rfmon() returned %d",
995                                        status);
996         }
997         pcap_close(pch);
998         g_free(caps);
999         return NULL;
1000     }
1001
1002     status = pcap_activate(pch);
1003     if (status < 0) {
1004         /* Error.  We ignore warnings (status > 0). */
1005         if (err_str != NULL) {
1006             if (status == PCAP_ERROR)
1007                 *err_str = g_strdup_printf("pcap_activate() failed: %s",
1008                                            pcap_geterr(pch));
1009             else
1010                 *err_str = g_strdup(pcap_statustostr(status));
1011         }
1012         pcap_close(pch);
1013         g_free(caps);
1014         return NULL;
1015     }
1016 #else
1017     pch = pcap_open_live(devname, MIN_PACKET_SIZE, 0, 0, errbuf);
1018     caps->can_set_rfmon = FALSE;
1019     if (pch == NULL) {
1020         if (err_str != NULL)
1021             *err_str = g_strdup(errbuf);
1022         g_free(caps);
1023         return NULL;
1024     }
1025 #endif
1026     deflt = get_pcap_linktype(pch, devname);
1027 #ifdef HAVE_PCAP_LIST_DATALINKS
1028     nlt = pcap_list_datalinks(pch, &linktypes);
1029     if (nlt == 0 || linktypes == NULL) {
1030         pcap_close(pch);
1031         if (err_str != NULL)
1032             *err_str = NULL; /* an empty list doesn't mean an error */
1033         return NULL;
1034     }
1035     caps->data_link_types = NULL;
1036     for (i = 0; i < nlt; i++) {
1037         data_link_info = create_data_link_info(linktypes[i]);
1038
1039         /*
1040          * XXX - for 802.11, make the most detailed 802.11
1041          * version the default, rather than the one the
1042          * device has as the default?
1043          */
1044         if (linktypes[i] == deflt)
1045             caps->data_link_types = g_list_prepend(caps->data_link_types,
1046                                                    data_link_info);
1047         else
1048             caps->data_link_types = g_list_append(caps->data_link_types,
1049                                                   data_link_info);
1050     }
1051 #ifdef HAVE_PCAP_FREE_DATALINKS
1052     pcap_free_datalinks(linktypes);
1053 #else
1054     /*
1055      * In Windows, there's no guarantee that if you have a library
1056      * built with one version of the MSVC++ run-time library, and
1057      * it returns a pointer to allocated data, you can free that
1058      * data from a program linked with another version of the
1059      * MSVC++ run-time library.
1060      *
1061      * This is not an issue on UN*X.
1062      *
1063      * See the mail threads starting at
1064      *
1065      *    http://www.winpcap.org/pipermail/winpcap-users/2006-September/001421.html
1066      *
1067      * and
1068      *
1069      *    http://www.winpcap.org/pipermail/winpcap-users/2008-May/002498.html
1070      */
1071 #ifndef _WIN32
1072 #define xx_free free  /* hack so checkAPIs doesn't complain */
1073     xx_free(linktypes);
1074 #endif /* _WIN32 */
1075 #endif /* HAVE_PCAP_FREE_DATALINKS */
1076 #else /* HAVE_PCAP_LIST_DATALINKS */
1077
1078     data_link_info = create_data_link_info(deflt);
1079     caps->data_link_types = g_list_append(caps->data_link_types,
1080                                           data_link_info);
1081 #endif /* HAVE_PCAP_LIST_DATALINKS */
1082
1083     pcap_close(pch);
1084
1085     if (err_str != NULL)
1086         *err_str = NULL;
1087     return caps;
1088 }
1089
1090 #define ADDRSTRLEN 46 /* Covers IPv4 & IPv6 */
1091 static void
1092 print_machine_readable_interfaces(GList *if_list)
1093 {
1094     int         i;
1095     GList       *if_entry;
1096     if_info_t   *if_info;
1097     GSList      *addr;
1098     if_addr_t   *if_addr;
1099     char        addr_str[ADDRSTRLEN];
1100
1101     if (capture_child) {
1102         /* Let our parent know we succeeded. */
1103         pipe_write_block(2, SP_SUCCESS, NULL);
1104     }
1105
1106     i = 1;  /* Interface id number */
1107     for (if_entry = g_list_first(if_list); if_entry != NULL;
1108          if_entry = g_list_next(if_entry)) {
1109         if_info = (if_info_t *)if_entry->data;
1110         printf("%d. %s", i++, if_info->name);
1111
1112         /*
1113          * Print the contents of the if_entry struct in a parseable format.
1114          * Each if_entry element is tab-separated.  Addresses are comma-
1115          * separated.
1116          */
1117         /* XXX - Make sure our description doesn't contain a tab */
1118         if (if_info->description != NULL)
1119             printf("\t%s\t", if_info->description);
1120         else
1121             printf("\t\t");
1122
1123         for(addr = g_slist_nth(if_info->addrs, 0); addr != NULL;
1124                     addr = g_slist_next(addr)) {
1125             if (addr != g_slist_nth(if_info->addrs, 0))
1126                 printf(",");
1127
1128             if_addr = (if_addr_t *)addr->data;
1129             switch(if_addr->ifat_type) {
1130             case IF_AT_IPv4:
1131                 if (inet_ntop(AF_INET, &if_addr->addr.ip4_addr, addr_str,
1132                               ADDRSTRLEN)) {
1133                     printf("%s", addr_str);
1134                 } else {
1135                     printf("<unknown IPv4>");
1136                 }
1137                 break;
1138             case IF_AT_IPv6:
1139                 if (inet_ntop(AF_INET6, &if_addr->addr.ip6_addr,
1140                               addr_str, ADDRSTRLEN)) {
1141                     printf("%s", addr_str);
1142                 } else {
1143                     printf("<unknown IPv6>");
1144                 }
1145                 break;
1146             default:
1147                 printf("<type unknown %u>", if_addr->ifat_type);
1148             }
1149         }
1150
1151         if (if_info->loopback)
1152             printf("\tloopback");
1153         else
1154             printf("\tnetwork");
1155
1156         printf("\n");
1157     }
1158 }
1159
1160 /*
1161  * If you change the machine-readable output format of this function,
1162  * you MUST update capture_ifinfo.c:capture_get_if_capabilities() accordingly!
1163  */
1164 static void
1165 print_machine_readable_if_capabilities(if_capabilities_t *caps)
1166 {
1167     GList *lt_entry;
1168     data_link_info_t *data_link_info;
1169     const gchar *desc_str;
1170
1171     if (capture_child) {
1172         /* Let our parent know we succeeded. */
1173         pipe_write_block(2, SP_SUCCESS, NULL);
1174     }
1175
1176     if (caps->can_set_rfmon)
1177         printf("1\n");
1178     else
1179         printf("0\n");
1180     for (lt_entry = caps->data_link_types; lt_entry != NULL;
1181          lt_entry = g_list_next(lt_entry)) {
1182       data_link_info = (data_link_info_t *)lt_entry->data;
1183       if (data_link_info->description != NULL)
1184         desc_str = data_link_info->description;
1185       else
1186         desc_str = "(not supported)";
1187       printf("%d\t%s\t%s\n", data_link_info->dlt, data_link_info->name,
1188              desc_str);
1189     }
1190 }
1191
1192 typedef struct {
1193     char *name;
1194     pcap_t *pch;
1195 } if_stat_t;
1196
1197 /* Print the number of packets captured for each interface until we're killed. */
1198 static int
1199 print_statistics_loop(gboolean machine_readable)
1200 {
1201     GList       *if_list, *if_entry, *stat_list = NULL, *stat_entry;
1202     if_info_t   *if_info;
1203     if_stat_t   *if_stat;
1204     int         err;
1205     gchar       *err_str;
1206     pcap_t      *pch;
1207     char        errbuf[PCAP_ERRBUF_SIZE];
1208     struct pcap_stat ps;
1209
1210     if_list = get_interface_list(&err, &err_str);
1211     if (if_list == NULL) {
1212         switch (err) {
1213         case CANT_GET_INTERFACE_LIST:
1214             cmdarg_err("%s", err_str);
1215             g_free(err_str);
1216             break;
1217
1218         case NO_INTERFACES_FOUND:
1219             cmdarg_err("There are no interfaces on which a capture can be done");
1220             break;
1221         }
1222         return err;
1223     }
1224
1225     for (if_entry = g_list_first(if_list); if_entry != NULL; if_entry = g_list_next(if_entry)) {
1226         if_info = (if_info_t *)if_entry->data;
1227 #ifdef HAVE_PCAP_OPEN
1228         pch = pcap_open(if_info->name, MIN_PACKET_SIZE, 0, 0, NULL, errbuf);
1229 #else
1230         pch = pcap_open_live(if_info->name, MIN_PACKET_SIZE, 0, 0, errbuf);
1231 #endif
1232
1233         if (pch) {
1234             if_stat = (if_stat_t *)g_malloc(sizeof(if_stat_t));
1235             if_stat->name = g_strdup(if_info->name);
1236             if_stat->pch = pch;
1237             stat_list = g_list_append(stat_list, if_stat);
1238         }
1239     }
1240
1241     if (!stat_list) {
1242         cmdarg_err("There are no interfaces on which a capture can be done");
1243         return 2;
1244     }
1245
1246     if (capture_child) {
1247         /* Let our parent know we succeeded. */
1248         pipe_write_block(2, SP_SUCCESS, NULL);
1249     }
1250
1251     if (!machine_readable) {
1252         printf("%-15s  %10s  %10s\n", "Interface", "Received",
1253             "Dropped");
1254     }
1255
1256     global_ld.go = TRUE;
1257     while (global_ld.go) {
1258         for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1259             if_stat = (if_stat_t *)stat_entry->data;
1260             pcap_stats(if_stat->pch, &ps);
1261
1262             if (!machine_readable) {
1263                 printf("%-15s  %10u  %10u\n", if_stat->name,
1264                     ps.ps_recv, ps.ps_drop);
1265             } else {
1266                 printf("%s\t%u\t%u\n", if_stat->name,
1267                     ps.ps_recv, ps.ps_drop);
1268                 fflush(stdout);
1269             }
1270         }
1271 #ifdef _WIN32
1272         if (! global_ld.from_cap_pipe)
1273             Sleep(1 * 1000);
1274 #else
1275         sleep(1);
1276 #endif
1277     }
1278
1279     /* XXX - Not reached.  Should we look for 'q' in stdin? */
1280     for (stat_entry = g_list_first(stat_list); stat_entry != NULL; stat_entry = g_list_next(stat_entry)) {
1281         if_stat = (if_stat_t *)stat_entry->data;
1282         pcap_close(if_stat->pch);
1283         g_free(if_stat->name);
1284         g_free(if_stat);
1285     }
1286     g_list_free(stat_list);
1287     free_interface_list(if_list);
1288
1289     return 0;
1290 }
1291
1292
1293 #ifdef _WIN32
1294 static BOOL WINAPI
1295 capture_cleanup_handler(DWORD dwCtrlType)
1296 {
1297     /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1298        Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1299        is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1300        like SIGTERM at least when the machine's shutting down.
1301
1302        For now, if we're running as a command rather than a capture child,
1303        we handle all but CTRL_LOGOFF_EVENT as indications that we should
1304        clean up and quit, just as we handle SIGINT, SIGHUP, and SIGTERM
1305        in that way on UN*X.
1306
1307        If we're not running as a capture child, we might be running as
1308        a service; ignore CTRL_LOGOFF_EVENT, so we keep running after the
1309        user logs out.  (XXX - can we explicitly check whether we're
1310        running as a service?) */
1311
1312     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
1313         "Console: Control signal");
1314     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
1315         "Console: Control signal, CtrlType: %u", dwCtrlType);
1316
1317     /* Keep capture running if we're a service and a user logs off */
1318     if (capture_child || (dwCtrlType != CTRL_LOGOFF_EVENT)) {
1319         capture_loop_stop();
1320         return TRUE;
1321     } else {
1322         return FALSE;
1323     }
1324 }
1325 #else
1326 static void
1327 capture_cleanup_handler(int signum _U_)
1328 {
1329     /* On UN*X, we cleanly shut down the capture on SIGINT, SIGHUP, and
1330        SIGTERM.  We assume that if the user wanted it to keep running
1331        after they logged out, they'd have nohupped it. */
1332
1333     /* Note: don't call g_log() in the signal handler: if we happened to be in
1334      * g_log() in process context when the signal came in, g_log will detect
1335      * the "recursion" and abort.
1336      */
1337
1338     capture_loop_stop();
1339 }
1340 #endif
1341
1342
1343 #ifdef SIGINFO
1344 static void
1345 report_counts(void)
1346 {
1347   /* Don't print this if we're a capture child. */
1348   if (!capture_child) {
1349     if (quiet) {
1350       /* Report the count only if we aren't printing a packet count
1351          as packets arrive. */
1352       fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
1353               plurality(global_ld.packet_count, "", "s"));
1354     }
1355   }
1356   infoprint = FALSE; /* we just reported it */
1357 }
1358
1359 static void
1360 report_counts_siginfo(int signum _U_)
1361 {
1362   int sav_errno = errno;
1363
1364   /* If we've been told to delay printing, just set a flag asking
1365      that we print counts (if we're supposed to), otherwise print
1366      the count of packets captured (if we're supposed to). */
1367   if (infodelay)
1368     infoprint = TRUE;
1369   else
1370     report_counts();
1371   errno = sav_errno;
1372 }
1373 #endif /* SIGINFO */
1374
1375 static void exit_main(int status)
1376 {
1377 #ifdef _WIN32
1378   /* Shutdown windows sockets */
1379   WSACleanup();
1380
1381   /* can be helpful for debugging */
1382 #ifdef DEBUG_DUMPCAP
1383   printf("Press any key\n");
1384   _getch();
1385 #endif
1386
1387 #endif /* _WIN32 */
1388
1389   exit(status);
1390 }
1391
1392 #ifdef HAVE_LIBCAP
1393 /*
1394  * If we were linked with libcap (not libpcap), make sure we have
1395  * CAP_NET_ADMIN and CAP_NET_RAW, then relinquish our permissions.
1396  * (See comment in main() for details)
1397  */
1398 static void
1399 relinquish_privs_except_capture(void)
1400 {
1401     /* If 'started_with_special_privs' (ie: suid) then enable for
1402      *  ourself the  NET_ADMIN and NET_RAW capabilities and then
1403      *  drop our suid privileges.
1404      *
1405      * CAP_NET_ADMIN: Promiscuous mode and a truckload of other
1406      *                stuff we don't need (and shouldn't have).
1407      * CAP_NET_RAW:   Packet capture (raw sockets).
1408      */
1409
1410     if (started_with_special_privs()) {
1411         cap_value_t cap_list[2] = { CAP_NET_ADMIN, CAP_NET_RAW };
1412         int cl_len = sizeof(cap_list) / sizeof(cap_value_t);
1413
1414         cap_t caps = cap_init();    /* all capabilities initialized to off */
1415
1416         print_caps("Pre drop, pre set");
1417
1418         if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) {
1419             cmdarg_err("prctl() fail return: %s", strerror(errno));
1420         }
1421
1422         cap_set_flag(caps, CAP_PERMITTED,   cl_len, cap_list, CAP_SET);
1423         cap_set_flag(caps, CAP_INHERITABLE, cl_len, cap_list, CAP_SET);
1424
1425         if (cap_set_proc(caps)) {
1426             cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
1427         }
1428         print_caps("Pre drop, post set");
1429
1430         relinquish_special_privs_perm();
1431
1432         print_caps("Post drop, pre set");
1433         cap_set_flag(caps, CAP_EFFECTIVE,   cl_len, cap_list, CAP_SET);
1434         if (cap_set_proc(caps)) {
1435             cmdarg_err("cap_set_proc() fail return: %s", strerror(errno));
1436         }
1437         print_caps("Post drop, post set");
1438
1439         cap_free(caps);
1440     }
1441 }
1442
1443 #endif /* HAVE_LIBCAP */
1444
1445 /* Take care of byte order in the libpcap headers read from pipes.
1446  * (function taken from wiretap/libpcap.c) */
1447 static void
1448 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1449 {
1450   if (byte_swapped) {
1451     /* Byte-swap the record header fields. */
1452     rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
1453     rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
1454     rechdr->incl_len = BSWAP32(rechdr->incl_len);
1455     rechdr->orig_len = BSWAP32(rechdr->orig_len);
1456   }
1457
1458   /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1459      swapped, in order to match the BPF header layout.
1460
1461      Unfortunately, some files were, according to a comment in the "libpcap"
1462      source, written with version 2.3 in their headers but without the
1463      interchanged fields, so if "incl_len" is greater than "orig_len" - which
1464      would make no sense - we assume that we need to swap them.  */
1465   if (hdr->version_major == 2 &&
1466       (hdr->version_minor < 3 ||
1467        (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1468     guint32 temp;
1469
1470     temp = rechdr->orig_len;
1471     rechdr->orig_len = rechdr->incl_len;
1472     rechdr->incl_len = temp;
1473   }
1474 }
1475
1476 #ifdef USE_THREADS
1477 /*
1478  * Thread function that reads from a pipe and pushes the data
1479  * to the main application thread.
1480  */
1481 /*
1482  * XXX Right now we use async queues for basic signaling. The main thread
1483  * sets cap_pipe_buf and cap_bytes_to_read, then pushes an item onto
1484  * cap_pipe_pending_q which triggers a read in the cap_pipe_read thread.
1485  * Iff the read is successful cap_pipe_read pushes an item onto
1486  * cap_pipe_done_q, otherwise an error is signaled. No data is passed in
1487  * the queues themselves (yet).
1488  *
1489  * We might want to move some of the cap_pipe_dispatch logic here so that
1490  * we can let cap_pipe_read run independently, queuing up multiple reads
1491  * for the main thread (and possibly get rid of cap_pipe_read_mtx).
1492  */
1493 static void *cap_pipe_read(void *ld_ptr) {
1494     loop_data *ld = (loop_data *)ld_ptr;
1495     int bytes_read;
1496 #ifdef _WIN32
1497     BOOL res;
1498     DWORD b, last_err;
1499 #else /* _WIN32 */
1500     int b;
1501 #endif /* _WIN32 */
1502
1503     while (ld->cap_pipe_err == PIPOK) {
1504         g_async_queue_pop(cap_pipe_pending_q); /* Wait for our cue (ahem) from the main thread */
1505         g_mutex_lock(cap_pipe_read_mtx);
1506         bytes_read = 0;
1507         while (bytes_read < (int) ld->cap_pipe_bytes_to_read) {
1508 #ifdef _WIN32
1509             /* If we try to use read() on a named pipe on Windows with partial
1510              * data it appears to return EOF.
1511              */
1512             res = ReadFile(ld->cap_pipe_h, ld->cap_pipe_buf+bytes_read,
1513                            ld->cap_pipe_bytes_to_read - bytes_read,
1514                            &b, NULL);
1515
1516             bytes_read += b;
1517             if (!res) {
1518                 last_err = GetLastError();
1519                 if (last_err == ERROR_MORE_DATA) {
1520                     continue;
1521                 } else if (last_err == ERROR_HANDLE_EOF || last_err == ERROR_BROKEN_PIPE || last_err == ERROR_PIPE_NOT_CONNECTED) {
1522                     ld->cap_pipe_err = PIPEOF;
1523                     bytes_read = 0;
1524                     break;
1525                 }
1526                 ld->cap_pipe_err = PIPERR;
1527                 bytes_read = -1;
1528                 break;
1529             } else if (b == 0 && ld->cap_pipe_bytes_to_read > 0) {
1530                 ld->cap_pipe_err = PIPEOF;
1531                 bytes_read = 0;
1532                 break;
1533             }
1534 #else /* _WIN32 */
1535             b = read(ld->cap_pipe_fd, ld->cap_pipe_buf+bytes_read,
1536                      ld->cap_pipe_bytes_to_read - bytes_read);
1537             if (b <= 0) {
1538                 if (b == 0) {
1539                     ld->cap_pipe_err = PIPEOF;
1540                     bytes_read = 0;
1541                     break;
1542                 } else {
1543                     ld->cap_pipe_err = PIPERR;
1544                     bytes_read = -1;
1545                     break;
1546                 }
1547             } else {
1548                 bytes_read += b;
1549             }
1550 #endif /*_WIN32 */
1551         }
1552         ld->cap_pipe_bytes_read = bytes_read;
1553         if (ld->cap_pipe_bytes_read >= ld->cap_pipe_bytes_to_read) {
1554             g_async_queue_push(cap_pipe_done_q, ld->cap_pipe_buf); /* Any non-NULL value will do */
1555         }
1556         g_mutex_unlock(cap_pipe_read_mtx);
1557     }
1558     return NULL;
1559 }
1560 #endif /* USE_THREADS */
1561
1562 /* Provide select() functionality for a single file descriptor
1563  * on UNIX/POSIX. Windows uses cap_pipe_read via a thread.
1564  *
1565  * Returns the same values as select.  If an error is returned,
1566  * the string cap_pipe_err_str should be used instead of errno.
1567  */
1568 static int
1569 cap_pipe_select(int pipe_fd) {
1570   fd_set      rfds;
1571   struct timeval timeout, *pto;
1572   int sel_ret;
1573
1574   cap_pipe_err_str = "Unknown error";
1575
1576   FD_ZERO(&rfds);
1577   FD_SET(pipe_fd, &rfds);
1578
1579   timeout.tv_sec = 0;
1580   timeout.tv_usec = CAP_READ_TIMEOUT * 1000;
1581   pto = &timeout;
1582
1583   sel_ret = select(pipe_fd+1, &rfds, NULL, NULL, pto);
1584   if (sel_ret < 0)
1585     cap_pipe_err_str = strerror(errno);
1586   return sel_ret;
1587 }
1588
1589
1590 /* Mimic pcap_open_live() for pipe captures
1591
1592  * We check if "pipename" is "-" (stdin), a AF_UNIX socket, or a FIFO,
1593  * open it, and read the header.
1594  *
1595  * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1596  * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1597 static void
1598 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
1599                    char *errmsg, int errmsgl)
1600 {
1601 #ifndef _WIN32
1602   struct stat pipe_stat;
1603   struct sockaddr_un sa;
1604   int          sel_ret;
1605   int          b;
1606   unsigned int bytes_read;
1607   int          fd;
1608 #else /* _WIN32 */
1609 #if 1
1610   char *pncopy, *pos;
1611   wchar_t *err_str;
1612 #endif
1613 #endif
1614   guint32       magic = 0;
1615
1616 #ifndef _WIN32
1617   ld->cap_pipe_fd = -1;
1618 #else
1619   ld->cap_pipe_h = INVALID_HANDLE_VALUE;
1620 #endif
1621   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
1622
1623   /*
1624    * XXX - this blocks until a pcap per-file header has been written to
1625    * the pipe, so it could block indefinitely.
1626    */
1627   if (strcmp(pipename, "-") == 0) {
1628 #ifndef _WIN32
1629     fd = 0; /* read from stdin */
1630 #else /* _WIN32 */
1631     ld->cap_pipe_h = GetStdHandle(STD_INPUT_HANDLE);
1632 #endif  /* _WIN32 */
1633   } else {
1634 #ifndef _WIN32
1635     if (ws_stat(pipename, &pipe_stat) < 0) {
1636       if (errno == ENOENT || errno == ENOTDIR)
1637         ld->cap_pipe_err = PIPNEXIST;
1638       else {
1639         g_snprintf(errmsg, errmsgl,
1640           "The capture session could not be initiated "
1641           "due to error getting information on pipe/socket: %s", strerror(errno));
1642         ld->cap_pipe_err = PIPERR;
1643       }
1644       return;
1645     }
1646     if (S_ISFIFO(pipe_stat.st_mode)) {
1647       fd = ws_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
1648       if (fd == -1) {
1649         g_snprintf(errmsg, errmsgl,
1650             "The capture session could not be initiated "
1651             "due to error on pipe open: %s", strerror(errno));
1652         ld->cap_pipe_err = PIPERR;
1653         return;
1654       }
1655     } else if (S_ISSOCK(pipe_stat.st_mode)) {
1656       fd = socket(AF_UNIX, SOCK_STREAM, 0);
1657       if (fd == -1) {
1658         g_snprintf(errmsg, errmsgl,
1659             "The capture session could not be initiated "
1660             "due to error on socket create: %s", strerror(errno));
1661         ld->cap_pipe_err = PIPERR;
1662         return;
1663       }
1664       sa.sun_family = AF_UNIX;
1665       /*
1666        * The Single UNIX Specification says:
1667        *
1668        *   The size of sun_path has intentionally been left undefined.
1669        *   This is because different implementations use different sizes.
1670        *   For example, 4.3 BSD uses a size of 108, and 4.4 BSD uses a size
1671        *   of 104. Since most implementations originate from BSD versions,
1672        *   the size is typically in the range 92 to 108.
1673        *
1674        *   Applications should not assume a particular length for sun_path
1675        *   or assume that it can hold {_POSIX_PATH_MAX} bytes (256).
1676        *
1677        * It also says
1678        *
1679        *   The <sys/un.h> header shall define the sockaddr_un structure,
1680        *   which shall include at least the following members:
1681        *
1682        *   sa_family_t  sun_family  Address family.
1683        *   char         sun_path[]  Socket pathname.
1684        *
1685        * so we assume that it's an array, with a specified size,
1686        * and that the size reflects the maximum path length.
1687        */
1688       if (g_strlcpy(sa.sun_path, pipename, sizeof sa.sun_path) > sizeof sa.sun_path) {
1689         /* Path name too long */
1690         g_snprintf(errmsg, errmsgl,
1691             "The capture session coud not be initiated "
1692             "due to error on socket connect: Path name too long");
1693         ld->cap_pipe_err = PIPERR;
1694         return;
1695       }
1696       b = connect(fd, (struct sockaddr *)&sa, sizeof sa);
1697       if (b == -1) {
1698         g_snprintf(errmsg, errmsgl,
1699             "The capture session coud not be initiated "
1700             "due to error on socket connect: %s", strerror(errno));
1701         ld->cap_pipe_err = PIPERR;
1702         return;
1703       }
1704     } else {
1705       if (S_ISCHR(pipe_stat.st_mode)) {
1706         /*
1707          * Assume the user specified an interface on a system where
1708          * interfaces are in /dev.  Pretend we haven't seen it.
1709          */
1710          ld->cap_pipe_err = PIPNEXIST;
1711       } else
1712       {
1713         g_snprintf(errmsg, errmsgl,
1714             "The capture session could not be initiated because\n"
1715             "\"%s\" is neither an interface nor a socket nor a pipe", pipename);
1716         ld->cap_pipe_err = PIPERR;
1717       }
1718       return;
1719     }
1720 #else /* _WIN32 */
1721 #define PIPE_STR "\\pipe\\"
1722     /* Under Windows, named pipes _must_ have the form
1723      * "\\<server>\pipe\<pipename>".  <server> may be "." for localhost.
1724      */
1725     pncopy = g_strdup(pipename);
1726     if ( (pos=strstr(pncopy, "\\\\")) == pncopy) {
1727       pos = strchr(pncopy + 3, '\\');
1728       if (pos && g_ascii_strncasecmp(pos, PIPE_STR, strlen(PIPE_STR)) != 0)
1729         pos = NULL;
1730     }
1731
1732     g_free(pncopy);
1733
1734     if (!pos) {
1735       g_snprintf(errmsg, errmsgl,
1736           "The capture session could not be initiated because\n"
1737           "\"%s\" is neither an interface nor a pipe", pipename);
1738       ld->cap_pipe_err = PIPNEXIST;
1739       return;
1740     }
1741
1742     /* Wait for the pipe to appear */
1743     while (1) {
1744       ld->cap_pipe_h = CreateFile(utf_8to16(pipename), GENERIC_READ, 0, NULL,
1745           OPEN_EXISTING, 0, NULL);
1746
1747       if (ld->cap_pipe_h != INVALID_HANDLE_VALUE)
1748         break;
1749
1750       if (GetLastError() != ERROR_PIPE_BUSY) {
1751         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1752           NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1753         g_snprintf(errmsg, errmsgl,
1754             "The capture session on \"%s\" could not be started "
1755             "due to error on pipe open: %s (error %d)",
1756             pipename, utf_16to8(err_str), GetLastError());
1757         LocalFree(err_str);
1758         ld->cap_pipe_err = PIPERR;
1759         return;
1760       }
1761
1762       if (!WaitNamedPipe(utf_8to16(pipename), 30 * 1000)) {
1763         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
1764           NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
1765         g_snprintf(errmsg, errmsgl,
1766             "The capture session on \"%s\" timed out during "
1767             "pipe open: %s (error %d)",
1768             pipename, utf_16to8(err_str), GetLastError());
1769         LocalFree(err_str);
1770         ld->cap_pipe_err = PIPERR;
1771         return;
1772       }
1773     }
1774 #endif /* _WIN32 */
1775   }
1776
1777   ld->from_cap_pipe = TRUE;
1778
1779 #ifndef USE_THREADS
1780   /* read the pcap header */
1781   bytes_read = 0;
1782   while (bytes_read < sizeof magic) {
1783     sel_ret = cap_pipe_select(fd);
1784     if (sel_ret < 0) {
1785       g_snprintf(errmsg, errmsgl,
1786         "Unexpected error from select: %s", strerror(errno));
1787       goto error;
1788     } else if (sel_ret > 0) {
1789       b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
1790       if (b <= 0) {
1791         if (b == 0)
1792           g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1793         else
1794           g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1795             strerror(errno));
1796         goto error;
1797       }
1798       bytes_read += b;
1799     }
1800   }
1801 #else /* USE_THREADS */
1802   g_thread_create(&cap_pipe_read, ld, FALSE, NULL);
1803
1804   ld->cap_pipe_buf = (char *) &magic;
1805   ld->cap_pipe_bytes_read = 0;
1806   ld->cap_pipe_bytes_to_read = sizeof(magic);
1807   /* We don't have to worry about cap_pipe_read_mtx here */
1808   g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1809   g_async_queue_pop(cap_pipe_done_q);
1810   if (ld->cap_pipe_bytes_read <= 0) {
1811     if (ld->cap_pipe_bytes_read == 0)
1812       g_snprintf(errmsg, errmsgl, "End of file on pipe magic during open");
1813     else
1814       g_snprintf(errmsg, errmsgl, "Error on pipe magic during open: %s",
1815                  strerror(errno));
1816     goto error;
1817   }
1818
1819 #endif /* USE_THREADS */
1820
1821   switch (magic) {
1822   case PCAP_MAGIC:
1823     /* Host that wrote it has our byte order, and was running
1824        a program using either standard or ss990417 libpcap. */
1825     ld->cap_pipe_byte_swapped = FALSE;
1826     ld->cap_pipe_modified = FALSE;
1827     break;
1828   case PCAP_MODIFIED_MAGIC:
1829     /* Host that wrote it has our byte order, but was running
1830        a program using either ss990915 or ss991029 libpcap. */
1831     ld->cap_pipe_byte_swapped = FALSE;
1832     ld->cap_pipe_modified = TRUE;
1833     break;
1834   case PCAP_SWAPPED_MAGIC:
1835     /* Host that wrote it has a byte order opposite to ours,
1836        and was running a program using either standard or
1837        ss990417 libpcap. */
1838     ld->cap_pipe_byte_swapped = TRUE;
1839     ld->cap_pipe_modified = FALSE;
1840     break;
1841   case PCAP_SWAPPED_MODIFIED_MAGIC:
1842     /* Host that wrote it out has a byte order opposite to
1843        ours, and was running a program using either ss990915
1844        or ss991029 libpcap. */
1845     ld->cap_pipe_byte_swapped = TRUE;
1846     ld->cap_pipe_modified = TRUE;
1847     break;
1848   default:
1849     /* Not a "libpcap" type we know about. */
1850     g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
1851     goto error;
1852   }
1853
1854 #ifndef USE_THREADS
1855   /* Read the rest of the header */
1856   bytes_read = 0;
1857   while (bytes_read < sizeof(struct pcap_hdr)) {
1858     sel_ret = cap_pipe_select(fd);
1859     if (sel_ret < 0) {
1860       g_snprintf(errmsg, errmsgl,
1861         "Unexpected error from select: %s", strerror(errno));
1862       goto error;
1863     } else if (sel_ret > 0) {
1864       b = read(fd, ((char *)hdr)+bytes_read,
1865             sizeof(struct pcap_hdr) - bytes_read);
1866       if (b <= 0) {
1867         if (b == 0)
1868           g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1869         else
1870           g_snprintf(errmsg, errmsgl, "Error on pipe header during open: %s",
1871             strerror(errno));
1872         goto error;
1873       }
1874       bytes_read += b;
1875     }
1876   }
1877 #else /* USE_THREADS */
1878   ld->cap_pipe_buf = (char *) hdr;
1879   ld->cap_pipe_bytes_read = 0;
1880   ld->cap_pipe_bytes_to_read = sizeof(struct pcap_hdr);
1881   g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1882   g_async_queue_pop(cap_pipe_done_q);
1883   if (ld->cap_pipe_bytes_read <= 0) {
1884     if (ld->cap_pipe_bytes_read == 0)
1885       g_snprintf(errmsg, errmsgl, "End of file on pipe header during open");
1886     else
1887       g_snprintf(errmsg, errmsgl, "Error on pipe header header during open: %s",
1888             strerror(errno));
1889     goto error;
1890   }
1891 #endif /* USE_THREADS */
1892
1893   if (ld->cap_pipe_byte_swapped) {
1894     /* Byte-swap the header fields about which we care. */
1895     hdr->version_major = BSWAP16(hdr->version_major);
1896     hdr->version_minor = BSWAP16(hdr->version_minor);
1897     hdr->snaplen = BSWAP32(hdr->snaplen);
1898     hdr->network = BSWAP32(hdr->network);
1899   }
1900   ld->linktype = hdr->network;
1901
1902   if (hdr->version_major < 2) {
1903     g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1904     goto error;
1905   }
1906
1907   ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1908   ld->cap_pipe_err = PIPOK;
1909 #ifndef _WIN32
1910   ld->cap_pipe_fd = fd;
1911 #endif
1912   return;
1913
1914 error:
1915   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
1916   ld->cap_pipe_err = PIPERR;
1917 #ifndef _WIN32
1918   ws_close(fd);
1919   ld->cap_pipe_fd = -1;
1920 #endif
1921   return;
1922
1923 }
1924
1925
1926 /* We read one record from the pipe, take care of byte order in the record
1927  * header, write the record to the capture file, and update capture statistics. */
1928 static int
1929 cap_pipe_dispatch(loop_data *ld, guchar *data, char *errmsg, int errmsgl)
1930 {
1931   struct pcap_pkthdr phdr;
1932   enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1933          PD_ERR } result;
1934 #ifdef USE_THREADS
1935   GTimeVal wait_time;
1936   gpointer q_status;
1937 #else
1938   int b;
1939 #endif
1940 #ifdef _WIN32
1941   wchar_t *err_str;
1942 #endif
1943
1944 #ifdef LOG_CAPTURE_VERBOSE
1945   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
1946 #endif
1947
1948   switch (ld->cap_pipe_state) {
1949
1950   case STATE_EXPECT_REC_HDR:
1951 #ifdef USE_THREADS
1952     if (g_mutex_trylock(cap_pipe_read_mtx)) {
1953 #endif
1954
1955     ld->cap_pipe_state = STATE_READ_REC_HDR;
1956     ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
1957       sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1958     ld->cap_pipe_bytes_read = 0;
1959
1960 #ifdef USE_THREADS
1961       ld->cap_pipe_buf = (char *) &ld->cap_pipe_rechdr;
1962       g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
1963       g_mutex_unlock(cap_pipe_read_mtx);
1964     }
1965 #endif
1966     /* Fall through */
1967
1968   case STATE_READ_REC_HDR:
1969 #ifndef USE_THREADS
1970     b = read(ld->cap_pipe_fd, ((char *)&ld->cap_pipe_rechdr)+ld->cap_pipe_bytes_read,
1971              ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
1972     if (b <= 0) {
1973       if (b == 0)
1974         result = PD_PIPE_EOF;
1975       else
1976         result = PD_PIPE_ERR;
1977       break;
1978     }
1979     ld->cap_pipe_bytes_read += b;
1980 #else /* USE_THREADS */
1981     g_get_current_time(&wait_time);
1982     g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
1983     q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
1984     if (ld->cap_pipe_err == PIPEOF) {
1985       result = PD_PIPE_EOF;
1986       break;
1987     } else if (ld->cap_pipe_err == PIPERR) {
1988       result = PD_PIPE_ERR;
1989       break;
1990     }
1991     if (!q_status) {
1992       return 0;
1993     }
1994 #endif /* USE_THREADS */
1995     if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
1996         return 0;
1997     result = PD_REC_HDR_READ;
1998     break;
1999
2000   case STATE_EXPECT_DATA:
2001 #ifdef USE_THREADS
2002     if (g_mutex_trylock(cap_pipe_read_mtx)) {
2003 #endif
2004
2005     ld->cap_pipe_state = STATE_READ_DATA;
2006     ld->cap_pipe_bytes_to_read = ld->cap_pipe_rechdr.hdr.incl_len;
2007     ld->cap_pipe_bytes_read = 0;
2008
2009 #ifdef USE_THREADS
2010       ld->cap_pipe_buf = (char *) data;
2011       g_async_queue_push(cap_pipe_pending_q, ld->cap_pipe_buf);
2012       g_mutex_unlock(cap_pipe_read_mtx);
2013     }
2014 #endif
2015     /* Fall through */
2016
2017   case STATE_READ_DATA:
2018 #ifndef USE_THREADS
2019     b = read(ld->cap_pipe_fd, data+ld->cap_pipe_bytes_read,
2020              ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
2021     if (b <= 0) {
2022       if (b == 0)
2023         result = PD_PIPE_EOF;
2024       else
2025         result = PD_PIPE_ERR;
2026       break;
2027     }
2028     ld->cap_pipe_bytes_read += b;
2029 #else /* USE_THREADS */
2030     g_get_current_time(&wait_time);
2031     g_time_val_add(&wait_time, THREAD_READ_TIMEOUT);
2032     q_status = g_async_queue_timed_pop(cap_pipe_done_q, &wait_time);
2033     if (ld->cap_pipe_err == PIPEOF) {
2034       result = PD_PIPE_EOF;
2035       break;
2036     } else if (ld->cap_pipe_err == PIPERR) {
2037       result = PD_PIPE_ERR;
2038       break;
2039     }
2040     if (!q_status) {
2041       return 0;
2042     }
2043 #endif /* USE_THREADS */
2044     if ((ld->cap_pipe_bytes_read) < ld->cap_pipe_bytes_to_read)
2045         return 0;
2046     result = PD_DATA_READ;
2047     break;
2048
2049   default:
2050     g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
2051     result = PD_ERR;
2052
2053   } /* switch (ld->cap_pipe_state) */
2054
2055   /*
2056    * We've now read as much data as we were expecting, so process it.
2057    */
2058   switch (result) {
2059
2060   case PD_REC_HDR_READ:
2061     /* We've read the header. Take care of byte order. */
2062     cap_pipe_adjust_header(ld->cap_pipe_byte_swapped, &ld->cap_pipe_hdr,
2063                            &ld->cap_pipe_rechdr.hdr);
2064     if (ld->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
2065       g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
2066         ld->packet_count+1, ld->cap_pipe_rechdr.hdr.incl_len);
2067       break;
2068     }
2069     ld->cap_pipe_state = STATE_EXPECT_DATA;
2070     return 0;
2071
2072   case PD_DATA_READ:
2073     /* Fill in a "struct pcap_pkthdr", and process the packet. */
2074     phdr.ts.tv_sec = ld->cap_pipe_rechdr.hdr.ts_sec;
2075     phdr.ts.tv_usec = ld->cap_pipe_rechdr.hdr.ts_usec;
2076     phdr.caplen = ld->cap_pipe_rechdr.hdr.incl_len;
2077     phdr.len = ld->cap_pipe_rechdr.hdr.orig_len;
2078
2079     capture_loop_packet_cb((u_char *)ld, &phdr, data);
2080
2081     ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
2082     return 1;
2083
2084   case PD_PIPE_EOF:
2085     ld->cap_pipe_err = PIPEOF;
2086     return -1;
2087
2088   case PD_PIPE_ERR:
2089 #ifdef _WIN32
2090     FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
2091       NULL, GetLastError(), 0, (LPTSTR) &err_str, 0, NULL);
2092     g_snprintf(errmsg, errmsgl,
2093         "Error reading from pipe: %s (error %d)",
2094         utf_16to8(err_str), GetLastError());
2095     LocalFree(err_str);
2096 #else
2097     g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
2098       strerror(errno));
2099 #endif
2100     /* Fall through */
2101   case PD_ERR:
2102     break;
2103   }
2104
2105   ld->cap_pipe_err = PIPERR;
2106   /* Return here rather than inside the switch to prevent GCC warning */
2107   return -1;
2108 }
2109
2110
2111 /** Open the capture input file (pcap or capture pipe).
2112  *  Returns TRUE if it succeeds, FALSE otherwise. */
2113 static gboolean
2114 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
2115                         char *errmsg, size_t errmsg_len,
2116                         char *secondary_errmsg, size_t secondary_errmsg_len)
2117 {
2118   gchar       open_err_str[PCAP_ERRBUF_SIZE];
2119   gchar      *sync_msg_str;
2120 #ifdef _WIN32
2121   int         err;
2122   gchar      *sync_secondary_msg_str;
2123   WORD        wVersionRequested;
2124   WSADATA     wsaData;
2125 #endif
2126
2127   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
2128
2129
2130 /* XXX - opening Winsock on tshark? */
2131
2132   /* Initialize Windows Socket if we are in a WIN32 OS
2133      This needs to be done before querying the interface for network/netmask */
2134 #ifdef _WIN32
2135   /* XXX - do we really require 1.1 or earlier?
2136      Are there any versions that support only 2.0 or higher? */
2137   wVersionRequested = MAKEWORD(1, 1);
2138   err = WSAStartup(wVersionRequested, &wsaData);
2139   if (err != 0) {
2140     switch (err) {
2141
2142     case WSASYSNOTREADY:
2143       g_snprintf(errmsg, (gulong) errmsg_len,
2144         "Couldn't initialize Windows Sockets: Network system not ready for network communication");
2145       break;
2146
2147     case WSAVERNOTSUPPORTED:
2148       g_snprintf(errmsg, (gulong) errmsg_len,
2149         "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
2150         LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
2151       break;
2152
2153     case WSAEINPROGRESS:
2154       g_snprintf(errmsg, (gulong) errmsg_len,
2155         "Couldn't initialize Windows Sockets: Blocking operation is in progress");
2156       break;
2157
2158     case WSAEPROCLIM:
2159       g_snprintf(errmsg, (gulong) errmsg_len,
2160         "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
2161       break;
2162
2163     case WSAEFAULT:
2164       g_snprintf(errmsg, (gulong) errmsg_len,
2165         "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
2166       break;
2167
2168     default:
2169       g_snprintf(errmsg, (gulong) errmsg_len,
2170         "Couldn't initialize Windows Sockets: error %d", err);
2171       break;
2172     }
2173     g_snprintf(secondary_errmsg, (gulong) secondary_errmsg_len, please_report);
2174     return FALSE;
2175   }
2176 #endif
2177
2178   ld->pcap_h = open_capture_device(capture_opts, &open_err_str);
2179
2180   if (ld->pcap_h != NULL) {
2181     /* we've opened "iface" as a network device */
2182 #ifdef _WIN32
2183     /* try to set the capture buffer size */
2184     if (capture_opts->buffer_size > 1 &&
2185         pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
2186         sync_secondary_msg_str = g_strdup_printf(
2187           "The capture buffer size of %dMB seems to be too high for your machine,\n"
2188           "the default of 1MB will be used.\n"
2189           "\n"
2190           "Nonetheless, the capture is started.\n",
2191           capture_opts->buffer_size);
2192         report_capture_error("Couldn't set the capture buffer size!",
2193                                    sync_secondary_msg_str);
2194         g_free(sync_secondary_msg_str);
2195     }
2196 #endif
2197
2198 #if defined(HAVE_PCAP_REMOTE) && defined(HAVE_PCAP_SETSAMPLING)
2199     if ((capture_opts->sampling_method != CAPTURE_SAMP_NONE) &&
2200         (strncmp (capture_opts->iface, "rpcap://", 8) == 0))
2201     {
2202         struct pcap_samp *samp;
2203
2204         if ((samp = pcap_setsampling(ld->pcap_h)) != NULL)
2205         {
2206             switch (capture_opts->sampling_method)
2207             {
2208                 case CAPTURE_SAMP_BY_COUNT:
2209                     samp->method = PCAP_SAMP_1_EVERY_N;
2210                     break;
2211
2212                 case CAPTURE_SAMP_BY_TIMER:
2213                     samp->method = PCAP_SAMP_FIRST_AFTER_N_MS;
2214                     break;
2215
2216                 default:
2217                     sync_msg_str = g_strdup_printf(
2218                             "Unknown sampling method %d specified,\n"
2219                             "continue without packet sampling",
2220                             capture_opts->sampling_method);
2221                     report_capture_error("Couldn't set the capture "
2222                             "sampling", sync_msg_str);
2223                     g_free(sync_msg_str);
2224             }
2225             samp->value = capture_opts->sampling_param;
2226         }
2227         else
2228         {
2229             report_capture_error("Couldn't set the capture sampling",
2230                     "Cannot get packet sampling data structure");
2231         }
2232
2233     }
2234 #endif
2235
2236     /* setting the data link type only works on real interfaces */
2237     if (!set_pcap_linktype(ld->pcap_h, capture_opts, errmsg, errmsg_len,
2238                            secondary_errmsg, secondary_errmsg_len))
2239       return FALSE;
2240     ld->linktype = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
2241   } else {
2242     /* We couldn't open "iface" as a network device. */
2243     /* Try to open it as a pipe */
2244     cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, (int) errmsg_len);
2245
2246 #ifndef _WIN32
2247     if (ld->cap_pipe_fd == -1) {
2248 #else
2249     if (ld->cap_pipe_h == INVALID_HANDLE_VALUE) {
2250 #endif
2251
2252       if (ld->cap_pipe_err == PIPNEXIST) {
2253         /* Pipe doesn't exist, so output message for interface */
2254         get_capture_device_open_failure_messages(open_err_str,
2255                                                  capture_opts->iface,
2256                                                  errmsg,
2257                                                  errmsg_len,
2258                                                  secondary_errmsg,
2259                                                  secondary_errmsg_len);
2260       }
2261       /*
2262        * Else pipe (or file) does exist and cap_pipe_open_live() has
2263        * filled in errmsg
2264        */
2265       return FALSE;
2266     } else
2267       /* cap_pipe_open_live() succeeded; don't want
2268          error message from pcap_open_live() */
2269       open_err_str[0] = '\0';
2270   }
2271
2272 /* XXX - will this work for tshark? */
2273 #ifdef MUST_DO_SELECT
2274   if (!ld->from_cap_pipe) {
2275 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
2276     ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
2277 #else
2278     ld->pcap_fd = pcap_fileno(ld->pcap_h);
2279 #endif
2280   }
2281 #endif
2282
2283   /* Does "open_err_str" contain a non-empty string?  If so, "pcap_open_live()"
2284      returned a warning; print it, but keep capturing. */
2285   if (open_err_str[0] != '\0') {
2286     sync_msg_str = g_strdup_printf("%s.", open_err_str);
2287     report_capture_error(sync_msg_str, "");
2288     g_free(sync_msg_str);
2289   }
2290
2291   return TRUE;
2292 }
2293
2294 /* close the capture input file (pcap or capture pipe) */
2295 static void capture_loop_close_input(loop_data *ld) {
2296
2297   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
2298
2299   /* if open, close the capture pipe "input file" */
2300 #ifndef _WIN32
2301   if (ld->cap_pipe_fd >= 0) {
2302     g_assert(ld->from_cap_pipe);
2303     ws_close(ld->cap_pipe_fd);
2304     ld->cap_pipe_fd = 0;
2305   }
2306 #else
2307   if (ld->cap_pipe_h != INVALID_HANDLE_VALUE) {
2308     CloseHandle(ld->cap_pipe_h);
2309     ld->cap_pipe_h = INVALID_HANDLE_VALUE;
2310   }
2311 #endif
2312
2313   /* if open, close the pcap "input file" */
2314   if(ld->pcap_h != NULL) {
2315     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input: closing %p", (void *)ld->pcap_h);
2316     g_assert(!ld->from_cap_pipe);
2317     pcap_close(ld->pcap_h);
2318     ld->pcap_h = NULL;
2319   }
2320
2321   ld->go = FALSE;
2322
2323 #ifdef _WIN32
2324   /* Shut down windows sockets */
2325   WSACleanup();
2326 #endif
2327 }
2328
2329
2330 /* init the capture filter */
2331 static initfilter_status_t
2332 capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe,
2333                          gchar * iface, gchar * cfilter)
2334 {
2335   struct bpf_program fcode;
2336
2337   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
2338
2339   /* capture filters only work on real interfaces */
2340   if (cfilter && !from_cap_pipe) {
2341     /* A capture filter was specified; set it up. */
2342     if (!compile_capture_filter(iface, pcap_h, &fcode, cfilter)) {
2343       /* Treat this specially - our caller might try to compile this
2344          as a display filter and, if that succeeds, warn the user that
2345          the display and capture filter syntaxes are different. */
2346       return INITFILTER_BAD_FILTER;
2347     }
2348     if (pcap_setfilter(pcap_h, &fcode) < 0) {
2349 #ifdef HAVE_PCAP_FREECODE
2350       pcap_freecode(&fcode);
2351 #endif
2352       return INITFILTER_OTHER_ERROR;
2353     }
2354 #ifdef HAVE_PCAP_FREECODE
2355     pcap_freecode(&fcode);
2356 #endif
2357   }
2358
2359   return INITFILTER_NO_ERROR;
2360 }
2361
2362
2363 /* set up to write to the already-opened capture output file/files */
2364 static gboolean
2365 capture_loop_init_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len) {
2366   int         err;
2367
2368
2369   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
2370
2371   /* get snaplen */
2372   if (ld->from_cap_pipe) {
2373     ld->file_snaplen = ld->cap_pipe_hdr.snaplen;
2374   } else
2375   {
2376     ld->file_snaplen = pcap_snapshot(ld->pcap_h);
2377   }
2378
2379   /* Set up to write to the capture file. */
2380   if (capture_opts->multi_files_on) {
2381     ld->pdh = ringbuf_init_libpcap_fdopen(&err);
2382   } else {
2383     ld->pdh = libpcap_fdopen(ld->save_file_fd, &err);
2384   }
2385   if (ld->pdh) {
2386     gboolean successful;
2387
2388     ld->bytes_written = 0;
2389     if (capture_opts->use_pcapng) {
2390       char appname[100];
2391
2392       g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2393       successful = libpcap_write_session_header_block(ld->pdh, appname, &ld->bytes_written, &err) &&
2394                    libpcap_write_interface_description_block(ld->pdh, capture_opts->iface, capture_opts->cfilter, ld->linktype, ld->file_snaplen, &ld->bytes_written, &err);
2395     } else {
2396       successful = libpcap_write_file_header(ld->pdh, ld->linktype, ld->file_snaplen,
2397                                              &ld->bytes_written, &err);
2398     }
2399     if (!successful) {
2400       fclose(ld->pdh);
2401       ld->pdh = NULL;
2402     }
2403   }
2404
2405   if (ld->pdh == NULL) {
2406     /* We couldn't set up to write to the capture file. */
2407     /* XXX - use cf_open_error_message from tshark instead? */
2408     switch (err) {
2409
2410     case WTAP_ERR_CANT_OPEN:
2411       g_snprintf(errmsg, errmsg_len, "The file to which the capture would be saved"
2412                " couldn't be created for some unknown reason.");
2413       break;
2414
2415     case WTAP_ERR_SHORT_WRITE:
2416       g_snprintf(errmsg, errmsg_len, "A full header couldn't be written to the file"
2417                " to which the capture would be saved.");
2418       break;
2419
2420     default:
2421       if (err < 0) {
2422         g_snprintf(errmsg, errmsg_len,
2423                    "The file to which the capture would be"
2424                    " saved (\"%s\") could not be opened: Error %d.",
2425                    capture_opts->save_file, err);
2426       } else {
2427         g_snprintf(errmsg, errmsg_len,
2428                     "The file to which the capture would be"
2429                     " saved (\"%s\") could not be opened: %s.",
2430                     capture_opts->save_file, strerror(err));
2431       }
2432       break;
2433     }
2434
2435     return FALSE;
2436   }
2437
2438   return TRUE;
2439 }
2440
2441 static gboolean
2442 capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
2443
2444   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
2445
2446   if (capture_opts->multi_files_on) {
2447     return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
2448   } else {
2449     if (capture_opts->use_pcapng) {
2450       libpcap_write_interface_statistics_block(ld->pdh, 0, ld->pcap_h, &ld->bytes_written, err_close);
2451     }
2452     return libpcap_dump_close(ld->pdh, err_close);
2453   }
2454 }
2455
2456 /* dispatch incoming packets (pcap or capture pipe)
2457  *
2458  * Waits for incoming packets to be available, and calls pcap_dispatch()
2459  * to cause them to be processed.
2460  *
2461  * Returns the number of packets which were processed.
2462  *
2463  * Times out (returning zero) after CAP_READ_TIMEOUT ms; this ensures that the
2464  * packet-batching behaviour does not cause packets to get held back
2465  * indefinitely.
2466  */
2467 static int
2468 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
2469                       char *errmsg, int errmsg_len)
2470 {
2471   int       inpkts;
2472   gint      packet_count_before;
2473   guchar    pcap_data[WTAP_MAX_PACKET_SIZE];
2474 #ifndef USE_THREADS
2475   int       sel_ret;
2476 #endif
2477
2478   packet_count_before = ld->packet_count;
2479   if (ld->from_cap_pipe) {
2480     /* dispatch from capture pipe */
2481 #ifdef LOG_CAPTURE_VERBOSE
2482     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
2483 #endif
2484 #ifndef USE_THREADS
2485     sel_ret = cap_pipe_select(ld->cap_pipe_fd);
2486     if (sel_ret <= 0) {
2487       inpkts = 0;
2488       if (sel_ret < 0 && errno != EINTR) {
2489         g_snprintf(errmsg, errmsg_len,
2490           "Unexpected error from select: %s", strerror(errno));
2491         report_capture_error(errmsg, please_report);
2492         ld->go = FALSE;
2493       }
2494     } else {
2495       /*
2496        * "select()" says we can read from the pipe without blocking
2497        */
2498 #endif /* USE_THREADS */
2499       inpkts = cap_pipe_dispatch(ld, pcap_data, errmsg, errmsg_len);
2500       if (inpkts < 0) {
2501         ld->go = FALSE;
2502       }
2503 #ifndef USE_THREADS
2504     }
2505 #endif
2506   }
2507   else
2508   {
2509     /* dispatch from pcap */
2510 #ifdef MUST_DO_SELECT
2511     /*
2512      * If we have "pcap_get_selectable_fd()", we use it to get the
2513      * descriptor on which to select; if that's -1, it means there
2514      * is no descriptor on which you can do a "select()" (perhaps
2515      * because you're capturing on a special device, and that device's
2516      * driver unfortunately doesn't support "select()", in which case
2517      * we don't do the select - which means it might not be possible
2518      * to stop a capture until a packet arrives.  If that's unacceptable,
2519      * plead with whoever supplies the software for that device to add
2520      * "select()" support, or upgrade to libpcap 0.8.1 or later, and
2521      * rebuild Wireshark or get a version built with libpcap 0.8.1 or
2522      * later, so it can use pcap_breakloop().
2523      */
2524 #ifdef LOG_CAPTURE_VERBOSE
2525     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
2526 #endif
2527     if (ld->pcap_fd != -1) {
2528       sel_ret = cap_pipe_select(ld->pcap_fd);
2529       if (sel_ret > 0) {
2530         /*
2531          * "select()" says we can read from it without blocking; go for
2532          * it.
2533          *
2534          * We don't have pcap_breakloop(), so we only process one packet
2535          * per pcap_dispatch() call, to allow a signal to stop the
2536          * processing immediately, rather than processing all packets
2537          * in a batch before quitting.
2538          */
2539         inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb,
2540                                (u_char *)ld);
2541         if (inpkts < 0) {
2542             if (inpkts == -1) {
2543                 /* Error, rather than pcap_breakloop(). */
2544                 ld->pcap_err = TRUE;
2545             }
2546           ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2547         }
2548       } else {
2549         if (sel_ret < 0 && errno != EINTR) {
2550           g_snprintf(errmsg, errmsg_len,
2551             "Unexpected error from select: %s", strerror(errno));
2552           report_capture_error(errmsg, please_report);
2553           ld->go = FALSE;
2554         }
2555       }
2556     }
2557     else
2558 #endif /* MUST_DO_SELECT */
2559     {
2560       /* dispatch from pcap without select */
2561 #if 1
2562 #ifdef LOG_CAPTURE_VERBOSE
2563       g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
2564 #endif
2565 #ifdef _WIN32
2566       /*
2567        * On Windows, we don't support asynchronously telling a process to
2568        * stop capturing; instead, we check for an indication on a pipe
2569        * after processing packets.  We therefore process only one packet
2570        * at a time, so that we can check the pipe after every packet.
2571        */
2572       inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb, (u_char *) ld);
2573 #else
2574       inpkts = pcap_dispatch(ld->pcap_h, -1, capture_loop_packet_cb, (u_char *) ld);
2575 #endif
2576       if (inpkts < 0) {
2577         if (inpkts == -1) {
2578           /* Error, rather than pcap_breakloop(). */
2579           ld->pcap_err = TRUE;
2580         }
2581         ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
2582       }
2583 #else /* pcap_next_ex */
2584 #ifdef LOG_CAPTURE_VERBOSE
2585       g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
2586 #endif
2587       /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
2588
2589       /*
2590        * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
2591        * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
2592        * This should be fixed in the WinPcap 4.0 alpha release.
2593        *
2594        * For reference, an example remote interface:
2595        * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
2596        */
2597
2598       /* emulate dispatch from pcap */
2599       {
2600         int in;
2601         struct pcap_pkthdr *pkt_header;
2602         u_char *pkt_data;
2603
2604         in = 0;
2605         while(ld->go &&
2606               (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1)
2607           capture_loop_packet_cb( (u_char *) ld, pkt_header, pkt_data);
2608
2609         if(in < 0) {
2610           ld->pcap_err = TRUE;
2611           ld->go = FALSE;
2612         }
2613       }
2614 #endif /* pcap_next_ex */
2615     }
2616   }
2617
2618 #ifdef LOG_CAPTURE_VERBOSE
2619   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
2620 #endif
2621
2622   return ld->packet_count - packet_count_before;
2623 }
2624
2625
2626 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
2627 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
2628 static gboolean
2629 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
2630                       char *errmsg, int errmsg_len) {
2631
2632   char *tmpname;
2633   gchar *capfile_name;
2634   gboolean is_tempfile;
2635 #ifndef _WIN32
2636   int ret;
2637 #endif
2638
2639   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
2640       (capture_opts->save_file) ? capture_opts->save_file : "");
2641
2642   if (capture_opts->save_file != NULL) {
2643     /* We return to the caller while the capture is in progress.
2644      * Therefore we need to take a copy of save_file in
2645      * case the caller destroys it after we return.
2646      */
2647     capfile_name = g_strdup(capture_opts->save_file);
2648
2649     if (capture_opts->output_to_pipe == TRUE) { /* either "-" or named pipe */
2650       if (capture_opts->multi_files_on) {
2651         /* ringbuffer is enabled; that doesn't work with standard output or a named pipe */
2652         g_snprintf(errmsg, errmsg_len,
2653             "Ring buffer requested, but capture is being written to standard output or to a named pipe.");
2654         g_free(capfile_name);
2655         return FALSE;
2656       }
2657       if (strcmp(capfile_name, "-") == 0) {
2658         /* write to stdout */
2659         *save_file_fd = 1;
2660 #ifdef _WIN32
2661         /* set output pipe to binary mode to avoid Windows text-mode processing (eg: for CR/LF)  */
2662         _setmode(1, O_BINARY);
2663 #endif
2664       }
2665     } /* if (...output_to_pipe ... */
2666
2667     else {
2668       if (capture_opts->multi_files_on) {
2669         /* ringbuffer is enabled */
2670         *save_file_fd = ringbuf_init(capfile_name,
2671             (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
2672
2673         /* we need the ringbuf name */
2674         if(*save_file_fd != -1) {
2675             g_free(capfile_name);
2676             capfile_name = g_strdup(ringbuf_current_filename());
2677         }
2678       } else {
2679         /* Try to open/create the specified file for use as a capture buffer. */
2680         *save_file_fd = ws_open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
2681                              0600);
2682       }
2683     }
2684     is_tempfile = FALSE;
2685   } else {
2686     /* Choose a random name for the temporary capture buffer */
2687     *save_file_fd = create_tempfile(&tmpname, "wireshark");
2688     capfile_name = g_strdup(tmpname);
2689     is_tempfile = TRUE;
2690   }
2691
2692   /* did we fail to open the output file? */
2693   if (*save_file_fd == -1) {
2694     if (is_tempfile) {
2695       g_snprintf(errmsg, errmsg_len,
2696         "The temporary file to which the capture would be saved (\"%s\") "
2697         "could not be opened: %s.", capfile_name, strerror(errno));
2698     } else {
2699       if (capture_opts->multi_files_on) {
2700         ringbuf_error_cleanup();
2701       }
2702
2703       g_snprintf(errmsg, errmsg_len,
2704             "The file to which the capture would be saved (\"%s\") "
2705         "could not be opened: %s.", capfile_name,
2706         strerror(errno));
2707     }
2708     g_free(capfile_name);
2709     return FALSE;
2710   }
2711
2712   if(capture_opts->save_file != NULL) {
2713     g_free(capture_opts->save_file);
2714   }
2715   capture_opts->save_file = capfile_name;
2716   /* capture_opts.save_file is "g_free"ed later, which is equivalent to
2717      "g_free(capfile_name)". */
2718 #ifndef _WIN32
2719   ret = fchown(*save_file_fd, capture_opts->owner, capture_opts->group);
2720 #endif
2721
2722   return TRUE;
2723 }
2724
2725
2726 #ifdef _WIN32
2727 #define TIME_GET() GetTickCount()
2728 #else
2729 #define TIME_GET() time(NULL)
2730 #endif
2731
2732 /* Do the work of handling either the file size or file duration capture
2733    conditions being reached, and switching files or stopping. */
2734 static gboolean
2735 do_file_switch_or_stop(capture_options *capture_opts,
2736                        condition *cnd_autostop_files,
2737                        condition *cnd_autostop_size,
2738                        condition *cnd_file_duration)
2739 {
2740   if (capture_opts->multi_files_on) {
2741     if (cnd_autostop_files != NULL &&
2742         cnd_eval(cnd_autostop_files, ++global_ld.autostop_files)) {
2743       /* no files left: stop here */
2744       global_ld.go = FALSE;
2745       return FALSE;
2746     }
2747
2748     /* Switch to the next ringbuffer file */
2749     if (ringbuf_switch_file(&global_ld.pdh, &capture_opts->save_file,
2750                             &global_ld.save_file_fd, &global_ld.err)) {
2751       gboolean successful;
2752
2753       /* File switch succeeded: reset the conditions */
2754       global_ld.bytes_written = 0;
2755       if (capture_opts->use_pcapng) {
2756         char appname[100];
2757
2758         g_snprintf(appname, sizeof(appname), "Dumpcap " VERSION "%s", wireshark_svnversion);
2759         successful = libpcap_write_session_header_block(global_ld.pdh, appname, &global_ld.bytes_written, &global_ld.err) &&
2760                      libpcap_write_interface_description_block(global_ld.pdh, capture_opts->iface, capture_opts->cfilter, global_ld.linktype, global_ld.file_snaplen, &global_ld.bytes_written, &global_ld.err);
2761       } else {
2762         successful = libpcap_write_file_header(global_ld.pdh, global_ld.linktype, global_ld.file_snaplen,
2763                                                &global_ld.bytes_written, &global_ld.err);
2764       }
2765       if (!successful) {
2766         fclose(global_ld.pdh);
2767         global_ld.pdh = NULL;
2768         global_ld.go = FALSE;
2769         return FALSE;
2770       }
2771       if(cnd_autostop_size)
2772         cnd_reset(cnd_autostop_size);
2773       if(cnd_file_duration)
2774         cnd_reset(cnd_file_duration);
2775       libpcap_dump_flush(global_ld.pdh, NULL);
2776       if (!quiet)
2777         report_packet_count(global_ld.inpkts_to_sync_pipe);
2778       global_ld.inpkts_to_sync_pipe = 0;
2779       report_new_capture_file(capture_opts->save_file);
2780     } else {
2781       /* File switch failed: stop here */
2782       global_ld.go = FALSE;
2783       return FALSE;
2784     }
2785   } else {
2786     /* single file, stop now */
2787     global_ld.go = FALSE;
2788     return FALSE;
2789   }
2790   return TRUE;
2791 }
2792
2793 /* Do the low-level work of a capture.
2794    Returns TRUE if it succeeds, FALSE otherwise. */
2795 static gboolean
2796 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
2797 {
2798   time_t      upd_time, cur_time;
2799   time_t      start_time;
2800   int         err_close;
2801   int         inpkts;
2802   condition  *cnd_file_duration = NULL;
2803   condition  *cnd_autostop_files = NULL;
2804   condition  *cnd_autostop_size = NULL;
2805   condition  *cnd_autostop_duration = NULL;
2806   gboolean    write_ok;
2807   gboolean    close_ok;
2808   gboolean    cfilter_error = FALSE;
2809   char        errmsg[MSG_MAX_LENGTH+1];
2810   char        secondary_errmsg[MSG_MAX_LENGTH+1];
2811
2812   *errmsg           = '\0';
2813   *secondary_errmsg = '\0';
2814
2815   /* init the loop data */
2816   global_ld.go                  = TRUE;
2817   global_ld.packet_count        = 0;
2818 #ifdef SIGINFO
2819   global_ld.report_packet_count = FALSE;
2820 #endif
2821   if (capture_opts->has_autostop_packets)
2822     global_ld.packet_max        = capture_opts->autostop_packets;
2823   else
2824     global_ld.packet_max        = 0;    /* no limit */
2825   global_ld.inpkts_to_sync_pipe = 0;
2826   global_ld.err                 = 0;    /* no error seen yet */
2827   global_ld.wtap_linktype       = WTAP_ENCAP_UNKNOWN;
2828   global_ld.pcap_err            = FALSE;
2829   global_ld.from_cap_pipe       = FALSE;
2830   global_ld.pdh                 = NULL;
2831 #ifndef _WIN32
2832   global_ld.cap_pipe_fd         = -1;
2833 #else
2834   global_ld.cap_pipe_h          = INVALID_HANDLE_VALUE;
2835 #endif
2836 #ifdef MUST_DO_SELECT
2837   global_ld.pcap_fd             = 0;
2838 #endif
2839   global_ld.autostop_files      = 0;
2840   global_ld.save_file_fd        = -1;
2841
2842   /* We haven't yet gotten the capture statistics. */
2843   *stats_known      = FALSE;
2844
2845   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
2846   capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
2847
2848   /* open the "input file" from network interface or capture pipe */
2849   if (!capture_loop_open_input(capture_opts, &global_ld, errmsg, sizeof(errmsg),
2850                                secondary_errmsg, sizeof(secondary_errmsg))) {
2851     goto error;
2852   }
2853
2854   /* init the input filter from the network interface (capture pipe will do nothing) */
2855   switch (capture_loop_init_filter(global_ld.pcap_h, global_ld.from_cap_pipe,
2856                                    capture_opts->iface,
2857                                    capture_opts->cfilter)) {
2858
2859   case INITFILTER_NO_ERROR:
2860     break;
2861
2862   case INITFILTER_BAD_FILTER:
2863     cfilter_error = TRUE;
2864     g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(global_ld.pcap_h));
2865     goto error;
2866
2867   case INITFILTER_OTHER_ERROR:
2868     g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
2869                pcap_geterr(global_ld.pcap_h));
2870     g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
2871     goto error;
2872   }
2873
2874   /* If we're supposed to write to a capture file, open it for output
2875      (temporary/specified name/ringbuffer) */
2876   if (capture_opts->saving_to_file) {
2877     if (!capture_loop_open_output(capture_opts, &global_ld.save_file_fd,
2878                                   errmsg, sizeof(errmsg))) {
2879       goto error;
2880     }
2881
2882     /* set up to write to the already-opened capture output file/files */
2883     if (!capture_loop_init_output(capture_opts, &global_ld, errmsg,
2884                                   sizeof(errmsg))) {
2885       goto error;
2886     }
2887
2888   /* XXX - capture SIGTERM and close the capture, in case we're on a
2889      Linux 2.0[.x] system and you have to explicitly close the capture
2890      stream in order to turn promiscuous mode off?  We need to do that
2891      in other places as well - and I don't think that works all the
2892      time in any case, due to libpcap bugs. */
2893
2894     /* Well, we should be able to start capturing.
2895
2896        Sync out the capture file, so the header makes it to the file system,
2897        and send a "capture started successfully and capture file created"
2898        message to our parent so that they'll open the capture file and
2899        update its windows to indicate that we have a live capture in
2900        progress. */
2901     libpcap_dump_flush(global_ld.pdh, NULL);
2902     report_new_capture_file(capture_opts->save_file);
2903   }
2904
2905   /* initialize capture stop (and alike) conditions */
2906   init_capture_stop_conditions();
2907   /* create stop conditions */
2908   if (capture_opts->has_autostop_filesize)
2909     cnd_autostop_size =
2910         cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
2911   if (capture_opts->has_autostop_duration)
2912     cnd_autostop_duration =
2913         cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
2914
2915   if (capture_opts->multi_files_on) {
2916       if (capture_opts->has_file_duration)
2917         cnd_file_duration =
2918             cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
2919
2920       if (capture_opts->has_autostop_files)
2921         cnd_autostop_files =
2922             cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
2923   }
2924
2925   /* init the time values */
2926   start_time = TIME_GET();
2927   upd_time = TIME_GET();
2928
2929   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
2930
2931   /* WOW, everything is prepared! */
2932   /* please fasten your seat belts, we will enter now the actual capture loop */
2933   while (global_ld.go) {
2934     /* dispatch incoming packets */
2935     inpkts = capture_loop_dispatch(capture_opts, &global_ld, errmsg,
2936                                    sizeof(errmsg));
2937
2938 #ifdef SIGINFO
2939     /* Were we asked to print packet counts by the SIGINFO handler? */
2940     if (global_ld.report_packet_count) {
2941         fprintf(stderr, "%u packet%s captured\n", global_ld.packet_count,
2942                 plurality(global_ld.packet_count, "", "s"));
2943         global_ld.report_packet_count = FALSE;
2944     }
2945 #endif
2946
2947 #ifdef _WIN32
2948     /* any news from our parent (signal pipe)? -> just stop the capture */
2949     if (!signal_pipe_check_running()) {
2950       global_ld.go = FALSE;
2951     }
2952 #endif
2953
2954     if (inpkts > 0) {
2955       global_ld.inpkts_to_sync_pipe += inpkts;
2956
2957       /* check capture size condition */
2958       if (cnd_autostop_size != NULL &&
2959           cnd_eval(cnd_autostop_size, (guint32)global_ld.bytes_written)) {
2960         /* Capture size limit reached, do we have another file? */
2961         if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
2962                                     cnd_autostop_size, cnd_file_duration))
2963           continue;
2964       } /* cnd_autostop_size */
2965       if (capture_opts->output_to_pipe) {
2966         libpcap_dump_flush(global_ld.pdh, NULL);
2967       }
2968     } /* inpkts */
2969
2970     /* Only update once a second (Win32: 500ms) so as not to overload slow
2971      * displays. This also prevents too much context-switching between the
2972      * dumpcap and wireshark processes */
2973     cur_time = TIME_GET();
2974 #ifdef _WIN32
2975     if ( (cur_time - upd_time) > 500) {
2976 #else
2977     if (cur_time - upd_time > 0) {
2978 #endif
2979         upd_time = cur_time;
2980
2981       /*if (pcap_stats(pch, stats) >= 0) {
2982         *stats_known = TRUE;
2983       }*/
2984
2985       /* Let the parent process know. */
2986       if (global_ld.inpkts_to_sync_pipe) {
2987         /* do sync here */
2988         libpcap_dump_flush(global_ld.pdh, NULL);
2989
2990         /* Send our parent a message saying we've written out
2991            "global_ld.inpkts_to_sync_pipe" packets to the capture file. */
2992         if (!quiet)
2993           report_packet_count(global_ld.inpkts_to_sync_pipe);
2994
2995         global_ld.inpkts_to_sync_pipe = 0;
2996       }
2997
2998       /* check capture duration condition */
2999       if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
3000         /* The maximum capture time has elapsed; stop the capture. */
3001         global_ld.go = FALSE;
3002         continue;
3003       }
3004
3005       /* check capture file duration condition */
3006       if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
3007         /* duration limit reached, do we have another file? */
3008         if (!do_file_switch_or_stop(capture_opts, cnd_autostop_files,
3009                                     cnd_autostop_size, cnd_file_duration))
3010           continue;
3011       } /* cnd_file_duration */
3012     }
3013
3014   } /* while (global_ld.go) */
3015
3016   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
3017
3018   /* delete stop conditions */
3019   if (cnd_file_duration != NULL)
3020     cnd_delete(cnd_file_duration);
3021   if (cnd_autostop_files != NULL)
3022     cnd_delete(cnd_autostop_files);
3023   if (cnd_autostop_size != NULL)
3024     cnd_delete(cnd_autostop_size);
3025   if (cnd_autostop_duration != NULL)
3026     cnd_delete(cnd_autostop_duration);
3027
3028   /* did we had a pcap (input) error? */
3029   if (global_ld.pcap_err) {
3030     /* On Linux, if an interface goes down while you're capturing on it,
3031        you'll get a "recvfrom: Network is down" error (ENETDOWN).
3032        (At least you will if strerror() doesn't show a local translation
3033        of the error.)
3034
3035        On FreeBSD and OS X, if a network adapter disappears while
3036        you're capturing on it, you'll get a "read: Device not configured"
3037        error (ENXIO).  (See previous parenthetical note.)
3038
3039        On OpenBSD, you get "read: I/O error" (EIO) in the same case.
3040
3041        These should *not* be reported to the Wireshark developers. */
3042     char *cap_err_str;
3043
3044     cap_err_str = pcap_geterr(global_ld.pcap_h);
3045     if (strcmp(cap_err_str, "recvfrom: Network is down") == 0 ||
3046         strcmp(cap_err_str, "read: Device not configured") == 0 ||
3047         strcmp(cap_err_str, "read: I/O error") == 0) {
3048       report_capture_error("The network adapter on which the capture was being done "
3049                            "is no longer running; the capture has stopped.",
3050                            "");
3051     } else {
3052       g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
3053         cap_err_str);
3054       report_capture_error(errmsg, please_report);
3055     }
3056   }
3057   else if (global_ld.from_cap_pipe && global_ld.cap_pipe_err == PIPERR)
3058     report_capture_error(errmsg, "");
3059
3060   /* did we had an error while capturing? */
3061   if (global_ld.err == 0) {
3062     write_ok = TRUE;
3063   } else {
3064     capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file,
3065                             global_ld.err, FALSE);
3066     report_capture_error(errmsg, please_report);
3067     write_ok = FALSE;
3068   }
3069
3070   if (capture_opts->saving_to_file) {
3071     /* close the wiretap (output) file */
3072     close_ok = capture_loop_close_output(capture_opts, &global_ld, &err_close);
3073   } else
3074     close_ok = TRUE;
3075
3076   /* there might be packets not yet notified to the parent */
3077   /* (do this after closing the file, so all packets are already flushed) */
3078   if(global_ld.inpkts_to_sync_pipe) {
3079     if (!quiet)
3080       report_packet_count(global_ld.inpkts_to_sync_pipe);
3081     global_ld.inpkts_to_sync_pipe = 0;
3082   }
3083
3084   /* If we've displayed a message about a write error, there's no point
3085      in displaying another message about an error on close. */
3086   if (!close_ok && write_ok) {
3087     capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
3088                 TRUE);
3089     report_capture_error(errmsg, "");
3090   }
3091
3092   /*
3093    * XXX We exhibit different behaviour between normal mode and sync mode
3094    * when the pipe is stdin and not already at EOF.  If we're a child, the
3095    * parent's stdin isn't closed, so if the user starts another capture,
3096    * cap_pipe_open_live() will very likely not see the expected magic bytes and
3097    * will say "Unrecognized libpcap format".  On the other hand, in normal
3098    * mode, cap_pipe_open_live() will say "End of file on pipe during open".
3099    */
3100
3101   /* get packet drop statistics from pcap */
3102   if(global_ld.pcap_h != NULL) {
3103     g_assert(!global_ld.from_cap_pipe);
3104     /* Get the capture statistics, so we know how many packets were
3105        dropped. */
3106     if (pcap_stats(global_ld.pcap_h, stats) >= 0) {
3107       *stats_known = TRUE;
3108       /* Let the parent process know. */
3109       report_packet_drops(stats->ps_drop);
3110     } else {
3111       g_snprintf(errmsg, sizeof(errmsg),
3112                 "Can't get packet-drop statistics: %s",
3113                 pcap_geterr(global_ld.pcap_h));
3114       report_capture_error(errmsg, please_report);
3115     }
3116   }
3117
3118   /* close the input file (pcap or capture pipe) */
3119   capture_loop_close_input(&global_ld);
3120
3121   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
3122
3123   /* ok, if the write and the close were successful. */
3124   return write_ok && close_ok;
3125
3126 error:
3127   if (capture_opts->multi_files_on) {
3128     /* cleanup ringbuffer */
3129     ringbuf_error_cleanup();
3130   } else {
3131     /* We can't use the save file, and we have no FILE * for the stream
3132        to close in order to close it, so close the FD directly. */
3133     if(global_ld.save_file_fd != -1) {
3134       ws_close(global_ld.save_file_fd);
3135     }
3136
3137     /* We couldn't even start the capture, so get rid of the capture
3138        file. */
3139     if(capture_opts->save_file != NULL) {
3140       ws_unlink(capture_opts->save_file);
3141       g_free(capture_opts->save_file);
3142     }
3143   }
3144   capture_opts->save_file = NULL;
3145   if (cfilter_error)
3146     report_cfilter_error(capture_opts->cfilter, errmsg);
3147   else
3148     report_capture_error(errmsg, secondary_errmsg);
3149
3150   /* close the input file (pcap or cap_pipe) */
3151   capture_loop_close_input(&global_ld);
3152
3153   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
3154
3155   return FALSE;
3156 }
3157
3158
3159 static void capture_loop_stop(void)
3160 {
3161 #ifdef HAVE_PCAP_BREAKLOOP
3162   if(global_ld.pcap_h != NULL)
3163     pcap_breakloop(global_ld.pcap_h);
3164 #endif
3165   global_ld.go = FALSE;
3166 }
3167
3168
3169 static void
3170 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
3171                           int err, gboolean is_close)
3172 {
3173   switch (err) {
3174
3175   case ENOSPC:
3176     g_snprintf(errmsg, errmsglen,
3177                 "Not all the packets could be written to the file"
3178                 " to which the capture was being saved\n"
3179                 "(\"%s\") because there is no space left on the file system\n"
3180                 "on which that file resides.",
3181                 fname);
3182     break;
3183
3184 #ifdef EDQUOT
3185   case EDQUOT:
3186     g_snprintf(errmsg, errmsglen,
3187                 "Not all the packets could be written to the file"
3188                 " to which the capture was being saved\n"
3189                 "(\"%s\") because you are too close to, or over,"
3190                 " your disk quota\n"
3191                 "on the file system on which that file resides.",
3192                 fname);
3193   break;
3194 #endif
3195
3196   case WTAP_ERR_CANT_CLOSE:
3197     g_snprintf(errmsg, errmsglen,
3198                 "The file to which the capture was being saved"
3199                 " couldn't be closed for some unknown reason.");
3200     break;
3201
3202   case WTAP_ERR_SHORT_WRITE:
3203     g_snprintf(errmsg, errmsglen,
3204                 "Not all the packets could be written to the file"
3205                 " to which the capture was being saved\n"
3206                 "(\"%s\").",
3207                 fname);
3208     break;
3209
3210   default:
3211     if (is_close) {
3212       g_snprintf(errmsg, errmsglen,
3213                 "The file to which the capture was being saved\n"
3214                 "(\"%s\") could not be closed: %s.",
3215                 fname, wtap_strerror(err));
3216     } else {
3217       g_snprintf(errmsg, errmsglen,
3218                 "An error occurred while writing to the file"
3219                 " to which the capture was being saved\n"
3220                 "(\"%s\"): %s.",
3221                 fname, wtap_strerror(err));
3222     }
3223     break;
3224   }
3225 }
3226
3227
3228 /* one packet was captured, process it */
3229 static void
3230 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
3231   const u_char *pd)
3232 {
3233   loop_data *ld = (loop_data *) (void *) user;
3234   int err;
3235
3236   /* We may be called multiple times from pcap_dispatch(); if we've set
3237      the "stop capturing" flag, ignore this packet, as we're not
3238      supposed to be saving any more packets. */
3239   if (!ld->go)
3240     return;
3241
3242   if (ld->pdh) {
3243     gboolean successful;
3244     /* We're supposed to write the packet to a file; do so.
3245        If this fails, set "ld->go" to FALSE, to stop the capture, and set
3246        "ld->err" to the error. */
3247     if (global_capture_opts.use_pcapng) {
3248       successful = libpcap_write_enhanced_packet_block(ld->pdh, phdr, 0, pd, &ld->bytes_written, &err);
3249     } else {
3250       successful = libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err);
3251     }
3252     if (!successful) {
3253       ld->go = FALSE;
3254       ld->err = err;
3255     } else {
3256       ld->packet_count++;
3257       /* if the user told us to stop after x packets, do we already have enough? */
3258       if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
3259       {
3260         ld->go = FALSE;
3261       }
3262     }
3263   }
3264 }
3265
3266
3267 /* And now our feature presentation... [ fade to music ] */
3268 int
3269 main(int argc, char *argv[])
3270 {
3271   int                  opt;
3272   gboolean             arg_error = FALSE;
3273
3274 #ifdef _WIN32
3275   WSADATA              wsaData;
3276 #else
3277   struct sigaction action, oldaction;
3278 #endif
3279
3280   gboolean             start_capture = TRUE;
3281   gboolean             stats_known;
3282   struct pcap_stat     stats;
3283   GLogLevelFlags       log_flags;
3284   gboolean             list_interfaces = FALSE;
3285   gboolean             list_link_layer_types = FALSE;
3286 #ifdef HAVE_BPF_IMAGE
3287   gboolean             print_bpf_code = FALSE;
3288 #endif
3289   gboolean             machine_readable = FALSE;
3290   gboolean             print_statistics = FALSE;
3291   int                  status, run_once_args = 0;
3292   gint                 i;
3293 #if defined(__APPLE__) && defined(__LP64__)
3294   struct utsname       osinfo;
3295 #endif
3296
3297 #ifdef HAVE_PCAP_REMOTE
3298 #define OPTSTRING_A "A:"
3299 #define OPTSTRING_r "r"
3300 #define OPTSTRING_u "u"
3301 #else
3302 #define OPTSTRING_A ""
3303 #define OPTSTRING_r ""
3304 #define OPTSTRING_u ""
3305 #endif
3306
3307 #ifdef HAVE_PCAP_SETSAMPLING
3308 #define OPTSTRING_m "m:"
3309 #else
3310 #define OPTSTRING_m ""
3311 #endif
3312
3313 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
3314 #define OPTSTRING_B "B:"
3315 #else
3316 #define OPTSTRING_B ""
3317 #endif  /* _WIN32 or HAVE_PCAP_CREATE */
3318
3319 #ifdef HAVE_PCAP_CREATE
3320 #define OPTSTRING_I "I"
3321 #else
3322 #define OPTSTRING_I ""
3323 #endif
3324
3325 #ifdef HAVE_BPF_IMAGE
3326 #define OPTSTRING_d "d"
3327 #else
3328 #define OPTSTRING_d ""
3329 #endif
3330
3331 #define OPTSTRING "a:" OPTSTRING_A "b:" OPTSTRING_B "c:" OPTSTRING_d "Df:hi:" OPTSTRING_I "L" OPTSTRING_m "Mnpq" OPTSTRING_r "Ss:" OPTSTRING_u "vw:y:Z:"
3332
3333 #ifdef DEBUG_CHILD_DUMPCAP
3334   if ((debug_log = ws_fopen("dumpcap_debug_log.tmp","w")) == NULL) {
3335           fprintf (stderr, "Unable to open debug log file !\n");
3336           exit (1);
3337   }
3338 #endif
3339
3340 #if defined(__APPLE__) && defined(__LP64__)
3341   /*
3342    * Is this Mac OS X 10.6.x, other than 10.6.2?  If so, we need a bug
3343    * workaround - timeouts less than 1 second don't work with libpcap
3344    * in 64-bit code.  (The bug was introduced in 10.6, fixed in 10.6.2,
3345    * and re-introduced in 10.6.3.  We don't know whether it'll be fixed
3346    * again in a later 10.6.x release; we'll assume that it'll be fixed
3347    * in any future major releases.)
3348    */
3349   if (uname(&osinfo) == 0) {
3350     /*
3351      * Mac OS X 10.x uses Darwin {x+4}.0.0.  Mac OS X 10.x.y uses Darwin
3352      * {x+4}.y.0 (except that 10.6.1 appears to have a uname version
3353      * number of 10.0.0, not 10.1.0 - go figure).
3354      */
3355     if (strncmp(osinfo.release, "10.", 3) == 0) {
3356       /*
3357        * OK, it's Snow Leopard - which version?
3358        */
3359       if (strcmp(osinfo.release, "10.2.0") != 0) {
3360         /* Not 10.6.2. */
3361         need_timeout_workaround = TRUE;
3362       }
3363     }
3364   }
3365 #endif
3366
3367   /*
3368    * Determine if dumpcap is being requested to run in a special
3369    * capture_child mode by going thru the command line args to see if
3370    * a -Z is present. (-Z is a hidden option).
3371    *
3372    * The primary result of running in capture_child mode is that
3373    * all messages sent out on stderr are in a special type/len/string
3374    * format to allow message processing by type.  These messages include
3375    * error messages if dumpcap fails to start the operation it was
3376    * requested to do, as well as various "status" messages which are sent
3377    * when an actual capture is in progress, and a "success" message sent
3378    * if dumpcap was requested to perform an operation other than a
3379    * capture.
3380    *
3381    * Capture_child mode would normally be requested by a parent process
3382    * which invokes dumpcap and obtains dumpcap stderr output via a pipe
3383    * to which dumpcap stderr has been redirected.  It might also have
3384    * another pipe to obtain dumpcap stdout output; for operations other
3385    * than a capture, that information is formatted specially for easier
3386    * parsing by the parent process.
3387    *
3388    * Capture_child mode needs to be determined immediately upon
3389    * startup so that any messages generated by dumpcap in this mode
3390    * (eg: during initialization) will be formatted properly.
3391    */
3392
3393   for (i=1; i<argc; i++) {
3394     if (strcmp("-Z", argv[i]) == 0) {
3395       capture_child = TRUE;
3396       machine_readable = TRUE;  /* request machine-readable output */
3397 #ifdef _WIN32
3398       /* set output pipe to binary mode, to avoid ugly text conversions */
3399       _setmode(2, O_BINARY);
3400 #endif
3401     }
3402   }
3403
3404   /* The default_log_handler will use stdout, which makes trouble in   */
3405   /* capture child mode, as it uses stdout for it's sync_pipe.         */
3406   /* So: the filtering is done in the console_log_handler and not here.*/
3407   /* We set the log handlers right up front to make sure that any log  */
3408   /* messages when running as child will be sent back to the parent    */
3409   /* with the correct format.                                          */
3410
3411   log_flags =
3412                     G_LOG_LEVEL_ERROR|
3413                     G_LOG_LEVEL_CRITICAL|
3414                     G_LOG_LEVEL_WARNING|
3415                     G_LOG_LEVEL_MESSAGE|
3416                     G_LOG_LEVEL_INFO|
3417                     G_LOG_LEVEL_DEBUG|
3418                     G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION;
3419
3420   g_log_set_handler(NULL,
3421                     log_flags,
3422                     console_log_handler, NULL /* user_data */);
3423   g_log_set_handler(LOG_DOMAIN_MAIN,
3424                     log_flags,
3425                     console_log_handler, NULL /* user_data */);
3426   g_log_set_handler(LOG_DOMAIN_CAPTURE,
3427                     log_flags,
3428                     console_log_handler, NULL /* user_data */);
3429   g_log_set_handler(LOG_DOMAIN_CAPTURE_CHILD,
3430                     log_flags,
3431                     console_log_handler, NULL /* user_data */);
3432
3433 #ifdef _WIN32
3434   /* Load wpcap if possible. Do this before collecting the run-time version information */
3435   load_wpcap();
3436
3437   /* ... and also load the packet.dll from wpcap */
3438   /* XXX - currently not required, may change later. */
3439   /*wpcap_packet_load();*/
3440
3441   /* Start windows sockets */
3442   WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
3443
3444   /* Set handler for Ctrl+C key */
3445   SetConsoleCtrlHandler(capture_cleanup_handler, TRUE);
3446
3447   /* Prepare to read from a pipe */
3448   if (!g_thread_supported ())
3449     g_thread_init (NULL);
3450   cap_pipe_pending_q = g_async_queue_new();
3451   cap_pipe_done_q = g_async_queue_new();
3452   cap_pipe_read_mtx = g_mutex_new();
3453
3454 #else
3455   /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
3456      and exit. */
3457   action.sa_handler = capture_cleanup_handler;
3458   /*
3459    * Arrange that system calls not get restarted, because when
3460    * our signal handler returns we don't want to restart
3461    * a call that was waiting for packets to arrive.
3462    */
3463   action.sa_flags = 0;
3464   sigemptyset(&action.sa_mask);
3465   sigaction(SIGTERM, &action, NULL);
3466   sigaction(SIGINT, &action, NULL);
3467   sigaction(SIGPIPE, &action, NULL);
3468   sigaction(SIGHUP, NULL, &oldaction);
3469   if (oldaction.sa_handler == SIG_DFL)
3470     sigaction(SIGHUP, &action, NULL);
3471
3472 #ifdef SIGINFO
3473   /* Catch SIGINFO and, if we get it and we're capturing in
3474      quiet mode, report the number of packets we've captured. */
3475   action.sa_handler = report_counts_siginfo;
3476   action.sa_flags = SA_RESTART;
3477   sigemptyset(&action.sa_mask);
3478   sigaction(SIGINFO, &action, NULL);
3479 #endif /* SIGINFO */
3480 #endif  /* _WIN32 */
3481
3482   /* ----------------------------------------------------------------- */
3483   /* Privilege and capability handling                                 */
3484   /* Cases:                                                            */
3485   /* 1. Running not as root or suid root; no special capabilities.     */
3486   /*    Action: none                                                   */
3487   /*                                                                   */
3488   /* 2. Running logged in as root (euid=0; ruid=0); Not using libcap.  */
3489   /*    Action: none                                                   */
3490   /*                                                                   */
3491   /* 3. Running logged in as root (euid=0; ruid=0). Using libcap.      */
3492   /*    Action:                                                        */
3493   /*      - Near start of program: Enable NET_RAW and NET_ADMIN        */
3494   /*        capabilities; Drop all other capabilities;                 */
3495   /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
3496   /*        else: after  pcap_open_live() in capture_loop_open_input() */
3497   /*         drop all capabilities (NET_RAW and NET_ADMIN);            */
3498   /*         (Note: this means that the process, although logged in    */
3499   /*          as root, does not have various permissions such as the   */
3500   /*          ability to bypass file access permissions).              */
3501   /*      XXX: Should we just leave capabilities alone in this case    */
3502   /*          so that user gets expected effect that root can do       */
3503   /*          anything ??                                              */
3504   /*                                                                   */
3505   /* 4. Running as suid root (euid=0, ruid=n); Not using libcap.       */
3506   /*    Action:                                                        */
3507   /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
3508   /*        else: after  pcap_open_live() in capture_loop_open_input() */
3509   /*         drop suid root (set euid=ruid).(ie: keep suid until after */
3510   /*         pcap_open_live).                                          */
3511   /*                                                                   */
3512   /* 5. Running as suid root (euid=0, ruid=n); Using libcap.           */
3513   /*    Action:                                                        */
3514   /*      - Near start of program: Enable NET_RAW and NET_ADMIN        */
3515   /*        capabilities; Drop all other capabilities;                 */
3516   /*        Drop suid privileges (euid=ruid);                          */
3517   /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
3518   /*        else: after  pcap_open_live() in capture_loop_open_input() */
3519   /*         drop all capabilities (NET_RAW and NET_ADMIN).            */
3520   /*                                                                   */
3521   /*      XXX: For some Linux versions/distros with capabilities       */
3522   /*        a 'normal' process with any capabilities cannot be         */
3523   /*        'killed' (signaled) from another (same uid) non-privileged */
3524   /*        process.                                                   */
3525   /*        For example: If (non-suid) Wireshark forks a               */
3526   /*        child suid dumpcap which acts as described here (case 5),  */
3527   /*        Wireshark will be unable to kill (signal) the child        */
3528   /*        dumpcap process until the capabilities have been dropped   */
3529   /*        (after pcap_open_live()).                                  */
3530   /*        This behaviour will apparently be changed in the kernel    */
3531   /*        to allow the kill (signal) in this case.                   */
3532   /*        See the following for details:                             */
3533   /*           http://www.mail-archive.com/  [wrapped]                 */
3534   /*             linux-security-module@vger.kernel.org/msg02913.html   */
3535   /*                                                                   */
3536   /*        It is therefore conceivable that if dumpcap somehow hangs  */
3537   /*        in pcap_open_live or before that wireshark will not        */
3538   /*        be able to stop dumpcap using a signal (INT, TERM, etc).  */
3539   /*        In this case, exiting wireshark will kill the child        */
3540   /*        dumpcap process.                                           */
3541   /*                                                                   */
3542   /* 6. Not root or suid root; Running with NET_RAW & NET_ADMIN        */
3543   /*     capabilities; Using libcap.  Note: capset cmd (which see)     */
3544   /*     used to assign capabilities to file.                          */
3545   /*    Action:                                                        */
3546   /*      - If not -w  (ie: doing -S or -D, etc) run to completion;    */
3547   /*        else: after  pcap_open_live() in capture_loop_open_input() */
3548   /*         drop all capabilities (NET_RAW and NET_ADMIN)             */
3549   /*                                                                   */
3550   /* ToDo: -S (stats) should drop privileges/capabilities when no      */
3551   /*       longer required (similar to capture).                        */
3552   /*                                                                   */
3553   /* ----------------------------------------------------------------- */
3554
3555   get_credential_info();
3556
3557 #ifdef HAVE_LIBCAP
3558   /* If 'started with special privileges' (and using libcap)  */
3559   /*   Set to keep only NET_RAW and NET_ADMIN capabilities;   */
3560   /*   Set euid/egid = ruid/rgid to remove suid privileges    */
3561   relinquish_privs_except_capture();
3562 #endif
3563
3564   /* Set the initial values in the capture options. This might be overwritten
3565      by the command line parameters. */
3566   capture_opts_init(&global_capture_opts, NULL);
3567
3568   /* Default to capturing the entire packet. */
3569   global_capture_opts.snaplen             = WTAP_MAX_PACKET_SIZE;
3570
3571   /* We always save to a file - if no file was specified, we save to a
3572      temporary file. */
3573   global_capture_opts.saving_to_file      = TRUE;
3574   global_capture_opts.has_ring_num_files  = TRUE;
3575
3576   /* Now get our args */
3577   while ((opt = getopt(argc, argv, OPTSTRING)) != -1) {
3578     switch (opt) {
3579       case 'h':        /* Print help and exit */
3580         print_usage(TRUE);
3581         exit_main(0);
3582         break;
3583       case 'v':        /* Show version and exit */
3584       {
3585         GString             *comp_info_str;
3586         GString             *runtime_info_str;
3587         /* Assemble the compile-time version information string */
3588         comp_info_str = g_string_new("Compiled ");
3589         get_compiled_version_info(comp_info_str, NULL);
3590
3591         /* Assemble the run-time version information string */
3592         runtime_info_str = g_string_new("Running ");
3593         get_runtime_version_info(runtime_info_str, NULL);
3594         show_version(comp_info_str, runtime_info_str);
3595         g_string_free(comp_info_str, TRUE);
3596         g_string_free(runtime_info_str, TRUE);
3597         exit_main(0);
3598         break;
3599       }
3600       /*** capture option specific ***/
3601       case 'a':        /* autostop criteria */
3602       case 'b':        /* Ringbuffer option */
3603       case 'c':        /* Capture x packets */
3604       case 'f':        /* capture filter */
3605       case 'i':        /* Use interface x */
3606       case 'n':        /* Use pcapng format */
3607       case 'p':        /* Don't capture in promiscuous mode */
3608       case 's':        /* Set the snapshot (capture) length */
3609       case 'w':        /* Write to capture file x */
3610       case 'y':        /* Set the pcap data link type */
3611 #ifdef HAVE_PCAP_REMOTE
3612       case 'u':        /* Use UDP for data transfer */
3613       case 'r':        /* Capture own RPCAP traffic too */
3614       case 'A':        /* Authentication */
3615 #endif
3616 #ifdef HAVE_PCAP_SETSAMPLING
3617       case 'm':        /* Sampling */
3618 #endif
3619 #if defined(_WIN32) || defined(HAVE_PCAP_CREATE)
3620       case 'B':        /* Buffer size */
3621 #endif /* _WIN32 or HAVE_PCAP_CREATE */
3622 #ifdef HAVE_PCAP_CREATE
3623       case 'I':        /* Monitor mode */
3624 #endif
3625         status = capture_opts_add_opt(&global_capture_opts, opt, optarg, &start_capture);
3626         if(status != 0) {
3627           exit_main(status);
3628         }
3629         break;
3630       /*** hidden option: Wireshark child mode (using binary output messages) ***/
3631       case 'Z':
3632         capture_child = TRUE;
3633 #ifdef _WIN32
3634         /* set output pipe to binary mode, to avoid ugly text conversions */
3635         _setmode(2, O_BINARY);
3636         /*
3637          * optarg = the control ID, aka the PPID, currently used for the
3638          * signal pipe name.
3639          */
3640         if (strcmp(optarg, SIGNAL_PIPE_CTRL_ID_NONE) != 0) {
3641           sig_pipe_name = g_strdup_printf(SIGNAL_PIPE_FORMAT, optarg);
3642           sig_pipe_handle = CreateFile(utf_8to16(sig_pipe_name),
3643               GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
3644
3645           if (sig_pipe_handle == INVALID_HANDLE_VALUE) {
3646             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
3647                   "Signal pipe: Unable to open %s.  Dead parent?",
3648                   sig_pipe_name);
3649             exit_main(1);
3650           }
3651         }
3652 #endif
3653         break;
3654
3655       case 'q':        /* Quiet */
3656         quiet = TRUE;
3657         break;
3658
3659       /*** all non capture option specific ***/
3660       case 'D':        /* Print a list of capture devices and exit */
3661         list_interfaces = TRUE;
3662         run_once_args++;
3663         break;
3664       case 'L':        /* Print list of link-layer types and exit */
3665         list_link_layer_types = TRUE;
3666         run_once_args++;
3667         break;
3668 #ifdef HAVE_BPF_IMAGE
3669       case 'd':        /* Print BPF code for capture filter and exit */
3670         print_bpf_code = TRUE;
3671         run_once_args++;
3672         break;
3673 #endif
3674       case 'S':        /* Print interface statistics once a second */
3675         print_statistics = TRUE;
3676         run_once_args++;
3677         break;
3678       case 'M':        /* For -D, -L, and -S, print machine-readable output */
3679         machine_readable = TRUE;
3680         break;
3681       default:
3682       case '?':        /* Bad flag - print usage message */
3683         cmdarg_err("Invalid Option: %s", argv[optind-1]);
3684         arg_error = TRUE;
3685         break;
3686     }
3687   }
3688   argc -= optind;
3689   argv += optind;
3690   if (argc >= 1) {
3691     /* user specified file name as regular command-line argument */
3692     /* XXX - use it as the capture file name (or something else)? */
3693     argc--;
3694     argv++;
3695   }
3696
3697   if (argc != 0) {
3698     /*
3699      * Extra command line arguments were specified; complain.
3700      * XXX - interpret as capture filter, as tcpdump and tshark do?
3701      */
3702     cmdarg_err("Invalid argument: %s", argv[0]);
3703     arg_error = TRUE;
3704   }
3705
3706   if (arg_error) {
3707     print_usage(FALSE);
3708     exit_main(1);
3709   }
3710
3711   if (run_once_args > 1) {
3712     cmdarg_err("Only one of -D, -L, or -S may be supplied.");
3713     exit_main(1);
3714   } else if (run_once_args == 1) {
3715     /* We're supposed to print some information, rather than
3716        to capture traffic; did they specify a ring buffer option? */
3717     if (global_capture_opts.multi_files_on) {
3718       cmdarg_err("Ring buffer requested, but a capture isn't being done.");
3719       exit_main(1);
3720     }
3721   } else {
3722     /* We're supposed to capture traffic; was the ring buffer option
3723        specified and, if so, does it make sense? */
3724     if (global_capture_opts.multi_files_on) {
3725       /* Ring buffer works only under certain conditions:
3726          a) ring buffer does not work with temporary files;
3727          b) it makes no sense to enable the ring buffer if the maximum
3728             file size is set to "infinite". */
3729       if (global_capture_opts.save_file == NULL) {
3730         cmdarg_err("Ring buffer requested, but capture isn't being saved to a permanent file.");
3731         global_capture_opts.multi_files_on = FALSE;
3732       }
3733       if (!global_capture_opts.has_autostop_filesize && !global_capture_opts.has_file_duration) {
3734         cmdarg_err("Ring buffer requested, but no maximum capture file size or duration were specified.");
3735 /* XXX - this must be redesigned as the conditions changed */
3736 /*      global_capture_opts.multi_files_on = FALSE;*/
3737       }
3738     }
3739   }
3740
3741   /*
3742    * "-D" requires no interface to be selected; it's supposed to list
3743    * all interfaces.
3744    */
3745   if (list_interfaces) {
3746     /* Get the list of interfaces */
3747     GList       *if_list;
3748     int         err;
3749     gchar       *err_str;
3750
3751     if_list = capture_interface_list(&err, &err_str);
3752     if (if_list == NULL) {
3753         switch (err) {
3754         case CANT_GET_INTERFACE_LIST:
3755             cmdarg_err("%s", err_str);
3756             g_free(err_str);
3757             exit_main(2);
3758             break;
3759
3760         case NO_INTERFACES_FOUND:
3761             /*
3762              * If we're being run by another program, just give them
3763              * an empty list of interfaces, don't report this as
3764              * an error; that lets them decide whether to report
3765              * this as an error or not.
3766              */
3767             if (!machine_readable) {
3768                 cmdarg_err("There are no interfaces on which a capture can be done");
3769                 exit_main(2);
3770             }
3771             break;
3772         }
3773     }
3774
3775     if (machine_readable)      /* tab-separated values to stdout */
3776       print_machine_readable_interfaces(if_list);
3777     else
3778       capture_opts_print_interfaces(if_list);
3779     free_interface_list(if_list);
3780     exit_main(0);
3781   }
3782
3783   /*
3784    * "-S" requires no interface to be selected; it gives statistics
3785    * for all interfaces.
3786    */
3787   if (print_statistics) {
3788     status = print_statistics_loop(machine_readable);
3789     exit_main(status);
3790   }
3791
3792   /*
3793    * "-L", "-d", and capturing act on a particular interface, so we have to
3794    * have an interface; if none was specified, pick a default.
3795    */
3796   if (capture_opts_trim_iface(&global_capture_opts, NULL) == FALSE) {
3797     /* cmdarg_err() already called .... */
3798     exit_main(1);
3799   }
3800
3801   /* Let the user know what interface was chosen. */
3802   /* get_interface_descriptive_name() is not available! */
3803   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Interface: %s\n", global_capture_opts.iface);
3804
3805   if (list_link_layer_types) {
3806     /* Get the list of link-layer types for the capture device. */
3807     if_capabilities_t *caps;
3808     gchar *err_str;
3809
3810     caps = get_if_capabilities(global_capture_opts.iface,
3811                                global_capture_opts.monitor_mode, &err_str);
3812     if (caps == NULL) {
3813       cmdarg_err("The capabilities of the capture device \"%s\" could not be obtained (%s).\n"
3814        "Please check to make sure you have sufficient permissions, and that\n"
3815        "you have the proper interface or pipe specified.", global_capture_opts.iface, err_str);
3816       g_free(err_str);
3817       exit_main(2);
3818     }
3819     if (caps->data_link_types == NULL) {
3820       cmdarg_err("The capture device \"%s\" has no data link types.", global_capture_opts.iface);
3821       exit_main(2);
3822     }
3823     if (machine_readable)      /* tab-separated values to stdout */
3824       print_machine_readable_if_capabilities(caps);
3825     else
3826       capture_opts_print_if_capabilities(caps,
3827                                          global_capture_opts.monitor_mode);
3828     free_if_capabilities(caps);
3829     exit_main(0);
3830   }
3831
3832   /* We're supposed to do a capture, or print the BPF code for a filter.
3833      Process the snapshot length, as that affects the generated BPF code. */
3834   capture_opts_trim_snaplen(&global_capture_opts, MIN_PACKET_SIZE);
3835
3836 #ifdef HAVE_BPF_IMAGE
3837   if (print_bpf_code) {
3838     show_filter_code(&global_capture_opts);
3839     exit_main(0);
3840   }
3841 #endif
3842
3843   /* We're supposed to do a capture.  Process the ring buffer arguments. */
3844   capture_opts_trim_ring_num_files(&global_capture_opts);
3845
3846   /* Now start the capture. */
3847
3848   if(capture_loop_start(&global_capture_opts, &stats_known, &stats) == TRUE) {
3849     /* capture ok */
3850     exit_main(0);
3851   } else {
3852     /* capture failed */
3853     exit_main(1);
3854   }
3855 }
3856
3857
3858 static void
3859 console_log_handler(const char *log_domain, GLogLevelFlags log_level,
3860                     const char *message, gpointer user_data _U_)
3861 {
3862   time_t curr;
3863   struct tm  *today;
3864   const char *level;
3865   gchar      *msg;
3866
3867   /* ignore log message, if log_level isn't interesting */
3868   if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3869 #if !defined(DEBUG_DUMPCAP) && !defined(DEBUG_CHILD_DUMPCAP)
3870     return;
3871 #endif
3872   }
3873
3874   /* create a "timestamp" */
3875   time(&curr);
3876   today = localtime(&curr);
3877
3878   switch(log_level & G_LOG_LEVEL_MASK) {
3879   case G_LOG_LEVEL_ERROR:
3880     level = "Err ";
3881     break;
3882   case G_LOG_LEVEL_CRITICAL:
3883     level = "Crit";
3884     break;
3885   case G_LOG_LEVEL_WARNING:
3886     level = "Warn";
3887     break;
3888   case G_LOG_LEVEL_MESSAGE:
3889     level = "Msg ";
3890     break;
3891   case G_LOG_LEVEL_INFO:
3892     level = "Info";
3893     break;
3894   case G_LOG_LEVEL_DEBUG:
3895     level = "Dbg ";
3896     break;
3897   default:
3898     fprintf(stderr, "unknown log_level %u\n", log_level);
3899     level = NULL;
3900     g_assert_not_reached();
3901   }
3902
3903   /* Generate the output message                                  */
3904   if(log_level & G_LOG_LEVEL_MESSAGE) {
3905     /* normal user messages without additional infos */
3906     msg =  g_strdup_printf("%s\n", message);
3907   } else {
3908     /* info/debug messages with additional infos */
3909     msg = g_strdup_printf("%02u:%02u:%02u %8s %s %s\n",
3910             today->tm_hour, today->tm_min, today->tm_sec,
3911             log_domain != NULL ? log_domain : "",
3912             level, message);
3913   }
3914
3915   /* DEBUG & INFO msgs (if we're debugging today)                 */
3916 #if defined(DEBUG_DUMPCAP) || defined(DEBUG_CHILD_DUMPCAP)
3917   if( !(log_level & G_LOG_LEVEL_MASK & ~(G_LOG_LEVEL_DEBUG|G_LOG_LEVEL_INFO))) {
3918 #ifdef DEBUG_DUMPCAP
3919     fprintf(stderr, "%s", msg);
3920     fflush(stderr);
3921 #endif
3922 #ifdef DEBUG_CHILD_DUMPCAP
3923     fprintf(debug_log, "%s", msg);
3924     fflush(debug_log);
3925 #endif
3926     g_free(msg);
3927     return;
3928   }
3929 #endif
3930
3931   /* ERROR, CRITICAL, WARNING, MESSAGE messages goto stderr or    */
3932   /*  to parent especially formatted if dumpcap running as child. */
3933   if (capture_child) {
3934     sync_pipe_errmsg_to_parent(2, msg, "");
3935   } else {
3936     fprintf(stderr, "%s", msg);
3937     fflush(stderr);
3938   }
3939   g_free(msg);
3940 }
3941
3942
3943 /****************************************************************************************************************/
3944 /* indication report routines */
3945
3946
3947 static void
3948 report_packet_count(int packet_count)
3949 {
3950     char tmp[SP_DECISIZE+1+1];
3951     static int count = 0;
3952
3953     if(capture_child) {
3954         g_snprintf(tmp, sizeof(tmp), "%d", packet_count);
3955         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets: %s", tmp);
3956         pipe_write_block(2, SP_PACKET_COUNT, tmp);
3957     } else {
3958         count += packet_count;
3959         fprintf(stderr, "\rPackets: %u ", count);
3960         /* stderr could be line buffered */
3961         fflush(stderr);
3962     }
3963 }
3964
3965 void
3966 report_new_capture_file(const char *filename)
3967 {
3968     if(capture_child) {
3969         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "File: %s", filename);
3970         pipe_write_block(2, SP_FILE, filename);
3971     } else {
3972 #ifdef SIGINFO
3973         /*
3974          * Prevent a SIGINFO handler from writing to the standard error
3975          * while we're doing so; instead, have it just set a flag telling
3976          * us to print that information when we're done.
3977          */
3978         infodelay = TRUE;
3979 #endif /* SIGINFO */
3980         fprintf(stderr, "File: %s\n", filename);
3981         /* stderr could be line buffered */
3982         fflush(stderr);
3983
3984 #ifdef SIGINFO
3985         /*
3986          * Allow SIGINFO handlers to write.
3987          */
3988         infodelay = FALSE;
3989
3990         /*
3991          * If a SIGINFO handler asked us to write out capture counts, do so.
3992          */
3993         if (infoprint)
3994           report_counts();
3995 #endif /* SIGINFO */
3996     }
3997 }
3998
3999 void
4000 report_cfilter_error(const char *cfilter, const char *errmsg)
4001 {
4002     if (capture_child) {
4003         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Capture filter error: %s", errmsg);
4004         pipe_write_block(2, SP_BAD_FILTER, errmsg);
4005     } else {
4006         fprintf(stderr,
4007           "Invalid capture filter: \"%s\"!\n"
4008           "\n"
4009           "That string isn't a valid capture filter (%s).\n"
4010           "See the User's Guide for a description of the capture filter syntax.\n",
4011           cfilter, errmsg);
4012     }
4013 }
4014
4015 void
4016 report_capture_error(const char *error_msg, const char *secondary_error_msg)
4017 {
4018     if(capture_child) {
4019         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4020             "Primary Error: %s", error_msg);
4021         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4022             "Secondary Error: %s", secondary_error_msg);
4023         sync_pipe_errmsg_to_parent(2, error_msg, secondary_error_msg);
4024     } else {
4025         fprintf(stderr, "%s\n", error_msg);
4026         if (secondary_error_msg[0] != '\0')
4027           fprintf(stderr, "%s\n", secondary_error_msg);
4028     }
4029 }
4030
4031 void
4032 report_packet_drops(guint32 drops)
4033 {
4034     char tmp[SP_DECISIZE+1+1];
4035
4036     g_snprintf(tmp, sizeof(tmp), "%u", drops);
4037
4038     if(capture_child) {
4039         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "Packets dropped: %s", tmp);
4040         pipe_write_block(2, SP_DROPS, tmp);
4041     } else {
4042         fprintf(stderr, "Packets dropped: %s\n", tmp);
4043         /* stderr could be line buffered */
4044         fflush(stderr);
4045     }
4046 }
4047
4048
4049 /****************************************************************************************************************/
4050 /* signal_pipe handling */
4051
4052
4053 #ifdef _WIN32
4054 static gboolean
4055 signal_pipe_check_running(void)
4056 {
4057     /* any news from our parent? -> just stop the capture */
4058     DWORD avail = 0;
4059     gboolean result;
4060
4061     /* if we are running standalone, no check required */
4062     if(!capture_child) {
4063         return TRUE;
4064     }
4065
4066     if(!sig_pipe_name || !sig_pipe_handle) {
4067         /* This shouldn't happen */
4068         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4069             "Signal pipe: No name or handle");
4070         return FALSE;
4071     }
4072
4073     /*
4074      * XXX - We should have the process ID of the parent (from the "-Z" flag)
4075      * at this point.  Should we check to see if the parent is still alive,
4076      * e.g. by using OpenProcess?
4077      */
4078
4079     result = PeekNamedPipe(sig_pipe_handle, NULL, 0, NULL, &avail, NULL);
4080
4081     if(!result || avail > 0) {
4082         /* peek failed or some bytes really available */
4083         /* (if not piping from stdin this would fail) */
4084         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO,
4085             "Signal pipe: Stop capture: %s", sig_pipe_name);
4086         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG,
4087             "Signal pipe: %s (%p) result: %u avail: %u", sig_pipe_name,
4088             sig_pipe_handle, result, avail);
4089         return FALSE;
4090     } else {
4091         /* pipe ok and no bytes available */
4092         return TRUE;
4093     }
4094 }
4095 #endif
4096
4097 /*
4098  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
4099  *
4100  * Local variables:
4101  * c-basic-offset: 4
4102  * tab-width: 8
4103  * indent-tabs-mode: nil
4104  * End:
4105  *
4106  * vi: set shiftwidth=4 tabstop=8 expandtab
4107  * :indentSize=4:tabSize=8:noTabs=true:
4108  */