Handle a null-string file name in "capture_loop_open_output()" - that's
[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 (strcmp(capfile_name, "") == 0) {
1019       /* Write to the standard output. */
1020       if (capture_opts->multi_files_on) {
1021         /* ringbuffer is enabled; that doesn't work with standard output */
1022         g_snprintf(errmsg, errmsg_len,
1023             "Ring buffer requested, but capture is being written to the standard error.");
1024         g_free(capfile_name);
1025         return FALSE;
1026       } else {
1027         *save_file_fd = 1;
1028       }
1029     } else {
1030       if (capture_opts->multi_files_on) {
1031         /* ringbuffer is enabled */
1032         *save_file_fd = ringbuf_init(capfile_name,
1033             (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
1034
1035         /* we need the ringbuf name */
1036         if(*save_file_fd != -1) {
1037             g_free(capfile_name);
1038             capfile_name = g_strdup(ringbuf_current_filename());
1039         }
1040       } else {
1041         /* Try to open/create the specified file for use as a capture buffer. */
1042         *save_file_fd = open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
1043                              0600);
1044       }
1045     }
1046     is_tempfile = FALSE;
1047   } else {
1048     /* Choose a random name for the temporary capture buffer */
1049     *save_file_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
1050     capfile_name = g_strdup(tmpname);
1051     is_tempfile = TRUE;
1052   }
1053
1054   /* did we fail to open the output file? */
1055   if (*save_file_fd == -1) {
1056     if (is_tempfile) {
1057       g_snprintf(errmsg, errmsg_len,
1058         "The temporary file to which the capture would be saved (\"%s\") "
1059         "could not be opened: %s.", capfile_name, strerror(errno));
1060     } else {
1061       if (capture_opts->multi_files_on) {
1062         ringbuf_error_cleanup();
1063       }
1064
1065       g_snprintf(errmsg, errmsg_len,
1066             "The file to which the capture would be saved (\"%s\") "
1067         "could not be opened: %s.", capfile_name, 
1068         strerror(errno));
1069     }
1070     g_free(capfile_name);
1071     return FALSE;
1072   }
1073
1074   if(capture_opts->save_file != NULL) {
1075     g_free(capture_opts->save_file);
1076   }
1077   capture_opts->save_file = capfile_name;
1078   /* capture_opts.save_file is "g_free"ed later, which is equivalent to
1079      "g_free(capfile_name)". */
1080
1081   return TRUE;
1082 }
1083
1084
1085 #ifndef _WIN32
1086 static void
1087 capture_loop_stop_signal_handler(int signo _U_)
1088 {
1089   capture_loop_stop();
1090 }
1091 #endif
1092
1093 #ifdef _WIN32
1094 #define TIME_GET() GetTickCount()
1095 #else
1096 #define TIME_GET() time(NULL)
1097 #endif
1098
1099 #ifdef _WIN32
1100 static gboolean
1101 signal_pipe_stopped(void)
1102 {
1103     /* some news from our parent (signal pipe)? -> just stop the capture */
1104     HANDLE handle;
1105     DWORD avail = 0;
1106     gboolean result;
1107
1108
1109     handle = (HANDLE) _get_osfhandle (0);
1110     result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
1111
1112     /*g_warning("check pipe: handle: %x result: %u avail: %u", handle, result, avail);*/
1113
1114     if(!result || avail > 0) {
1115         /* peek failed or some bytes really available */
1116         return TRUE;
1117     } else {
1118         /* pipe ok and no bytes available */
1119         return FALSE;
1120     }
1121 }
1122 #endif
1123
1124
1125 /* Do the low-level work of a capture.
1126    Returns TRUE if it succeeds, FALSE otherwise. */
1127 int
1128 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
1129 {
1130   time_t      upd_time, cur_time;
1131   time_t      start_time;
1132   int         err_close;
1133   int         inpkts;
1134   gint        inpkts_to_sync_pipe = 0;     /* packets not already send out to the sync_pipe */
1135   condition  *cnd_file_duration = NULL;
1136   condition  *cnd_autostop_files = NULL;
1137   condition  *cnd_autostop_size = NULL;
1138   condition  *cnd_autostop_duration = NULL;
1139   guint32     autostop_files = 0;
1140   gboolean    write_ok;
1141   gboolean    close_ok;
1142   char        errmsg[4096+1];
1143   int         save_file_fd;
1144
1145
1146   /* init the loop data */
1147   ld.go                 = TRUE;
1148   ld.packet_count       = 0;
1149   if (capture_opts->has_autostop_packets)
1150     ld.packet_max       = capture_opts->autostop_packets;
1151   else
1152     ld.packet_max       = 0;    /* no limit */
1153   ld.err                = 0;    /* no error seen yet */
1154   ld.wtap_linktype      = WTAP_ENCAP_UNKNOWN;
1155   ld.pcap_err           = FALSE;
1156   ld.from_cap_pipe      = FALSE;
1157   ld.wtap_pdh           = NULL;
1158 #ifndef _WIN32
1159   ld.cap_pipe_fd        = -1;
1160 #endif
1161 #ifdef MUST_DO_SELECT
1162   ld.pcap_fd            = 0;
1163 #endif
1164   ld.packet_cb          = capture_loop_packet_cb;
1165
1166
1167   /* We haven't yet gotten the capture statistics. */
1168   *stats_known      = FALSE;
1169
1170 #ifndef _WIN32
1171   /*
1172    * Catch SIGUSR1, so that we exit cleanly if the parent process
1173    * kills us with it due to the user selecting "Capture->Stop".
1174    */
1175     signal(SIGUSR1, capture_loop_stop_signal_handler);
1176 #endif
1177
1178   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture child starting ...");
1179   capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
1180
1181   /* open the output file (temporary/specified name/ringbuffer) */
1182   if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
1183     goto error;    
1184   }
1185
1186   /* open the "input file" from network interface or capture pipe */
1187   if (!capture_loop_open_input(capture_opts, &ld, errmsg, sizeof(errmsg))) {
1188     goto error;
1189   }
1190
1191   /* init the input filter from the network interface (capture pipe will do nothing) */
1192   if (!capture_loop_init_filter(ld.pcap_h, ld.from_cap_pipe, capture_opts->iface, capture_opts->cfilter, errmsg, sizeof(errmsg))) {
1193     goto error;
1194   }
1195
1196   /* open the wiretap part of the output file (the output file is already open) */
1197   if (!capture_loop_init_wiretap_output(capture_opts, save_file_fd, &ld, errmsg, sizeof(errmsg))) {
1198     goto error;
1199   }
1200
1201   /* XXX - capture SIGTERM and close the capture, in case we're on a
1202      Linux 2.0[.x] system and you have to explicitly close the capture
1203      stream in order to turn promiscuous mode off?  We need to do that
1204      in other places as well - and I don't think that works all the
1205      time in any case, due to libpcap bugs. */
1206
1207   /* Well, we should be able to start capturing.
1208
1209      Sync out the capture file, so the header makes it to the file system,
1210      and send a "capture started successfully and capture file created"
1211      message to our parent so that they'll open the capture file and
1212      update its windows to indicate that we have a live capture in
1213      progress. */
1214   wtap_dump_flush(ld.wtap_pdh);
1215   sync_pipe_filename_to_parent(capture_opts->save_file);
1216
1217   /* initialize capture stop (and alike) conditions */
1218   init_capture_stop_conditions();
1219   /* create stop conditions */
1220   if (capture_opts->has_autostop_filesize)
1221     cnd_autostop_size =
1222         cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
1223   if (capture_opts->has_autostop_duration)
1224     cnd_autostop_duration =
1225         cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
1226
1227   if (capture_opts->multi_files_on) {
1228       if (capture_opts->has_file_duration)
1229         cnd_file_duration =
1230             cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
1231
1232       if (capture_opts->has_autostop_files)
1233         cnd_autostop_files =
1234             cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
1235   }
1236
1237   /* init the time values */
1238   start_time = TIME_GET();
1239   upd_time = TIME_GET();
1240
1241   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture child running!");
1242
1243   /* WOW, everything is prepared! */
1244   /* please fasten your seat belts, we will enter now the actual capture loop */
1245   while (ld.go) {
1246     /* dispatch incoming packets */
1247     inpkts = capture_loop_dispatch(capture_opts, &ld, errmsg, sizeof(errmsg));
1248
1249 #ifdef _WIN32
1250     /*fprintf(stderr, "fd: %u ret: %u\n", capture_opts->signal_pipe_fd, signal_pipe_stopped());*/
1251
1252     /* any news from our parent (signal pipe)? -> just stop the capture */
1253     if (capture_opts->signal_pipe_fd != -1 && signal_pipe_stopped()) {
1254       ld.go = FALSE;
1255     }
1256 #endif
1257
1258     if (inpkts > 0) {
1259       inpkts_to_sync_pipe += inpkts;
1260
1261       /* check capture size condition */
1262       if (cnd_autostop_size != NULL && cnd_eval(cnd_autostop_size,
1263                     (guint32)wtap_get_bytes_dumped(ld.wtap_pdh))){
1264         /* Capture size limit reached, do we have another file? */
1265         if (capture_opts->multi_files_on) {
1266           if (cnd_autostop_files != NULL && cnd_eval(cnd_autostop_files, ++autostop_files)) {
1267             /* no files left: stop here */
1268             ld.go = FALSE;
1269             continue;
1270           }
1271
1272           /* Switch to the next ringbuffer file */
1273           if (ringbuf_switch_file(&ld.wtap_pdh, &capture_opts->save_file, &save_file_fd, &ld.err)) {
1274             /* File switch succeeded: reset the conditions */
1275             cnd_reset(cnd_autostop_size);
1276             if (cnd_file_duration) {
1277               cnd_reset(cnd_file_duration);
1278             }
1279             wtap_dump_flush(ld.wtap_pdh);
1280             sync_pipe_filename_to_parent(capture_opts->save_file);
1281                         inpkts_to_sync_pipe = 0;
1282           } else {
1283             /* File switch failed: stop here */
1284             ld.go = FALSE;
1285             continue;
1286           }
1287         } else {
1288           /* single file, stop now */
1289           ld.go = FALSE;
1290           continue;
1291         }
1292       } /* cnd_autostop_size */
1293     } /* inpkts */
1294
1295     /* Only update once a second (Win32: 500ms) so as not to overload slow displays */
1296     cur_time = TIME_GET();
1297 #ifdef _WIN32
1298     if ( (cur_time - upd_time) > 500) {
1299 #else
1300     if (cur_time - upd_time > 0) {
1301 #endif
1302         upd_time = cur_time;
1303
1304       /*if (pcap_stats(pch, stats) >= 0) {
1305         *stats_known = TRUE;
1306       }*/
1307
1308       /* Let the parent process know. */
1309       if (inpkts_to_sync_pipe) {
1310         /* do sync here */
1311         wtap_dump_flush(ld.wtap_pdh);
1312
1313           /* Send our parent a message saying we've written out "inpkts_to_sync_pipe"
1314              packets to the capture file. */
1315         sync_pipe_packet_count_to_parent(inpkts_to_sync_pipe);
1316
1317         inpkts_to_sync_pipe = 0;
1318       }
1319
1320       /* check capture duration condition */
1321       if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
1322         /* The maximum capture time has elapsed; stop the capture. */
1323         ld.go = FALSE;
1324         continue;
1325       }
1326       
1327       /* check capture file duration condition */
1328       if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
1329         /* duration limit reached, do we have another file? */
1330         if (capture_opts->multi_files_on) {
1331           if (cnd_autostop_files != NULL && cnd_eval(cnd_autostop_files, ++autostop_files)) {
1332             /* no files left: stop here */
1333             ld.go = FALSE;
1334             continue;
1335           }
1336
1337           /* Switch to the next ringbuffer file */
1338           if (ringbuf_switch_file(&ld.wtap_pdh, &capture_opts->save_file, &save_file_fd, &ld.err)) {
1339             /* file switch succeeded: reset the conditions */
1340             cnd_reset(cnd_file_duration);
1341             if(cnd_autostop_size)
1342               cnd_reset(cnd_autostop_size);
1343             wtap_dump_flush(ld.wtap_pdh);
1344             sync_pipe_filename_to_parent(capture_opts->save_file);
1345                         inpkts_to_sync_pipe = 0;
1346           } else {
1347             /* File switch failed: stop here */
1348                 ld.go = FALSE;
1349             continue;
1350           }
1351         } else {
1352           /* single file, stop now */
1353           ld.go = FALSE;
1354           continue;
1355         }
1356       } /* cnd_file_duration */
1357     }
1358
1359   } /* while (ld.go) */
1360
1361   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture child stopping ...");
1362
1363   /* delete stop conditions */
1364   if (cnd_file_duration != NULL)
1365     cnd_delete(cnd_file_duration);
1366   if (cnd_autostop_files != NULL)
1367     cnd_delete(cnd_autostop_files);
1368   if (cnd_autostop_size != NULL)
1369     cnd_delete(cnd_autostop_size);
1370   if (cnd_autostop_duration != NULL)
1371     cnd_delete(cnd_autostop_duration);
1372
1373   /* did we had a pcap (input) error? */
1374   if (ld.pcap_err) {
1375     g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
1376       pcap_geterr(ld.pcap_h));
1377     sync_pipe_errmsg_to_parent(errmsg);
1378   }
1379 #ifndef _WIN32
1380     else if (ld.from_cap_pipe && ld.cap_pipe_err == PIPERR)
1381       sync_pipe_errmsg_to_parent(errmsg);
1382 #endif
1383
1384   /* did we had an error while capturing? */
1385   if (ld.err == 0) {
1386     write_ok = TRUE;
1387   } else {
1388     capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, ld.err,
1389                               FALSE);
1390     sync_pipe_errmsg_to_parent(errmsg);
1391     write_ok = FALSE;
1392   }
1393
1394   /* close the wiretap (output) file */
1395   close_ok = capture_loop_close_output(capture_opts, &ld, &err_close);
1396
1397   /* If we've displayed a message about a write error, there's no point
1398      in displaying another message about an error on close. */
1399   if (!close_ok && write_ok) {
1400     capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
1401                 TRUE);
1402     sync_pipe_errmsg_to_parent(errmsg);
1403   }
1404
1405   /*
1406    * XXX We exhibit different behaviour between normal mode and sync mode
1407    * when the pipe is stdin and not already at EOF.  If we're a child, the
1408    * parent's stdin isn't closed, so if the user starts another capture,
1409    * cap_pipe_open_live() will very likely not see the expected magic bytes and
1410    * will say "Unrecognized libpcap format".  On the other hand, in normal
1411    * mode, cap_pipe_open_live() will say "End of file on pipe during open".
1412    */
1413
1414   /* get packet drop statistics from pcap */
1415   if(ld.pcap_h != NULL) {
1416     g_assert(!ld.from_cap_pipe);
1417     /* Get the capture statistics, so we know how many packets were
1418        dropped. */
1419     if (pcap_stats(ld.pcap_h, stats) >= 0) {
1420       *stats_known = TRUE;
1421       /* Let the parent process know. */
1422       sync_pipe_drops_to_parent(stats->ps_drop);
1423     } else {
1424       g_snprintf(errmsg, sizeof(errmsg),
1425                 "Can't get packet-drop statistics: %s",
1426                 pcap_geterr(ld.pcap_h));
1427       sync_pipe_errmsg_to_parent(errmsg);
1428     }
1429   }
1430
1431   /* close the input file (pcap or capture pipe) */
1432   capture_loop_close_input(&ld);
1433
1434   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture child stopped!");
1435
1436   /* ok, if the write and the close were successful. */
1437   return write_ok && close_ok;
1438
1439 error:
1440   if (capture_opts->multi_files_on) {
1441     /* cleanup ringbuffer */
1442     ringbuf_error_cleanup();
1443   } else {
1444     /* We can't use the save file, and we have no wtap_dump stream
1445        to close in order to close it, so close the FD directly. */
1446     eth_close(save_file_fd);
1447
1448     /* We couldn't even start the capture, so get rid of the capture
1449        file. */
1450     eth_unlink(capture_opts->save_file); /* silently ignore error */
1451     g_free(capture_opts->save_file);
1452   }
1453   capture_opts->save_file = NULL;
1454   sync_pipe_errmsg_to_parent(errmsg);
1455
1456   /* close the input file (pcap or cap_pipe) */
1457   capture_loop_close_input(&ld);
1458
1459   g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture child stopped with error");
1460
1461   return FALSE;
1462 }
1463
1464
1465 void capture_loop_stop(void)
1466 {
1467     ld.go = FALSE;
1468 }
1469  
1470
1471 static void
1472 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
1473                           int err, gboolean is_close)
1474 {
1475   switch (err) {
1476
1477   case ENOSPC:
1478     g_snprintf(errmsg, errmsglen,
1479                 "Not all the packets could be written to the file"
1480                 " to which the capture was being saved\n"
1481                 "(\"%s\") because there is no space left on the file system\n"
1482                 "on which that file resides.",
1483                 fname);
1484     break;
1485
1486 #ifdef EDQUOT
1487   case EDQUOT:
1488     g_snprintf(errmsg, errmsglen,
1489                 "Not all the packets could be written to the file"
1490                 " to which the capture was being saved\n"
1491                 "(\"%s\") because you are too close to, or over,"
1492                 " your disk quota\n"
1493                 "on the file system on which that file resides.",
1494                 fname);
1495   break;
1496 #endif
1497
1498   case WTAP_ERR_CANT_CLOSE:
1499     g_snprintf(errmsg, errmsglen,
1500                 "The file to which the capture was being saved"
1501                 " couldn't be closed for some unknown reason.");
1502     break;
1503
1504   case WTAP_ERR_SHORT_WRITE:
1505     g_snprintf(errmsg, errmsglen,
1506                 "Not all the packets could be written to the file"
1507                 " to which the capture was being saved\n"
1508                 "(\"%s\").",
1509                 fname);
1510     break;
1511
1512   default:
1513     if (is_close) {
1514       g_snprintf(errmsg, errmsglen,
1515                 "The file to which the capture was being saved\n"
1516                 "(\"%s\") could not be closed: %s.",
1517                 fname, wtap_strerror(err));
1518     } else {
1519       g_snprintf(errmsg, errmsglen,
1520                 "An error occurred while writing to the file"
1521                 " to which the capture was being saved\n"
1522                 "(\"%s\"): %s.",
1523                 fname, wtap_strerror(err));
1524     }
1525     break;
1526   }
1527 }
1528
1529
1530 /* one packet was captured, process it */
1531 static void
1532 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
1533   const u_char *pd)
1534 {
1535   struct wtap_pkthdr whdr;
1536   union wtap_pseudo_header pseudo_header;
1537   loop_data *ld = (loop_data *) user;
1538   int err;
1539
1540   /* if the user told us to stop after x packets, do we have enough? */
1541   ld->packet_count++;
1542   if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
1543   {
1544      ld->go = FALSE;
1545   }
1546
1547   /* Convert from libpcap to Wiretap format.
1548      If that fails, set "ld->go" to FALSE, to stop the capture, and set
1549      "ld->err" to the error. */
1550   pd = wtap_process_pcap_packet(ld->wtap_linktype, phdr, pd, &pseudo_header,
1551                                 &whdr, &err);
1552   if (pd == NULL) {
1553     ld->go = FALSE;
1554     ld->err = err;
1555     return;
1556   }
1557
1558   if (ld->wtap_pdh) {
1559     /* We're supposed to write the packet to a file; do so.
1560        If this fails, set "ld->go" to FALSE, to stop the capture, and set
1561        "ld->err" to the error. */
1562     if (!wtap_dump(ld->wtap_pdh, &whdr, &pseudo_header, pd, &err)) {
1563       ld->go = FALSE;
1564       ld->err = err;
1565     }
1566   }
1567 }
1568
1569 #endif /* HAVE_LIBPCAP */
1570