2 * Routines for packet capture windows
4 * $Id: capture.c,v 1.240 2004/02/21 13:40:06 ulfl Exp $
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.
31 #ifdef HAVE_SYS_STAT_H
32 # include <sys/stat.h>
35 #ifdef HAVE_SYS_WAIT_H
36 # include <sys/wait.h>
41 * Define various POSIX macros (and, in the case of WCOREDUMP, non-POSIX
42 * macros) on UNIX systems that don't have them.
45 # define WIFEXITED(status) (((status) & 0177) == 0)
48 # define WIFSTOPPED(status) (((status) & 0177) == 0177)
51 # define WIFSIGNALED(status) (!WIFSTOPPED(status) && !WIFEXITED(status))
54 # define WEXITSTATUS(status) ((status) >> 8)
57 # define WTERMSIG(status) ((status) & 0177)
60 # define WCOREDUMP(status) ((status) & 0200)
63 # define WSTOPSIG(status) ((status) >> 8)
89 #ifdef HAVE_SYS_SOCKET_H
90 #include <sys/socket.h>
93 #ifdef HAVE_SYS_IOCTL_H
94 #include <sys/ioctl.h>
100 #ifdef NEED_SNPRINTF_H
101 # include "snprintf.h"
105 #include <process.h> /* For spawning child process */
109 * We don't want to do a "select()" on the pcap_t's file descriptor on
110 * BSD (because "select()" doesn't work correctly on BPF devices on at
111 * least some releases of some flavors of BSD), and we don't want to do
112 * it on Windows (because "select()" is something for sockets, not for
113 * arbitrary handles). (Note that "Windows" here includes Cygwin;
114 * even in its pretend-it's-UNIX environment, we're using WinPcap, not
117 * We *do* want to do it on other platforms, as, on other platforms (with
118 * the possible exception of Ultrix and Digital UNIX), the read timeout
119 * doesn't expire if no packets have arrived, so a "pcap_dispatch()" call
120 * will block until packets arrive, causing the UI to hang.
122 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
123 * want to include it if it's not present on this platform, however.
125 #if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
126 !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
128 # define MUST_DO_SELECT
131 #include <epan/packet.h>
132 #include <epan/dfilter/dfilter.h>
136 #include "pcap-util.h"
137 #include "alert_box.h"
138 #include "simple_dialog.h"
141 #include "conditions.h"
142 #include "capture_stop_conditions.h"
143 #include "ringbuffer.h"
145 #include "wiretap/libpcap.h"
146 #include "wiretap/wtap.h"
147 #include "wiretap/wtap-capture.h"
149 #include "packet-atalk.h"
150 #include "packet-atm.h"
151 #include "packet-clip.h"
152 #include "packet-eth.h"
153 #include "packet-fddi.h"
154 #include "packet-null.h"
155 #include "packet-ppp.h"
156 #include "packet-raw.h"
157 #include "packet-sll.h"
158 #include "packet-tr.h"
159 #include "packet-ieee80211.h"
160 #include "packet-chdlc.h"
161 #include "packet-prism.h"
162 #include "packet-ipfc.h"
163 #include "packet-arcnet.h"
166 #include "capture-wpcap.h"
173 capture_options capture_opts;
174 gboolean quit_after_cap = FALSE;/* Makes a "capture only mode". Implies -k */
175 gboolean capture_child; /* if this is the child for "-S" */
177 static int sync_pipe[2]; /* used to sync father */
178 enum PIPES { READ, WRITE }; /* Constants 0 and 1 for READ and WRITE */
179 static int fork_child = -1; /* If not -1, in parent, process ID of child */
181 /* Size of buffer to hold decimal representation of
182 signed/unsigned 64-bit int */
183 #define SP_DECISIZE 20
186 * Indications sent out on the sync pipe.
188 #define SP_CAPSTART ';' /* capture start message */
189 #define SP_PACKET_COUNT '*' /* followed by count of packets captured since last message */
190 #define SP_ERROR_MSG '!' /* followed by length of error message that follows */
191 #define SP_DROPS '#' /* followed by count of packets dropped in capture */
194 static gboolean sync_pipe_do_capture(gboolean is_tempfile);
195 static gboolean sync_pipe_input_cb(gint source, gpointer user_data);
196 static void sync_pipe_wait_for_child(gboolean);
197 static void sync_pipe_errmsg_to_parent(const char *);
199 static char *sync_pipe_signame(int);
202 static gboolean normal_do_capture(gboolean is_tempfile);
203 static void capture_pcap_cb(guchar *, const struct pcap_pkthdr *,
205 static void get_capture_file_io_error(char *, int, const char *, int, gboolean);
206 static void popup_errmsg(const char *);
207 static void stop_capture_signal_handler(int signo);
210 static void cap_pipe_adjust_header(loop_data *, struct pcap_hdr *, struct pcaprec_hdr *);
211 static int cap_pipe_open_live(char *, struct pcap_hdr *, loop_data *, char *, int);
212 static int cap_pipe_dispatch(int, loop_data *, struct pcap_hdr *, \
213 struct pcaprec_modified_hdr *, guchar *, char *, int);
216 typedef struct _loop_data {
217 gboolean go; /* TRUE as long as we're supposed to keep capturing */
218 gint max; /* Number of packets we're supposed to capture - 0 means infinite */
219 int err; /* if non-zero, error seen while capturing */
222 gboolean pcap_err; /* TRUE if error from pcap */
223 gboolean from_cap_pipe;/* TRUE if we are capturing data from a pipe */
224 packet_counts counts;
227 gboolean modified; /* TRUE if data in the pipe uses modified pcap headers */
228 gboolean byte_swapped; /* TRUE if data in the pipe is byte swapped */
229 unsigned int bytes_to_read, bytes_read; /* Used by cap_pipe_dispatch */
231 STATE_EXPECT_REC_HDR, STATE_READ_REC_HDR,
232 STATE_EXPECT_DATA, STATE_READ_DATA
235 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
239 /* Win32 needs the O_BINARY flag for open() */
250 /* Open a specified file, or create a temporary file, and start a capture
251 to the file in question. Returns TRUE if the capture starts
252 successfully, FALSE otherwise. */
254 do_capture(const char *save_file)
257 gboolean is_tempfile;
260 if (save_file != NULL) {
261 /* If the Sync option is set, we return to the caller while the capture
262 * is in progress. Therefore we need to take a copy of save_file in
263 * case the caller destroys it after we return.
265 capfile_name = g_strdup(save_file);
266 if (capture_opts.ringbuffer_on) {
267 /* ringbuffer is enabled */
268 cfile.save_file_fd = ringbuf_init(capfile_name,
269 capture_opts.ringbuffer_num_files);
271 /* Try to open/create the specified file for use as a capture buffer. */
272 cfile.save_file_fd = open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
277 /* Choose a random name for the capture buffer */
278 cfile.save_file_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
279 capfile_name = g_strdup(tmpname);
282 if (cfile.save_file_fd == -1) {
284 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
285 "The temporary file to which the capture would be saved (\"%s\")"
286 "could not be opened: %s.", capfile_name, strerror(errno));
288 if (capture_opts.ringbuffer_on) {
289 ringbuf_error_cleanup();
291 open_failure_alert_box(capfile_name, errno, TRUE);
293 g_free(capfile_name);
297 g_assert(cfile.save_file == NULL);
298 cfile.save_file = capfile_name;
299 /* cfile.save_file is "g_free"ed below, which is equivalent to
300 "g_free(capfile_name)". */
302 if (capture_opts.sync_mode) {
303 /* sync mode: do the capture in a child process */
304 return sync_pipe_do_capture(is_tempfile);
305 /* capture is still running */
307 /* normal mode: do the capture synchronously */
308 return normal_do_capture(is_tempfile);
309 /* capture is finished here */
315 /* Add a string pointer to a NULL-terminated array of string pointers. */
317 sync_pipe_add_arg(char **args, int *argc, char *arg)
319 /* Grow the array; "*argc" currently contains the number of string
320 pointers, *not* counting the NULL pointer at the end, so we have
321 to add 2 in order to get the new size of the array, including the
322 new pointer and the terminating NULL pointer. */
323 args = g_realloc(args, (*argc + 2) * sizeof (char *));
325 /* Stuff the pointer into the penultimate element of the array, which
326 is the one at the index specified by "*argc". */
329 /* Now bump the count. */
332 /* We overwrite the NULL pointer; put it back right after the
340 /* Given a string, return a pointer to a quote-encapsulated version of
341 the string, so we can pass it as an argument with "spawnvp" even
342 if it contains blanks. */
344 sync_pipe_quote_encapsulate(const char *string)
346 char *encapsulated_string;
348 encapsulated_string = g_new(char, strlen(string) + 3);
349 sprintf(encapsulated_string, "\"%s\"", string);
350 return encapsulated_string;
357 sync_pipe_do_capture(gboolean is_tempfile) {
364 char scount[24]; /* need a constant for len of numbers */
365 char sautostop_filesize[24]; /* need a constant for len of numbers */
366 char sautostop_duration[24]; /* need a constant for len of numbers */
367 char save_file_fd[24];
375 char sync_pipe_fd[24];
380 /* Allocate the string pointer array with enough space for the
381 terminating NULL pointer. */
383 argv = g_malloc(sizeof (char *));
386 /* Now add those arguments used on all platforms. */
387 argv = sync_pipe_add_arg(argv, &argc, CHILD_NAME);
389 argv = sync_pipe_add_arg(argv, &argc, "-i");
390 argv = sync_pipe_add_arg(argv, &argc, cfile.iface);
392 argv = sync_pipe_add_arg(argv, &argc, "-w");
393 argv = sync_pipe_add_arg(argv, &argc, cfile.save_file);
395 argv = sync_pipe_add_arg(argv, &argc, "-W");
396 sprintf(save_file_fd,"%d",cfile.save_file_fd); /* in lieu of itoa */
397 argv = sync_pipe_add_arg(argv, &argc, save_file_fd);
399 if (capture_opts.has_autostop_count) {
400 argv = sync_pipe_add_arg(argv, &argc, "-c");
401 sprintf(scount,"%d",capture_opts.autostop_count);
402 argv = sync_pipe_add_arg(argv, &argc, scount);
405 if (capture_opts.has_snaplen) {
406 argv = sync_pipe_add_arg(argv, &argc, "-s");
407 sprintf(ssnap,"%d",capture_opts.snaplen);
408 argv = sync_pipe_add_arg(argv, &argc, ssnap);
411 if (capture_opts.linktype != -1) {
412 argv = sync_pipe_add_arg(argv, &argc, "-y");
413 sprintf(ssnap,"%d",capture_opts.linktype);
414 argv = sync_pipe_add_arg(argv, &argc, ssnap);
417 if (capture_opts.has_autostop_filesize) {
418 argv = sync_pipe_add_arg(argv, &argc, "-a");
419 sprintf(sautostop_filesize,"filesize:%d",capture_opts.autostop_filesize);
420 argv = sync_pipe_add_arg(argv, &argc, sautostop_filesize);
423 if (capture_opts.has_autostop_duration) {
424 argv = sync_pipe_add_arg(argv, &argc, "-a");
425 sprintf(sautostop_duration,"duration:%d",capture_opts.autostop_duration);
426 argv = sync_pipe_add_arg(argv, &argc, sautostop_duration);
429 if (!capture_opts.promisc_mode)
430 argv = sync_pipe_add_arg(argv, &argc, "-p");
433 /* Create a pipe for the child process */
435 if(_pipe(sync_pipe, 512, O_BINARY) < 0) {
436 /* Couldn't create the pipe between parent and child. */
438 unlink(cfile.save_file);
439 g_free(cfile.save_file);
440 cfile.save_file = NULL;
441 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "Couldn't create sync pipe: %s",
446 /* Convert font name to a quote-encapsulated string and pass to child */
447 argv = sync_pipe_add_arg(argv, &argc, "-m");
448 fontstring = sync_pipe_quote_encapsulate(prefs.PREFS_GUI_FONT_NAME);
449 argv = sync_pipe_add_arg(argv, &argc, fontstring);
451 /* Convert pipe write handle to a string and pass to child */
452 argv = sync_pipe_add_arg(argv, &argc, "-Z");
453 itoa(sync_pipe[WRITE], sync_pipe_fd, 10);
454 argv = sync_pipe_add_arg(argv, &argc, sync_pipe_fd);
456 /* Convert filter string to a quote delimited string and pass to child */
458 if (cfile.cfilter != NULL && strlen(cfile.cfilter) != 0) {
459 argv = sync_pipe_add_arg(argv, &argc, "-f");
460 filterstring = sync_pipe_quote_encapsulate(cfile.cfilter);
461 argv = sync_pipe_add_arg(argv, &argc, filterstring);
465 fork_child = spawnvp(_P_NOWAIT, ethereal_path, argv);
468 g_free(filterstring);
471 if (pipe(sync_pipe) < 0) {
472 /* Couldn't create the pipe between parent and child. */
474 unlink(cfile.save_file);
475 g_free(cfile.save_file);
476 cfile.save_file = NULL;
477 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "Couldn't create sync pipe: %s",
482 argv = sync_pipe_add_arg(argv, &argc, "-m");
483 argv = sync_pipe_add_arg(argv, &argc, prefs.PREFS_GUI_FONT_NAME);
485 if (cfile.cfilter != NULL && strlen(cfile.cfilter) != 0) {
486 argv = sync_pipe_add_arg(argv, &argc, "-f");
487 argv = sync_pipe_add_arg(argv, &argc, cfile.cfilter);
490 if ((fork_child = fork()) == 0) {
492 * Child process - run Ethereal with the right arguments to make
493 * it just pop up the live capture dialog box and capture with
494 * the specified capture parameters, writing to the specified file.
496 * args: -i interface specification
498 * -W file descriptor to write
499 * -c count to capture
502 * -f "filter expression"
505 dup(sync_pipe[WRITE]);
506 close(sync_pipe[READ]);
507 execvp(ethereal_path, argv);
508 snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
509 ethereal_path, strerror(errno));
510 sync_pipe_errmsg_to_parent(errmsg);
512 /* Exit with "_exit()", so that we don't close the connection
513 to the X server (and cause stuff buffered up by our parent but
514 not yet sent to be sent, as that stuff should only be sent by
520 /* Parent process - read messages from the child process over the
522 g_free(argv); /* free up arg array */
524 /* Close the write side of the pipe, so that only the child has it
525 open, and thus it completely closes, and thus returns to us
526 an EOF indication, if the child closes it (either deliberately
527 or by exiting abnormally). */
528 close(sync_pipe[WRITE]);
530 /* Close the save file FD, as we won't be using it - we'll be opening
531 it and reading the save file through Wiretap. */
532 close(cfile.save_file_fd);
534 if (fork_child == -1) {
535 /* We couldn't even create the child process. */
537 close(sync_pipe[READ]);
538 unlink(cfile.save_file);
539 g_free(cfile.save_file);
540 cfile.save_file = NULL;
541 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK,
542 "Couldn't create child process: %s", strerror(error));
546 /* Read a byte count from "sync_pipe[READ]", terminated with a
547 colon; if the count is 0, the child process created the
548 capture file and we should start reading from it, otherwise
549 the capture couldn't start and the count is a count of bytes
550 of error message, and we should display the message. */
553 i = read(sync_pipe[READ], &c, 1);
555 /* EOF - the child process died.
556 Close the read side of the sync pipe, remove the capture file,
557 and report the failure. */
558 close(sync_pipe[READ]);
559 unlink(cfile.save_file);
560 g_free(cfile.save_file);
561 cfile.save_file = NULL;
562 sync_pipe_wait_for_child(TRUE);
565 if (c == SP_CAPSTART || c == SP_ERROR_MSG)
568 /* Child process handed us crap.
569 Close the read side of the sync pipe, remove the capture file,
570 and report the failure. */
571 close(sync_pipe[READ]);
572 unlink(cfile.save_file);
573 g_free(cfile.save_file);
574 cfile.save_file = NULL;
575 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
576 "Capture child process sent us a bad message");
579 byte_count = byte_count*10 + c - '0';
581 if (c != SP_CAPSTART) {
582 /* Failure - the child process sent us a message indicating
583 what the problem was. */
584 if (byte_count == 0) {
585 /* Zero-length message? */
586 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
587 "Capture child process failed, but its error message was empty.");
589 msg = g_malloc(byte_count + 1);
591 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
592 "Capture child process failed, but its error message was too big.");
594 i = read(sync_pipe[READ], msg, byte_count);
595 msg[byte_count] = '\0';
597 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
598 "Capture child process failed: Error %s reading its error message.",
601 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
602 "Capture child process failed: EOF reading its error message.");
603 sync_pipe_wait_for_child(FALSE);
605 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, msg);
609 /* Close the sync pipe. */
610 close(sync_pipe[READ]);
612 /* Get rid of the save file - the capture never started. */
613 unlink(cfile.save_file);
614 g_free(cfile.save_file);
615 cfile.save_file = NULL;
620 /* The child process started a capture.
621 Attempt to open the capture file and set up to read it. */
622 err = cf_start_tail(cfile.save_file, is_tempfile, &cfile);
624 /* We weren't able to open the capture file; user has been
625 alerted. Close the sync pipe. */
627 close(sync_pipe[READ]);
629 /* Don't unlink the save file - leave it around, for debugging
631 g_free(cfile.save_file);
632 cfile.save_file = NULL;
635 /* We were able to open and set up to read the capture file;
636 arrange that our callback be called whenever it's possible
637 to read from the sync pipe, so that it's called when
638 the child process wants to tell us something. */
639 pipe_input_set_handler(sync_pipe[READ], (gpointer) &cfile, &fork_child, sync_pipe_input_cb);
645 /* There's stuff to read from the sync pipe, meaning the child has sent
646 us a message, or the sync pipe has closed, meaning the child has
647 closed it (perhaps because it exited). */
649 sync_pipe_input_cb(gint source, gpointer user_data)
651 capture_file *cf = (capture_file *)user_data;
653 char buffer[BUFSIZE+1], *p = buffer, *q = buffer, *msg, *r;
654 int nread, msglen, chars_to_copy;
659 if ((nread = read(source, buffer, BUFSIZE)) <= 0) {
660 /* The child has closed the sync pipe, meaning it's not going to be
661 capturing any more packets. Pick up its exit status, and
662 complain if it did anything other than exit with status 0. */
663 sync_pipe_wait_for_child(FALSE);
665 /* Read what remains of the capture file, and finish the capture.
666 XXX - do something if this fails? */
667 switch (cf_finish_tail(cf, &err)) {
671 simple_dialog(ESD_TYPE_INFO, ESD_BTN_OK,
672 "%sNo packets captured!%s\n\n"
673 "As no data was captured, closing the %scapture file!",
674 simple_dialog_primary_start(), simple_dialog_primary_end(),
675 (cf->is_tempfile) ? "temporary " : "");
680 /* Just because we got an error, that doesn't mean we were unable
681 to read any of the file; we handle what we could get from the
686 /* Exit by leaving the main loop, so that any quit functions
687 we registered get called. */
692 /* We're not doing a capture any more, so we don't have a save
694 g_free(cf->save_file);
695 cf->save_file = NULL;
700 buffer[nread] = '\0';
703 /* look for (possibly multiple) indications */
705 case SP_PACKET_COUNT :
712 cf->drops_known = TRUE;
724 /* Read the entire message.
725 XXX - if the child hasn't sent it all yet, this could cause us
726 to hang until they do. */
727 msg = g_malloc(msglen + 1);
729 while (msglen != 0) {
732 if ((nread = read(source, buffer, BUFSIZE)) <= 0)
737 chars_to_copy = MIN(msglen, nread);
738 memcpy(r, q, chars_to_copy);
741 nread -= chars_to_copy;
742 msglen -= chars_to_copy;
745 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, msg);
755 /* Read from the capture file the number of records the child told us
757 XXX - do something if this fails? */
758 switch (cf_continue_tail(cf, to_read, &err)) {
762 /* Just because we got an error, that doesn't mean we were unable
763 to read any of the file; we handle what we could get from the
766 XXX - abort on a read error? */
770 /* Kill the child capture process; the user wants to exit, and we
771 shouldn't just leave it running. */
772 kill_capture_child();
780 sync_pipe_wait_for_child(gboolean always_report)
785 /* XXX - analyze the wait status and display more information
787 XXX - set "fork_child" to -1 if we find it exited? */
788 if (_cwait(&wstatus, fork_child, _WAIT_CHILD) == -1) {
789 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
790 "Child capture process stopped unexpectedly");
793 if (wait(&wstatus) != -1) {
794 if (WIFEXITED(wstatus)) {
795 /* The child exited; display its exit status, if it's not zero,
796 and even if it's zero if "always_report" is true. */
797 if (always_report || WEXITSTATUS(wstatus) != 0) {
798 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
799 "Child capture process exited: exit status %d",
800 WEXITSTATUS(wstatus));
802 } else if (WIFSTOPPED(wstatus)) {
803 /* It stopped, rather than exiting. "Should not happen." */
804 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
805 "Child capture process stopped: %s",
806 sync_pipe_signame(WSTOPSIG(wstatus)));
807 } else if (WIFSIGNALED(wstatus)) {
808 /* It died with a signal. */
809 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
810 "Child capture process died: %s%s",
811 sync_pipe_signame(WTERMSIG(wstatus)),
812 WCOREDUMP(wstatus) ? " - core dumped" : "");
814 /* What? It had to either have exited, or stopped, or died with
815 a signal; what happened here? */
816 simple_dialog(ESD_TYPE_WARN, ESD_BTN_OK,
817 "Child capture process died: wait status %#o", wstatus);
821 /* No more child process. */
827 sync_pipe_errmsg_to_parent(const char *errmsg)
829 int msglen = strlen(errmsg);
830 char lenbuf[SP_DECISIZE+1+1];
832 sprintf(lenbuf, "%u%c", msglen, SP_ERROR_MSG);
833 write(1, lenbuf, strlen(lenbuf));
834 write(1, errmsg, msglen);
838 sync_pipe_drops_to_parent(int drops)
840 char tmp[SP_DECISIZE+1+1];
841 sprintf(tmp, "%d%c", drops, SP_DROPS);
842 write(1, tmp, strlen(tmp));
846 sync_pipe_packet_count_to_parent(int packet_count)
848 char tmp[SP_DECISIZE+1+1];
849 sprintf(tmp, "%d%c", packet_count, SP_PACKET_COUNT);
850 write(1, tmp, strlen(tmp));
854 sync_pipe_capstart_to_parent(void)
856 static const char capstart_msg = SP_CAPSTART;
858 write(1, &capstart_msg, 1);
863 sync_pipe_signame(int sig)
866 static char sigmsg_buf[6+1+3+1];
875 sigmsg = "Interrupted";
883 sigmsg = "Illegal instruction";
887 sigmsg = "Trace trap";
895 sigmsg = "Arithmetic exception";
903 sigmsg = "Bus error";
907 sigmsg = "Segmentation violation";
910 /* http://metalab.unc.edu/pub/Linux/docs/HOWTO/GCC-HOWTO
911 Linux is POSIX compliant. These are not POSIX-defined signals ---
912 ISO/IEC 9945-1:1990 (IEEE Std 1003.1-1990), paragraph B.3.3.1.1 sez:
914 ``The signals SIGBUS, SIGEMT, SIGIOT, SIGTRAP, and SIGSYS
915 were omitted from POSIX.1 because their behavior is
916 implementation dependent and could not be adequately catego-
917 rized. Conforming implementations may deliver these sig-
918 nals, but must document the circumstances under which they
919 are delivered and note any restrictions concerning their
922 So we only check for SIGSYS on those systems that happen to
923 implement them (a system can be POSIX-compliant and implement
924 them, it's just that POSIX doesn't *require* a POSIX-compliant
925 system to implement them).
930 sigmsg = "Bad system call";
935 sigmsg = "Broken pipe";
939 sigmsg = "Alarm clock";
943 sigmsg = "Terminated";
947 sprintf(sigmsg_buf, "Signal %d", sig);
961 normal_do_capture(gboolean is_tempfile)
963 int capture_succeeded;
964 gboolean stats_known;
965 struct pcap_stat stats;
969 capture_succeeded = capture(&stats_known, &stats);
970 if (quit_after_cap) {
971 /* DON'T unlink the save file. Presumably someone wants it. */
974 if (!capture_succeeded) {
975 /* We didn't succeed in doing the capture, so we don't have a save
977 if (capture_opts.ringbuffer_on) {
980 g_free(cfile.save_file);
982 cfile.save_file = NULL;
985 /* Capture succeeded; attempt to read in the capture file. */
986 if ((err = cf_open(cfile.save_file, is_tempfile, &cfile)) != 0) {
987 /* We're not doing a capture any more, so we don't have a save
989 if (capture_opts.ringbuffer_on) {
992 g_free(cfile.save_file);
994 cfile.save_file = NULL;
998 /* Set the read filter to NULL. */
1001 /* Get the packet-drop statistics.
1003 XXX - there are currently no packet-drop statistics stored
1004 in libpcap captures, and that's what we're reading.
1006 At some point, we will add support in Wiretap to return
1007 packet-drop statistics for capture file formats that store it,
1008 and will make "cf_read()" get those statistics from Wiretap.
1009 We clear the statistics (marking them as "not known") in
1010 "cf_open()", and "cf_read()" will only fetch them and mark
1011 them as known if Wiretap supplies them, so if we get the
1012 statistics now, after calling "cf_open()" but before calling
1013 "cf_read()", the values we store will be used by "cf_read()".
1015 If a future libpcap capture file format stores the statistics,
1016 we'll put them into the capture file that we write, and will
1017 thus not have to set them here - "cf_read()" will get them from
1018 the file and use them. */
1020 cfile.drops_known = TRUE;
1022 /* XXX - on some systems, libpcap doesn't bother filling in
1023 "ps_ifdrop" - it doesn't even set it to zero - so we don't
1024 bother looking at it.
1026 Ideally, libpcap would have an interface that gave us
1027 several statistics - perhaps including various interface
1028 error statistics - and would tell us which of them it
1029 supplies, allowing us to display only the ones it does. */
1030 cfile.drops = stats.ps_drop;
1032 switch (cf_read(&cfile)) {
1036 /* Just because we got an error, that doesn't mean we were unable
1037 to read any of the file; we handle what we could get from the
1042 /* Exit by leaving the main loop, so that any quit functions
1043 we registered get called. */
1044 main_window_nested_quit();
1048 /* We're not doing a capture any more, so we don't have a save
1050 if (capture_opts.ringbuffer_on) {
1053 g_free(cfile.save_file);
1055 cfile.save_file = NULL;
1057 /* if we didn't captured even a single packet, close the file again */
1058 if(cfile.count == 0) {
1059 simple_dialog(ESD_TYPE_INFO, ESD_BTN_OK,
1060 "%sNo packets captured!%s\n\n"
1061 "As no data was captured, closing the %scapture file!",
1062 simple_dialog_primary_start(), simple_dialog_primary_end(),
1063 (cfile.is_tempfile) ? "temporary " : "");
1070 * Timeout, in milliseconds, for reads from the stream of captured packets.
1072 #define CAP_READ_TIMEOUT 250
1075 /* Take care of byte order in the libpcap headers read from pipes.
1076 * (function taken from wiretap/libpcap.c) */
1078 cap_pipe_adjust_header(loop_data *ld, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1080 if (ld->byte_swapped) {
1081 /* Byte-swap the record header fields. */
1082 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
1083 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
1084 rechdr->incl_len = BSWAP32(rechdr->incl_len);
1085 rechdr->orig_len = BSWAP32(rechdr->orig_len);
1088 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1089 swapped, in order to match the BPF header layout.
1091 Unfortunately, some files were, according to a comment in the "libpcap"
1092 source, written with version 2.3 in their headers but without the
1093 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1094 would make no sense - we assume that we need to swap them. */
1095 if (hdr->version_major == 2 &&
1096 (hdr->version_minor < 3 ||
1097 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1100 temp = rechdr->orig_len;
1101 rechdr->orig_len = rechdr->incl_len;
1102 rechdr->incl_len = temp;
1106 /* Mimic pcap_open_live() for pipe captures
1107 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
1109 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1110 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1112 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
1113 char *errmsg, int errmsgl)
1115 struct stat pipe_stat;
1119 unsigned int bytes_read;
1121 struct timeval timeout;
1124 * XXX Ethereal blocks until we return
1126 if (strcmp(pipename, "-") == 0)
1127 fd = 0; /* read from stdin */
1129 if (stat(pipename, &pipe_stat) < 0) {
1130 if (errno == ENOENT || errno == ENOTDIR)
1131 ld->cap_pipe_err = PIPNEXIST;
1133 snprintf(errmsg, errmsgl,
1134 "The capture session could not be initiated "
1135 "due to error on pipe: %s", strerror(errno));
1136 ld->cap_pipe_err = PIPERR;
1140 if (! S_ISFIFO(pipe_stat.st_mode)) {
1141 if (S_ISCHR(pipe_stat.st_mode)) {
1143 * Assume the user specified an interface on a system where
1144 * interfaces are in /dev. Pretend we haven't seen it.
1146 ld->cap_pipe_err = PIPNEXIST;
1148 snprintf(errmsg, errmsgl,
1149 "The capture session could not be initiated because\n"
1150 "\"%s\" is neither an interface nor a pipe", pipename);
1151 ld->cap_pipe_err = PIPERR;
1155 fd = open(pipename, O_RDONLY | O_NONBLOCK);
1157 snprintf(errmsg, errmsgl,
1158 "The capture session could not be initiated "
1159 "due to error on pipe open: %s", strerror(errno));
1160 ld->cap_pipe_err = PIPERR;
1165 ld->from_cap_pipe = TRUE;
1167 /* read the pcap header */
1170 while (bytes_read < sizeof magic) {
1173 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1174 sel_ret = select(fd+1, &rfds, NULL, NULL, &timeout);
1176 snprintf(errmsg, errmsgl,
1177 "Unexpected error from select: %s", strerror(errno));
1179 } else if (sel_ret > 0) {
1180 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
1183 snprintf(errmsg, errmsgl, "End of file on pipe during open");
1185 snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
1195 /* Host that wrote it has our byte order, and was running
1196 a program using either standard or ss990417 libpcap. */
1197 ld->byte_swapped = FALSE;
1198 ld->modified = FALSE;
1200 case PCAP_MODIFIED_MAGIC:
1201 /* Host that wrote it has our byte order, but was running
1202 a program using either ss990915 or ss991029 libpcap. */
1203 ld->byte_swapped = FALSE;
1204 ld->modified = TRUE;
1206 case PCAP_SWAPPED_MAGIC:
1207 /* Host that wrote it has a byte order opposite to ours,
1208 and was running a program using either standard or
1209 ss990417 libpcap. */
1210 ld->byte_swapped = TRUE;
1211 ld->modified = FALSE;
1213 case PCAP_SWAPPED_MODIFIED_MAGIC:
1214 /* Host that wrote it out has a byte order opposite to
1215 ours, and was running a program using either ss990915
1216 or ss991029 libpcap. */
1217 ld->byte_swapped = TRUE;
1218 ld->modified = TRUE;
1221 /* Not a "libpcap" type we know about. */
1222 snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
1226 /* Read the rest of the header */
1228 while (bytes_read < sizeof(struct pcap_hdr)) {
1231 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1232 sel_ret = select(fd+1, &rfds, NULL, NULL, &timeout);
1234 snprintf(errmsg, errmsgl,
1235 "Unexpected error from select: %s", strerror(errno));
1237 } else if (sel_ret > 0) {
1238 b = read(fd, ((char *)hdr)+bytes_read,
1239 sizeof(struct pcap_hdr) - bytes_read);
1242 snprintf(errmsg, errmsgl, "End of file on pipe during open");
1244 snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
1252 if (ld->byte_swapped) {
1253 /* Byte-swap the header fields about which we care. */
1254 hdr->version_major = BSWAP16(hdr->version_major);
1255 hdr->version_minor = BSWAP16(hdr->version_minor);
1256 hdr->snaplen = BSWAP32(hdr->snaplen);
1257 hdr->network = BSWAP32(hdr->network);
1260 if (hdr->version_major < 2) {
1261 snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1265 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1266 ld->cap_pipe_err = PIPOK;
1270 ld->cap_pipe_err = PIPERR;
1276 /* We read one record from the pipe, take care of byte order in the record
1277 * header, write the record in the capture file, and update capture statistics. */
1280 cap_pipe_dispatch(int fd, loop_data *ld, struct pcap_hdr *hdr,
1281 struct pcaprec_modified_hdr *rechdr, guchar *data,
1282 char *errmsg, int errmsgl)
1284 struct pcap_pkthdr phdr;
1286 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1289 switch (ld->cap_pipe_state) {
1291 case STATE_EXPECT_REC_HDR:
1292 ld->bytes_to_read = ld->modified ?
1293 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1295 ld->cap_pipe_state = STATE_READ_REC_HDR;
1298 case STATE_READ_REC_HDR:
1299 b = read(fd, ((char *)rechdr)+ld->bytes_read,
1300 ld->bytes_to_read - ld->bytes_read);
1303 result = PD_PIPE_EOF;
1305 result = PD_PIPE_ERR;
1308 if ((ld->bytes_read += b) < ld->bytes_to_read)
1310 result = PD_REC_HDR_READ;
1313 case STATE_EXPECT_DATA:
1315 ld->cap_pipe_state = STATE_READ_DATA;
1318 case STATE_READ_DATA:
1319 b = read(fd, data+ld->bytes_read, rechdr->hdr.incl_len - ld->bytes_read);
1322 result = PD_PIPE_EOF;
1324 result = PD_PIPE_ERR;
1327 if ((ld->bytes_read += b) < rechdr->hdr.incl_len)
1329 result = PD_DATA_READ;
1333 snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
1336 } /* switch (ld->cap_pipe_state) */
1339 * We've now read as much data as we were expecting, so process it.
1343 case PD_REC_HDR_READ:
1344 /* We've read the header. Take care of byte order. */
1345 cap_pipe_adjust_header(ld, hdr, &rechdr->hdr);
1346 if (rechdr->hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1347 snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
1348 ld->counts.total+1, rechdr->hdr.incl_len);
1351 ld->cap_pipe_state = STATE_EXPECT_DATA;
1355 /* Fill in a "struct pcap_pkthdr", and process the packet. */
1356 phdr.ts.tv_sec = rechdr->hdr.ts_sec;
1357 phdr.ts.tv_usec = rechdr->hdr.ts_usec;
1358 phdr.caplen = rechdr->hdr.incl_len;
1359 phdr.len = rechdr->hdr.orig_len;
1361 capture_pcap_cb((guchar *)ld, &phdr, data);
1363 ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
1367 ld->cap_pipe_err = PIPEOF;
1371 snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
1378 ld->cap_pipe_err = PIPERR;
1379 /* Return here rather than inside the switch to prevent GCC warning */
1382 #endif /* not _WIN32 */
1385 * This needs to be static, so that the SIGUSR1 handler can clear the "go"
1388 static loop_data ld;
1390 /* Do the low-level work of a capture.
1391 Returns TRUE if it succeeds, FALSE otherwise. */
1393 capture(gboolean *stats_known, struct pcap_stat *stats)
1398 gchar open_err_str[PCAP_ERRBUF_SIZE];
1399 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
1400 bpf_u_int32 netnum, netmask;
1401 struct bpf_program fcode;
1402 const char *set_linktype_err_str;
1403 time_t upd_time, cur_time;
1406 condition *cnd_stop_capturesize = NULL;
1407 condition *cnd_stop_timeout = NULL;
1408 condition *cnd_ring_timeout = NULL;
1409 char errmsg[4096+1];
1412 capture_info capture_ui;
1415 WORD wVersionRequested;
1419 struct timeval timeout;
1420 static const char ppamsg[] = "can't find PPA for ";
1424 struct pcap_hdr hdr;
1425 struct pcaprec_modified_hdr rechdr;
1426 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1428 #ifdef MUST_DO_SELECT
1432 /* Initialize Windows Socket if we are in a WIN32 OS
1433 This needs to be done before querying the interface for network/netmask */
1435 /* XXX - do we really require 1.1 or earlier?
1436 Are there any versions that support only 2.0 or higher? */
1437 wVersionRequested = MAKEWORD(1, 1);
1438 err = WSAStartup(wVersionRequested, &wsaData);
1442 case WSASYSNOTREADY:
1443 snprintf(errmsg, sizeof errmsg,
1444 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
1447 case WSAVERNOTSUPPORTED:
1448 snprintf(errmsg, sizeof errmsg,
1449 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
1450 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
1453 case WSAEINPROGRESS:
1454 snprintf(errmsg, sizeof errmsg,
1455 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
1459 snprintf(errmsg, sizeof errmsg,
1460 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
1464 snprintf(errmsg, sizeof errmsg,
1465 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
1469 snprintf(errmsg, sizeof errmsg,
1470 "Couldn't initialize Windows Sockets: error %d", err);
1479 ld.counts.total = 0;
1480 if (capture_opts.has_autostop_count)
1481 ld.max = capture_opts.autostop_count;
1483 ld.max = 0; /* no limit */
1484 ld.err = 0; /* no error seen yet */
1485 ld.linktype = WTAP_ENCAP_UNKNOWN;
1486 ld.pcap_err = FALSE;
1487 ld.from_cap_pipe = FALSE;
1488 ld.sync_packets = 0;
1496 ld.counts.netbios = 0;
1497 ld.counts.vines = 0;
1498 ld.counts.other = 0;
1502 /* We haven't yet gotten the capture statistics. */
1503 *stats_known = FALSE;
1505 /* Open the network interface to capture from it.
1506 Some versions of libpcap may put warnings into the error buffer
1507 if they succeed; to tell if that's happened, we have to clear
1508 the error buffer, and check if it's still a null string. */
1509 open_err_str[0] = '\0';
1510 pch = pcap_open_live(cfile.iface,
1511 capture_opts.has_snaplen ? capture_opts.snaplen :
1512 WTAP_MAX_PACKET_SIZE,
1513 capture_opts.promisc_mode, CAP_READ_TIMEOUT,
1517 /* setting the data link type only works on real interfaces */
1518 if (capture_opts.linktype != -1) {
1519 set_linktype_err_str = set_pcap_linktype(pch, cfile.iface,
1520 capture_opts.linktype);
1521 if (set_linktype_err_str != NULL) {
1522 snprintf(errmsg, sizeof errmsg, "Unable to set data link type (%s).",
1523 set_linktype_err_str);
1528 /* We couldn't open "cfile.iface" as a network device. */
1530 /* On Windows, we don't support capturing on pipes, so we give up.
1531 If this is a child process that does the capturing in sync
1532 mode or fork mode, it shouldn't do any UI stuff until we pop up the
1533 capture-progress window, and, since we couldn't start the
1534 capture, we haven't popped it up. */
1535 if (!capture_child) {
1536 main_window_update();
1539 /* On Win32 OSes, the capture devices are probably available to all
1540 users; don't warn about permissions problems.
1542 Do, however, warn that WAN devices aren't supported. */
1543 snprintf(errmsg, sizeof errmsg,
1544 "The capture session could not be initiated (%s).\n"
1545 "Please check that you have the proper interface specified.\n"
1547 "Note that the WinPcap 2.x version of the driver Ethereal uses for packet\n"
1548 "capture on Windows doesn't support capturing on PPP/WAN interfaces in\n"
1549 "Windows NT/2000/XP/2003 Server, and that the WinPcap 3.0 and later versions\n"
1550 "don't support capturing on PPP/WAN interfaces at all.",
1554 /* try to open cfile.iface as a pipe */
1555 pipe_fd = cap_pipe_open_live(cfile.iface, &hdr, &ld, errmsg, sizeof errmsg);
1557 if (pipe_fd == -1) {
1559 /* If this is a child process that does the capturing in sync
1560 * mode or fork mode, it shouldn't do any UI stuff until we pop up the
1561 * capture-progress window, and, since we couldn't start the
1562 * capture, we haven't popped it up.
1564 if (!capture_child) {
1565 main_window_update();
1568 if (ld.cap_pipe_err == PIPNEXIST) {
1569 /* Pipe doesn't exist, so output message for interface */
1571 /* If we got a "can't find PPA for XXX" message, warn the user (who
1572 is running Ethereal on HP-UX) that they don't have a version
1573 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1574 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1575 PPA for XXX" rather than "can't find PPA for XXX"). */
1576 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1579 "You are running Ethereal with a version of the libpcap library\n"
1580 "that doesn't handle HP-UX network devices well; this means that\n"
1581 "Ethereal may not be able to capture packets.\n"
1583 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1584 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1585 "packaged binary form from the Software Porting And Archive Centre\n"
1586 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1587 "at the URL lists a number of mirror sites.";
1590 snprintf(errmsg, sizeof errmsg,
1591 "The capture session could not be initiated (%s).\n"
1592 "Please check to make sure you have sufficient permissions, and that\n"
1593 "you have the proper interface or pipe specified.%s", open_err_str,
1597 * Else pipe (or file) does exist and cap_pipe_open_live() has
1602 /* cap_pipe_open_live() succeeded; don't want
1603 error message from pcap_open_live() */
1604 open_err_str[0] = '\0';
1608 /* capture filters only work on real interfaces */
1609 if (cfile.cfilter && !ld.from_cap_pipe) {
1610 /* A capture filter was specified; set it up. */
1611 if (pcap_lookupnet(cfile.iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1613 * Well, we can't get the netmask for this interface; it's used
1614 * only for filters that check for broadcast IP addresses, so
1615 * we just punt and use 0. It might be nice to warn the user,
1616 * but that's a pain in a GUI application, as it'd involve popping
1617 * up a message box, and it's not clear how often this would make
1618 * a difference (only filters that check for IP broadcast addresses
1623 if (pcap_compile(pch, &fcode, cfile.cfilter, 1, netmask) < 0) {
1624 dfilter_t *rfcode = NULL;
1625 /* filter string invalid, did the user tried a display filter? */
1626 if (dfilter_compile(cfile.cfilter, &rfcode) && rfcode != NULL) {
1627 snprintf(errmsg, sizeof errmsg,
1628 "%sInvalid capture filter: \"%s\"!%s\n"
1630 "That string looks like a valid display filter; however, it is not a valid\n"
1631 "capture filter (%s).\n"
1633 "Note that display filters and capture filters don't have the same syntax,\n"
1634 "so you can't use most display filter expressions as capture filters.\n"
1636 "See the help for a description of the capture filter syntax.",
1637 simple_dialog_primary_start(), cfile.cfilter, simple_dialog_primary_end(),
1639 dfilter_free(rfcode);
1641 snprintf(errmsg, sizeof errmsg,
1642 "%sInvalid capture filter: \"%s\"!%s\n"
1644 "That string is not a valid capture filter (%s).\n"
1645 "See the help for a description of the capture filter syntax.",
1646 simple_dialog_primary_start(), cfile.cfilter, simple_dialog_primary_end(),
1651 if (pcap_setfilter(pch, &fcode) < 0) {
1652 snprintf(errmsg, sizeof errmsg, "Can't install filter (%s).",
1658 /* Set up to write to the capture file. */
1660 if (ld.from_cap_pipe) {
1661 pcap_encap = hdr.network;
1662 file_snaplen = hdr.snaplen;
1666 pcap_encap = get_pcap_linktype(pch, cfile.iface);
1667 file_snaplen = pcap_snapshot(pch);
1669 ld.linktype = wtap_pcap_encap_to_wtap_encap(pcap_encap);
1670 if (ld.linktype == WTAP_ENCAP_UNKNOWN) {
1671 snprintf(errmsg, sizeof errmsg,
1672 "The network you're capturing from is of a type"
1673 " that Ethereal doesn't support (data link type %d).", pcap_encap);
1676 if (capture_opts.ringbuffer_on) {
1677 ld.pdh = ringbuf_init_wtap_dump_fdopen(WTAP_FILE_PCAP, ld.linktype,
1678 file_snaplen, &err);
1680 ld.pdh = wtap_dump_fdopen(cfile.save_file_fd, WTAP_FILE_PCAP,
1681 ld.linktype, file_snaplen, &err);
1684 if (ld.pdh == NULL) {
1685 /* We couldn't set up to write to the capture file. */
1688 case WTAP_ERR_CANT_OPEN:
1689 strcpy(errmsg, "The file to which the capture would be saved"
1690 " couldn't be created for some unknown reason.");
1693 case WTAP_ERR_SHORT_WRITE:
1694 strcpy(errmsg, "A full header couldn't be written to the file"
1695 " to which the capture would be saved.");
1700 snprintf(errmsg, sizeof(errmsg),
1701 "The file to which the capture would be"
1702 " saved (\"%s\") could not be opened: Error %d.",
1703 cfile.save_file, err);
1705 snprintf(errmsg, sizeof(errmsg),
1706 "The file to which the capture would be"
1707 " saved (\"%s\") could not be opened: %s.",
1708 cfile.save_file, strerror(err));
1715 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1716 returned a warning; print it, but keep capturing. */
1717 if (open_err_str[0] != '\0')
1718 g_warning("%s.", open_err_str);
1720 /* XXX - capture SIGTERM and close the capture, in case we're on a
1721 Linux 2.0[.x] system and you have to explicitly close the capture
1722 stream in order to turn promiscuous mode off? We need to do that
1723 in other places as well - and I don't think that works all the
1724 time in any case, due to libpcap bugs. */
1726 if (capture_child) {
1727 /* Well, we should be able to start capturing.
1729 This is the child process for a sync mode capture, so sync out
1730 the capture file, so the header makes it to the file system,
1731 and send a "capture started successfully and capture file created"
1732 message to our parent so that they'll open the capture file and
1733 update its windows to indicate that we have a live capture in
1735 fflush(wtap_dump_file(ld.pdh));
1736 sync_pipe_capstart_to_parent();
1739 /* start capture info dialog */
1740 capture_ui.callback_data = &ld;
1741 capture_ui.counts = &ld.counts;
1742 capture_info_create(&capture_ui);
1744 start_time = time(NULL);
1745 upd_time = time(NULL);
1746 #ifdef MUST_DO_SELECT
1747 if (!ld.from_cap_pipe) pcap_fd = pcap_fileno(pch);
1752 * Catch SIGUSR1, so that we exit cleanly if the parent process
1753 * kills us with it due to the user selecting "Capture->Stop".
1756 signal(SIGUSR1, stop_capture_signal_handler);
1758 /* initialize capture stop conditions */
1759 init_capture_stop_conditions();
1760 /* create stop conditions */
1761 if (capture_opts.has_autostop_filesize)
1762 cnd_stop_capturesize =
1763 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts.autostop_filesize * 1000);
1764 if (capture_opts.has_autostop_duration)
1766 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts.autostop_duration);
1768 if (capture_opts.ringbuffer_on && capture_opts.has_ring_duration)
1770 cnd_new(CND_CLASS_TIMEOUT, capture_opts.ringbuffer_duration);
1773 /* WOW, everything is prepared! */
1774 /* please fasten your seat belts, we will enter now the actual capture loop */
1776 main_window_update();
1779 if (ld.from_cap_pipe) {
1781 FD_SET(pipe_fd, &set1);
1783 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1784 sel_ret = select(pipe_fd+1, &set1, NULL, NULL, &timeout);
1787 if (sel_ret < 0 && errno != EINTR) {
1788 snprintf(errmsg, sizeof(errmsg),
1789 "Unexpected error from select: %s", strerror(errno));
1790 popup_errmsg(errmsg);
1795 * "select()" says we can read from the pipe without blocking
1797 inpkts = cap_pipe_dispatch(pipe_fd, &ld, &hdr, &rechdr, pcap_data,
1798 errmsg, sizeof errmsg);
1807 #ifdef MUST_DO_SELECT
1809 * Sigh. The semantics of the read timeout argument to
1810 * "pcap_open_live()" aren't particularly well specified by
1811 * the "pcap" man page - at least with the BSD BPF code, the
1812 * intent appears to be, at least in part, a way of cutting
1813 * down the number of reads done on a capture, by blocking
1814 * until the buffer fills or a timer expires - and the Linux
1815 * libpcap doesn't actually support it, so we can't use it
1816 * to break out of the "pcap_dispatch()" every 1/4 of a second
1817 * or so. Linux's libpcap is not the only libpcap that doesn't
1818 * support the read timeout.
1820 * Furthermore, at least on Solaris, the bufmod STREAMS module's
1821 * read timeout won't go off if no data has arrived, i.e. it cannot
1822 * be used to guarantee that a read from a DLPI stream will return
1823 * within a specified amount of time regardless of whether any
1824 * data arrives or not.
1826 * Thus, on all platforms other than BSD, we do a "select()" on the
1827 * file descriptor for the capture, with a timeout of CAP_READ_TIMEOUT
1828 * milliseconds, or CAP_READ_TIMEOUT*1000 microseconds.
1830 * "select()", on BPF devices, doesn't work as you might expect;
1831 * at least on some versions of some flavors of BSD, the timer
1832 * doesn't start until a read is done, so it won't expire if
1833 * only a "select()" or "poll()" is posted.
1836 FD_SET(pcap_fd, &set1);
1838 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1839 sel_ret = select(pcap_fd+1, &set1, NULL, NULL, &timeout);
1842 * "select()" says we can read from it without blocking; go for
1845 inpkts = pcap_dispatch(pch, 1, capture_pcap_cb, (guchar *) &ld);
1852 if (sel_ret < 0 && errno != EINTR) {
1853 snprintf(errmsg, sizeof(errmsg),
1854 "Unexpected error from select: %s", strerror(errno));
1855 popup_errmsg(errmsg);
1860 inpkts = pcap_dispatch(pch, 1, capture_pcap_cb, (guchar *) &ld);
1869 ld.sync_packets += inpkts;
1870 /* check capture stop conditons */
1871 if (cnd_stop_capturesize != NULL && cnd_eval(cnd_stop_capturesize,
1872 (guint32)wtap_get_bytes_dumped(ld.pdh))){
1873 /* Capture file reached its maximum size. */
1874 if (capture_opts.ringbuffer_on) {
1875 /* Switch to the next ringbuffer file */
1876 if (ringbuf_switch_file(&cfile, &ld.pdh, &ld.err)) {
1877 /* File switch succeeded: reset the condition */
1878 cnd_reset(cnd_stop_capturesize);
1879 if (cnd_ring_timeout) {
1880 cnd_reset(cnd_ring_timeout);
1883 /* File switch failed: stop here */
1888 /* no ringbuffer - just stop */
1894 /* Only update once a second so as not to overload slow displays */
1895 cur_time = time(NULL);
1896 if (cur_time > upd_time) {
1897 upd_time = cur_time;
1899 /*if (pcap_stats(pch, stats) >= 0) {
1900 *stats_known = TRUE;
1903 /* Let the parent process know. */
1904 /* calculate and display running time */
1905 cur_time -= start_time;
1906 capture_ui.running_time = cur_time;
1907 capture_ui.new_packets = ld.sync_packets;
1908 capture_info_update(&capture_ui);
1910 if (ld.sync_packets) {
1912 fflush(wtap_dump_file(ld.pdh));
1914 if (capture_child) {
1915 /* This is the child process for a sync mode capture, so send
1916 our parent a message saying we've written out "ld.sync_packets"
1917 packets to the capture file. */
1918 sync_pipe_packet_count_to_parent(ld.sync_packets);
1921 ld.sync_packets = 0;
1925 if (cnd_stop_timeout != NULL && cnd_eval(cnd_stop_timeout)) {
1926 /* The specified capture time has elapsed; stop the capture. */
1928 } else if (cnd_ring_timeout != NULL && cnd_eval(cnd_ring_timeout)) {
1929 /* time elasped for this ring file, swith to the next */
1930 if (ringbuf_switch_file(&cfile, &ld.pdh, &ld.err)) {
1931 /* File switch succeeded: reset the condition */
1932 cnd_reset(cnd_ring_timeout);
1934 /* File switch failed: stop here */
1940 } /* while (ld.go) */
1942 /* delete stop conditions */
1943 if (cnd_stop_capturesize != NULL)
1944 cnd_delete(cnd_stop_capturesize);
1945 if (cnd_stop_timeout != NULL)
1946 cnd_delete(cnd_stop_timeout);
1947 if (cnd_ring_timeout != NULL)
1948 cnd_delete(cnd_ring_timeout);
1951 snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
1953 popup_errmsg(errmsg);
1957 } else if (ld.from_cap_pipe && ld.cap_pipe_err == PIPERR)
1958 popup_errmsg(errmsg);
1964 get_capture_file_io_error(errmsg, sizeof(errmsg), cfile.save_file, ld.err,
1966 popup_errmsg(errmsg);
1970 if (capture_opts.ringbuffer_on) {
1971 close_ok = ringbuf_wtap_dump_close(&cfile, &err);
1973 close_ok = wtap_dump_close(ld.pdh, &err);
1975 /* If we've displayed a message about a write error, there's no point
1976 in displaying another message about an error on close. */
1977 if (!close_ok && write_ok) {
1978 get_capture_file_io_error(errmsg, sizeof(errmsg), cfile.save_file, err,
1980 popup_errmsg(errmsg);
1982 /* Set write_ok to mean the write and the close were successful. */
1983 write_ok = (write_ok && close_ok);
1987 * XXX We exhibit different behaviour between normal mode and sync mode
1988 * when the pipe is stdin and not already at EOF. If we're a child, the
1989 * parent's stdin isn't closed, so if the user starts another capture,
1990 * cap_pipe_open_live() will very likely not see the expected magic bytes and
1991 * will say "Unrecognized libpcap format". On the other hand, in normal
1992 * mode, cap_pipe_open_live() will say "End of file on pipe during open".
1994 if (ld.from_cap_pipe && pipe_fd >= 0)
1999 /* Get the capture statistics, so we know how many packets were
2001 if (pcap_stats(pch, stats) >= 0) {
2002 *stats_known = TRUE;
2003 if (capture_child) {
2004 /* Let the parent process know. */
2005 sync_pipe_drops_to_parent(stats->ps_drop);
2008 snprintf(errmsg, sizeof(errmsg),
2009 "Can't get packet-drop statistics: %s",
2011 popup_errmsg(errmsg);
2017 /* Shut down windows sockets */
2021 capture_info_destroy(&capture_ui);
2026 if (capture_opts.ringbuffer_on) {
2027 /* cleanup ringbuffer */
2028 ringbuf_error_cleanup();
2030 /* We can't use the save file, and we have no wtap_dump stream
2031 to close in order to close it, so close the FD directly. */
2032 close(cfile.save_file_fd);
2034 /* We couldn't even start the capture, so get rid of the capture
2036 unlink(cfile.save_file); /* silently ignore error */
2037 g_free(cfile.save_file);
2039 cfile.save_file = NULL;
2040 popup_errmsg(errmsg);
2043 if (ld.from_cap_pipe) {
2057 get_capture_file_io_error(char *errmsg, int errmsglen, const char *fname,
2058 int err, gboolean is_close)
2063 snprintf(errmsg, errmsglen,
2064 "Not all the packets could be written to the file"
2065 " to which the capture was being saved\n"
2066 "(\"%s\") because there is no space left on the file system\n"
2067 "on which that file resides.",
2073 snprintf(errmsg, errmsglen,
2074 "Not all the packets could be written to the file"
2075 " to which the capture was being saved\n"
2076 "(\"%s\") because you are too close to, or over,"
2077 " your disk quota\n"
2078 "on the file system on which that file resides.",
2083 case WTAP_ERR_CANT_CLOSE:
2084 snprintf(errmsg, errmsglen,
2085 "The file to which the capture was being saved"
2086 " couldn't be closed for some unknown reason.");
2089 case WTAP_ERR_SHORT_WRITE:
2090 snprintf(errmsg, errmsglen,
2091 "Not all the packets could be written to the file"
2092 " to which the capture was being saved\n"
2099 snprintf(errmsg, errmsglen,
2100 "The file to which the capture was being saved\n"
2101 "(\"%s\") could not be closed: %s.",
2102 fname, wtap_strerror(err));
2104 snprintf(errmsg, errmsglen,
2105 "An error occurred while writing to the file"
2106 " to which the capture was being saved\n"
2108 fname, wtap_strerror(err));
2115 popup_errmsg(const char *errmsg)
2117 if (capture_child) {
2118 /* This is the child process for a sync mode capture.
2119 Send the error message to our parent, so they can display a
2120 dialog box containing it. */
2121 sync_pipe_errmsg_to_parent(errmsg);
2123 /* Display the dialog box ourselves; there's no parent. */
2124 simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", errmsg);
2129 stop_capture_signal_handler(int signo _U_)
2138 if (fork_child != -1) {
2140 kill(fork_child, SIGUSR1);
2142 /* XXX: this is not the preferred method of closing a process!
2143 * the clean way would be getting the process id of the child process,
2144 * then getting window handle hWnd of that process (using EnumChildWindows),
2145 * and then do a SendMessage(hWnd, WM_CLOSE, 0, 0)
2147 * Unfortunately, I don't know how to get the process id from the handle */
2148 /* Hint: OpenProcess will get an handle from the id, not vice versa :-(
2150 * Hint: GenerateConsoleCtrlEvent() will only work, if both processes are
2151 * running in the same console, I don't know if that is true for our case.
2152 * And this also will require to have the process id
2154 TerminateProcess((HANDLE) fork_child, 0);
2162 kill_capture_child(void)
2164 if (fork_child != -1)
2166 kill(fork_child, SIGTERM); /* SIGTERM so it can clean up if necessary */
2168 /* XXX: this is not the preferred method of closing a process!
2169 * the clean way would be getting the process id of the child process,
2170 * then getting window handle hWnd of that process (using EnumChildWindows),
2171 * and then do a SendMessage(hWnd, WM_CLOSE, 0, 0)
2173 * Unfortunately, I don't know how to get the process id from the handle */
2174 /* Hint: OpenProcess will get an handle from the id, not vice versa :-(
2176 * Hint: GenerateConsoleCtrlEvent() will only work, if both processes are
2177 * running in the same console, I don't know if that is true for our case.
2178 * And this also will require to have the process id
2180 TerminateProcess((HANDLE) fork_child, 0);
2184 /* one packet was captured, process it */
2186 capture_pcap_cb(guchar *user, const struct pcap_pkthdr *phdr,
2189 struct wtap_pkthdr whdr;
2190 union wtap_pseudo_header pseudo_header;
2191 loop_data *ld = (loop_data *) user;
2194 /* user told us to stop after x packets, do we have enough? */
2195 if ((++ld->counts.total >= ld->max) && (ld->max > 0))
2200 /* Convert from libpcap to Wiretap format.
2201 If that fails, set "ld->go" to FALSE, to stop the capture, and set
2202 "ld->err" to the error. */
2203 pd = wtap_process_pcap_packet(ld->linktype, phdr, pd, &pseudo_header,
2212 /* We're supposed to write the packet to a file; do so.
2213 If this fails, set "ld->go" to FALSE, to stop the capture, and set
2214 "ld->err" to the error. */
2215 if (!wtap_dump(ld->pdh, &whdr, &pseudo_header, pd, &err)) {
2221 switch (ld->linktype) {
2222 case WTAP_ENCAP_ETHERNET:
2223 capture_eth(pd, 0, whdr.caplen, &ld->counts);
2225 case WTAP_ENCAP_FDDI:
2226 case WTAP_ENCAP_FDDI_BITSWAPPED:
2227 capture_fddi(pd, whdr.caplen, &ld->counts);
2229 case WTAP_ENCAP_PRISM_HEADER:
2230 capture_prism(pd, 0, whdr.caplen, &ld->counts);
2232 case WTAP_ENCAP_TOKEN_RING:
2233 capture_tr(pd, 0, whdr.caplen, &ld->counts);
2235 case WTAP_ENCAP_NULL:
2236 capture_null(pd, whdr.caplen, &ld->counts);
2238 case WTAP_ENCAP_PPP:
2239 capture_ppp_hdlc(pd, 0, whdr.caplen, &ld->counts);
2241 case WTAP_ENCAP_RAW_IP:
2242 capture_raw(pd, whdr.caplen, &ld->counts);
2244 case WTAP_ENCAP_SLL:
2245 capture_sll(pd, whdr.caplen, &ld->counts);
2247 case WTAP_ENCAP_LINUX_ATM_CLIP:
2248 capture_clip(pd, whdr.caplen, &ld->counts);
2250 case WTAP_ENCAP_IEEE_802_11:
2251 case WTAP_ENCAP_IEEE_802_11_WITH_RADIO:
2252 capture_ieee80211(pd, 0, whdr.caplen, &ld->counts);
2254 case WTAP_ENCAP_CHDLC:
2255 capture_chdlc(pd, 0, whdr.caplen, &ld->counts);
2257 case WTAP_ENCAP_LOCALTALK:
2258 capture_llap(&ld->counts);
2260 case WTAP_ENCAP_ATM_PDUS:
2261 capture_atm(&pseudo_header, pd, whdr.caplen, &ld->counts);
2263 case WTAP_ENCAP_IP_OVER_FC:
2264 capture_ipfc(pd, whdr.caplen, &ld->counts);
2266 case WTAP_ENCAP_ARCNET:
2267 capture_arcnet(pd, whdr.caplen, &ld->counts, FALSE, TRUE);
2269 case WTAP_ENCAP_ARCNET_LINUX:
2270 capture_arcnet(pd, whdr.caplen, &ld->counts, TRUE, FALSE);
2272 /* XXX - some ATM drivers on FreeBSD might prepend a 4-byte ATM
2273 pseudo-header to DLT_ATM_RFC1483, with LLC header following;
2274 we might have to implement that at some point. */
2278 #endif /* HAVE_LIBPCAP */