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