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);
304 if (hdr->version_major < 2) {
305 g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
309 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
310 ld->cap_pipe_err = PIPOK;
314 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_open_live: error %s", errmsg);
315 ld->cap_pipe_err = PIPERR;
322 /* We read one record from the pipe, take care of byte order in the record
323 * header, write the record to the capture file, and update capture statistics. */
325 cap_pipe_dispatch(int fd, loop_data *ld, struct pcap_hdr *hdr,
326 struct pcaprec_modified_hdr *rechdr, guchar *data,
327 char *errmsg, int errmsgl)
329 struct pcap_pkthdr phdr;
331 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
335 #ifdef LOG_CAPTURE_VERBOSE
336 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "cap_pipe_dispatch");
339 switch (ld->cap_pipe_state) {
341 case STATE_EXPECT_REC_HDR:
342 ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
343 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
344 ld->cap_pipe_bytes_read = 0;
345 ld->cap_pipe_state = STATE_READ_REC_HDR;
348 case STATE_READ_REC_HDR:
349 b = read(fd, ((char *)rechdr)+ld->cap_pipe_bytes_read,
350 ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
353 result = PD_PIPE_EOF;
355 result = PD_PIPE_ERR;
358 if ((ld->cap_pipe_bytes_read += b) < ld->cap_pipe_bytes_to_read)
360 result = PD_REC_HDR_READ;
363 case STATE_EXPECT_DATA:
364 ld->cap_pipe_bytes_read = 0;
365 ld->cap_pipe_state = STATE_READ_DATA;
368 case STATE_READ_DATA:
369 b = read(fd, data+ld->cap_pipe_bytes_read, 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) < 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, hdr, &rechdr->hdr);
396 if (rechdr->hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
397 g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
398 ld->packet_count+1, rechdr->hdr.incl_len);
401 ld->cap_pipe_state = STATE_EXPECT_DATA;
405 /* Fill in a "struct pcap_pkthdr", and process the packet. */
406 phdr.ts.tv_sec = rechdr->hdr.ts_sec;
407 phdr.ts.tv_usec = rechdr->hdr.ts_usec;
408 phdr.caplen = rechdr->hdr.incl_len;
409 phdr.len = rechdr->hdr.orig_len;
411 ld->packet_cb((u_char *)ld, &phdr, data);
413 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
417 ld->cap_pipe_err = PIPEOF;
421 g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
428 ld->cap_pipe_err = PIPERR;
429 /* Return here rather than inside the switch to prevent GCC warning */
432 #endif /* not _WIN32 */
435 /* open the capture input file (pcap or capture pipe) */
437 capture_loop_open_input(capture_options *capture_opts, loop_data *ld,
438 char *errmsg, size_t errmsg_len,
439 char *secondary_errmsg, size_t secondary_errmsg_len)
441 gchar open_err_str[PCAP_ERRBUF_SIZE];
444 gchar *sync_secondary_msg_str;
446 const char *set_linktype_err_str;
449 WORD wVersionRequested;
452 static const char ppamsg[] = "can't find PPA for ";
453 const char *libpcap_warn;
457 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_input : %s", capture_opts->iface);
460 /* XXX - opening Winsock on tethereal? */
462 /* Initialize Windows Socket if we are in a WIN32 OS
463 This needs to be done before querying the interface for network/netmask */
465 /* XXX - do we really require 1.1 or earlier?
466 Are there any versions that support only 2.0 or higher? */
467 wVersionRequested = MAKEWORD(1, 1);
468 err = WSAStartup(wVersionRequested, &wsaData);
473 g_snprintf(errmsg, errmsg_len,
474 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
477 case WSAVERNOTSUPPORTED:
478 g_snprintf(errmsg, errmsg_len,
479 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
480 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
484 g_snprintf(errmsg, errmsg_len,
485 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
489 g_snprintf(errmsg, errmsg_len,
490 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
494 g_snprintf(errmsg, errmsg_len,
495 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
499 g_snprintf(errmsg, errmsg_len,
500 "Couldn't initialize Windows Sockets: error %d", err);
503 g_snprintf(secondary_errmsg, secondary_errmsg_len, please_report);
508 /* Open the network interface to capture from it.
509 Some versions of libpcap may put warnings into the error buffer
510 if they succeed; to tell if that's happened, we have to clear
511 the error buffer, and check if it's still a null string. */
512 open_err_str[0] = '\0';
513 ld->pcap_h = pcap_open_live(capture_opts->iface,
514 capture_opts->has_snaplen ? capture_opts->snaplen :
515 WTAP_MAX_PACKET_SIZE,
516 capture_opts->promisc_mode, CAP_READ_TIMEOUT,
519 if (ld->pcap_h != NULL) {
520 /* we've opened "iface" as a network device */
522 /* try to set the capture buffer size */
523 if (pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
524 sync_secondary_msg_str = g_strdup_printf(
525 "The capture buffer size of %luMB seems to be too high for your machine,\n"
526 "the default of 1MB will be used.\n"
528 "Nonetheless, the capture is started.\n",
529 capture_opts->buffer_size);
530 sync_pipe_errmsg_to_parent("Couldn't set the capture buffer size!",
531 sync_secondary_msg_str);
532 g_free(sync_secondary_msg_str);
536 /* setting the data link type only works on real interfaces */
537 if (capture_opts->linktype != -1) {
538 set_linktype_err_str = set_pcap_linktype(ld->pcap_h, capture_opts->iface,
539 capture_opts->linktype);
540 if (set_linktype_err_str != NULL) {
541 g_snprintf(errmsg, errmsg_len, "Unable to set data link type (%s).",
542 set_linktype_err_str);
543 g_snprintf(secondary_errmsg, secondary_errmsg_len,
544 "Please report this to the Ethereal developers");
549 /* We couldn't open "iface" as a network device. */
551 /* On Windows, we don't support capturing on pipes, so we give up. */
553 /* On Win32 OSes, the capture devices are probably available to all
554 users; don't warn about permissions problems.
556 Do, however, warn about the lack of 64-bit support, and warn that
557 WAN devices aren't supported. */
558 g_snprintf(errmsg, errmsg_len,
559 "The capture session could not be initiated.\n"
562 g_snprintf(secondary_errmsg, secondary_errmsg_len,
564 "Please check that \"%s\" is the proper interface.\n"
567 "Help can be found at:\n"
569 " http://wiki.ethereal.com/CaptureSetup\n"
572 "WinPcap does not support 64-bit Windows; you will have to use some other\n"
573 "tool to capture traffic, such as netcap.\n"
574 "For netcap details see: http://support.microsoft.com/?id=310875\n"
577 "Note that version 3.0 of WinPcap, and earlier versions of WinPcap, don't\n"
578 "support capturing on PPP/WAN interfaces on Windows NT 4.0 / 2000 / XP /\n"
580 "WinPcap 3.1 has support for it on Windows 2000 / XP / Server 2003, but has no\n"
581 "support for it on Windows NT 4.0 or Windows Vista (Beta 1).",
582 capture_opts->iface);
585 /* try to open iface as a pipe */
586 ld->cap_pipe_fd = cap_pipe_open_live(capture_opts->iface, &ld->cap_pipe_hdr, ld, errmsg, errmsg_len);
588 if (ld->cap_pipe_fd == -1) {
590 if (ld->cap_pipe_err == PIPNEXIST) {
591 /* Pipe doesn't exist, so output message for interface */
593 /* If we got a "can't find PPA for XXX" message, warn the user (who
594 is running (T)Ethereal on HP-UX) that they don't have a version
595 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
596 versions, which properly handle HP-UX, say "can't find /dev/dlpi
597 PPA for XXX" rather than "can't find PPA for XXX"). */
598 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
601 "You are running (T)Ethereal with a version of the libpcap library\n"
602 "that doesn't handle HP-UX network devices well; this means that\n"
603 "(T)Ethereal may not be able to capture packets.\n"
605 "To fix this, you should install libpcap 0.6.2, or a later version\n"
606 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
607 "packaged binary form from the Software Porting And Archive Centre\n"
608 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
609 "at the URL lists a number of mirror sites.";
612 g_snprintf(errmsg, errmsg_len,
613 "The capture session could not be initiated (%s).", open_err_str);
614 g_snprintf(secondary_errmsg, secondary_errmsg_len,
615 "Please check to make sure you have sufficient permissions, and that you have\n"
616 "the proper interface or pipe specified.%s", libpcap_warn);
619 * Else pipe (or file) does exist and cap_pipe_open_live() has
624 /* cap_pipe_open_live() succeeded; don't want
625 error message from pcap_open_live() */
626 open_err_str[0] = '\0';
630 /* XXX - will this work for tethereal? */
631 #ifdef MUST_DO_SELECT
632 if (!ld->from_cap_pipe) {
633 #ifdef HAVE_PCAP_GET_SELECTABLE_FD
634 ld->pcap_fd = pcap_get_selectable_fd(ld->pcap_h);
636 ld->pcap_fd = pcap_fileno(ld->pcap_h);
641 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
642 returned a warning; print it, but keep capturing. */
643 if (open_err_str[0] != '\0') {
644 sync_msg_str = g_strdup_printf("%s.", open_err_str);
645 sync_pipe_errmsg_to_parent(sync_msg_str, "");
646 g_free(sync_msg_str);
653 /* close the capture input file (pcap or capture pipe) */
654 static void capture_loop_close_input(loop_data *ld) {
656 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_input");
659 /* if open, close the capture pipe "input file" */
660 if (ld->cap_pipe_fd >= 0) {
661 g_assert(ld->from_cap_pipe);
662 eth_close(ld->cap_pipe_fd);
666 /* if open, close the pcap "input file" */
667 if(ld->pcap_h != NULL) {
668 g_assert(!ld->from_cap_pipe);
669 pcap_close(ld->pcap_h);
673 /* Shut down windows sockets */
679 /* init the capture filter */
680 initfilter_status_t capture_loop_init_filter(pcap_t *pcap_h, gboolean from_cap_pipe, const gchar * iface, gchar * cfilter) {
681 bpf_u_int32 netnum, netmask;
682 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
683 struct bpf_program fcode;
686 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_init_filter: %s", cfilter);
688 /* capture filters only work on real interfaces */
689 if (cfilter && !from_cap_pipe) {
690 /* A capture filter was specified; set it up. */
691 if (pcap_lookupnet(iface, &netnum, &netmask, lookup_net_err_str) < 0) {
693 * Well, we can't get the netmask for this interface; it's used
694 * only for filters that check for broadcast IP addresses, so
695 * we just punt and use 0. It might be nice to warn the user,
696 * but that's a pain in a GUI application, as it'd involve popping
697 * up a message box, and it's not clear how often this would make
698 * a difference (only filters that check for IP broadcast addresses
702 "Warning: Couldn't obtain netmask info (%s).", lookup_net_err_str);*/
705 if (pcap_compile(pcap_h, &fcode, cfilter, 1, netmask) < 0) {
706 /* Treat this specially - our caller might try to compile this
707 as a display filter and, if that succeeds, warn the user that
708 the display and capture filter syntaxes are different. */
709 return INITFILTER_BAD_FILTER;
711 if (pcap_setfilter(pcap_h, &fcode) < 0) {
712 #ifdef HAVE_PCAP_FREECODE
713 pcap_freecode(&fcode);
715 return INITFILTER_OTHER_ERROR;
717 #ifdef HAVE_PCAP_FREECODE
718 pcap_freecode(&fcode);
722 return INITFILTER_NO_ERROR;
726 /* set up to write to the already-opened capture output file/files */
727 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");
735 /* get packet encapsulation type and snaplen */
737 if (ld->from_cap_pipe) {
738 pcap_encap = ld->cap_pipe_hdr.network;
739 file_snaplen = ld->cap_pipe_hdr.snaplen;
743 pcap_encap = get_pcap_linktype(ld->pcap_h, capture_opts->iface);
744 file_snaplen = pcap_snapshot(ld->pcap_h);
747 /* Set up to write to the capture file. */
748 ld->linktype = pcap_encap;
749 if (capture_opts->multi_files_on) {
750 ld->pdh = ringbuf_init_libpcap_fdopen(ld->linktype, file_snaplen, &err);
752 ld->pdh = libpcap_fdopen(save_file_fd, ld->linktype, file_snaplen,
753 &ld->bytes_written, &err);
756 if (ld->pdh == NULL) {
757 /* We couldn't set up to write to the capture file. */
758 /* XXX - use cf_open_error_message from tethereal instead? */
761 case WTAP_ERR_CANT_OPEN:
762 strcpy(errmsg, "The file to which the capture would be saved"
763 " couldn't be created for some unknown reason.");
766 case WTAP_ERR_SHORT_WRITE:
767 strcpy(errmsg, "A full header couldn't be written to the file"
768 " to which the capture would be saved.");
773 g_snprintf(errmsg, errmsg_len,
774 "The file to which the capture would be"
775 " saved (\"%s\") could not be opened: Error %d.",
776 capture_opts->save_file, err);
778 g_snprintf(errmsg, errmsg_len,
779 "The file to which the capture would be"
780 " saved (\"%s\") could not be opened: %s.",
781 capture_opts->save_file, strerror(err));
792 gboolean capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
794 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
796 if (capture_opts->multi_files_on) {
797 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
799 return libpcap_dump_close(ld->pdh, err_close);
803 /* dispatch incoming packets (pcap or capture pipe) */
805 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
806 char *errmsg, int errmsg_len) {
810 struct timeval timeout;
812 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
816 if (ld->from_cap_pipe) {
817 /* dispatch from capture pipe */
818 #ifdef LOG_CAPTURE_VERBOSE
819 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
822 FD_SET(ld->cap_pipe_fd, &set1);
824 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
825 sel_ret = select(ld->cap_pipe_fd+1, &set1, NULL, NULL, &timeout);
828 if (sel_ret < 0 && errno != EINTR) {
829 g_snprintf(errmsg, errmsg_len,
830 "Unexpected error from select: %s", strerror(errno));
831 sync_pipe_errmsg_to_parent(errmsg, please_report);
836 * "select()" says we can read from the pipe without blocking
838 inpkts = cap_pipe_dispatch(ld->cap_pipe_fd, ld, &ld->cap_pipe_hdr, &ld->cap_pipe_rechdr, pcap_data,
848 /* dispatch from pcap */
849 #ifdef MUST_DO_SELECT
851 * Sigh. The semantics of the read timeout argument to
852 * "pcap_open_live()" aren't particularly well specified by
853 * the "pcap" man page - at least with the BSD BPF code, the
854 * intent appears to be, at least in part, a way of cutting
855 * down the number of reads done on a capture, by blocking
856 * until the buffer fills or a timer expires - and the Linux
857 * libpcap doesn't actually support it, so we can't use it
858 * to break out of the "pcap_dispatch()" every 1/4 of a second
859 * or so. Linux's libpcap is not the only libpcap that doesn't
860 * support the read timeout.
862 * Furthermore, at least on Solaris, the bufmod STREAMS module's
863 * read timeout won't go off if no data has arrived, i.e. it cannot
864 * be used to guarantee that a read from a DLPI stream will return
865 * within a specified amount of time regardless of whether any
866 * data arrives or not.
868 * Thus, on all platforms other than BSD, we do a "select()" on the
869 * file descriptor for the capture, with a timeout of CAP_READ_TIMEOUT
870 * milliseconds, or CAP_READ_TIMEOUT*1000 microseconds.
872 * "select()", on BPF devices, doesn't work as you might expect;
873 * at least on some versions of some flavors of BSD, the timer
874 * doesn't start until a read is done, so it won't expire if
875 * only a "select()" or "poll()" is posted.
877 * If we have "pcap_get_selectable_fd()", we use it to get the
878 * descriptor on which to select; if that's -1, it means there
879 * is no descriptor on which you can do a "select()" (perhaps
880 * because you're capturing on a special device, and that device's
881 * driver unfortunately doesn't support "select()", in which case
882 * we don't do the select - which means Ethereal might block,
883 * unable to accept user input, until a packet arrives. If
884 * that's unacceptable, plead with whoever supplies the software
885 * for that device to add "select()" support.
887 #ifdef LOG_CAPTURE_VERBOSE
888 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
890 if (ld->pcap_fd != -1) {
892 FD_SET(ld->pcap_fd, &set1);
894 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
895 sel_ret = select(ld->pcap_fd+1, &set1, NULL, NULL, &timeout);
898 * "select()" says we can read from it without blocking; go for
901 inpkts = pcap_dispatch(ld->pcap_h, 1, ld->packet_cb, (u_char *)ld);
908 if (sel_ret < 0 && errno != EINTR) {
909 g_snprintf(errmsg, errmsg_len,
910 "Unexpected error from select: %s", strerror(errno));
911 sync_pipe_errmsg_to_parent(errmsg, please_report);
917 #endif /* MUST_DO_SELECT */
919 /* dispatch from pcap without select */
921 #ifdef LOG_CAPTURE_VERBOSE
922 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
924 inpkts = pcap_dispatch(ld->pcap_h, 1, ld->packet_cb, (u_char *) ld);
931 #ifdef LOG_CAPTURE_VERBOSE
932 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
934 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
936 /* WinPcap's remote capturing feature doesn't work, see http://wiki.ethereal.com/CaptureSetup_2fWinPcapRemote */
937 /* for reference, an example remote interface: rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C} */
939 /* emulate dispatch from pcap */
941 struct pcap_pkthdr *pkt_header;
945 while( (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1) {
946 ld->packet_cb( (u_char *) ld, pkt_header, pkt_data);
960 #ifdef LOG_CAPTURE_VERBOSE
961 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
968 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
969 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
971 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
972 char *errmsg, int errmsg_len) {
976 gboolean is_tempfile;
979 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
980 (capture_opts->save_file) ? capture_opts->save_file : "");
982 if (capture_opts->save_file != NULL) {
983 /* We return to the caller while the capture is in progress.
984 * Therefore we need to take a copy of save_file in
985 * case the caller destroys it after we return.
987 capfile_name = g_strdup(capture_opts->save_file);
988 if (strcmp(capfile_name, "-") == 0) {
989 /* Write to the standard output. */
990 if (capture_opts->multi_files_on) {
991 /* ringbuffer is enabled; that doesn't work with standard output */
992 g_snprintf(errmsg, errmsg_len,
993 "Ring buffer requested, but capture is being written to the standard output.");
994 g_free(capfile_name);
1000 if (capture_opts->multi_files_on) {
1001 /* ringbuffer is enabled */
1002 *save_file_fd = ringbuf_init(capfile_name,
1003 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
1005 /* we need the ringbuf name */
1006 if(*save_file_fd != -1) {
1007 g_free(capfile_name);
1008 capfile_name = g_strdup(ringbuf_current_filename());
1011 /* Try to open/create the specified file for use as a capture buffer. */
1012 *save_file_fd = open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
1016 is_tempfile = FALSE;
1018 /* Choose a random name for the temporary capture buffer */
1019 *save_file_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
1020 capfile_name = g_strdup(tmpname);
1024 /* did we fail to open the output file? */
1025 if (*save_file_fd == -1) {
1027 g_snprintf(errmsg, errmsg_len,
1028 "The temporary file to which the capture would be saved (\"%s\") "
1029 "could not be opened: %s.", capfile_name, strerror(errno));
1031 if (capture_opts->multi_files_on) {
1032 ringbuf_error_cleanup();
1035 g_snprintf(errmsg, errmsg_len,
1036 "The file to which the capture would be saved (\"%s\") "
1037 "could not be opened: %s.", capfile_name,
1040 g_free(capfile_name);
1044 if(capture_opts->save_file != NULL) {
1045 g_free(capture_opts->save_file);
1047 capture_opts->save_file = capfile_name;
1048 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
1049 "g_free(capfile_name)". */
1057 capture_loop_stop_signal_handler(int signo _U_)
1059 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Signal: Stop capture");
1060 capture_loop_stop();
1065 #define TIME_GET() GetTickCount()
1067 #define TIME_GET() time(NULL)
1070 /* Do the low-level work of a capture.
1071 Returns TRUE if it succeeds, FALSE otherwise. */
1073 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
1075 time_t upd_time, cur_time;
1079 gint inpkts_to_sync_pipe = 0; /* packets not already send out to the sync_pipe */
1080 condition *cnd_file_duration = NULL;
1081 condition *cnd_autostop_files = NULL;
1082 condition *cnd_autostop_size = NULL;
1083 condition *cnd_autostop_duration = NULL;
1084 guint32 autostop_files = 0;
1087 gboolean cfilter_error = FALSE;
1088 char errmsg[4096+1];
1089 char secondary_errmsg[4096+1];
1090 int save_file_fd = -1;
1093 /* init the loop data */
1095 ld.packet_count = 0;
1096 if (capture_opts->has_autostop_packets)
1097 ld.packet_max = capture_opts->autostop_packets;
1099 ld.packet_max = 0; /* no limit */
1100 ld.err = 0; /* no error seen yet */
1101 ld.wtap_linktype = WTAP_ENCAP_UNKNOWN;
1102 ld.pcap_err = FALSE;
1103 ld.from_cap_pipe = FALSE;
1106 ld.cap_pipe_fd = -1;
1108 #ifdef MUST_DO_SELECT
1111 ld.packet_cb = capture_loop_packet_cb;
1114 /* We haven't yet gotten the capture statistics. */
1115 *stats_known = FALSE;
1119 * Catch SIGUSR1, so that we exit cleanly if the parent process
1120 * kills us with it due to the user selecting "Capture->Stop".
1122 signal(SIGUSR1, capture_loop_stop_signal_handler);
1125 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
1126 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
1128 /* open the "input file" from network interface or capture pipe */
1129 if (!capture_loop_open_input(capture_opts, &ld, errmsg, sizeof(errmsg),
1130 secondary_errmsg, sizeof(secondary_errmsg))) {
1134 /* init the input filter from the network interface (capture pipe will do nothing) */
1135 switch (capture_loop_init_filter(ld.pcap_h, ld.from_cap_pipe, capture_opts->iface, capture_opts->cfilter)) {
1137 case INITFILTER_NO_ERROR:
1140 case INITFILTER_BAD_FILTER:
1141 cfilter_error = TRUE;
1142 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(ld.pcap_h));
1143 *secondary_errmsg = '\0';
1146 case INITFILTER_OTHER_ERROR:
1147 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
1148 pcap_geterr(ld.pcap_h));
1149 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
1153 /* open the output file (temporary/specified name/ringbuffer) */
1154 if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
1155 *secondary_errmsg = '\0';
1159 /* set up to write to the already-opened capture output file/files */
1160 if (!capture_loop_init_output(capture_opts, save_file_fd, &ld, errmsg, sizeof(errmsg))) {
1161 *secondary_errmsg = '\0';
1165 /* XXX - capture SIGTERM and close the capture, in case we're on a
1166 Linux 2.0[.x] system and you have to explicitly close the capture
1167 stream in order to turn promiscuous mode off? We need to do that
1168 in other places as well - and I don't think that works all the
1169 time in any case, due to libpcap bugs. */
1171 /* Well, we should be able to start capturing.
1173 Sync out the capture file, so the header makes it to the file system,
1174 and send a "capture started successfully and capture file created"
1175 message to our parent so that they'll open the capture file and
1176 update its windows to indicate that we have a live capture in
1178 libpcap_dump_flush(ld.pdh, NULL);
1179 sync_pipe_filename_to_parent(capture_opts->save_file);
1181 /* initialize capture stop (and alike) conditions */
1182 init_capture_stop_conditions();
1183 /* create stop conditions */
1184 if (capture_opts->has_autostop_filesize)
1186 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
1187 if (capture_opts->has_autostop_duration)
1188 cnd_autostop_duration =
1189 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
1191 if (capture_opts->multi_files_on) {
1192 if (capture_opts->has_file_duration)
1194 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
1196 if (capture_opts->has_autostop_files)
1197 cnd_autostop_files =
1198 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
1201 /* init the time values */
1202 start_time = TIME_GET();
1203 upd_time = TIME_GET();
1205 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
1207 /* WOW, everything is prepared! */
1208 /* please fasten your seat belts, we will enter now the actual capture loop */
1210 /* dispatch incoming packets */
1211 inpkts = capture_loop_dispatch(capture_opts, &ld, errmsg, sizeof(errmsg));
1214 /* any news from our parent (signal pipe)? -> just stop the capture */
1215 if (!signal_pipe_check_running()) {
1221 inpkts_to_sync_pipe += inpkts;
1223 /* check capture size condition */
1224 if (cnd_autostop_size != NULL && cnd_eval(cnd_autostop_size,
1225 (guint32)ld.bytes_written)){
1226 /* Capture size limit reached, do we have another file? */
1227 if (capture_opts->multi_files_on) {
1228 if (cnd_autostop_files != NULL && 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, &save_file_fd, &ld.err)) {
1236 /* File switch succeeded: reset the conditions */
1237 cnd_reset(cnd_autostop_size);
1238 if (cnd_file_duration) {
1239 cnd_reset(cnd_file_duration);
1241 libpcap_dump_flush(ld.pdh, NULL);
1242 sync_pipe_packet_count_to_parent(inpkts_to_sync_pipe);
1243 inpkts_to_sync_pipe = 0;
1244 sync_pipe_filename_to_parent(capture_opts->save_file);
1246 /* File switch failed: stop here */
1251 /* single file, stop now */
1255 } /* cnd_autostop_size */
1256 if (capture_opts->output_to_pipe) {
1257 libpcap_dump_flush(ld.pdh, NULL);
1261 /* Only update once a second (Win32: 500ms) so as not to overload slow displays */
1262 cur_time = TIME_GET();
1264 if ( (cur_time - upd_time) > 500) {
1266 if (cur_time - upd_time > 0) {
1268 upd_time = cur_time;
1270 /*if (pcap_stats(pch, stats) >= 0) {
1271 *stats_known = TRUE;
1274 /* Let the parent process know. */
1275 if (inpkts_to_sync_pipe) {
1277 libpcap_dump_flush(ld.pdh, NULL);
1279 /* Send our parent a message saying we've written out "inpkts_to_sync_pipe"
1280 packets to the capture file. */
1281 sync_pipe_packet_count_to_parent(inpkts_to_sync_pipe);
1283 inpkts_to_sync_pipe = 0;
1286 /* check capture duration condition */
1287 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
1288 /* The maximum capture time has elapsed; stop the capture. */
1293 /* check capture file duration condition */
1294 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
1295 /* duration limit reached, do we have another file? */
1296 if (capture_opts->multi_files_on) {
1297 if (cnd_autostop_files != NULL && cnd_eval(cnd_autostop_files, ++autostop_files)) {
1298 /* no files left: stop here */
1303 /* Switch to the next ringbuffer file */
1304 if (ringbuf_switch_file(&ld.pdh, &capture_opts->save_file, &save_file_fd, &ld.err)) {
1305 /* file switch succeeded: reset the conditions */
1306 cnd_reset(cnd_file_duration);
1307 if(cnd_autostop_size)
1308 cnd_reset(cnd_autostop_size);
1309 libpcap_dump_flush(ld.pdh, NULL);
1310 sync_pipe_packet_count_to_parent(inpkts_to_sync_pipe);
1311 inpkts_to_sync_pipe = 0;
1312 sync_pipe_filename_to_parent(capture_opts->save_file);
1314 /* File switch failed: stop here */
1319 /* single file, stop now */
1323 } /* cnd_file_duration */
1326 } /* while (ld.go) */
1328 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
1330 /* delete stop conditions */
1331 if (cnd_file_duration != NULL)
1332 cnd_delete(cnd_file_duration);
1333 if (cnd_autostop_files != NULL)
1334 cnd_delete(cnd_autostop_files);
1335 if (cnd_autostop_size != NULL)
1336 cnd_delete(cnd_autostop_size);
1337 if (cnd_autostop_duration != NULL)
1338 cnd_delete(cnd_autostop_duration);
1340 /* did we had a pcap (input) error? */
1342 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
1343 pcap_geterr(ld.pcap_h));
1344 sync_pipe_errmsg_to_parent(errmsg, please_report);
1347 else if (ld.from_cap_pipe && ld.cap_pipe_err == PIPERR)
1348 sync_pipe_errmsg_to_parent(errmsg, "");
1351 /* did we had an error while capturing? */
1355 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, ld.err,
1357 sync_pipe_errmsg_to_parent(errmsg, please_report);
1361 /* close the wiretap (output) file */
1362 close_ok = capture_loop_close_output(capture_opts, &ld, &err_close);
1364 /* there might be packets not yet notified to the parent */
1365 /* (do this after closing the file, so all packets are already flushed) */
1366 if(inpkts_to_sync_pipe) {
1367 sync_pipe_packet_count_to_parent(inpkts_to_sync_pipe);
1368 inpkts_to_sync_pipe = 0;
1371 /* If we've displayed a message about a write error, there's no point
1372 in displaying another message about an error on close. */
1373 if (!close_ok && write_ok) {
1374 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
1376 sync_pipe_errmsg_to_parent(errmsg, "");
1380 * XXX We exhibit different behaviour between normal mode and sync mode
1381 * when the pipe is stdin and not already at EOF. If we're a child, the
1382 * parent's stdin isn't closed, so if the user starts another capture,
1383 * cap_pipe_open_live() will very likely not see the expected magic bytes and
1384 * will say "Unrecognized libpcap format". On the other hand, in normal
1385 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
1388 /* get packet drop statistics from pcap */
1389 if(ld.pcap_h != NULL) {
1390 g_assert(!ld.from_cap_pipe);
1391 /* Get the capture statistics, so we know how many packets were
1393 if (pcap_stats(ld.pcap_h, stats) >= 0) {
1394 *stats_known = TRUE;
1395 /* Let the parent process know. */
1396 sync_pipe_drops_to_parent(stats->ps_drop);
1398 g_snprintf(errmsg, sizeof(errmsg),
1399 "Can't get packet-drop statistics: %s",
1400 pcap_geterr(ld.pcap_h));
1401 sync_pipe_errmsg_to_parent(errmsg, please_report);
1405 /* close the input file (pcap or capture pipe) */
1406 capture_loop_close_input(&ld);
1408 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
1410 /* ok, if the write and the close were successful. */
1411 return write_ok && close_ok;
1414 if (capture_opts->multi_files_on) {
1415 /* cleanup ringbuffer */
1416 ringbuf_error_cleanup();
1418 /* We can't use the save file, and we have no FILE * for the stream
1419 to close in order to close it, so close the FD directly. */
1420 if(save_file_fd != -1) {
1421 eth_close(save_file_fd);
1424 /* We couldn't even start the capture, so get rid of the capture
1426 if(capture_opts->save_file != NULL) {
1427 eth_unlink(capture_opts->save_file);
1428 g_free(capture_opts->save_file);
1431 capture_opts->save_file = NULL;
1433 sync_pipe_cfilter_error_to_parent(capture_opts->cfilter, errmsg);
1435 sync_pipe_errmsg_to_parent(errmsg, secondary_errmsg);
1437 /* close the input file (pcap or cap_pipe) */
1438 capture_loop_close_input(&ld);
1440 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
1446 void capture_loop_stop(void)
1453 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
1454 int err, gboolean is_close)
1459 g_snprintf(errmsg, errmsglen,
1460 "Not all the packets could be written to the file"
1461 " to which the capture was being saved\n"
1462 "(\"%s\") because there is no space left on the file system\n"
1463 "on which that file resides.",
1469 g_snprintf(errmsg, errmsglen,
1470 "Not all the packets could be written to the file"
1471 " to which the capture was being saved\n"
1472 "(\"%s\") because you are too close to, or over,"
1473 " your disk quota\n"
1474 "on the file system on which that file resides.",
1479 case WTAP_ERR_CANT_CLOSE:
1480 g_snprintf(errmsg, errmsglen,
1481 "The file to which the capture was being saved"
1482 " couldn't be closed for some unknown reason.");
1485 case WTAP_ERR_SHORT_WRITE:
1486 g_snprintf(errmsg, errmsglen,
1487 "Not all the packets could be written to the file"
1488 " to which the capture was being saved\n"
1495 g_snprintf(errmsg, errmsglen,
1496 "The file to which the capture was being saved\n"
1497 "(\"%s\") could not be closed: %s.",
1498 fname, wtap_strerror(err));
1500 g_snprintf(errmsg, errmsglen,
1501 "An error occurred while writing to the file"
1502 " to which the capture was being saved\n"
1504 fname, wtap_strerror(err));
1511 /* one packet was captured, process it */
1513 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
1516 loop_data *ld = (loop_data *) user;
1519 /* if the user told us to stop after x packets, do we have enough? */
1521 if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
1527 /* We're supposed to write the packet to a file; do so.
1528 If this fails, set "ld->go" to FALSE, to stop the capture, and set
1529 "ld->err" to the error. */
1530 if (!libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err)) {
1537 #endif /* HAVE_LIBPCAP */