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