2 * The actual capturing loop, getting packets and storing it
6 * Wireshark - Network traffic analyzer
7 * By Gerald Combs <gerald@wireshark.org>
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 Wireshark 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)Wireshark 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 twireshark? */
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.wireshark.org/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)Wireshark on HP-UX) that they don't have a version
596 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
597 versions, which properly handle HP-UX, say "can't find /dev/dlpi
598 PPA for X" rather than "can't find PPA for X"). */
599 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
602 "You are running (T)Wireshark with a version of the libpcap library\n"
603 "that doesn't handle HP-UX network devices well; this means that\n"
604 "(T)Wireshark may not be able to capture packets.\n"
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 twireshark? */
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,
748 &ld->bytes_written, &err);
750 ld->pdh = libpcap_fdopen(save_file_fd, ld->linktype, file_snaplen,
751 &ld->bytes_written, &err);
754 if (ld->pdh == NULL) {
755 /* We couldn't set up to write to the capture file. */
756 /* XXX - use cf_open_error_message from twireshark instead? */
759 case WTAP_ERR_CANT_OPEN:
760 strcpy(errmsg, "The file to which the capture would be saved"
761 " couldn't be created for some unknown reason.");
764 case WTAP_ERR_SHORT_WRITE:
765 strcpy(errmsg, "A full header couldn't be written to the file"
766 " to which the capture would be saved.");
771 g_snprintf(errmsg, errmsg_len,
772 "The file to which the capture would be"
773 " saved (\"%s\") could not be opened: Error %d.",
774 capture_opts->save_file, err);
776 g_snprintf(errmsg, errmsg_len,
777 "The file to which the capture would be"
778 " saved (\"%s\") could not be opened: %s.",
779 capture_opts->save_file, strerror(err));
790 gboolean capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
792 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_close_output");
794 if (capture_opts->multi_files_on) {
795 return ringbuf_libpcap_dump_close(&capture_opts->save_file, err_close);
797 return libpcap_dump_close(ld->pdh, err_close);
801 /* dispatch incoming packets (pcap or capture pipe) */
803 capture_loop_dispatch(capture_options *capture_opts _U_, loop_data *ld,
804 char *errmsg, int errmsg_len) {
808 struct timeval timeout;
810 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
814 if (ld->from_cap_pipe) {
815 /* dispatch from capture pipe */
816 #ifdef LOG_CAPTURE_VERBOSE
817 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from capture pipe");
820 FD_SET(ld->cap_pipe_fd, &set1);
822 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
823 sel_ret = select(ld->cap_pipe_fd+1, &set1, NULL, NULL, &timeout);
826 if (sel_ret < 0 && errno != EINTR) {
827 g_snprintf(errmsg, errmsg_len,
828 "Unexpected error from select: %s", strerror(errno));
829 report_capture_error(errmsg, please_report);
834 * "select()" says we can read from the pipe without blocking
836 inpkts = cap_pipe_dispatch(ld, pcap_data, errmsg, errmsg_len);
845 /* dispatch from pcap */
846 #ifdef MUST_DO_SELECT
848 * If we have "pcap_get_selectable_fd()", we use it to get the
849 * descriptor on which to select; if that's -1, it means there
850 * is no descriptor on which you can do a "select()" (perhaps
851 * because you're capturing on a special device, and that device's
852 * driver unfortunately doesn't support "select()", in which case
853 * we don't do the select - which means it might not be possible
854 * to stop a capture until a packet arrives. If that's unacceptable,
855 * plead with whoever supplies the software for that device to add
856 * "select()" support, or upgrade to libpcap 0.8.1 or later, and
857 * rebuild Wireshark or get a version built with libpcap 0.8.1 or
858 * later, so it can use pcap_breakloop().
860 #ifdef LOG_CAPTURE_VERBOSE
861 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch with select");
863 if (ld->pcap_fd != -1) {
865 FD_SET(ld->pcap_fd, &set1);
866 sel_ret = select(ld->pcap_fd+1, &set1, NULL, NULL, NULL);
869 * "select()" says we can read from it without blocking; go for
872 * We don't have pcap_breakloop(), so we only process one packet
873 * per pcap_dispatch() call, to allow a signal to stop the
874 * processing immediately, rather than processing all packets
875 * in a batch before quitting.
877 inpkts = pcap_dispatch(ld->pcap_h, 1, ld->packet_cb, (u_char *)ld);
880 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
884 if (sel_ret < 0 && errno != EINTR) {
885 g_snprintf(errmsg, errmsg_len,
886 "Unexpected error from select: %s", strerror(errno));
887 report_capture_error(errmsg, please_report);
893 #endif /* MUST_DO_SELECT */
895 /* dispatch from pcap without select */
897 #ifdef LOG_CAPTURE_VERBOSE
898 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_dispatch");
902 * On Windows, we don't support asynchronously telling a process to
903 * stop capturing; instead, we check for an indication on a pipe
904 * after processing packets. We therefore process only one packet
905 * at a time, so that we can check the pipe after every packet.
907 inpkts = pcap_dispatch(ld->pcap_h, 1, ld->packet_cb, (u_char *) ld);
909 inpkts = pcap_dispatch(ld->pcap_h, -1, ld->packet_cb, (u_char *) ld);
913 /* Error, rather than pcap_breakloop(). */
916 ld->go = FALSE; /* error or pcap_breakloop() - stop capturing */
918 #else /* pcap_next_ex */
919 #ifdef LOG_CAPTURE_VERBOSE
920 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: from pcap_next_ex");
922 /* XXX - this is currently unused, as there is some confusion with pcap_next_ex() vs. pcap_dispatch() */
925 * WinPcap's remote capturing feature doesn't work with pcap_dispatch(),
926 * see http://wiki.wireshark.org/CaptureSetup_2fWinPcapRemote
927 * This should be fixed in the WinPcap 4.0 alpha release.
929 * For reference, an example remote interface:
930 * rpcap://[1.2.3.4]/\Device\NPF_{39993D68-7C9B-4439-A329-F2D888DA7C5C}
933 /* emulate dispatch from pcap */
936 struct pcap_pkthdr *pkt_header;
942 (in = pcap_next_ex(ld->pcap_h, &pkt_header, &pkt_data)) == 1) {
943 ld->packet_cb( (u_char *) ld, pkt_header, pkt_data);
953 #endif /* pcap_next_ex */
957 #ifdef LOG_CAPTURE_VERBOSE
958 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_dispatch: %d new packet%s", inpkts, plurality(inpkts, "", "s"));
965 /* open the output file (temporary/specified name/ringbuffer/named pipe/stdout) */
966 /* Returns TRUE if the file opened successfully, FALSE otherwise. */
968 capture_loop_open_output(capture_options *capture_opts, int *save_file_fd,
969 char *errmsg, int errmsg_len) {
973 gboolean is_tempfile;
976 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, "capture_loop_open_output: %s",
977 (capture_opts->save_file) ? capture_opts->save_file : "");
979 if (capture_opts->save_file != NULL) {
980 /* We return to the caller while the capture is in progress.
981 * Therefore we need to take a copy of save_file in
982 * case the caller destroys it after we return.
984 capfile_name = g_strdup(capture_opts->save_file);
985 if (strcmp(capfile_name, "-") == 0) {
986 /* Write to the standard output. */
987 if (capture_opts->multi_files_on) {
988 /* ringbuffer is enabled; that doesn't work with standard output */
989 g_snprintf(errmsg, errmsg_len,
990 "Ring buffer requested, but capture is being written to the standard output.");
991 g_free(capfile_name);
997 if (capture_opts->multi_files_on) {
998 /* ringbuffer is enabled */
999 *save_file_fd = ringbuf_init(capfile_name,
1000 (capture_opts->has_ring_num_files) ? capture_opts->ring_num_files : 0);
1002 /* we need the ringbuf name */
1003 if(*save_file_fd != -1) {
1004 g_free(capfile_name);
1005 capfile_name = g_strdup(ringbuf_current_filename());
1008 /* Try to open/create the specified file for use as a capture buffer. */
1009 *save_file_fd = open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
1013 is_tempfile = FALSE;
1015 /* Choose a random name for the temporary capture buffer */
1016 *save_file_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
1017 capfile_name = g_strdup(tmpname);
1021 /* did we fail to open the output file? */
1022 if (*save_file_fd == -1) {
1024 g_snprintf(errmsg, errmsg_len,
1025 "The temporary file to which the capture would be saved (\"%s\") "
1026 "could not be opened: %s.", capfile_name, strerror(errno));
1028 if (capture_opts->multi_files_on) {
1029 ringbuf_error_cleanup();
1032 g_snprintf(errmsg, errmsg_len,
1033 "The file to which the capture would be saved (\"%s\") "
1034 "could not be opened: %s.", capfile_name,
1037 g_free(capfile_name);
1041 if(capture_opts->save_file != NULL) {
1042 g_free(capture_opts->save_file);
1044 capture_opts->save_file = capfile_name;
1045 /* capture_opts.save_file is "g_free"ed later, which is equivalent to
1046 "g_free(capfile_name)". */
1054 capture_loop_stop_signal_handler(int signo _U_)
1056 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Signal: Stop capture");
1057 capture_loop_stop();
1062 #define TIME_GET() GetTickCount()
1064 #define TIME_GET() time(NULL)
1067 /* Do the low-level work of a capture.
1068 Returns TRUE if it succeeds, FALSE otherwise. */
1070 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
1073 struct sigaction act;
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 act.sa_handler = capture_loop_stop_signal_handler;
1124 * Arrange that system calls not get restarted, because when
1125 * our signal handler returns we don't want to restart
1126 * a call that was waiting for packets to arrive.
1129 sigemptyset(&act.sa_mask);
1130 sigaction(SIGUSR1, &act, NULL);
1133 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop starting ...");
1134 capture_opts_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_DEBUG, capture_opts);
1136 /* open the "input file" from network interface or capture pipe */
1137 if (!capture_loop_open_input(capture_opts, &ld, errmsg, sizeof(errmsg),
1138 secondary_errmsg, sizeof(secondary_errmsg))) {
1142 /* init the input filter from the network interface (capture pipe will do nothing) */
1143 switch (capture_loop_init_filter(ld.pcap_h, ld.from_cap_pipe, capture_opts->iface, capture_opts->cfilter)) {
1145 case INITFILTER_NO_ERROR:
1148 case INITFILTER_BAD_FILTER:
1149 cfilter_error = TRUE;
1150 g_snprintf(errmsg, sizeof(errmsg), "%s", pcap_geterr(ld.pcap_h));
1151 *secondary_errmsg = '\0';
1154 case INITFILTER_OTHER_ERROR:
1155 g_snprintf(errmsg, sizeof(errmsg), "Can't install filter (%s).",
1156 pcap_geterr(ld.pcap_h));
1157 g_snprintf(secondary_errmsg, sizeof(secondary_errmsg), "%s", please_report);
1161 /* If we're supposed to write to a capture file, open it for output
1162 (temporary/specified name/ringbuffer) */
1163 if (capture_opts->saving_to_file) {
1164 if (!capture_loop_open_output(capture_opts, &save_file_fd, errmsg, sizeof(errmsg))) {
1165 *secondary_errmsg = '\0';
1169 /* set up to write to the already-opened capture output file/files */
1170 if (!capture_loop_init_output(capture_opts, save_file_fd, &ld, errmsg, sizeof(errmsg))) {
1171 *secondary_errmsg = '\0';
1175 /* XXX - capture SIGTERM and close the capture, in case we're on a
1176 Linux 2.0[.x] system and you have to explicitly close the capture
1177 stream in order to turn promiscuous mode off? We need to do that
1178 in other places as well - and I don't think that works all the
1179 time in any case, due to libpcap bugs. */
1181 /* Well, we should be able to start capturing.
1183 Sync out the capture file, so the header makes it to the file system,
1184 and send a "capture started successfully and capture file created"
1185 message to our parent so that they'll open the capture file and
1186 update its windows to indicate that we have a live capture in
1188 libpcap_dump_flush(ld.pdh, NULL);
1189 report_new_capture_file(capture_opts->save_file);
1192 /* initialize capture stop (and alike) conditions */
1193 init_capture_stop_conditions();
1194 /* create stop conditions */
1195 if (capture_opts->has_autostop_filesize)
1197 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize * 1024);
1198 if (capture_opts->has_autostop_duration)
1199 cnd_autostop_duration =
1200 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
1202 if (capture_opts->multi_files_on) {
1203 if (capture_opts->has_file_duration)
1205 cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
1207 if (capture_opts->has_autostop_files)
1208 cnd_autostop_files =
1209 cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
1212 /* init the time values */
1213 start_time = TIME_GET();
1214 upd_time = TIME_GET();
1216 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop running!");
1218 /* WOW, everything is prepared! */
1219 /* please fasten your seat belts, we will enter now the actual capture loop */
1221 /* dispatch incoming packets */
1222 inpkts = capture_loop_dispatch(capture_opts, &ld, errmsg, sizeof(errmsg));
1225 /* any news from our parent (signal pipe)? -> just stop the capture */
1226 if (!signal_pipe_check_running()) {
1232 inpkts_to_sync_pipe += inpkts;
1234 /* check capture size condition */
1235 if (cnd_autostop_size != NULL &&
1236 cnd_eval(cnd_autostop_size, (guint32)ld.bytes_written)){
1237 /* Capture size limit reached, do we have another file? */
1238 if (capture_opts->multi_files_on) {
1239 if (cnd_autostop_files != NULL &&
1240 cnd_eval(cnd_autostop_files, ++autostop_files)) {
1241 /* no files left: stop here */
1246 /* Switch to the next ringbuffer file */
1247 if (ringbuf_switch_file(&ld.pdh, &capture_opts->save_file,
1248 &save_file_fd, &ld.bytes_written, &ld.err)) {
1249 /* File switch succeeded: reset the conditions */
1250 cnd_reset(cnd_autostop_size);
1251 if (cnd_file_duration) {
1252 cnd_reset(cnd_file_duration);
1254 libpcap_dump_flush(ld.pdh, NULL);
1255 report_packet_count(inpkts_to_sync_pipe);
1256 inpkts_to_sync_pipe = 0;
1257 report_new_capture_file(capture_opts->save_file);
1259 /* File switch failed: stop here */
1264 /* single file, stop now */
1268 } /* cnd_autostop_size */
1269 if (capture_opts->output_to_pipe) {
1270 libpcap_dump_flush(ld.pdh, NULL);
1274 /* Only update once a second (Win32: 500ms) so as not to overload slow displays */
1275 cur_time = TIME_GET();
1277 if ( (cur_time - upd_time) > 500) {
1279 if (cur_time - upd_time > 0) {
1281 upd_time = cur_time;
1283 /*if (pcap_stats(pch, stats) >= 0) {
1284 *stats_known = TRUE;
1287 /* Let the parent process know. */
1288 if (inpkts_to_sync_pipe) {
1290 libpcap_dump_flush(ld.pdh, NULL);
1292 /* Send our parent a message saying we've written out "inpkts_to_sync_pipe"
1293 packets to the capture file. */
1294 report_packet_count(inpkts_to_sync_pipe);
1296 inpkts_to_sync_pipe = 0;
1299 /* check capture duration condition */
1300 if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
1301 /* The maximum capture time has elapsed; stop the capture. */
1306 /* check capture file duration condition */
1307 if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
1308 /* duration limit reached, do we have another file? */
1309 if (capture_opts->multi_files_on) {
1310 if (cnd_autostop_files != NULL &&
1311 cnd_eval(cnd_autostop_files, ++autostop_files)) {
1312 /* no files left: stop here */
1317 /* Switch to the next ringbuffer file */
1318 if (ringbuf_switch_file(&ld.pdh, &capture_opts->save_file,
1319 &save_file_fd, &ld.bytes_written, &ld.err)) {
1320 /* file switch succeeded: reset the conditions */
1321 cnd_reset(cnd_file_duration);
1322 if(cnd_autostop_size)
1323 cnd_reset(cnd_autostop_size);
1324 libpcap_dump_flush(ld.pdh, NULL);
1325 report_packet_count(inpkts_to_sync_pipe);
1326 inpkts_to_sync_pipe = 0;
1327 report_new_capture_file(capture_opts->save_file);
1329 /* File switch failed: stop here */
1334 /* single file, stop now */
1338 } /* cnd_file_duration */
1341 } /* while (ld.go) */
1343 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopping ...");
1345 /* delete stop conditions */
1346 if (cnd_file_duration != NULL)
1347 cnd_delete(cnd_file_duration);
1348 if (cnd_autostop_files != NULL)
1349 cnd_delete(cnd_autostop_files);
1350 if (cnd_autostop_size != NULL)
1351 cnd_delete(cnd_autostop_size);
1352 if (cnd_autostop_duration != NULL)
1353 cnd_delete(cnd_autostop_duration);
1355 /* did we had a pcap (input) error? */
1357 g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
1358 pcap_geterr(ld.pcap_h));
1359 report_capture_error(errmsg, please_report);
1362 else if (ld.from_cap_pipe && ld.cap_pipe_err == PIPERR)
1363 report_capture_error(errmsg, "");
1366 /* did we had an error while capturing? */
1370 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, ld.err,
1372 report_capture_error(errmsg, please_report);
1376 if (capture_opts->saving_to_file) {
1377 /* close the wiretap (output) file */
1378 close_ok = capture_loop_close_output(capture_opts, &ld, &err_close);
1382 /* there might be packets not yet notified to the parent */
1383 /* (do this after closing the file, so all packets are already flushed) */
1384 if(inpkts_to_sync_pipe) {
1385 report_packet_count(inpkts_to_sync_pipe);
1386 inpkts_to_sync_pipe = 0;
1389 /* If we've displayed a message about a write error, there's no point
1390 in displaying another message about an error on close. */
1391 if (!close_ok && write_ok) {
1392 capture_loop_get_errmsg(errmsg, sizeof(errmsg), capture_opts->save_file, err_close,
1394 report_capture_error(errmsg, "");
1398 * XXX We exhibit different behaviour between normal mode and sync mode
1399 * when the pipe is stdin and not already at EOF. If we're a child, the
1400 * parent's stdin isn't closed, so if the user starts another capture,
1401 * cap_pipe_open_live() will very likely not see the expected magic bytes and
1402 * will say "Unrecognized libpcap format". On the other hand, in normal
1403 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
1406 /* get packet drop statistics from pcap */
1407 if(ld.pcap_h != NULL) {
1408 g_assert(!ld.from_cap_pipe);
1409 /* Get the capture statistics, so we know how many packets were
1411 if (pcap_stats(ld.pcap_h, stats) >= 0) {
1412 *stats_known = TRUE;
1413 /* Let the parent process know. */
1414 report_packet_drops(stats->ps_drop);
1416 g_snprintf(errmsg, sizeof(errmsg),
1417 "Can't get packet-drop statistics: %s",
1418 pcap_geterr(ld.pcap_h));
1419 report_capture_error(errmsg, please_report);
1423 /* close the input file (pcap or capture pipe) */
1424 capture_loop_close_input(&ld);
1426 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped!");
1428 /* ok, if the write and the close were successful. */
1429 return write_ok && close_ok;
1432 if (capture_opts->multi_files_on) {
1433 /* cleanup ringbuffer */
1434 ringbuf_error_cleanup();
1436 /* We can't use the save file, and we have no FILE * for the stream
1437 to close in order to close it, so close the FD directly. */
1438 if(save_file_fd != -1) {
1439 eth_close(save_file_fd);
1442 /* We couldn't even start the capture, so get rid of the capture
1444 if(capture_opts->save_file != NULL) {
1445 eth_unlink(capture_opts->save_file);
1446 g_free(capture_opts->save_file);
1449 capture_opts->save_file = NULL;
1451 report_cfilter_error(capture_opts->cfilter, errmsg);
1453 report_capture_error(errmsg, secondary_errmsg);
1455 /* close the input file (pcap or cap_pipe) */
1456 capture_loop_close_input(&ld);
1458 g_log(LOG_DOMAIN_CAPTURE_CHILD, G_LOG_LEVEL_INFO, "Capture loop stopped with error");
1464 void capture_loop_stop(void)
1466 #ifdef HAVE_PCAP_BREAKLOOP
1467 pcap_breakloop(ld.pcap_h);
1475 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
1476 int err, gboolean is_close)
1481 g_snprintf(errmsg, errmsglen,
1482 "Not all the packets could be written to the file"
1483 " to which the capture was being saved\n"
1484 "(\"%s\") because there is no space left on the file system\n"
1485 "on which that file resides.",
1491 g_snprintf(errmsg, errmsglen,
1492 "Not all the packets could be written to the file"
1493 " to which the capture was being saved\n"
1494 "(\"%s\") because you are too close to, or over,"
1495 " your disk quota\n"
1496 "on the file system on which that file resides.",
1501 case WTAP_ERR_CANT_CLOSE:
1502 g_snprintf(errmsg, errmsglen,
1503 "The file to which the capture was being saved"
1504 " couldn't be closed for some unknown reason.");
1507 case WTAP_ERR_SHORT_WRITE:
1508 g_snprintf(errmsg, errmsglen,
1509 "Not all the packets could be written to the file"
1510 " to which the capture was being saved\n"
1517 g_snprintf(errmsg, errmsglen,
1518 "The file to which the capture was being saved\n"
1519 "(\"%s\") could not be closed: %s.",
1520 fname, wtap_strerror(err));
1522 g_snprintf(errmsg, errmsglen,
1523 "An error occurred while writing to the file"
1524 " to which the capture was being saved\n"
1526 fname, wtap_strerror(err));
1533 /* one packet was captured, process it */
1535 capture_loop_packet_cb(u_char *user, const struct pcap_pkthdr *phdr,
1538 loop_data *ld = (loop_data *) user;
1541 /* if the user told us to stop after x packets, do we have enough? */
1543 if ((ld->packet_max > 0) && (ld->packet_count >= ld->packet_max))
1549 /* We're supposed to write the packet to a file; do so.
1550 If this fails, set "ld->go" to FALSE, to stop the capture, and set
1551 "ld->err" to the error. */
1552 if (!libpcap_write_packet(ld->pdh, phdr, pd, &ld->bytes_written, &err)) {
1559 #endif /* HAVE_LIBPCAP */