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