At least on Tiger, multiple definitions of an external don't work.
[metze/wireshark/wip.git] / capture_loop.c
1 /* capture_loop.c
2  * The actual capturing loop, getting packets and storing it
3  *
4  * $Id$
5  *
6  * Ethereal - Network traffic analyzer
7  * By Gerald Combs <gerald@ethereal.com>
8  * Copyright 1998 Gerald Combs
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
23  */
24
25
26 /** @file
27  *  
28  * Capture loop (internal interface).
29  *
30  * It will open the input and output files, capture the packets, 
31  * change ringbuffer output files while capturing and close all files again.
32  * 
33  * The input file can be a network interface or capture pipe (unix only).
34  * The output file can be a single or a ringbuffer file handled by wiretap.
35  *
36  */
37
38 #ifdef HAVE_CONFIG_H
39 # include "config.h"
40 #endif
41
42 #ifdef HAVE_LIBPCAP
43
44 #include <string.h>
45
46 #ifdef HAVE_FCNTL_H
47 #include <fcntl.h>
48 #endif
49
50 #ifdef HAVE_UNISTD_H
51 #include <unistd.h>
52 #endif
53
54 #ifdef HAVE_SYS_TYPES_H
55 # include <sys/types.h>
56 #endif
57
58 #ifdef HAVE_SYS_STAT_H
59 # include <sys/stat.h>
60 #endif
61
62 #include <signal.h>
63 #include <errno.h>
64
65 #include <pcap.h>
66
67 #include <glib.h>
68
69 #include <epan/packet.h>
70 #include "capture.h"
71 #include "capture_sync.h"
72 #include "pcap-util.h"
73
74 #include "simple_dialog.h"
75 #include "conditions.h"
76 #include "capture_stop_conditions.h"
77 #include "ringbuffer.h"
78
79 #include "wiretap/libpcap.h"
80 #include "wiretap/wtap.h"
81 #include "wiretap/wtap-capture.h"
82
83 #include <epan/prefs.h>
84 /* XXX - try to remove this later */
85 #include "ui_util.h"
86 /* XXX - try to remove this later */
87 #include "util.h"
88 #include "alert_box.h"
89 #include "log.h"
90
91
92 #include <epan/dissectors/packet-ap1394.h>
93 #include <epan/dissectors/packet-atalk.h>
94 #include <epan/dissectors/packet-atm.h>
95 #include <epan/dissectors/packet-clip.h>
96 #include <epan/dissectors/packet-eth.h>
97 #include <epan/dissectors/packet-fddi.h>
98 #include <epan/dissectors/packet-fr.h>
99 #include <epan/dissectors/packet-null.h>
100 #include <epan/dissectors/packet-ppp.h>
101 #include <epan/dissectors/packet-raw.h>
102 #include <epan/dissectors/packet-sll.h>
103 #include <epan/dissectors/packet-tr.h>
104 #include <epan/dissectors/packet-ieee80211.h>
105 #include <epan/dissectors/packet-chdlc.h>
106 #include <epan/dissectors/packet-prism.h>
107 #include <epan/dissectors/packet-ipfc.h>
108 #include <epan/dissectors/packet-arcnet.h>
109
110 /* Win32 needs the O_BINARY flag for open() */
111 #ifndef O_BINARY
112 #define O_BINARY        0
113 #endif
114
115
116
117 /*
118  * We don't want to do a "select()" on the pcap_t's file descriptor on
119  * BSD (because "select()" doesn't work correctly on BPF devices on at
120  * least some releases of some flavors of BSD), and we don't want to do
121  * it on Windows (because "select()" is something for sockets, not for
122  * arbitrary handles).  (Note that "Windows" here includes Cygwin;
123  * even in its pretend-it's-UNIX environment, we're using WinPcap, not
124  * a UNIX libpcap.)
125  *
126  * We *do* want to do it on other platforms, as, on other platforms (with
127  * the possible exception of Ultrix and Digital UNIX), the read timeout
128  * doesn't expire if no packets have arrived, so a "pcap_dispatch()" call
129  * will block until packets arrive, causing the UI to hang.
130  *
131  * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
132  * want to include it if it's not present on this platform, however.
133  */
134 #if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
135     !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
136     !defined(__CYGWIN__)
137 # define MUST_DO_SELECT
138 #endif
139
140
141 typedef struct _loop_data {
142   /* common */
143   gboolean       go;                    /* TRUE as long as we're supposed to keep capturing */
144   int            err;                   /* if non-zero, error seen while capturing */
145   gint           packets_max;           /* Number of packets we're supposed to capture - 0 means infinite */
146   gint           packets_sync_pipe;     /* packets not already send out to the sync_pipe */
147   packet_counts  counts;                /* several packet type counters */
148
149   /* pcap "input file" */
150   pcap_t        *pcap_h;                /* pcap handle */
151   gboolean       pcap_err;              /* TRUE if error from pcap */
152 #ifdef MUST_DO_SELECT
153   int            pcap_fd;               /* pcap file descriptor */
154 #endif
155
156   /* capture pipe (unix only "input file") */
157   gboolean       from_cap_pipe;         /* TRUE if we are capturing data from a capture pipe */
158 #ifndef _WIN32
159   struct pcap_hdr cap_pipe_hdr;
160   struct pcaprec_modified_hdr cap_pipe_rechdr;
161   int            cap_pipe_fd;           /* the file descriptor of the capture pipe */
162   gboolean       cap_pipe_modified;     /* TRUE if data in the pipe uses modified pcap headers */
163   gboolean       cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
164   unsigned int   cap_pipe_bytes_to_read;/* Used by cap_pipe_dispatch */
165   unsigned int   cap_pipe_bytes_read;   /* Used by cap_pipe_dispatch */
166   enum {
167          STATE_EXPECT_REC_HDR,
168          STATE_READ_REC_HDR,
169          STATE_EXPECT_DATA,
170          STATE_READ_DATA
171        } cap_pipe_state;
172
173   enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
174 #endif
175
176   /* wiretap (output file) */
177   wtap_dumper   *wtap_pdh;
178   gint           wtap_linktype;
179
180 } loop_data;
181
182
183 /*
184  * Timeout, in milliseconds, for reads from the stream of captured packets.
185  */
186 #define CAP_READ_TIMEOUT        250
187
188 static void capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
189   const u_char *pd);
190 static void capture_loop_popup_errmsg(capture_options *capture_opts, const char *errmsg);
191 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
192                           int err, gboolean is_close);
193
194
195
196 #ifndef _WIN32
197 /* Take care of byte order in the libpcap headers read from pipes.
198  * (function taken from wiretap/libpcap.c) */
199 static void
200 cap_pipe_adjust_header(loop_data *ld, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
201 {
202   if (ld->cap_pipe_byte_swapped) {
203     /* Byte-swap the record header fields. */
204     rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
205     rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
206     rechdr->incl_len = BSWAP32(rechdr->incl_len);
207     rechdr->orig_len = BSWAP32(rechdr->orig_len);
208   }
209
210   /* In file format version 2.3, the "incl_len" and "orig_len" fields were
211      swapped, in order to match the BPF header layout.
212
213      Unfortunately, some files were, according to a comment in the "libpcap"
214      source, written with version 2.3 in their headers but without the
215      interchanged fields, so if "incl_len" is greater than "orig_len" - which
216      would make no sense - we assume that we need to swap them.  */
217   if (hdr->version_major == 2 &&
218       (hdr->version_minor < 3 ||
219        (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
220     guint32 temp;
221
222     temp = rechdr->orig_len;
223     rechdr->orig_len = rechdr->incl_len;
224     rechdr->incl_len = temp;
225   }
226 }
227
228 /* Mimic pcap_open_live() for pipe captures
229  * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
230  * header.
231  * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
232  * because we can't seek on pipes (see wiretap/libpcap.c for details) */
233 static int
234 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
235                  char *errmsg, int errmsgl)
236 {
237   struct stat pipe_stat;
238   int         fd;
239   guint32     magic;
240   int         b, sel_ret;
241   unsigned int bytes_read;
242   fd_set      rfds;
243   struct timeval timeout;
244
245
246   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
247
248   /*
249    * XXX Ethereal blocks until we return
250    */
251   if (strcmp(pipename, "-") == 0)
252     fd = 0; /* read from stdin */
253   else {
254     if (stat(pipename, &pipe_stat) < 0) {
255       if (errno == ENOENT || errno == ENOTDIR)
256         ld->cap_pipe_err = PIPNEXIST;
257       else {
258         g_snprintf(errmsg, errmsgl,
259           "The capture session could not be initiated "
260           "due to error on pipe: %s", strerror(errno));
261         ld->cap_pipe_err = PIPERR;
262       }
263       return -1;
264     }
265     if (! S_ISFIFO(pipe_stat.st_mode)) {
266       if (S_ISCHR(pipe_stat.st_mode)) {
267         /*
268          * Assume the user specified an interface on a system where
269          * interfaces are in /dev.  Pretend we haven't seen it.
270          */
271          ld->cap_pipe_err = PIPNEXIST;
272       } else {
273         g_snprintf(errmsg, errmsgl,
274             "The capture session could not be initiated because\n"
275             "\"%s\" is neither an interface nor a pipe", pipename);
276         ld->cap_pipe_err = PIPERR;
277       }
278       return -1;
279     }
280     fd = open(pipename, O_RDONLY | O_NONBLOCK);
281     if (fd == -1) {
282       g_snprintf(errmsg, errmsgl,
283           "The capture session could not be initiated "
284           "due to error on pipe open: %s", strerror(errno));
285       ld->cap_pipe_err = PIPERR;
286       return -1;
287     }
288   }
289
290   ld->from_cap_pipe = TRUE;
291
292   /* read the pcap header */
293   FD_ZERO(&rfds);
294   bytes_read = 0;
295   while (bytes_read < sizeof magic) {
296     FD_SET(fd, &rfds);
297     timeout.tv_sec = 0;
298     timeout.tv_usec = CAP_READ_TIMEOUT*1000;
299     sel_ret = select(fd+1, &rfds, NULL, NULL, &timeout);
300     if (sel_ret < 0) {
301       g_snprintf(errmsg, errmsgl,
302         "Unexpected error from select: %s", strerror(errno));
303       goto error;
304     } else if (sel_ret > 0) {
305       b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
306       if (b <= 0) {
307         if (b == 0)
308           g_snprintf(errmsg, errmsgl, "End of file on pipe during open");
309         else
310           g_snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
311             strerror(errno));
312         goto error;
313       }
314       bytes_read += b;
315     }
316   }
317
318   switch (magic) {
319   case PCAP_MAGIC:
320     /* Host that wrote it has our byte order, and was running
321        a program using either standard or ss990417 libpcap. */
322     ld->cap_pipe_byte_swapped = FALSE;
323     ld->cap_pipe_modified = FALSE;
324     break;
325   case PCAP_MODIFIED_MAGIC:
326     /* Host that wrote it has our byte order, but was running
327        a program using either ss990915 or ss991029 libpcap. */
328     ld->cap_pipe_byte_swapped = FALSE;
329     ld->cap_pipe_modified = TRUE;
330     break;
331   case PCAP_SWAPPED_MAGIC:
332     /* Host that wrote it has a byte order opposite to ours,
333        and was running a program using either standard or
334        ss990417 libpcap. */
335     ld->cap_pipe_byte_swapped = TRUE;
336     ld->cap_pipe_modified = FALSE;
337     break;
338   case PCAP_SWAPPED_MODIFIED_MAGIC:
339     /* Host that wrote it out has a byte order opposite to
340        ours, and was running a program using either ss990915
341        or ss991029 libpcap. */
342     ld->cap_pipe_byte_swapped = TRUE;
343     ld->cap_pipe_modified = TRUE;
344     break;
345   default:
346     /* Not a "libpcap" type we know about. */
347     g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
348     goto error;
349   }
350
351   /* Read the rest of the header */
352   bytes_read = 0;
353   while (bytes_read < sizeof(struct pcap_hdr)) {
354     FD_SET(fd, &rfds);
355     timeout.tv_sec = 0;
356     timeout.tv_usec = CAP_READ_TIMEOUT*1000;
357     sel_ret = select(fd+1, &rfds, NULL, NULL, &timeout);
358     if (sel_ret < 0) {
359       g_snprintf(errmsg, errmsgl,
360         "Unexpected error from select: %s", strerror(errno));
361       goto error;
362     } else if (sel_ret > 0) {
363       b = read(fd, ((char *)hdr)+bytes_read,
364             sizeof(struct pcap_hdr) - bytes_read);
365       if (b <= 0) {
366         if (b == 0)
367           g_snprintf(errmsg, errmsgl, "End of file on pipe during open");
368         else
369           g_snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
370             strerror(errno));
371         goto error;
372       }
373       bytes_read += b;
374     }
375   }
376
377   if (ld->cap_pipe_byte_swapped) {
378     /* Byte-swap the header fields about which we care. */
379     hdr->version_major = BSWAP16(hdr->version_major);
380     hdr->version_minor = BSWAP16(hdr->version_minor);
381     hdr->snaplen = BSWAP32(hdr->snaplen);
382     hdr->network = BSWAP32(hdr->network);
383   }
384
385   if (hdr->version_major < 2) {
386     g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
387     goto error;
388   }
389
390   ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
391   ld->cap_pipe_err = PIPOK;
392   return fd;
393
394 error:
395   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
396   ld->cap_pipe_err = PIPERR;
397   close(fd);
398   return -1;
399
400 }
401
402
403 /* We read one record from the pipe, take care of byte order in the record
404  * header, write the record to the capture file, and update capture statistics. */
405 static int
406 cap_pipe_dispatch(int fd, loop_data *ld, struct pcap_hdr *hdr,
407                 struct pcaprec_modified_hdr *rechdr, guchar *data,
408                 char *errmsg, int errmsgl)
409 {
410   struct pcap_pkthdr phdr;
411   int b;
412   enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
413           PD_ERR } result;
414
415
416 #ifdef LOG_CAPTURE_VERBOSE
417   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
418 #endif
419
420   switch (ld->cap_pipe_state) {
421
422   case STATE_EXPECT_REC_HDR:
423     ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
424       sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
425     ld->cap_pipe_bytes_read = 0;
426     ld->cap_pipe_state = STATE_READ_REC_HDR;
427     /* Fall through */
428
429   case STATE_READ_REC_HDR:
430     b = read(fd, ((char *)rechdr)+ld->cap_pipe_bytes_read,
431       ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
432     if (b <= 0) {
433       if (b == 0)
434         result = PD_PIPE_EOF;
435       else
436         result = PD_PIPE_ERR;
437       break;
438     }
439     if ((ld->cap_pipe_bytes_read += b) < ld->cap_pipe_bytes_to_read)
440         return 0;
441     result = PD_REC_HDR_READ;
442     break;
443
444   case STATE_EXPECT_DATA:
445     ld->cap_pipe_bytes_read = 0;
446     ld->cap_pipe_state = STATE_READ_DATA;
447     /* Fall through */
448
449   case STATE_READ_DATA:
450     b = read(fd, data+ld->cap_pipe_bytes_read, rechdr->hdr.incl_len - ld->cap_pipe_bytes_read);
451     if (b <= 0) {
452       if (b == 0)
453         result = PD_PIPE_EOF;
454       else
455         result = PD_PIPE_ERR;
456       break;
457     }
458     if ((ld->cap_pipe_bytes_read += b) < rechdr->hdr.incl_len)
459       return 0;
460     result = PD_DATA_READ;
461     break;
462
463   default:
464     g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
465     result = PD_ERR;
466
467   } /* switch (ld->cap_pipe_state) */
468
469   /*
470    * We've now read as much data as we were expecting, so process it.
471    */
472   switch (result) {
473
474   case PD_REC_HDR_READ:
475     /* We've read the header. Take care of byte order. */
476     cap_pipe_adjust_header(ld, hdr, &rechdr->hdr);
477     if (rechdr->hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
478       g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
479         ld->counts.total+1, rechdr->hdr.incl_len);
480       break;
481     }
482     ld->cap_pipe_state = STATE_EXPECT_DATA;
483     return 0;
484
485   case PD_DATA_READ:
486     /* Fill in a "struct pcap_pkthdr", and process the packet. */
487     phdr.ts.tv_sec = rechdr->hdr.ts_sec;
488     phdr.ts.tv_usec = rechdr->hdr.ts_usec;
489     phdr.caplen = rechdr->hdr.incl_len;
490     phdr.len = rechdr->hdr.orig_len;
491
492     capture_loop_packet_cb((u_char *)ld, &phdr, data);
493
494     ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
495     return 1;
496
497   case PD_PIPE_EOF:
498     ld->cap_pipe_err = PIPEOF;
499     return -1;
500
501   case PD_PIPE_ERR:
502     g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
503       strerror(errno));
504     /* Fall through */
505   case PD_ERR:
506     break;
507   }
508
509   ld->cap_pipe_err = PIPERR;
510   /* Return here rather than inside the switch to prevent GCC warning */
511   return -1;
512 }
513 #endif /* not _WIN32 */
514
515
516 /* open the capture input file (pcap or capture pipe) */
517 static int capture_loop_open_input(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len) {
518   gchar       open_err_str[PCAP_ERRBUF_SIZE];
519   const char *set_linktype_err_str;
520 #ifdef _WIN32
521   int         err;
522   WORD        wVersionRequested;
523   WSADATA     wsaData;
524 #else
525   static const char ppamsg[] = "can't find PPA for ";
526   const char  *libpcap_warn;
527 #endif
528
529
530   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
531
532   /* Initialize Windows Socket if we are in a WIN32 OS
533      This needs to be done before querying the interface for network/netmask */
534 #ifdef _WIN32
535   /* XXX - do we really require 1.1 or earlier?
536      Are there any versions that support only 2.0 or higher? */
537   wVersionRequested = MAKEWORD(1, 1);
538   err = WSAStartup(wVersionRequested, &wsaData);
539   if (err != 0) {
540     switch (err) {
541
542     case WSASYSNOTREADY:
543       g_snprintf(errmsg, errmsg_len,
544         "Couldn't initialize Windows Sockets: Network system not ready for network communication");
545       break;
546
547     case WSAVERNOTSUPPORTED:
548       g_snprintf(errmsg, errmsg_len,
549         "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
550         LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
551       break;
552
553     case WSAEINPROGRESS:
554       g_snprintf(errmsg, errmsg_len,
555         "Couldn't initialize Windows Sockets: Blocking operation is in progress");
556       break;
557
558     case WSAEPROCLIM:
559       g_snprintf(errmsg, errmsg_len,
560         "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
561       break;
562
563     case WSAEFAULT:
564       g_snprintf(errmsg, errmsg_len,
565         "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
566       break;
567
568     default:
569       g_snprintf(errmsg, errmsg_len,
570         "Couldn't initialize Windows Sockets: error %d", err);
571       break;
572     }
573     return FALSE;
574   }
575 #endif
576
577   /* Open the network interface to capture from it.
578      Some versions of libpcap may put warnings into the error buffer
579      if they succeed; to tell if that's happened, we have to clear
580      the error buffer, and check if it's still a null string.  */
581   open_err_str[0] = '\0';
582   ld->pcap_h = pcap_open_live(capture_opts->iface,
583                        capture_opts->has_snaplen ? capture_opts->snaplen :
584                                                   WTAP_MAX_PACKET_SIZE,
585                        capture_opts->promisc_mode, CAP_READ_TIMEOUT,
586                        open_err_str);
587
588   if (ld->pcap_h != NULL) {
589     /* we've opened "iface" as a network device */
590 #ifdef _WIN32
591     /* try to set the capture buffer size */
592     if (pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
593         simple_dialog(ESD_TYPE_INFO, ESD_BTN_OK,
594           "%sCouldn't set the capture buffer size!%s\n"
595           "\n"
596           "The capture buffer size of %luMB seems to be too high for your machine,\n"
597           "the default of 1MB will be used.\n"
598           "\n"
599           "Nonetheless, the capture is started.\n",
600           simple_dialog_primary_start(), simple_dialog_primary_end(), capture_opts->buffer_size);
601     }
602 #endif
603
604     /* setting the data link type only works on real interfaces */
605     if (capture_opts->linktype != -1) {
606       set_linktype_err_str = set_pcap_linktype(ld->pcap_h, capture_opts->iface,
607         capture_opts->linktype);
608       if (set_linktype_err_str != NULL) {
609         g_snprintf(errmsg, errmsg_len, "Unable to set data link type (%s).",
610           set_linktype_err_str);
611         return FALSE;
612       }
613     }
614   } else {
615     /* We couldn't open "iface" as a network device. */
616 #ifdef _WIN32
617     /* On Windows, we don't support capturing on pipes, so we give up. */
618
619     /* On Win32 OSes, the capture devices are probably available to all
620        users; don't warn about permissions problems.
621
622        Do, however, warn that WAN devices aren't supported. */
623     g_snprintf(errmsg, errmsg_len,
624 "%sThe capture session could not be initiated!%s\n"
625 "\n"
626 "(%s)\n"
627 "\n"
628 "Please check that you have the proper interface specified.\n"
629 "\n"
630 "Help can be found at: http://wiki.ethereal.com/CaptureSetup\n"
631 "\n"
632 "WinPcap does not support 64-bit Windows, so you will not be able to capture\n"
633 "traffic with Tethereal on 64-bit Windows.  You will have to use some other\n"
634 "tool to capture traffic, such as netcap; see\n"
635 "\n"
636 "       http://support.microsoft.com/?id=310875\n"
637 "\n"
638 "for information about netcap.\n"
639 "\n"
640 "Note that version 3.0 of WinPcap, and earlier versions of WinPcap, don't\n"
641 "support capturing on PPP/WAN interfaces on Windows NT 4.0 / 2000 / XP /\n"
642 "Server 2003.\n"
643 "WinPcap 3.1 has support for it on Windows 2000 / XP / Server 2003, but has no\n"
644 "support for it on Windows NT 4.0 or Windows Vista (Beta 1).",
645         simple_dialog_primary_start(), simple_dialog_primary_end(),
646     open_err_str);
647     return FALSE;
648 #else
649     /* try to open iface as a pipe */
650     ld->cap_pipe_fd = cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, errmsg_len);
651
652     if (ld->cap_pipe_fd == -1) {
653
654       if (ld->cap_pipe_err == PIPNEXIST) {
655         /* Pipe doesn't exist, so output message for interface */
656
657         /* If we got a "can't find PPA for XXX" message, warn the user (who
658            is running Ethereal on HP-UX) that they don't have a version
659            of libpcap that properly handles HP-UX (libpcap 0.6.x and later
660            versions, which properly handle HP-UX, say "can't find /dev/dlpi
661            PPA for XXX" rather than "can't find PPA for XXX"). */
662         if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
663           libpcap_warn =
664             "\n\n"
665             "You are running Ethereal with a version of the libpcap library\n"
666             "that doesn't handle HP-UX network devices well; this means that\n"
667             "Ethereal may not be able to capture packets.\n"
668             "\n"
669             "To fix this, you should install libpcap 0.6.2, or a later version\n"
670             "of libpcap, rather than libpcap 0.4 or 0.5.x.  It is available in\n"
671             "packaged binary form from the Software Porting And Archive Centre\n"
672             "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
673             "at the URL lists a number of mirror sites.";
674         else
675           libpcap_warn = "";
676         g_snprintf(errmsg, errmsg_len,
677           "The capture session could not be initiated (%s).\n"
678           "Please check to make sure you have sufficient permissions, and that\n"
679           "you have the proper interface or pipe specified.%s", open_err_str,
680           libpcap_warn);
681       }
682       /*
683        * Else pipe (or file) does exist and cap_pipe_open_live() has
684        * filled in errmsg
685        */
686       return FALSE;
687     } else
688       /* cap_pipe_open_live() succeeded; don't want
689          error message from pcap_open_live() */
690       open_err_str[0] = '\0';
691 #endif
692   }
693
694 #ifdef MUST_DO_SELECT
695   if (!ld->from_cap_pipe) {
696 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
697     ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
698 #else
699     ld->pcap_fd = pcap_fileno(ld->pcap_h);
700 #endif
701   }
702 #endif
703
704   /* Does "open_err_str" contain a non-empty string?  If so, "pcap_open_live()"
705      returned a warning; print it, but keep capturing. */
706   if (open_err_str[0] != '\0')
707     g_warning("%s.", open_err_str);
708
709   return TRUE;
710 }
711
712
713 /* open the capture input file (pcap or capture pipe) */
714 static void capture_loop_close_input(loop_data *ld) {
715
716   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
717
718 #ifndef _WIN32
719   /* if open, close the capture pipe "input file" */
720   if (ld->cap_pipe_fd >= 0) {
721     g_assert(ld->from_cap_pipe);
722     close(ld->cap_pipe_fd);
723   }
724 #endif
725
726   /* if open, close the pcap "input file" */
727   if(ld->pcap_h != NULL) {
728     g_assert(!ld->from_cap_pipe);
729     pcap_close(ld->pcap_h);
730   }
731
732 #ifdef _WIN32
733   /* Shut down windows sockets */
734   WSACleanup();
735 #endif
736 }
737
738
739 /* init the capture filter */
740 static int capture_loop_init_filter(loop_data *ld, const gchar * iface, gchar * cfilter, char *errmsg, int errmsg_len) {
741   bpf_u_int32 netnum, netmask;
742   gchar       lookup_net_err_str[PCAP_ERRBUF_SIZE];
743   struct bpf_program fcode;
744
745
746   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
747
748   /* capture filters only work on real interfaces */
749   if (cfilter && !ld->from_cap_pipe) {
750     /* A capture filter was specified; set it up. */
751     if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
752       /*
753        * Well, we can't get the netmask for this interface; it's used
754        * only for filters that check for broadcast IP addresses, so
755        * we just punt and use 0.  It might be nice to warn the user,
756        * but that's a pain in a GUI application, as it'd involve popping
757        * up a message box, and it's not clear how often this would make
758        * a difference (only filters that check for IP broadcast addresses
759        * use the netmask).
760        */
761       netmask = 0;
762     }
763     if (pcap_compile(ld->pcap_h, &fcode, cfilter, 1, netmask) < 0) {
764       dfilter_t   *rfcode = NULL;
765       /* filter string invalid, did the user tried a display filter? */
766       if (dfilter_compile(cfilter, &rfcode) && rfcode != NULL) {
767         g_snprintf(errmsg, errmsg_len,
768           "%sInvalid capture filter: \"%s\"!%s\n"
769           "\n"
770           "That string looks like a valid display filter; however, it isn't a valid\n"
771           "capture filter (%s).\n"
772           "\n"
773           "Note that display filters and capture filters don't have the same syntax,\n"
774           "so you can't use most display filter expressions as capture filters.\n"
775           "\n"
776           "See the help for a description of the capture filter syntax.",
777           simple_dialog_primary_start(), cfilter, simple_dialog_primary_end(),
778           pcap_geterr(ld->pcap_h));
779         dfilter_free(rfcode);
780       } else {
781         g_snprintf(errmsg, errmsg_len,
782           "%sInvalid capture filter: \"%s\"!%s\n"
783           "\n"
784           "That string isn't a valid capture filter (%s).\n"
785           "See the help for a description of the capture filter syntax.",
786           simple_dialog_primary_start(), cfilter, simple_dialog_primary_end(),
787           pcap_geterr(ld->pcap_h));
788       }
789       return FALSE;
790     }
791     if (pcap_setfilter(ld->pcap_h, &fcode) < 0) {
792       g_snprintf(errmsg, errmsg_len, "Can't install filter (%s).",
793         pcap_geterr(ld->pcap_h));
794 #ifdef HAVE_PCAP_FREECODE
795       pcap_freecode(&fcode);
796 #endif
797       return FALSE;
798     }
799 #ifdef HAVE_PCAP_FREECODE
800     pcap_freecode(&fcode);
801 #endif
802   }
803
804   return TRUE;
805 }
806
807
808 /* open the wiretap part of the capture output file */
809 static int capture_loop_init_wiretap_output(capture_options *capture_opts, int save_file_fd, loop_data *ld, char *errmsg, int errmsg_len) {
810   int         pcap_encap;
811   int         file_snaplen;
812   int         err;
813
814
815   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_wiretap_output");
816
817   /* get packet encapsulation type and snaplen */
818 #ifndef _WIN32
819   if (ld->from_cap_pipe) {
820     pcap_encap = ld->cap_pipe_hdr.network;
821     file_snaplen = ld->cap_pipe_hdr.snaplen;
822   } else
823 #endif
824   {
825     pcap_encap = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
826     file_snaplen = pcap_snapshot(ld->pcap_h);
827   }
828
829   /* Set up to write to the capture file. */
830   ld->wtap_linktype = wtap_pcap_encap_to_wtap_encap(pcap_encap);
831   if (ld->wtap_linktype == WTAP_ENCAP_UNKNOWN) {
832     g_snprintf(errmsg, errmsg_len,
833         "The network you're capturing from is of a type"
834         " that Ethereal doesn't support (data link type %d).", pcap_encap);
835     return FALSE;
836   }
837   if (capture_opts->multi_files_on) {
838     ld->wtap_pdh = ringbuf_init_wtap_dump_fdopen(WTAP_FILE_PCAP, ld->wtap_linktype,
839       file_snaplen, &err);
840   } else {
841     ld->wtap_pdh = wtap_dump_fdopen(save_file_fd, WTAP_FILE_PCAP,
842       ld->wtap_linktype, file_snaplen, FALSE /* compressed */, &err);
843   }
844
845   if (ld->wtap_pdh == NULL) {
846     /* We couldn't set up to write to the capture file. */
847     switch (err) {
848
849     case WTAP_ERR_CANT_OPEN:
850       strcpy(errmsg, "The file to which the capture would be saved"
851                " couldn't be created for some unknown reason.");
852       break;
853
854     case WTAP_ERR_SHORT_WRITE:
855       strcpy(errmsg, "A full header couldn't be written to the file"
856                " to which the capture would be saved.");
857       break;
858
859     default:
860       if (err < 0) {
861         g_snprintf(errmsg, errmsg_len,
862                      "The file to which the capture would be"
863                      " saved (\"%s\") could not be opened: Error %d.",
864                         capture_opts->save_file, err);
865       } else {
866         g_snprintf(errmsg, errmsg_len,
867                      "The file to which the capture would be"
868                      " saved (\"%s\") could not be opened: %s.",
869                         capture_opts->save_file, strerror(err));
870       }
871       break;
872     }
873
874     return FALSE;
875   }
876
877   return TRUE;
878 }
879
880 static gboolean capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
881
882   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
883
884   if (capture_opts->multi_files_on) {
885     return ringbuf_wtap_dump_close(&capture_opts->save_file, err_close);
886   } else {
887     return wtap_dump_close(ld->wtap_pdh, err_close);
888   }
889 }
890
891 /* dispatch incoming packets (pcap or capture pipe) */
892 static int
893 capture_loop_dispatch(capture_options *capture_opts, loop_data *ld,
894                       char *errmsg, int errmsg_len) {
895   int       inpkts;
896 #ifndef _WIN32
897   fd_set    set1;
898   struct timeval timeout;
899   int         sel_ret;
900   guchar pcap_data[WTAP_MAX_PACKET_SIZE];
901 #endif
902
903 #ifndef _WIN32
904     if (ld->from_cap_pipe) {
905       /* dispatch from capture pipe */
906 #ifdef LOG_CAPTURE_VERBOSE
907       g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
908 #endif
909       FD_ZERO(&set1);
910       FD_SET(ld->cap_pipe_fd, &set1);
911       timeout.tv_sec = 0;
912       timeout.tv_usec = CAP_READ_TIMEOUT*1000;
913       sel_ret = select(ld->cap_pipe_fd+1, &set1, NULL, NULL, &timeout);
914       if (sel_ret <= 0) {
915         inpkts = 0;
916         if (sel_ret < 0 && errno != EINTR) {
917           g_snprintf(errmsg, errmsg_len,
918             "Unexpected error from select: %s", strerror(errno));
919           capture_loop_popup_errmsg(capture_opts, errmsg);
920           ld->go = FALSE;
921         }
922       } else {
923         /*
924          * "select()" says we can read from the pipe without blocking
925          */
926         inpkts = cap_pipe_dispatch(ld->cap_pipe_fd, ld, &ld->cap_pipe_hdr, &ld->cap_pipe_rechdr, pcap_data,
927           errmsg, errmsg_len);
928         if (inpkts < 0) {
929           ld->go = FALSE;
930         }
931       }
932     }
933     else
934 #endif /* _WIN32 */
935     {
936       /* dispatch from pcap */
937 #ifdef MUST_DO_SELECT
938       /*
939        * Sigh.  The semantics of the read timeout argument to
940        * "pcap_open_live()" aren't particularly well specified by
941        * the "pcap" man page - at least with the BSD BPF code, the
942        * intent appears to be, at least in part, a way of cutting
943        * down the number of reads done on a capture, by blocking
944        * until the buffer fills or a timer expires - and the Linux
945        * libpcap doesn't actually support it, so we can't use it
946        * to break out of the "pcap_dispatch()" every 1/4 of a second
947        * or so.  Linux's libpcap is not the only libpcap that doesn't
948        * support the read timeout.
949        *
950        * Furthermore, at least on Solaris, the bufmod STREAMS module's
951        * read timeout won't go off if no data has arrived, i.e. it cannot
952        * be used to guarantee that a read from a DLPI stream will return
953        * within a specified amount of time regardless of whether any
954        * data arrives or not.
955        *
956        * Thus, on all platforms other than BSD, we do a "select()" on the
957        * file descriptor for the capture, with a timeout of CAP_READ_TIMEOUT
958        * milliseconds, or CAP_READ_TIMEOUT*1000 microseconds.
959        *
960        * "select()", on BPF devices, doesn't work as you might expect;
961        * at least on some versions of some flavors of BSD, the timer
962        * doesn't start until a read is done, so it won't expire if
963        * only a "select()" or "poll()" is posted.
964        *
965        * If we have "pcap_get_selectable_fd()", we use it to get the
966        * descriptor on which to select; if that's -1, it means there
967        * is no descriptor on which you can do a "select()" (perhaps
968        * because you're capturing on a special device, and that device's
969        * driver unfortunately doesn't support "select()", in which case
970        * we don't do the select - which means Ethereal might block,
971        * unable to accept user input, until a packet arrives.  If
972        * that's unacceptable, plead with whoever supplies the software
973        * for that device to add "select()" support.
974        */
975 #ifdef LOG_CAPTURE_VERBOSE
976       g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
977 #endif
978       if (ld->pcap_fd != -1) {
979         FD_ZERO(&set1);
980         FD_SET(ld->pcap_fd, &set1);
981         timeout.tv_sec = 0;
982         timeout.tv_usec = CAP_READ_TIMEOUT*1000;
983         sel_ret = select(ld->pcap_fd+1, &set1, NULL, NULL, &timeout);
984         if (sel_ret > 0) {
985           /*
986            * "select()" says we can read from it without blocking; go for
987            * it.
988            */
989           inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb, (u_char *)ld);
990           if (inpkts < 0) {
991             ld->pcap_err = TRUE;
992             ld->go = FALSE;
993           }
994         } else {
995           inpkts = 0;
996           if (sel_ret < 0 && errno != EINTR) {
997             g_snprintf(errmsg, errmsg_len,
998               "Unexpected error from select: %s", strerror(errno));
999             capture_loop_popup_errmsg(capture_opts, errmsg);
1000             ld->go = FALSE;
1001           }
1002         }
1003       }
1004       else
1005 #endif /* MUST_DO_SELECT */
1006       {
1007         /* dispatch from pcap without select */
1008 #if 1
1009 #ifdef LOG_CAPTURE_VERBOSE
1010         g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
1011 #endif
1012         inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb, (u_char *) ld);
1013         if (inpkts < 0) {
1014           ld->pcap_err = TRUE;
1015           ld->go = FALSE;
1016         }
1017 #else
1018         {
1019 #ifdef LOG_CAPTURE_VERBOSE
1020             g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
1021 #endif
1022             /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
1023
1024             /* WinPcap's remote capturing feature doesn't work, see http://wiki.ethereal.com/CaptureSetup_2fWinPcapRemote */
1025             /* for reference, an example remote interface: rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C} */
1026
1027             /* emulate dispatch from pcap */
1028             int in;
1029             struct pcap_pkthdr *pkt_header;
1030                     u_char *pkt_data;
1031
1032             inpkts = 0;
1033             while( (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1) {
1034                 capture_loop_packet_cb( (u_char *) ld, pkt_header, pkt_data);
1035                 inpkts++;
1036             }
1037
1038             if(in < 0) {
1039               ld->pcap_err = TRUE;
1040               ld->go = FALSE;
1041               inpkts = in;
1042             }
1043         }
1044 #endif
1045       }
1046     }
1047
1048 #ifdef LOG_CAPTURE_VERBOSE
1049     g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
1050 #endif
1051
1052     return inpkts;
1053 }
1054
1055
1056 /* open the output file (temporary/specified name/ringbuffer) */
1057 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
1058 static gboolean
1059 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
1060                       char *errmsg, int errmsg_len) {
1061
1062   char tmpname[128+1];
1063   gchar *capfile_name;
1064   gboolean is_tempfile;
1065
1066
1067   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s", 
1068       (capture_opts->save_file) ? capture_opts->save_file : "");
1069
1070   if (capture_opts->save_file != NULL) {
1071     /* We return to the caller while the capture is in progress.  
1072      * Therefore we need to take a copy of save_file in
1073      * case the caller destroys it after we return.
1074      */
1075     capfile_name = g_strdup(capture_opts->save_file);
1076     if (capture_opts->multi_files_on) {
1077       /* ringbuffer is enabled */
1078       *save_file_fd = ringbuf_init(capfile_name,
1079           (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
1080
1081       /* we need the ringbuf name */
1082       if(*save_file_fd != -1) {
1083           g_free(capfile_name);
1084           capfile_name = g_strdup(ringbuf_current_filename());
1085       }
1086     } else {
1087       /* Try to open/create the specified file for use as a capture buffer. */
1088       *save_file_fd = open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
1089                                 0600);
1090     }
1091     is_tempfile = FALSE;
1092   } else {
1093     /* Choose a random name for the temporary capture buffer */
1094     *save_file_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
1095     capfile_name = g_strdup(tmpname);
1096     is_tempfile = TRUE;
1097   }
1098
1099   /* did we fail to open the output file? */
1100   if (*save_file_fd == -1) {
1101     if (is_tempfile) {
1102       g_snprintf(errmsg, errmsg_len,
1103         "The temporary file to which the capture would be saved (\"%s\") "
1104         "could not be opened: %s.", capfile_name, strerror(errno));
1105     } else {
1106       if (capture_opts->multi_files_on) {
1107         ringbuf_error_cleanup();
1108       }
1109
1110       g_snprintf(errmsg, errmsg_len,
1111             "The file to which the capture would be saved (\"%s\") "
1112         "could not be opened: %s.", capfile_name, 
1113         strerror(errno));
1114
1115       /*open_failure_alert_box(capfile_name, errno, TRUE);*/
1116     }
1117     g_free(capfile_name);
1118     return FALSE;
1119   }
1120
1121   if(capture_opts->save_file != NULL) {
1122     g_free(capture_opts->save_file);
1123   }
1124   capture_opts->save_file = capfile_name;
1125   /* capture_opts.save_file is "g_free"ed later, which is equivalent to
1126      "g_free(capfile_name)". */
1127
1128   return TRUE;
1129 }
1130
1131
1132 #ifndef _WIN32
1133 static void
1134 capture_loop_stop_signal_handler(int signo _U_)
1135 {
1136   capture_loop_stop();
1137 }
1138 #endif
1139
1140 #ifdef _WIN32
1141 #define TIME_GET() GetTickCount()
1142 #else
1143 #define TIME_GET() time(NULL)
1144 #endif
1145
1146 /*
1147  * This needs to be static, so that the SIGUSR1 handler can clear the "go"
1148  * flag.
1149  */
1150 static loop_data   ld;
1151
1152 /* Do the low-level work of a capture.
1153    Returns TRUE if it succeeds, FALSE otherwise. */
1154 int
1155 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
1156 {
1157   time_t      upd_time, cur_time;
1158   time_t      start_time;
1159   int         err_close, inpkts;
1160   condition  *cnd_file_duration = NULL;
1161   condition  *cnd_autostop_files = NULL;
1162   condition  *cnd_autostop_size = NULL;
1163   condition  *cnd_autostop_duration = NULL;
1164   guint32     autostop_files = 0;
1165   gboolean    write_ok;
1166   gboolean    close_ok;
1167   capture_info   capture_ui;
1168   char        errmsg[4096+1];
1169   int         save_file_fd;
1170
1171
1172   /* init the loop data */
1173   ld.go                 = TRUE;
1174   if (capture_opts->has_autostop_packets)
1175     ld.packets_max      = capture_opts->autostop_packets;
1176   else
1177     ld.packets_max      = 0;    /* no limit */
1178   ld.err                = 0;    /* no error seen yet */
1179   ld.wtap_linktype      = WTAP_ENCAP_UNKNOWN;
1180   ld.pcap_err           = FALSE;
1181   ld.from_cap_pipe      = FALSE;
1182   ld.packets_sync_pipe  = 0;
1183   ld.counts.total       = 0;
1184   ld.counts.sctp        = 0;
1185   ld.counts.tcp         = 0;
1186   ld.counts.udp         = 0;
1187   ld.counts.icmp        = 0;
1188   ld.counts.ospf        = 0;
1189   ld.counts.gre         = 0;
1190   ld.counts.ipx         = 0;
1191   ld.counts.netbios     = 0;
1192   ld.counts.vines       = 0;
1193   ld.counts.other       = 0;
1194   ld.counts.arp         = 0;
1195   ld.wtap_pdh           = NULL;
1196 #ifndef _WIN32
1197   ld.cap_pipe_fd        = -1;
1198 #endif
1199 #ifdef MUST_DO_SELECT
1200   ld.pcap_fd            = 0;
1201 #endif
1202
1203 #ifndef _WIN32
1204   /*
1205    * Catch SIGUSR1, so that we exit cleanly if the parent process
1206    * kills us with it due to the user selecting "Capture->Stop".
1207    */
1208     signal(SIGUSR1, capture_loop_stop_signal_handler);
1209 #endif
1210
1211   /* We haven't yet gotten the capture statistics. */
1212   *stats_known      = FALSE;
1213
1214   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture child starting ...");
1215   capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
1216
1217   /* open the output file (temporary/specified name/ringbuffer) */
1218   if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
1219     goto error;    
1220   }
1221
1222   /* open the "input file" from network interface or capture pipe */
1223   if (!capture_loop_open_input(capture_opts, &ld, errmsg, sizeof(errmsg))) {
1224     goto error;
1225   }
1226
1227   /* init the input filter from the network interface (capture pipe will do nothing) */
1228   if (!capture_loop_init_filter(&ld, capture_opts->iface, capture_opts->cfilter, errmsg, sizeof(errmsg))) {
1229     goto error;
1230   }
1231
1232   /* open the wiretap part of the output file (the output file is already open) */
1233   if (!capture_loop_init_wiretap_output(capture_opts, save_file_fd, &ld, errmsg, sizeof(errmsg))) {
1234     goto error;
1235   }
1236
1237   /* XXX - capture SIGTERM and close the capture, in case we're on a
1238      Linux 2.0[.x] system and you have to explicitly close the capture
1239      stream in order to turn promiscuous mode off?  We need to do that
1240      in other places as well - and I don't think that works all the
1241      time in any case, due to libpcap bugs. */
1242
1243   /* Well, we should be able to start capturing.
1244
1245      Sync out the capture file, so the header makes it to the file system,
1246      and send a "capture started successfully and capture file created"
1247      message to our parent so that they'll open the capture file and
1248      update its windows to indicate that we have a live capture in
1249      progress. */
1250   wtap_dump_flush(ld.wtap_pdh);
1251   sync_pipe_filename_to_parent(capture_opts->save_file);
1252
1253   /* initialize capture stop (and alike) conditions */
1254   init_capture_stop_conditions();
1255   /* create stop conditions */
1256   if (capture_opts->has_autostop_filesize)
1257     cnd_autostop_size =
1258         cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
1259   if (capture_opts->has_autostop_duration)
1260     cnd_autostop_duration =
1261         cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
1262
1263   if (capture_opts->multi_files_on) {
1264       if (capture_opts->has_file_duration)
1265         cnd_file_duration =
1266             cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
1267
1268       if (capture_opts->has_autostop_files)
1269         cnd_autostop_files =
1270             cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
1271   }
1272
1273   /* start capture info dialog */
1274   if(capture_opts->show_info) {
1275       capture_ui.callback_data  = &ld;
1276       capture_ui.counts         = &ld.counts;
1277       capture_info_create(&capture_ui, capture_opts->iface);
1278   }
1279
1280   /* init the time values */
1281   start_time = TIME_GET();
1282   upd_time = TIME_GET();
1283
1284
1285   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture child running!");
1286
1287   /* WOW, everything is prepared! */
1288   /* please fasten your seat belts, we will enter now the actual capture loop */
1289   while (ld.go) {
1290     main_window_update();
1291
1292     /* dispatch incoming packets */
1293     inpkts = capture_loop_dispatch(capture_opts, &ld, errmsg, sizeof(errmsg));
1294
1295     main_window_update();
1296
1297 #ifdef _WIN32
1298       /* some news from our parent (signal pipe)? -> just stop the capture */
1299       {
1300           HANDLE handle;
1301           DWORD avail = 0;
1302           gboolean result;
1303
1304
1305           handle = (HANDLE) _get_osfhandle (0);
1306           result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
1307
1308           if(!result || avail > 0) {
1309             ld.go = FALSE;
1310             /*g_warning("loop closing");*/
1311           }
1312       }
1313 #endif
1314
1315     if (inpkts > 0) {
1316       ld.packets_sync_pipe += inpkts;
1317
1318       /* check capture size condition */
1319       if (cnd_autostop_size != NULL && cnd_eval(cnd_autostop_size,
1320                     (guint32)wtap_get_bytes_dumped(ld.wtap_pdh))){
1321         /* Capture size limit reached, do we have another file? */
1322         if (capture_opts->multi_files_on) {
1323           if (cnd_autostop_files != NULL && cnd_eval(cnd_autostop_files, ++autostop_files)) {
1324             /* no files left: stop here */
1325             ld.go = FALSE;
1326             continue;
1327           }
1328
1329           /* Switch to the next ringbuffer file */
1330           if (ringbuf_switch_file(&ld.wtap_pdh, &capture_opts->save_file, &save_file_fd, &ld.err)) {
1331             /* File switch succeeded: reset the conditions */
1332             cnd_reset(cnd_autostop_size);
1333             if (cnd_file_duration) {
1334               cnd_reset(cnd_file_duration);
1335             }
1336             wtap_dump_flush(ld.wtap_pdh);
1337             sync_pipe_filename_to_parent(capture_opts->save_file);
1338                         ld.packets_sync_pipe = 0;
1339           } else {
1340             /* File switch failed: stop here */
1341             ld.go = FALSE;
1342             continue;
1343           }
1344         } else {
1345           /* single file, stop now */
1346           ld.go = FALSE;
1347           continue;
1348         }
1349       } /* cnd_autostop_size */
1350     } /* inpkts */
1351
1352     /* Only update once a second so as not to overload slow displays */
1353     cur_time = TIME_GET();
1354 #ifdef _WIN32
1355     if ( (cur_time - upd_time) > 500) {
1356 #else
1357     if (cur_time - upd_time > 0) {
1358 #endif
1359         upd_time = cur_time;
1360
1361       /*if (pcap_stats(pch, stats) >= 0) {
1362         *stats_known = TRUE;
1363       }*/
1364
1365       /* calculate and display running time */
1366       if(capture_opts->show_info) {
1367           cur_time -= start_time;
1368 #ifdef _WIN32
1369           capture_ui.running_time   = cur_time / 1000;
1370 #else
1371           capture_ui.running_time   = cur_time;
1372 #endif
1373           capture_ui.new_packets    = ld.packets_sync_pipe;
1374           capture_info_update(&capture_ui);
1375       }
1376
1377       /* Let the parent process know. */
1378       if (ld.packets_sync_pipe) {
1379         /* do sync here */
1380         wtap_dump_flush(ld.wtap_pdh);
1381
1382           /* Send our parent a message saying we've written out "ld.sync_packets"
1383              packets to the capture file. */
1384         sync_pipe_packet_count_to_parent(ld.packets_sync_pipe);
1385
1386         ld.packets_sync_pipe = 0;
1387       }
1388
1389       /* check capture duration condition */
1390       if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
1391         /* The maximum capture time has elapsed; stop the capture. */
1392         ld.go = FALSE;
1393         continue;
1394       }
1395       
1396       /* check capture file duration condition */
1397       if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
1398         /* duration limit reached, do we have another file? */
1399         if (capture_opts->multi_files_on) {
1400           if (cnd_autostop_files != NULL && cnd_eval(cnd_autostop_files, ++autostop_files)) {
1401             /* no files left: stop here */
1402             ld.go = FALSE;
1403             continue;
1404           }
1405
1406           /* Switch to the next ringbuffer file */
1407           if (ringbuf_switch_file(&ld.wtap_pdh, &capture_opts->save_file, &save_file_fd, &ld.err)) {
1408             /* file switch succeeded: reset the conditions */
1409             cnd_reset(cnd_file_duration);
1410             if(cnd_autostop_size)
1411               cnd_reset(cnd_autostop_size);
1412             wtap_dump_flush(ld.wtap_pdh);
1413             sync_pipe_filename_to_parent(capture_opts->save_file);
1414                         ld.packets_sync_pipe = 0;
1415           } else {
1416             /* File switch failed: stop here */
1417                 ld.go = FALSE;
1418             continue;
1419           }
1420         } else {
1421           /* single file, stop now */
1422           ld.go = FALSE;
1423           continue;
1424         }
1425       } /* cnd_file_duration */
1426     }
1427
1428   } /* while (ld.go) */
1429
1430   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture child stopping ...");
1431
1432   /* close capture info dialog */
1433   if(capture_opts->show_info) {
1434     capture_info_destroy(&capture_ui);
1435   }
1436
1437   /* delete stop conditions */
1438   if (cnd_file_duration != NULL)
1439     cnd_delete(cnd_file_duration);
1440   if (cnd_autostop_files != NULL)
1441     cnd_delete(cnd_autostop_files);
1442   if (cnd_autostop_size != NULL)
1443     cnd_delete(cnd_autostop_size);
1444   if (cnd_autostop_duration != NULL)
1445     cnd_delete(cnd_autostop_duration);
1446
1447   /* did we had a pcap (input) error? */
1448   if (ld.pcap_err) {
1449     g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
1450       pcap_geterr(ld.pcap_h));
1451     capture_loop_popup_errmsg(capture_opts, errmsg);
1452   }
1453 #ifndef _WIN32
1454     else if (ld.from_cap_pipe && ld.cap_pipe_err == PIPERR)
1455       capture_loop_popup_errmsg(capture_opts, errmsg);
1456 #endif
1457
1458   /* did we had an error while capturing? */
1459   if (ld.err == 0) {
1460     write_ok = TRUE;
1461   } else {
1462     capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, ld.err,
1463                               FALSE);
1464     capture_loop_popup_errmsg(capture_opts, errmsg);
1465     write_ok = FALSE;
1466   }
1467
1468   /* close the wiretap (output) file */
1469   close_ok = capture_loop_close_output(capture_opts, &ld, &err_close);
1470
1471   /* If we've displayed a message about a write error, there's no point
1472      in displaying another message about an error on close. */
1473   if (!close_ok && write_ok) {
1474     capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
1475                 TRUE);
1476     capture_loop_popup_errmsg(capture_opts, errmsg);
1477   }
1478
1479   /*
1480    * XXX We exhibit different behaviour between normal mode and sync mode
1481    * when the pipe is stdin and not already at EOF.  If we're a child, the
1482    * parent's stdin isn't closed, so if the user starts another capture,
1483    * cap_pipe_open_live() will very likely not see the expected magic bytes and
1484    * will say "Unrecognized libpcap format".  On the other hand, in normal
1485    * mode, cap_pipe_open_live() will say "End of file on pipe during open".
1486    */
1487
1488   /* get packet drop statistics from pcap */
1489   if(ld.pcap_h != NULL) {
1490     g_assert(!ld.from_cap_pipe);
1491     /* Get the capture statistics, so we know how many packets were
1492        dropped. */
1493     if (pcap_stats(ld.pcap_h, stats) >= 0) {
1494       *stats_known = TRUE;
1495       /* Let the parent process know. */
1496       sync_pipe_drops_to_parent(stats->ps_drop);
1497     } else {
1498       g_snprintf(errmsg, sizeof(errmsg),
1499                 "Can't get packet-drop statistics: %s",
1500                 pcap_geterr(ld.pcap_h));
1501       capture_loop_popup_errmsg(capture_opts, errmsg);
1502     }
1503   }
1504
1505   /* close the input file (pcap or capture pipe) */
1506   capture_loop_close_input(&ld);
1507
1508   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture child stopped!");
1509
1510   /* ok, if the write and the close were successful. */
1511   return write_ok && close_ok;
1512
1513 error:
1514   if (capture_opts->multi_files_on) {
1515     /* cleanup ringbuffer */
1516     ringbuf_error_cleanup();
1517   } else {
1518     /* We can't use the save file, and we have no wtap_dump stream
1519        to close in order to close it, so close the FD directly. */
1520     close(save_file_fd);
1521
1522     /* We couldn't even start the capture, so get rid of the capture
1523        file. */
1524     unlink(capture_opts->save_file); /* silently ignore error */
1525     g_free(capture_opts->save_file);
1526   }
1527   capture_opts->save_file = NULL;
1528   capture_loop_popup_errmsg(capture_opts, errmsg);
1529
1530   /* close the input file (pcap or cap_pipe) */
1531   capture_loop_close_input(&ld);
1532
1533   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture child stopped with error");
1534
1535   return FALSE;
1536 }
1537
1538
1539 void capture_loop_stop(void)
1540 {
1541     ld.go = FALSE;
1542 }
1543  
1544
1545 static void
1546 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
1547                           int err, gboolean is_close)
1548 {
1549   switch (err) {
1550
1551   case ENOSPC:
1552     g_snprintf(errmsg, errmsglen,
1553                 "Not all the packets could be written to the file"
1554                 " to which the capture was being saved\n"
1555                 "(\"%s\") because there is no space left on the file system\n"
1556                 "on which that file resides.",
1557                 fname);
1558     break;
1559
1560 #ifdef EDQUOT
1561   case EDQUOT:
1562     g_snprintf(errmsg, errmsglen,
1563                 "Not all the packets could be written to the file"
1564                 " to which the capture was being saved\n"
1565                 "(\"%s\") because you are too close to, or over,"
1566                 " your disk quota\n"
1567                 "on the file system on which that file resides.",
1568                 fname);
1569   break;
1570 #endif
1571
1572   case WTAP_ERR_CANT_CLOSE:
1573     g_snprintf(errmsg, errmsglen,
1574                 "The file to which the capture was being saved"
1575                 " couldn't be closed for some unknown reason.");
1576     break;
1577
1578   case WTAP_ERR_SHORT_WRITE:
1579     g_snprintf(errmsg, errmsglen,
1580                 "Not all the packets could be written to the file"
1581                 " to which the capture was being saved\n"
1582                 "(\"%s\").",
1583                 fname);
1584     break;
1585
1586   default:
1587     if (is_close) {
1588       g_snprintf(errmsg, errmsglen,
1589                 "The file to which the capture was being saved\n"
1590                 "(\"%s\") could not be closed: %s.",
1591                 fname, wtap_strerror(err));
1592     } else {
1593       g_snprintf(errmsg, errmsglen,
1594                 "An error occurred while writing to the file"
1595                 " to which the capture was being saved\n"
1596                 "(\"%s\"): %s.",
1597                 fname, wtap_strerror(err));
1598     }
1599     break;
1600   }
1601 }
1602
1603 static void
1604 capture_loop_popup_errmsg(capture_options *capture_opts _U_, const char *errmsg)
1605 {
1606     /* Send the error message to our parent, so they can display a
1607        dialog box containing it. */
1608     sync_pipe_errmsg_to_parent(errmsg);
1609 }
1610
1611
1612 /* one packet was captured, process it */
1613 static void
1614 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
1615   const u_char *pd)
1616 {
1617   struct wtap_pkthdr whdr;
1618   union wtap_pseudo_header pseudo_header;
1619   loop_data *ld = (loop_data *) user;
1620   int err;
1621
1622   /* if the user told us to stop after x packets, do we have enough? */
1623   ld->counts.total++;
1624   if ((ld->packets_max > 0) && (ld->counts.total >= ld->packets_max))
1625   {
1626      ld->go = FALSE;
1627   }
1628
1629   /* Convert from libpcap to Wiretap format.
1630      If that fails, set "ld->go" to FALSE, to stop the capture, and set
1631      "ld->err" to the error. */
1632   pd = wtap_process_pcap_packet(ld->wtap_linktype, phdr, pd, &pseudo_header,
1633                                 &whdr, &err);
1634   if (pd == NULL) {
1635     ld->go = FALSE;
1636     ld->err = err;
1637     return;
1638   }
1639
1640   if (ld->wtap_pdh) {
1641     /* We're supposed to write the packet to a file; do so.
1642        If this fails, set "ld->go" to FALSE, to stop the capture, and set
1643        "ld->err" to the error. */
1644     if (!wtap_dump(ld->wtap_pdh, &whdr, &pseudo_header, pd, &err)) {
1645       ld->go = FALSE;
1646       ld->err = err;
1647     }
1648   }
1649
1650   switch (ld->wtap_linktype) {
1651     case WTAP_ENCAP_ETHERNET:
1652       capture_eth(pd, 0, whdr.caplen, &ld->counts);
1653       break;
1654     case WTAP_ENCAP_FDDI:
1655     case WTAP_ENCAP_FDDI_BITSWAPPED:
1656       capture_fddi(pd, whdr.caplen, &ld->counts);
1657       break;
1658     case WTAP_ENCAP_PRISM_HEADER:
1659       capture_prism(pd, 0, whdr.caplen, &ld->counts);
1660       break;
1661     case WTAP_ENCAP_TOKEN_RING:
1662       capture_tr(pd, 0, whdr.caplen, &ld->counts);
1663       break;
1664     case WTAP_ENCAP_NULL:
1665       capture_null(pd, whdr.caplen, &ld->counts);
1666       break;
1667     case WTAP_ENCAP_PPP:
1668       capture_ppp_hdlc(pd, 0, whdr.caplen, &ld->counts);
1669       break;
1670     case WTAP_ENCAP_RAW_IP:
1671       capture_raw(pd, whdr.caplen, &ld->counts);
1672       break;
1673     case WTAP_ENCAP_SLL:
1674       capture_sll(pd, whdr.caplen, &ld->counts);
1675       break;
1676     case WTAP_ENCAP_LINUX_ATM_CLIP:
1677       capture_clip(pd, whdr.caplen, &ld->counts);
1678       break;
1679     case WTAP_ENCAP_IEEE_802_11:
1680     case WTAP_ENCAP_IEEE_802_11_WITH_RADIO:
1681       capture_ieee80211(pd, 0, whdr.caplen, &ld->counts);
1682       break;
1683     case WTAP_ENCAP_CHDLC:
1684       capture_chdlc(pd, 0, whdr.caplen, &ld->counts);
1685       break;
1686     case WTAP_ENCAP_LOCALTALK:
1687       capture_llap(&ld->counts);
1688       break;
1689     case WTAP_ENCAP_ATM_PDUS:
1690       capture_atm(&pseudo_header, pd, whdr.caplen, &ld->counts);
1691       break;
1692     case WTAP_ENCAP_IP_OVER_FC:
1693       capture_ipfc(pd, whdr.caplen, &ld->counts);
1694       break;
1695     case WTAP_ENCAP_ARCNET:
1696       capture_arcnet(pd, whdr.caplen, &ld->counts, FALSE, TRUE);
1697       break;
1698     case WTAP_ENCAP_ARCNET_LINUX:
1699       capture_arcnet(pd, whdr.caplen, &ld->counts, TRUE, FALSE);
1700       break;
1701     case WTAP_ENCAP_APPLE_IP_OVER_IEEE1394:
1702       capture_ap1394(pd, 0, whdr.caplen, &ld->counts);
1703       break;
1704     case WTAP_ENCAP_FRELAY:
1705     case WTAP_ENCAP_FRELAY_WITH_PHDR:
1706       capture_fr(pd, 0, whdr.caplen, &ld->counts);
1707       break;
1708     /* XXX - some ATM drivers on FreeBSD might prepend a 4-byte ATM
1709        pseudo-header to DLT_ATM_RFC1483, with LLC header following;
1710        we might have to implement that at some point. */
1711   }
1712 }
1713
1714 #endif /* HAVE_LIBPCAP */
1715