2 * The actual capturing loop, getting packets and storing it
6 * Ethereal - Network traffic analyzer
7 * By Gerald Combs <gerald@ethereal.com>
8 * Copyright 1998 Gerald Combs
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.
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.
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.
28 * Capture loop (internal interface).
30 * It will open the input and output files, capture the packets,
31 * change ringbuffer output files while capturing and close all files again.
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.
54 #ifdef HAVE_SYS_TYPES_H
55 # include <sys/types.h>
58 #ifdef HAVE_SYS_STAT_H
59 # include <sys/stat.h>
73 #include "capture-pcap-util.h"
76 #include "capture_sync.h"
78 #include "conditions.h"
79 #include "capture_stop_conditions.h"
80 #include "ringbuffer.h"
82 #include "simple_dialog.h"
85 #include "file_util.h"
88 #include "capture_loop.h"
91 * Standard secondary message for unexpected errors.
93 static const char please_report[] =
94 "Please report this to the Ethereal developers";
97 * This needs to be static, so that the SIGUSR1 handler can clear the "go"
104 * Timeout, in milliseconds, for reads from the stream of captured packets.
106 #define CAP_READ_TIMEOUT 250
108 static void capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
110 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
111 int err, gboolean is_close);
116 /* Take care of byte order in the libpcap headers read from pipes.
117 * (function taken from wiretap/libpcap.c) */
119 cap_pipe_adjust_header(gboolean byte_swapped, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
122 /* Byte-swap the record header fields. */
123 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
124 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
125 rechdr->incl_len = BSWAP32(rechdr->incl_len);
126 rechdr->orig_len = BSWAP32(rechdr->orig_len);
129 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
130 swapped, in order to match the BPF header layout.
132 Unfortunately, some files were, according to a comment in the "libpcap"
133 source, written with version 2.3 in their headers but without the
134 interchanged fields, so if "incl_len" is greater than "orig_len" - which
135 would make no sense - we assume that we need to swap them. */
136 if (hdr->version_major == 2 &&
137 (hdr->version_minor < 3 ||
138 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
141 temp = rechdr->orig_len;
142 rechdr->orig_len = rechdr->incl_len;
143 rechdr->incl_len = temp;
147 /* Mimic pcap_open_live() for pipe captures
148 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
150 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
151 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
153 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
154 char *errmsg, int errmsgl)
156 struct stat pipe_stat;
160 unsigned int bytes_read;
162 struct timeval timeout;
165 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: %s", pipename);
168 * XXX (T)Ethereal blocks until we return
170 if (strcmp(pipename, "-") == 0)
171 fd = 0; /* read from stdin */
173 if (eth_stat(pipename, &pipe_stat) < 0) {
174 if (errno == ENOENT || errno == ENOTDIR)
175 ld->cap_pipe_err = PIPNEXIST;
177 g_snprintf(errmsg, errmsgl,
178 "The capture session could not be initiated "
179 "due to error on pipe: %s", strerror(errno));
180 ld->cap_pipe_err = PIPERR;
184 if (! S_ISFIFO(pipe_stat.st_mode)) {
185 if (S_ISCHR(pipe_stat.st_mode)) {
187 * Assume the user specified an interface on a system where
188 * interfaces are in /dev. Pretend we haven't seen it.
190 ld->cap_pipe_err = PIPNEXIST;
192 g_snprintf(errmsg, errmsgl,
193 "The capture session could not be initiated because\n"
194 "\"%s\" is neither an interface nor a pipe", pipename);
195 ld->cap_pipe_err = PIPERR;
199 fd = eth_open(pipename, O_RDONLY | O_NONBLOCK, 0000 /* no creation so don't matter */);
201 g_snprintf(errmsg, errmsgl,
202 "The capture session could not be initiated "
203 "due to error on pipe open: %s", strerror(errno));
204 ld->cap_pipe_err = PIPERR;
209 ld->from_cap_pipe = TRUE;
211 /* read the pcap header */
214 while (bytes_read < sizeof magic) {
217 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
218 sel_ret = select(fd+1, &rfds, NULL, NULL, &timeout);
220 g_snprintf(errmsg, errmsgl,
221 "Unexpected error from select: %s", strerror(errno));
223 } else if (sel_ret > 0) {
224 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
227 g_snprintf(errmsg, errmsgl, "End of file on pipe during open");
229 g_snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
239 /* Host that wrote it has our byte order, and was running
240 a program using either standard or ss990417 libpcap. */
241 ld->cap_pipe_byte_swapped = FALSE;
242 ld->cap_pipe_modified = FALSE;
244 case PCAP_MODIFIED_MAGIC:
245 /* Host that wrote it has our byte order, but was running
246 a program using either ss990915 or ss991029 libpcap. */
247 ld->cap_pipe_byte_swapped = FALSE;
248 ld->cap_pipe_modified = TRUE;
250 case PCAP_SWAPPED_MAGIC:
251 /* Host that wrote it has a byte order opposite to ours,
252 and was running a program using either standard or
254 ld->cap_pipe_byte_swapped = TRUE;
255 ld->cap_pipe_modified = FALSE;
257 case PCAP_SWAPPED_MODIFIED_MAGIC:
258 /* Host that wrote it out has a byte order opposite to
259 ours, and was running a program using either ss990915
260 or ss991029 libpcap. */
261 ld->cap_pipe_byte_swapped = TRUE;
262 ld->cap_pipe_modified = TRUE;
265 /* Not a "libpcap" type we know about. */
266 g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
270 /* Read the rest of the header */
272 while (bytes_read < sizeof(struct pcap_hdr)) {
275 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
276 sel_ret = select(fd+1, &rfds, NULL, NULL, &timeout);
278 g_snprintf(errmsg, errmsgl,
279 "Unexpected error from select: %s", strerror(errno));
281 } else if (sel_ret > 0) {
282 b = read(fd, ((char *)hdr)+bytes_read,
283 sizeof(struct pcap_hdr) - bytes_read);
286 g_snprintf(errmsg, errmsgl, "End of file on pipe during open");
288 g_snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
296 if (ld->cap_pipe_byte_swapped) {
297 /* Byte-swap the header fields about which we care. */
298 hdr->version_major = BSWAP16(hdr->version_major);
299 hdr->version_minor = BSWAP16(hdr->version_minor);
300 hdr->snaplen = BSWAP32(hdr->snaplen);
301 hdr->network = BSWAP32(hdr->network);
303 ld->linktype = hdr->network;
305 if (hdr->version_major < 2) {
306 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
310 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
311 ld->cap_pipe_err = PIPOK;
315 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
316 ld->cap_pipe_err = PIPERR;
323 /* We read one record from the pipe, take care of byte order in the record
324 * header, write the record to the capture file, and update capture statistics. */
326 cap_pipe_dispatch(loop_data *ld, guchar *data, char *errmsg, int errmsgl)
328 struct pcap_pkthdr phdr;
330 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
334 #ifdef LOG_CAPTURE_VERBOSE
335 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
338 switch (ld->cap_pipe_state) {
340 case STATE_EXPECT_REC_HDR:
341 ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
342 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
343 ld->cap_pipe_bytes_read = 0;
344 ld->cap_pipe_state = STATE_READ_REC_HDR;
347 case STATE_READ_REC_HDR:
348 b = read(ld->cap_pipe_fd, ((char *)&ld->cap_pipe_rechdr)+ld->cap_pipe_bytes_read,
349 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
352 result = PD_PIPE_EOF;
354 result = PD_PIPE_ERR;
357 if ((ld->cap_pipe_bytes_read += b) < ld->cap_pipe_bytes_to_read)
359 result = PD_REC_HDR_READ;
362 case STATE_EXPECT_DATA:
363 ld->cap_pipe_bytes_read = 0;
364 ld->cap_pipe_state = STATE_READ_DATA;
367 case STATE_READ_DATA:
368 b = read(ld->cap_pipe_fd, data+ld->cap_pipe_bytes_read,
369 ld->cap_pipe_rechdr.hdr.incl_len - ld->cap_pipe_bytes_read);
372 result = PD_PIPE_EOF;
374 result = PD_PIPE_ERR;
377 if ((ld->cap_pipe_bytes_read += b) < ld->cap_pipe_rechdr.hdr.incl_len)
379 result = PD_DATA_READ;
383 g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
386 } /* switch (ld->cap_pipe_state) */
389 * We've now read as much data as we were expecting, so process it.
393 case PD_REC_HDR_READ:
394 /* We've read the header. Take care of byte order. */
395 cap_pipe_adjust_header(ld->cap_pipe_byte_swapped, &ld->cap_pipe_hdr,
396 &ld->cap_pipe_rechdr.hdr);
397 if (ld->cap_pipe_rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
398 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
399 ld->packet_count+1, ld->cap_pipe_rechdr.hdr.incl_len);
402 ld->cap_pipe_state = STATE_EXPECT_DATA;
406 /* Fill in a "struct pcap_pkthdr", and process the packet. */
407 phdr.ts.tv_sec = ld->cap_pipe_rechdr.hdr.ts_sec;
408 phdr.ts.tv_usec = ld->cap_pipe_rechdr.hdr.ts_usec;
409 phdr.caplen = ld->cap_pipe_rechdr.hdr.incl_len;
410 phdr.len = ld->cap_pipe_rechdr.hdr.orig_len;
412 ld->packet_cb((u_char *)ld, &phdr, data);
414 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
418 ld->cap_pipe_err = PIPEOF;
422 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
429 ld->cap_pipe_err = PIPERR;
430 /* Return here rather than inside the switch to prevent GCC warning */
433 #endif /* not _WIN32 */
436 /* open the capture input file (pcap or capture pipe) */
438 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
439 char *errmsg, size_t errmsg_len,
440 char *secondary_errmsg, size_t secondary_errmsg_len)
442 gchar open_err_str[PCAP_ERRBUF_SIZE];
445 gchar *sync_secondary_msg_str;
447 const char *set_linktype_err_str;
450 WORD wVersionRequested;
453 static const char ppamsg[] = "can't find PPA for ";
454 const char *libpcap_warn;
458 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
461 /* XXX - opening Winsock on tethereal? */
463 /* Initialize Windows Socket if we are in a WIN32 OS
464 This needs to be done before querying the interface for network/netmask */
466 /* XXX - do we really require 1.1 or earlier?
467 Are there any versions that support only 2.0 or higher? */
468 wVersionRequested = MAKEWORD(1, 1);
469 err = WSAStartup(wVersionRequested, &wsaData);
474 g_snprintf(errmsg, errmsg_len,
475 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
478 case WSAVERNOTSUPPORTED:
479 g_snprintf(errmsg, errmsg_len,
480 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
481 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
485 g_snprintf(errmsg, errmsg_len,
486 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
490 g_snprintf(errmsg, errmsg_len,
491 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
495 g_snprintf(errmsg, errmsg_len,
496 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
500 g_snprintf(errmsg, errmsg_len,
501 "Couldn't initialize Windows Sockets: error %d", err);
504 g_snprintf(secondary_errmsg, secondary_errmsg_len, please_report);
509 /* Open the network interface to capture from it.
510 Some versions of libpcap may put warnings into the error buffer
511 if they succeed; to tell if that's happened, we have to clear
512 the error buffer, and check if it's still a null string. */
513 open_err_str[0] = '\0';
514 ld->pcap_h = pcap_open_live(capture_opts->iface,
515 capture_opts->has_snaplen ? capture_opts->snaplen :
516 WTAP_MAX_PACKET_SIZE,
517 capture_opts->promisc_mode, CAP_READ_TIMEOUT,
520 if (ld->pcap_h != NULL) {
521 /* we've opened "iface" as a network device */
523 /* try to set the capture buffer size */
524 if (pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
525 sync_secondary_msg_str = g_strdup_printf(
526 "The capture buffer size of %luMB seems to be too high for your machine,\n"
527 "the default of 1MB will be used.\n"
529 "Nonetheless, the capture is started.\n",
530 capture_opts->buffer_size);
531 report_capture_error("Couldn't set the capture buffer size!",
532 sync_secondary_msg_str);
533 g_free(sync_secondary_msg_str);
537 /* setting the data link type only works on real interfaces */
538 if (capture_opts->linktype != -1) {
539 set_linktype_err_str = set_pcap_linktype(ld->pcap_h, capture_opts->iface,
540 capture_opts->linktype);
541 if (set_linktype_err_str != NULL) {
542 g_snprintf(errmsg, errmsg_len, "Unable to set data link type (%s).",
543 set_linktype_err_str);
544 g_snprintf(secondary_errmsg, secondary_errmsg_len, please_report);
548 ld->linktype = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
550 /* We couldn't open "iface" as a network device. */
552 /* On Windows, we don't support capturing on pipes, so we give up. */
554 /* On Win32 OSes, the capture devices are probably available to all
555 users; don't warn about permissions problems.
557 Do, however, warn about the lack of 64-bit support, and warn that
558 WAN devices aren't supported. */
559 g_snprintf(errmsg, errmsg_len,
560 "The capture session could not be initiated.\n"
563 g_snprintf(secondary_errmsg, secondary_errmsg_len,
565 "Please check that \"%s\" is the proper interface.\n"
568 "Help can be found at:\n"
570 " http://wiki.ethereal.com/CaptureSetup\n"
573 "WinPcap does not support 64-bit Windows; you will have to use some other\n"
574 "tool to capture traffic, such as netcap.\n"
575 "For netcap details see: http://support.microsoft.com/?id=310875\n"
578 "Note that version 3.0 of WinPcap, and earlier versions of WinPcap, don't\n"
579 "support capturing on PPP/WAN interfaces on Windows NT 4.0 / 2000 / XP /\n"
581 "WinPcap 3.1 has support for it on Windows 2000 / XP / Server 2003, but has no\n"
582 "support for it on Windows NT 4.0 or Windows Vista (Beta 1).",
583 capture_opts->iface);
586 /* try to open iface as a pipe */
587 ld->cap_pipe_fd = cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, errmsg_len);
589 if (ld->cap_pipe_fd == -1) {
591 if (ld->cap_pipe_err == PIPNEXIST) {
592 /* Pipe doesn't exist, so output message for interface */
594 /* If we got a "can't find PPA for X" message, warn the user (who
595 is running (T)Ethereal on HP-UX) that they don't have a version
596 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
597 versions, which properly handle HP-UX, say "can't find /dev/dlpi
598 PPA for X" rather than "can't find PPA for X"). */
599 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
602 "You are running (T)Ethereal with a version of the libpcap library\n"
603 "that doesn't handle HP-UX network devices well; this means that\n"
604 "(T)Ethereal may not be able to capture packets.\n"
606 "To fix this, you should install libpcap 0.6.2, or a later version\n"
607 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
608 "packaged binary form from the Software Porting And Archive Centre\n"
609 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
610 "at the URL lists a number of mirror sites.";
613 g_snprintf(errmsg, errmsg_len,
614 "The capture session could not be initiated (%s).", open_err_str);
615 g_snprintf(secondary_errmsg, secondary_errmsg_len,
616 "Please check to make sure you have sufficient permissions, and that you have\n"
617 "the proper interface or pipe specified.%s", libpcap_warn);
620 * Else pipe (or file) does exist and cap_pipe_open_live() has
625 /* cap_pipe_open_live() succeeded; don't want
626 error message from pcap_open_live() */
627 open_err_str[0] = '\0';
631 /* XXX - will this work for tethereal? */
632 #ifdef MUST_DO_SELECT
633 if (!ld->from_cap_pipe) {
634 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
635 ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
637 ld->pcap_fd = pcap_fileno(ld->pcap_h);
642 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
643 returned a warning; print it, but keep capturing. */
644 if (open_err_str[0] != '\0') {
645 sync_msg_str = g_strdup_printf("%s.", open_err_str);
646 report_capture_error(sync_msg_str, "");
647 g_free(sync_msg_str);
654 /* close the capture input file (pcap or capture pipe) */
655 static void capture_loop_close_input(loop_data *ld) {
657 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
660 /* if open, close the capture pipe "input file" */
661 if (ld->cap_pipe_fd >= 0) {
662 g_assert(ld->from_cap_pipe);
663 eth_close(ld->cap_pipe_fd);
667 /* if open, close the pcap "input file" */
668 if(ld->pcap_h != NULL) {
669 g_assert(!ld->from_cap_pipe);
670 pcap_close(ld->pcap_h);
674 /* Shut down windows sockets */
680 /* init the capture filter */
681 initfilter_status_t capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe, const gchar * iface, gchar * cfilter) {
682 bpf_u_int32 netnum, netmask;
683 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
684 struct bpf_program fcode;
687 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
689 /* capture filters only work on real interfaces */
690 if (cfilter && !from_cap_pipe) {
691 /* A capture filter was specified; set it up. */
692 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
694 * Well, we can't get the netmask for this interface; it's used
695 * only for filters that check for broadcast IP addresses, so
696 * we just punt and use 0. It might be nice to warn the user,
697 * but that's a pain in a GUI application, as it'd involve popping
698 * up a message box, and it's not clear how often this would make
699 * a difference (only filters that check for IP broadcast addresses
703 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
706 if (pcap_compile(pcap_h, &fcode, cfilter, 1, netmask) < 0) {
707 /* Treat this specially - our caller might try to compile this
708 as a display filter and, if that succeeds, warn the user that
709 the display and capture filter syntaxes are different. */
710 return INITFILTER_BAD_FILTER;
712 if (pcap_setfilter(pcap_h, &fcode) < 0) {
713 #ifdef HAVE_PCAP_FREECODE
714 pcap_freecode(&fcode);
716 return INITFILTER_OTHER_ERROR;
718 #ifdef HAVE_PCAP_FREECODE
719 pcap_freecode(&fcode);
723 return INITFILTER_NO_ERROR;
727 /* set up to write to the already-opened capture output file/files */
728 gboolean capture_loop_init_output(capture_options *capture_opts, int save_file_fd, loop_data *ld, char *errmsg, int errmsg_len) {
733 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_output");
737 if (ld->from_cap_pipe) {
738 file_snaplen = ld->cap_pipe_hdr.snaplen;
742 file_snaplen = pcap_snapshot(ld->pcap_h);
745 /* Set up to write to the capture file. */
746 if (capture_opts->multi_files_on) {
747 ld->pdh = ringbuf_init_libpcap_fdopen(ld->linktype, file_snaplen, &err);
749 ld->pdh = libpcap_fdopen(save_file_fd, ld->linktype, file_snaplen,
750 &ld->bytes_written, &err);
753 if (ld->pdh == NULL) {
754 /* We couldn't set up to write to the capture file. */
755 /* XXX - use cf_open_error_message from tethereal instead? */
758 case WTAP_ERR_CANT_OPEN:
759 strcpy(errmsg, "The file to which the capture would be saved"
760 " couldn't be created for some unknown reason.");
763 case WTAP_ERR_SHORT_WRITE:
764 strcpy(errmsg, "A full header couldn't be written to the file"
765 " to which the capture would be saved.");
770 g_snprintf(errmsg, errmsg_len,
771 "The file to which the capture would be"
772 " saved (\"%s\") could not be opened: Error %d.",
773 capture_opts->save_file, err);
775 g_snprintf(errmsg, errmsg_len,
776 "The file to which the capture would be"
777 " saved (\"%s\") could not be opened: %s.",
778 capture_opts->save_file, strerror(err));
789 gboolean capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
791 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
793 if (capture_opts->multi_files_on) {
794 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
796 return libpcap_dump_close(ld->pdh, err_close);
800 /* dispatch incoming packets (pcap or capture pipe) */
802 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
803 char *errmsg, int errmsg_len) {
807 struct timeval timeout;
809 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
813 if (ld->from_cap_pipe) {
814 /* dispatch from capture pipe */
815 #ifdef LOG_CAPTURE_VERBOSE
816 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
819 FD_SET(ld->cap_pipe_fd, &set1);
821 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
822 sel_ret = select(ld->cap_pipe_fd+1, &set1, NULL, NULL, &timeout);
825 if (sel_ret < 0 && errno != EINTR) {
826 g_snprintf(errmsg, errmsg_len,
827 "Unexpected error from select: %s", strerror(errno));
828 report_capture_error(errmsg, please_report);
833 * "select()" says we can read from the pipe without blocking
835 inpkts = cap_pipe_dispatch(ld, pcap_data, errmsg, errmsg_len);
844 /* dispatch from pcap */
845 #ifdef MUST_DO_SELECT
847 * Sigh. The semantics of the read timeout argument to
848 * "pcap_open_live()" aren't particularly well specified by
849 * the "pcap" man page - at least with the BSD BPF code, the
850 * intent appears to be, at least in part, a way of cutting
851 * down the number of reads done on a capture, by blocking
852 * until the buffer fills or a timer expires - and the Linux
853 * libpcap doesn't actually support it, so we can't use it
854 * to break out of the "pcap_dispatch()" every 1/4 of a second
855 * or so. Linux's libpcap is not the only libpcap that doesn't
856 * support the read timeout.
858 * Furthermore, at least on Solaris, the bufmod STREAMS module's
859 * read timeout won't go off if no data has arrived, i.e. it cannot
860 * be used to guarantee that a read from a DLPI stream will return
861 * within a specified amount of time regardless of whether any
862 * data arrives or not.
864 * Thus, on all platforms other than BSD, we do a "select()" on the
865 * file descriptor for the capture, with a timeout of CAP_READ_TIMEOUT
866 * milliseconds, or CAP_READ_TIMEOUT*1000 microseconds.
868 * "select()", on BPF devices, doesn't work as you might expect;
869 * at least on some versions of some flavors of BSD, the timer
870 * doesn't start until a read is done, so it won't expire if
871 * only a "select()" or "poll()" is posted.
873 * If we have "pcap_get_selectable_fd()", we use it to get the
874 * descriptor on which to select; if that's -1, it means there
875 * is no descriptor on which you can do a "select()" (perhaps
876 * because you're capturing on a special device, and that device's
877 * driver unfortunately doesn't support "select()", in which case
878 * we don't do the select - which means Ethereal might block,
879 * unable to accept user input, until a packet arrives. If
880 * that's unacceptable, plead with whoever supplies the software
881 * for that device to add "select()" support.
883 #ifdef LOG_CAPTURE_VERBOSE
884 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
886 if (ld->pcap_fd != -1) {
888 FD_SET(ld->pcap_fd, &set1);
890 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
891 sel_ret = select(ld->pcap_fd+1, &set1, NULL, NULL, &timeout);
894 * "select()" says we can read from it without blocking; go for
897 inpkts = pcap_dispatch(ld->pcap_h, 1, ld->packet_cb, (u_char *)ld);
904 if (sel_ret < 0 && errno != EINTR) {
905 g_snprintf(errmsg, errmsg_len,
906 "Unexpected error from select: %s", strerror(errno));
907 report_capture_error(errmsg, please_report);
913 #endif /* MUST_DO_SELECT */
915 /* dispatch from pcap without select */
917 #ifdef LOG_CAPTURE_VERBOSE
918 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
920 inpkts = pcap_dispatch(ld->pcap_h, 1, ld->packet_cb, (u_char *) ld);
927 #ifdef LOG_CAPTURE_VERBOSE
928 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
930 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
932 /* WinPcap's remote capturing feature doesn't work, see http://wiki.ethereal.com/CaptureSetup_2fWinPcapRemote */
933 /* for reference, an example remote interface: rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C} */
935 /* emulate dispatch from pcap */
937 struct pcap_pkthdr *pkt_header;
941 while( (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1) {
942 ld->packet_cb( (u_char *) ld, pkt_header, pkt_data);
956 #ifdef LOG_CAPTURE_VERBOSE
957 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
964 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
965 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
967 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
968 char *errmsg, int errmsg_len) {
972 gboolean is_tempfile;
975 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
976 (capture_opts->save_file) ? capture_opts->save_file : "");
978 if (capture_opts->save_file != NULL) {
979 /* We return to the caller while the capture is in progress.
980 * Therefore we need to take a copy of save_file in
981 * case the caller destroys it after we return.
983 capfile_name = g_strdup(capture_opts->save_file);
984 if (strcmp(capfile_name, "-") == 0) {
985 /* Write to the standard output. */
986 if (capture_opts->multi_files_on) {
987 /* ringbuffer is enabled; that doesn't work with standard output */
988 g_snprintf(errmsg, errmsg_len,
989 "Ring buffer requested, but capture is being written to the standard output.");
990 g_free(capfile_name);
996 if (capture_opts->multi_files_on) {
997 /* ringbuffer is enabled */
998 *save_file_fd = ringbuf_init(capfile_name,
999 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
1001 /* we need the ringbuf name */
1002 if(*save_file_fd != -1) {
1003 g_free(capfile_name);
1004 capfile_name = g_strdup(ringbuf_current_filename());
1007 /* Try to open/create the specified file for use as a capture buffer. */
1008 *save_file_fd = open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
1012 is_tempfile = FALSE;
1014 /* Choose a random name for the temporary capture buffer */
1015 *save_file_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
1016 capfile_name = g_strdup(tmpname);
1020 /* did we fail to open the output file? */
1021 if (*save_file_fd == -1) {
1023 g_snprintf(errmsg, errmsg_len,
1024 "The temporary file to which the capture would be saved (\"%s\") "
1025 "could not be opened: %s.", capfile_name, strerror(errno));
1027 if (capture_opts->multi_files_on) {
1028 ringbuf_error_cleanup();
1031 g_snprintf(errmsg, errmsg_len,
1032 "The file to which the capture would be saved (\"%s\") "
1033 "could not be opened: %s.", capfile_name,
1036 g_free(capfile_name);
1040 if(capture_opts->save_file != NULL) {
1041 g_free(capture_opts->save_file);
1043 capture_opts->save_file = capfile_name;
1044 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
1045 "g_free(capfile_name)". */
1053 capture_loop_stop_signal_handler(int signo _U_)
1055 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Signal: Stop capture");
1056 capture_loop_stop();
1061 #define TIME_GET() GetTickCount()
1063 #define TIME_GET() time(NULL)
1066 /* Do the low-level work of a capture.
1067 Returns TRUE if it succeeds, FALSE otherwise. */
1069 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
1071 time_t upd_time, cur_time;
1075 gint inpkts_to_sync_pipe = 0; /* packets not already send out to the sync_pipe */
1076 condition *cnd_file_duration = NULL;
1077 condition *cnd_autostop_files = NULL;
1078 condition *cnd_autostop_size = NULL;
1079 condition *cnd_autostop_duration = NULL;
1080 guint32 autostop_files = 0;
1083 gboolean cfilter_error = FALSE;
1084 char errmsg[4096+1];
1085 char secondary_errmsg[4096+1];
1086 int save_file_fd = -1;
1089 /* init the loop data */
1091 ld.packet_count = 0;
1092 if (capture_opts->has_autostop_packets)
1093 ld.packet_max = capture_opts->autostop_packets;
1095 ld.packet_max = 0; /* no limit */
1096 ld.err = 0; /* no error seen yet */
1097 ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
1098 ld.pcap_err = FALSE;
1099 ld.from_cap_pipe = FALSE;
1102 ld.cap_pipe_fd = -1;
1104 #ifdef MUST_DO_SELECT
1107 ld.packet_cb = capture_loop_packet_cb;
1110 /* We haven't yet gotten the capture statistics. */
1111 *stats_known = FALSE;
1115 * Catch SIGUSR1, so that we exit cleanly if the parent process
1116 * kills us with it due to the user selecting "Capture->Stop".
1118 signal(SIGUSR1, capture_loop_stop_signal_handler);
1121 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
1122 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
1124 /* open the "input file" from network interface or capture pipe */
1125 if (!capture_loop_open_input(capture_opts, &ld, errmsg, sizeof(errmsg),
1126 secondary_errmsg, sizeof(secondary_errmsg))) {
1130 /* init the input filter from the network interface (capture pipe will do nothing) */
1131 switch (capture_loop_init_filter(ld.pcap_h, ld.from_cap_pipe, capture_opts->iface, capture_opts->cfilter)) {
1133 case INITFILTER_NO_ERROR:
1136 case INITFILTER_BAD_FILTER:
1137 cfilter_error = TRUE;
1138 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(ld.pcap_h));
1139 *secondary_errmsg = '\0';
1142 case INITFILTER_OTHER_ERROR:
1143 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
1144 pcap_geterr(ld.pcap_h));
1145 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
1149 /* If we're supposed to write to a capture file, open it for output
1150 (temporary/specified name/ringbuffer) */
1151 if (capture_opts->saving_to_file) {
1152 if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
1153 *secondary_errmsg = '\0';
1157 /* set up to write to the already-opened capture output file/files */
1158 if (!capture_loop_init_output(capture_opts, save_file_fd, &ld, errmsg, sizeof(errmsg))) {
1159 *secondary_errmsg = '\0';
1163 /* XXX - capture SIGTERM and close the capture, in case we're on a
1164 Linux 2.0[.x] system and you have to explicitly close the capture
1165 stream in order to turn promiscuous mode off? We need to do that
1166 in other places as well - and I don't think that works all the
1167 time in any case, due to libpcap bugs. */
1169 /* Well, we should be able to start capturing.
1171 Sync out the capture file, so the header makes it to the file system,
1172 and send a "capture started successfully and capture file created"
1173 message to our parent so that they'll open the capture file and
1174 update its windows to indicate that we have a live capture in
1176 libpcap_dump_flush(ld.pdh, NULL);
1177 report_new_capture_file(capture_opts->save_file);
1180 /* initialize capture stop (and alike) conditions */
1181 init_capture_stop_conditions();
1182 /* create stop conditions */
1183 if (capture_opts->has_autostop_filesize)
1185 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
1186 if (capture_opts->has_autostop_duration)
1187 cnd_autostop_duration =
1188 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
1190 if (capture_opts->multi_files_on) {
1191 if (capture_opts->has_file_duration)
1193 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
1195 if (capture_opts->has_autostop_files)
1196 cnd_autostop_files =
1197 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
1200 /* init the time values */
1201 start_time = TIME_GET();
1202 upd_time = TIME_GET();
1204 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
1206 /* WOW, everything is prepared! */
1207 /* please fasten your seat belts, we will enter now the actual capture loop */
1209 /* dispatch incoming packets */
1210 inpkts = capture_loop_dispatch(capture_opts, &ld, errmsg, sizeof(errmsg));
1213 /* any news from our parent (signal pipe)? -> just stop the capture */
1214 if (!signal_pipe_check_running()) {
1220 inpkts_to_sync_pipe += inpkts;
1222 /* check capture size condition */
1223 if (cnd_autostop_size != NULL &&
1224 cnd_eval(cnd_autostop_size, (guint32)ld.bytes_written)){
1225 /* Capture size limit reached, do we have another file? */
1226 if (capture_opts->multi_files_on) {
1227 if (cnd_autostop_files != NULL &&
1228 cnd_eval(cnd_autostop_files, ++autostop_files)) {
1229 /* no files left: stop here */
1234 /* Switch to the next ringbuffer file */
1235 if (ringbuf_switch_file(&ld.pdh, &capture_opts->save_file,
1236 &save_file_fd, &ld.err)) {
1237 /* File switch succeeded: reset the conditions */
1238 cnd_reset(cnd_autostop_size);
1239 if (cnd_file_duration) {
1240 cnd_reset(cnd_file_duration);
1242 libpcap_dump_flush(ld.pdh, NULL);
1243 report_packet_count(inpkts_to_sync_pipe);
1244 inpkts_to_sync_pipe = 0;
1245 report_new_capture_file(capture_opts->save_file);
1247 /* File switch failed: stop here */
1252 /* single file, stop now */
1256 } /* cnd_autostop_size */
1257 if (capture_opts->output_to_pipe) {
1258 libpcap_dump_flush(ld.pdh, NULL);
1262 /* Only update once a second (Win32: 500ms) so as not to overload slow displays */
1263 cur_time = TIME_GET();
1265 if ( (cur_time - upd_time) > 500) {
1267 if (cur_time - upd_time > 0) {
1269 upd_time = cur_time;
1271 /*if (pcap_stats(pch, stats) >= 0) {
1272 *stats_known = TRUE;
1275 /* Let the parent process know. */
1276 if (inpkts_to_sync_pipe) {
1278 libpcap_dump_flush(ld.pdh, NULL);
1280 /* Send our parent a message saying we've written out "inpkts_to_sync_pipe"
1281 packets to the capture file. */
1282 report_packet_count(inpkts_to_sync_pipe);
1284 inpkts_to_sync_pipe = 0;
1287 /* check capture duration condition */
1288 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
1289 /* The maximum capture time has elapsed; stop the capture. */
1294 /* check capture file duration condition */
1295 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
1296 /* duration limit reached, do we have another file? */
1297 if (capture_opts->multi_files_on) {
1298 if (cnd_autostop_files != NULL &&
1299 cnd_eval(cnd_autostop_files, ++autostop_files)) {
1300 /* no files left: stop here */
1305 /* Switch to the next ringbuffer file */
1306 if (ringbuf_switch_file(&ld.pdh, &capture_opts->save_file, &save_file_fd, &ld.err)) {
1307 /* file switch succeeded: reset the conditions */
1308 cnd_reset(cnd_file_duration);
1309 if(cnd_autostop_size)
1310 cnd_reset(cnd_autostop_size);
1311 libpcap_dump_flush(ld.pdh, NULL);
1312 report_packet_count(inpkts_to_sync_pipe);
1313 inpkts_to_sync_pipe = 0;
1314 report_new_capture_file(capture_opts->save_file);
1316 /* File switch failed: stop here */
1321 /* single file, stop now */
1325 } /* cnd_file_duration */
1328 } /* while (ld.go) */
1330 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
1332 /* delete stop conditions */
1333 if (cnd_file_duration != NULL)
1334 cnd_delete(cnd_file_duration);
1335 if (cnd_autostop_files != NULL)
1336 cnd_delete(cnd_autostop_files);
1337 if (cnd_autostop_size != NULL)
1338 cnd_delete(cnd_autostop_size);
1339 if (cnd_autostop_duration != NULL)
1340 cnd_delete(cnd_autostop_duration);
1342 /* did we had a pcap (input) error? */
1344 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
1345 pcap_geterr(ld.pcap_h));
1346 report_capture_error(errmsg, please_report);
1349 else if (ld.from_cap_pipe && ld.cap_pipe_err == PIPERR)
1350 report_capture_error(errmsg, "");
1353 /* did we had an error while capturing? */
1357 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, ld.err,
1359 report_capture_error(errmsg, please_report);
1363 if (capture_opts->saving_to_file) {
1364 /* close the wiretap (output) file */
1365 close_ok = capture_loop_close_output(capture_opts, &ld, &err_close);
1369 /* there might be packets not yet notified to the parent */
1370 /* (do this after closing the file, so all packets are already flushed) */
1371 if(inpkts_to_sync_pipe) {
1372 report_packet_count(inpkts_to_sync_pipe);
1373 inpkts_to_sync_pipe = 0;
1376 /* If we've displayed a message about a write error, there's no point
1377 in displaying another message about an error on close. */
1378 if (!close_ok && write_ok) {
1379 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
1381 report_capture_error(errmsg, "");
1385 * XXX We exhibit different behaviour between normal mode and sync mode
1386 * when the pipe is stdin and not already at EOF. If we're a child, the
1387 * parent's stdin isn't closed, so if the user starts another capture,
1388 * cap_pipe_open_live() will very likely not see the expected magic bytes and
1389 * will say "Unrecognized libpcap format". On the other hand, in normal
1390 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
1393 /* get packet drop statistics from pcap */
1394 if(ld.pcap_h != NULL) {
1395 g_assert(!ld.from_cap_pipe);
1396 /* Get the capture statistics, so we know how many packets were
1398 if (pcap_stats(ld.pcap_h, stats) >= 0) {
1399 *stats_known = TRUE;
1400 /* Let the parent process know. */
1401 report_packet_drops(stats->ps_drop);
1403 g_snprintf(errmsg, sizeof(errmsg),
1404 "Can't get packet-drop statistics: %s",
1405 pcap_geterr(ld.pcap_h));
1406 report_capture_error(errmsg, please_report);
1410 /* close the input file (pcap or capture pipe) */
1411 capture_loop_close_input(&ld);
1413 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
1415 /* ok, if the write and the close were successful. */
1416 return write_ok && close_ok;
1419 if (capture_opts->multi_files_on) {
1420 /* cleanup ringbuffer */
1421 ringbuf_error_cleanup();
1423 /* We can't use the save file, and we have no FILE * for the stream
1424 to close in order to close it, so close the FD directly. */
1425 if(save_file_fd != -1) {
1426 eth_close(save_file_fd);
1429 /* We couldn't even start the capture, so get rid of the capture
1431 if(capture_opts->save_file != NULL) {
1432 eth_unlink(capture_opts->save_file);
1433 g_free(capture_opts->save_file);
1436 capture_opts->save_file = NULL;
1438 report_cfilter_error(capture_opts->cfilter, errmsg);
1440 report_capture_error(errmsg, secondary_errmsg);
1442 /* close the input file (pcap or cap_pipe) */
1443 capture_loop_close_input(&ld);
1445 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
1451 void capture_loop_stop(void)
1458 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
1459 int err, gboolean is_close)
1464 g_snprintf(errmsg, errmsglen,
1465 "Not all the packets could be written to the file"
1466 " to which the capture was being saved\n"
1467 "(\"%s\") because there is no space left on the file system\n"
1468 "on which that file resides.",
1474 g_snprintf(errmsg, errmsglen,
1475 "Not all the packets could be written to the file"
1476 " to which the capture was being saved\n"
1477 "(\"%s\") because you are too close to, or over,"
1478 " your disk quota\n"
1479 "on the file system on which that file resides.",
1484 case WTAP_ERR_CANT_CLOSE:
1485 g_snprintf(errmsg, errmsglen,
1486 "The file to which the capture was being saved"
1487 " couldn't be closed for some unknown reason.");
1490 case WTAP_ERR_SHORT_WRITE:
1491 g_snprintf(errmsg, errmsglen,
1492 "Not all the packets could be written to the file"
1493 " to which the capture was being saved\n"
1500 g_snprintf(errmsg, errmsglen,
1501 "The file to which the capture was being saved\n"
1502 "(\"%s\") could not be closed: %s.",
1503 fname, wtap_strerror(err));
1505 g_snprintf(errmsg, errmsglen,
1506 "An error occurred while writing to the file"
1507 " to which the capture was being saved\n"
1509 fname, wtap_strerror(err));
1516 /* one packet was captured, process it */
1518 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
1521 loop_data *ld = (loop_data *) user;
1524 /* if the user told us to stop after x packets, do we have enough? */
1526 if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
1532 /* We're supposed to write the packet to a file; do so.
1533 If this fails, set "ld->go" to FALSE, to stop the capture, and set
1534 "ld->err" to the error. */
1535 if (!libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err)) {
1542 #endif /* HAVE_LIBPCAP */