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