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