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