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