2 * Routines for packet capture windows
4 * $Id: capture.c,v 1.231 2004/01/31 02:29:19 guy 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>
133 #include <epan/filesystem.h>
137 #include "pcap-util.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;
175 static int sync_pipe[2]; /* used to sync father */
176 enum PIPES { READ, WRITE }; /* Constants 0 and 1 for READ and WRITE */
177 int quit_after_cap; /* Makes a "capture only mode". Implies -k */
178 gboolean capture_child; /* if this is the child for "-S" */
179 static int fork_child = -1; /* If not -1, in parent, process ID of child */
182 * Indications sent out on the sync pipe.
184 #define SP_CAPSTART ';' /* capture start message */
185 #define SP_PACKET_COUNT '*' /* followed by count of packets captured since last message */
186 #define SP_ERROR_MSG '!' /* followed by length of error message that follows */
187 #define SP_DROPS '#' /* followed by count of packets dropped in capture */
190 static gboolean cap_pipe_input_cb(gint source, gpointer user_data);
191 static void wait_for_child(gboolean);
193 static char *signame(int);
195 static void capture_pcap_cb(guchar *, const struct pcap_pkthdr *,
197 static void get_capture_file_io_error(char *, int, const char *, int, gboolean);
198 static void popup_errmsg(const char *);
199 static void send_errmsg_to_parent(const char *);
200 static void stop_capture(int signo);
202 typedef struct _loop_data {
203 gboolean go; /* TRUE as long as we're supposed to keep capturing */
204 gint max; /* Number of packets we're supposed to capture - 0 means infinite */
205 int err; /* if non-zero, error seen while capturing */
208 gboolean pcap_err; /* TRUE if error from pcap */
209 gboolean from_pipe; /* TRUE if we are capturing data from a pipe */
210 packet_counts counts;
213 gboolean modified; /* TRUE if data in the pipe uses modified pcap headers */
214 gboolean byte_swapped; /* TRUE if data in the pipe is byte swapped */
215 unsigned int bytes_to_read, bytes_read; /* Used by pipe_dispatch */
217 STATE_EXPECT_REC_HDR, STATE_READ_REC_HDR,
218 STATE_EXPECT_DATA, STATE_READ_DATA
221 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } pipe_err;
226 static void adjust_header(loop_data *, struct pcap_hdr *, struct pcaprec_hdr *);
227 static int pipe_open_live(char *, struct pcap_hdr *, loop_data *, char *, int);
228 static int pipe_dispatch(int, loop_data *, struct pcap_hdr *, \
229 struct pcaprec_modified_hdr *, guchar *, char *, int);
232 /* Win32 needs the O_BINARY flag for open() */
237 /* Add a string pointer to a NULL-terminated array of string pointers. */
239 add_arg(char **args, int *argc, char *arg)
241 /* Grow the array; "*argc" currently contains the number of string
242 pointers, *not* counting the NULL pointer at the end, so we have
243 to add 2 in order to get the new size of the array, including the
244 new pointer and the terminating NULL pointer. */
245 args = g_realloc(args, (*argc + 2) * sizeof (char *));
247 /* Stuff the pointer into the penultimate element of the array, which
248 is the one at the index specified by "*argc". */
251 /* Now bump the count. */
254 /* We overwrite the NULL pointer; put it back right after the
262 /* Given a string, return a pointer to a quote-encapsulated version of
263 the string, so we can pass it as an argument with "spawnvp" even
264 if it contains blanks. */
266 quote_encapsulate(const char *string)
268 char *encapsulated_string;
270 encapsulated_string = g_new(char, strlen(string) + 3);
271 sprintf(encapsulated_string, "\"%s\"", string);
272 return encapsulated_string;
276 /* Open a specified file, or create a temporary file, and start a capture
277 to the file in question. Returns TRUE if the capture starts
278 successfully, FALSE otherwise. */
280 do_capture(const char *save_file)
283 gboolean is_tempfile;
289 int capture_succeeded;
290 gboolean stats_known;
291 struct pcap_stat stats;
294 if (save_file != NULL) {
295 /* If the Sync option is set, we return to the caller while the capture
296 * is in progress. Therefore we need to take a copy of save_file in
297 * case the caller destroys it after we return.
299 capfile_name = g_strdup(save_file);
300 if (capture_opts.ringbuffer_on) {
301 /* ringbuffer is enabled */
302 cfile.save_file_fd = ringbuf_init(capfile_name,
303 capture_opts.ringbuffer_num_files);
305 /* Try to open/create the specified file for use as a capture buffer. */
306 cfile.save_file_fd = open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
311 /* Choose a random name for the capture buffer */
312 cfile.save_file_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
313 capfile_name = g_strdup(tmpname);
316 if (cfile.save_file_fd == -1) {
318 simple_dialog(ESD_TYPE_ERROR, NULL,
319 "The temporary file to which the capture would be saved (\"%s\")"
320 "could not be opened: %s.", capfile_name, strerror(errno));
322 if (capture_opts.ringbuffer_on) {
323 ringbuf_error_cleanup();
325 simple_dialog(ESD_TYPE_ERROR, NULL,
326 file_open_error_message(errno, TRUE), capfile_name);
328 g_free(capfile_name);
332 g_assert(cfile.save_file == NULL);
333 cfile.save_file = capfile_name;
334 /* cfile.save_file is "g_free"ed below, which is equivalent to
335 "g_free(capfile_name)". */
337 if (capture_opts.sync_mode) { /* do the capture in a child process */
339 char scount[24]; /* need a constant for len of numbers */
340 char sautostop_filesize[24]; /* need a constant for len of numbers */
341 char sautostop_duration[24]; /* need a constant for len of numbers */
342 char save_file_fd[24];
350 char sync_pipe_fd[24];
355 /* Allocate the string pointer array with enough space for the
356 terminating NULL pointer. */
358 argv = g_malloc(sizeof (char *));
361 /* Now add those arguments used on all platforms. */
362 argv = add_arg(argv, &argc, CHILD_NAME);
364 argv = add_arg(argv, &argc, "-i");
365 argv = add_arg(argv, &argc, cfile.iface);
367 argv = add_arg(argv, &argc, "-w");
368 argv = add_arg(argv, &argc, cfile.save_file);
370 argv = add_arg(argv, &argc, "-W");
371 sprintf(save_file_fd,"%d",cfile.save_file_fd); /* in lieu of itoa */
372 argv = add_arg(argv, &argc, save_file_fd);
374 if (capture_opts.has_autostop_count) {
375 argv = add_arg(argv, &argc, "-c");
376 sprintf(scount,"%d",capture_opts.autostop_count);
377 argv = add_arg(argv, &argc, scount);
380 if (capture_opts.has_snaplen) {
381 argv = add_arg(argv, &argc, "-s");
382 sprintf(ssnap,"%d",capture_opts.snaplen);
383 argv = add_arg(argv, &argc, ssnap);
386 if (capture_opts.linktype != -1) {
387 argv = add_arg(argv, &argc, "-y");
388 sprintf(ssnap,"%d",capture_opts.linktype);
389 argv = add_arg(argv, &argc, ssnap);
392 if (capture_opts.has_autostop_filesize) {
393 argv = add_arg(argv, &argc, "-a");
394 sprintf(sautostop_filesize,"filesize:%d",capture_opts.autostop_filesize);
395 argv = add_arg(argv, &argc, sautostop_filesize);
398 if (capture_opts.has_autostop_duration) {
399 argv = add_arg(argv, &argc, "-a");
400 sprintf(sautostop_duration,"duration:%d",capture_opts.autostop_duration);
401 argv = add_arg(argv, &argc, sautostop_duration);
404 if (!capture_opts.promisc_mode)
405 argv = add_arg(argv, &argc, "-p");
408 /* Create a pipe for the child process */
410 if(_pipe(sync_pipe, 512, O_BINARY) < 0) {
411 /* Couldn't create the pipe between parent and child. */
413 unlink(cfile.save_file);
414 g_free(cfile.save_file);
415 cfile.save_file = NULL;
416 simple_dialog(ESD_TYPE_ERROR, NULL, "Couldn't create sync pipe: %s",
421 /* Convert font name to a quote-encapsulated string and pass to child */
422 argv = add_arg(argv, &argc, "-m");
423 fontstring = quote_encapsulate(prefs.PREFS_GUI_FONT_NAME);
424 argv = add_arg(argv, &argc, fontstring);
426 /* Convert pipe write handle to a string and pass to child */
427 argv = add_arg(argv, &argc, "-Z");
428 itoa(sync_pipe[WRITE], sync_pipe_fd, 10);
429 argv = add_arg(argv, &argc, sync_pipe_fd);
431 /* Convert filter string to a quote delimited string and pass to child */
433 if (cfile.cfilter != NULL && strlen(cfile.cfilter) != 0) {
434 argv = add_arg(argv, &argc, "-f");
435 filterstring = quote_encapsulate(cfile.cfilter);
436 argv = add_arg(argv, &argc, filterstring);
440 fork_child = spawnvp(_P_NOWAIT, ethereal_path, argv);
443 g_free(filterstring);
446 if (pipe(sync_pipe) < 0) {
447 /* Couldn't create the pipe between parent and child. */
449 unlink(cfile.save_file);
450 g_free(cfile.save_file);
451 cfile.save_file = NULL;
452 simple_dialog(ESD_TYPE_ERROR, NULL, "Couldn't create sync pipe: %s",
457 argv = add_arg(argv, &argc, "-m");
458 argv = add_arg(argv, &argc, prefs.PREFS_GUI_FONT_NAME);
460 if (cfile.cfilter != NULL && strlen(cfile.cfilter) != 0) {
461 argv = add_arg(argv, &argc, "-f");
462 argv = add_arg(argv, &argc, cfile.cfilter);
465 if ((fork_child = fork()) == 0) {
467 * Child process - run Ethereal with the right arguments to make
468 * it just pop up the live capture dialog box and capture with
469 * the specified capture parameters, writing to the specified file.
471 * args: -i interface specification
473 * -W file descriptor to write
474 * -c count to capture
477 * -f "filter expression"
480 dup(sync_pipe[WRITE]);
481 close(sync_pipe[READ]);
482 execvp(ethereal_path, argv);
483 snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
484 ethereal_path, strerror(errno));
485 send_errmsg_to_parent(errmsg);
487 /* Exit with "_exit()", so that we don't close the connection
488 to the X server (and cause stuff buffered up by our parent but
489 not yet sent to be sent, as that stuff should only be sent by
495 /* Parent process - read messages from the child process over the
497 g_free(argv); /* free up arg array */
499 /* Close the write side of the pipe, so that only the child has it
500 open, and thus it completely closes, and thus returns to us
501 an EOF indication, if the child closes it (either deliberately
502 or by exiting abnormally). */
503 close(sync_pipe[WRITE]);
505 /* Close the save file FD, as we won't be using it - we'll be opening
506 it and reading the save file through Wiretap. */
507 close(cfile.save_file_fd);
509 if (fork_child == -1) {
510 /* We couldn't even create the child process. */
512 close(sync_pipe[READ]);
513 unlink(cfile.save_file);
514 g_free(cfile.save_file);
515 cfile.save_file = NULL;
516 simple_dialog(ESD_TYPE_ERROR, NULL, "Couldn't create child process: %s",
521 /* Read a byte count from "sync_pipe[READ]", terminated with a
522 colon; if the count is 0, the child process created the
523 capture file and we should start reading from it, otherwise
524 the capture couldn't start and the count is a count of bytes
525 of error message, and we should display the message. */
528 i = read(sync_pipe[READ], &c, 1);
530 /* EOF - the child process died.
531 Close the read side of the sync pipe, remove the capture file,
532 and report the failure. */
533 close(sync_pipe[READ]);
534 unlink(cfile.save_file);
535 g_free(cfile.save_file);
536 cfile.save_file = NULL;
537 wait_for_child(TRUE);
540 if (c == SP_CAPSTART || c == SP_ERROR_MSG)
543 /* Child process handed us crap.
544 Close the read side of the sync pipe, remove the capture file,
545 and report the failure. */
546 close(sync_pipe[READ]);
547 unlink(cfile.save_file);
548 g_free(cfile.save_file);
549 cfile.save_file = NULL;
550 simple_dialog(ESD_TYPE_WARN, NULL,
551 "Capture child process sent us a bad message");
554 byte_count = byte_count*10 + c - '0';
556 if (c != SP_CAPSTART) {
557 /* Failure - the child process sent us a message indicating
558 what the problem was. */
559 if (byte_count == 0) {
560 /* Zero-length message? */
561 simple_dialog(ESD_TYPE_WARN, NULL,
562 "Capture child process failed, but its error message was empty.");
564 msg = g_malloc(byte_count + 1);
566 simple_dialog(ESD_TYPE_WARN, NULL,
567 "Capture child process failed, but its error message was too big.");
569 i = read(sync_pipe[READ], msg, byte_count);
570 msg[byte_count] = '\0';
572 simple_dialog(ESD_TYPE_WARN, NULL,
573 "Capture child process failed: Error %s reading its error message.",
576 simple_dialog(ESD_TYPE_WARN, NULL,
577 "Capture child process failed: EOF reading its error message.");
578 wait_for_child(FALSE);
580 simple_dialog(ESD_TYPE_ERROR, NULL, msg);
584 /* Close the sync pipe. */
585 close(sync_pipe[READ]);
587 /* Get rid of the save file - the capture never started. */
588 unlink(cfile.save_file);
589 g_free(cfile.save_file);
590 cfile.save_file = NULL;
595 /* The child process started a capture.
596 Attempt to open the capture file and set up to read it. */
597 err = cf_start_tail(cfile.save_file, is_tempfile, &cfile);
599 /* We weren't able to open the capture file; user has been
600 alerted. Close the sync pipe. */
602 close(sync_pipe[READ]);
604 /* Don't unlink the save file - leave it around, for debugging
606 g_free(cfile.save_file);
607 cfile.save_file = NULL;
610 /* We were able to open and set up to read the capture file;
611 arrange that our callback be called whenever it's possible
612 to read from the sync pipe, so that it's called when
613 the child process wants to tell us something. */
614 pipe_input_set_handler(sync_pipe[READ], (gpointer) &cfile, &fork_child, cap_pipe_input_cb);
617 capture_succeeded = capture(&stats_known, &stats);
618 if (quit_after_cap) {
619 /* DON'T unlink the save file. Presumably someone wants it. */
622 if (!capture_succeeded) {
623 /* We didn't succeed in doing the capture, so we don't have a save
625 if (capture_opts.ringbuffer_on) {
628 g_free(cfile.save_file);
630 cfile.save_file = NULL;
633 /* Capture succeeded; attempt to read in the capture file. */
634 if ((err = cf_open(cfile.save_file, is_tempfile, &cfile)) != 0) {
635 /* We're not doing a capture any more, so we don't have a save
637 if (capture_opts.ringbuffer_on) {
640 g_free(cfile.save_file);
642 cfile.save_file = NULL;
646 /* Set the read filter to NULL. */
649 /* Get the packet-drop statistics.
651 XXX - there are currently no packet-drop statistics stored
652 in libpcap captures, and that's what we're reading.
654 At some point, we will add support in Wiretap to return
655 packet-drop statistics for capture file formats that store it,
656 and will make "cf_read()" get those statistics from Wiretap.
657 We clear the statistics (marking them as "not known") in
658 "cf_open()", and "cf_read()" will only fetch them and mark
659 them as known if Wiretap supplies them, so if we get the
660 statistics now, after calling "cf_open()" but before calling
661 "cf_read()", the values we store will be used by "cf_read()".
663 If a future libpcap capture file format stores the statistics,
664 we'll put them into the capture file that we write, and will
665 thus not have to set them here - "cf_read()" will get them from
666 the file and use them. */
668 cfile.drops_known = TRUE;
670 /* XXX - on some systems, libpcap doesn't bother filling in
671 "ps_ifdrop" - it doesn't even set it to zero - so we don't
672 bother looking at it.
674 Ideally, libpcap would have an interface that gave us
675 several statistics - perhaps including various interface
676 error statistics - and would tell us which of them it
677 supplies, allowing us to display only the ones it does. */
678 cfile.drops = stats.ps_drop;
680 switch (cf_read(&cfile)) {
684 /* Just because we got an error, that doesn't mean we were unable
685 to read any of the file; we handle what we could get from the
690 /* Exit by leaving the main loop, so that any quit functions
691 we registered get called. */
692 main_window_nested_quit();
696 /* We're not doing a capture any more, so we don't have a save
698 if (capture_opts.ringbuffer_on) {
701 g_free(cfile.save_file);
703 cfile.save_file = NULL;
709 /* There's stuff to read from the sync pipe, meaning the child has sent
710 us a message, or the sync pipe has closed, meaning the child has
711 closed it (perhaps because it exited). */
713 cap_pipe_input_cb(gint source, gpointer user_data)
715 capture_file *cf = (capture_file *)user_data;
717 char buffer[BUFSIZE+1], *p = buffer, *q = buffer, *msg, *r;
718 int nread, msglen, chars_to_copy;
723 if ((nread = read(source, buffer, BUFSIZE)) <= 0) {
724 /* The child has closed the sync pipe, meaning it's not going to be
725 capturing any more packets. Pick up its exit status, and
726 complain if it did anything other than exit with status 0. */
727 wait_for_child(FALSE);
729 /* Read what remains of the capture file, and finish the capture.
730 XXX - do something if this fails? */
731 switch (cf_finish_tail(cf, &err)) {
735 /* Just because we got an error, that doesn't mean we were unable
736 to read any of the file; we handle what we could get from the
741 /* Exit by leaving the main loop, so that any quit functions
742 we registered get called. */
747 /* We're not doing a capture any more, so we don't have a save
749 g_free(cf->save_file);
750 cf->save_file = NULL;
755 buffer[nread] = '\0';
758 /* look for (possibly multiple) indications */
760 case SP_PACKET_COUNT :
767 cf->drops_known = TRUE;
779 /* Read the entire message.
780 XXX - if the child hasn't sent it all yet, this could cause us
781 to hang until they do. */
782 msg = g_malloc(msglen + 1);
784 while (msglen != 0) {
787 if ((nread = read(source, buffer, BUFSIZE)) <= 0)
792 chars_to_copy = MIN(msglen, nread);
793 memcpy(r, q, chars_to_copy);
796 nread -= chars_to_copy;
797 msglen -= chars_to_copy;
800 simple_dialog(ESD_TYPE_ERROR, NULL, msg);
810 /* Read from the capture file the number of records the child told us
812 XXX - do something if this fails? */
813 switch (cf_continue_tail(cf, to_read, &err)) {
817 /* Just because we got an error, that doesn't mean we were unable
818 to read any of the file; we handle what we could get from the
821 XXX - abort on a read error? */
825 /* Kill the child capture process; the user wants to exit, and we
826 shouldn't just leave it running. */
827 kill_capture_child();
835 wait_for_child(gboolean always_report)
840 /* XXX - analyze the wait status and display more information
842 XXX - set "fork_child" to -1 if we find it exited? */
843 if (_cwait(&wstatus, fork_child, _WAIT_CHILD) == -1) {
844 simple_dialog(ESD_TYPE_WARN, NULL, "Child capture process stopped unexpectedly");
847 if (wait(&wstatus) != -1) {
848 if (WIFEXITED(wstatus)) {
849 /* The child exited; display its exit status, if it's not zero,
850 and even if it's zero if "always_report" is true. */
851 if (always_report || WEXITSTATUS(wstatus) != 0) {
852 simple_dialog(ESD_TYPE_WARN, NULL,
853 "Child capture process exited: exit status %d",
854 WEXITSTATUS(wstatus));
856 } else if (WIFSTOPPED(wstatus)) {
857 /* It stopped, rather than exiting. "Should not happen." */
858 simple_dialog(ESD_TYPE_WARN, NULL,
859 "Child capture process stopped: %s",
860 signame(WSTOPSIG(wstatus)));
861 } else if (WIFSIGNALED(wstatus)) {
862 /* It died with a signal. */
863 simple_dialog(ESD_TYPE_WARN, NULL,
864 "Child capture process died: %s%s",
865 signame(WTERMSIG(wstatus)),
866 WCOREDUMP(wstatus) ? " - core dumped" : "");
868 /* What? It had to either have exited, or stopped, or died with
869 a signal; what happened here? */
870 simple_dialog(ESD_TYPE_WARN, NULL,
871 "Child capture process died: wait status %#o", wstatus);
875 /* No more child process. */
885 static char sigmsg_buf[6+1+3+1];
894 sigmsg = "Interrupted";
902 sigmsg = "Illegal instruction";
906 sigmsg = "Trace trap";
914 sigmsg = "Arithmetic exception";
922 sigmsg = "Bus error";
926 sigmsg = "Segmentation violation";
929 /* http://metalab.unc.edu/pub/Linux/docs/HOWTO/GCC-HOWTO
930 Linux is POSIX compliant. These are not POSIX-defined signals ---
931 ISO/IEC 9945-1:1990 (IEEE Std 1003.1-1990), paragraph B.3.3.1.1 sez:
933 ``The signals SIGBUS, SIGEMT, SIGIOT, SIGTRAP, and SIGSYS
934 were omitted from POSIX.1 because their behavior is
935 implementation dependent and could not be adequately catego-
936 rized. Conforming implementations may deliver these sig-
937 nals, but must document the circumstances under which they
938 are delivered and note any restrictions concerning their
941 So we only check for SIGSYS on those systems that happen to
942 implement them (a system can be POSIX-compliant and implement
943 them, it's just that POSIX doesn't *require* a POSIX-compliant
944 system to implement them).
949 sigmsg = "Bad system call";
954 sigmsg = "Broken pipe";
958 sigmsg = "Alarm clock";
962 sigmsg = "Terminated";
966 sprintf(sigmsg_buf, "Signal %d", sig);
975 * Timeout, in milliseconds, for reads from the stream of captured packets.
977 #define CAP_READ_TIMEOUT 250
980 /* Take care of byte order in the libpcap headers read from pipes.
981 * (function taken from wiretap/libpcap.c) */
983 adjust_header(loop_data *ld, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
985 if (ld->byte_swapped) {
986 /* Byte-swap the record header fields. */
987 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
988 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
989 rechdr->incl_len = BSWAP32(rechdr->incl_len);
990 rechdr->orig_len = BSWAP32(rechdr->orig_len);
993 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
994 swapped, in order to match the BPF header layout.
996 Unfortunately, some files were, according to a comment in the "libpcap"
997 source, written with version 2.3 in their headers but without the
998 interchanged fields, so if "incl_len" is greater than "orig_len" - which
999 would make no sense - we assume that we need to swap them. */
1000 if (hdr->version_major == 2 &&
1001 (hdr->version_minor < 3 ||
1002 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1005 temp = rechdr->orig_len;
1006 rechdr->orig_len = rechdr->incl_len;
1007 rechdr->incl_len = temp;
1011 /* Mimic pcap_open_live() for pipe captures
1012 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
1014 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1015 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1017 pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
1018 char *errmsg, int errmsgl)
1020 struct stat pipe_stat;
1024 unsigned int bytes_read;
1026 struct timeval timeout;
1029 * XXX Ethereal blocks until we return
1031 if (strcmp(pipename, "-") == 0)
1032 fd = 0; /* read from stdin */
1034 if (stat(pipename, &pipe_stat) < 0) {
1035 if (errno == ENOENT || errno == ENOTDIR)
1036 ld->pipe_err = PIPNEXIST;
1038 snprintf(errmsg, errmsgl,
1039 "The capture session could not be initiated "
1040 "due to error on pipe: %s", strerror(errno));
1041 ld->pipe_err = PIPERR;
1045 if (! S_ISFIFO(pipe_stat.st_mode)) {
1046 if (S_ISCHR(pipe_stat.st_mode)) {
1048 * Assume the user specified an interface on a system where
1049 * interfaces are in /dev. Pretend we haven't seen it.
1051 ld->pipe_err = PIPNEXIST;
1053 snprintf(errmsg, errmsgl,
1054 "The capture session could not be initiated because\n"
1055 "\"%s\" is neither an interface nor a pipe", pipename);
1056 ld->pipe_err = PIPERR;
1060 fd = open(pipename, O_RDONLY | O_NONBLOCK);
1062 snprintf(errmsg, errmsgl,
1063 "The capture session could not be initiated "
1064 "due to error on pipe open: %s", strerror(errno));
1065 ld->pipe_err = PIPERR;
1070 ld->from_pipe = TRUE;
1072 /* read the pcap header */
1075 while (bytes_read < sizeof magic) {
1078 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1079 sel_ret = select(fd+1, &rfds, NULL, NULL, &timeout);
1081 snprintf(errmsg, errmsgl,
1082 "Unexpected error from select: %s", strerror(errno));
1084 } else if (sel_ret > 0) {
1085 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
1088 snprintf(errmsg, errmsgl, "End of file on pipe during open");
1090 snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
1100 /* Host that wrote it has our byte order, and was running
1101 a program using either standard or ss990417 libpcap. */
1102 ld->byte_swapped = FALSE;
1103 ld->modified = FALSE;
1105 case PCAP_MODIFIED_MAGIC:
1106 /* Host that wrote it has our byte order, but was running
1107 a program using either ss990915 or ss991029 libpcap. */
1108 ld->byte_swapped = FALSE;
1109 ld->modified = TRUE;
1111 case PCAP_SWAPPED_MAGIC:
1112 /* Host that wrote it has a byte order opposite to ours,
1113 and was running a program using either standard or
1114 ss990417 libpcap. */
1115 ld->byte_swapped = TRUE;
1116 ld->modified = FALSE;
1118 case PCAP_SWAPPED_MODIFIED_MAGIC:
1119 /* Host that wrote it out has a byte order opposite to
1120 ours, and was running a program using either ss990915
1121 or ss991029 libpcap. */
1122 ld->byte_swapped = TRUE;
1123 ld->modified = TRUE;
1126 /* Not a "libpcap" type we know about. */
1127 snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
1131 /* Read the rest of the header */
1133 while (bytes_read < sizeof(struct pcap_hdr)) {
1136 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1137 sel_ret = select(fd+1, &rfds, NULL, NULL, &timeout);
1139 snprintf(errmsg, errmsgl,
1140 "Unexpected error from select: %s", strerror(errno));
1142 } else if (sel_ret > 0) {
1143 b = read(fd, ((char *)hdr)+bytes_read,
1144 sizeof(struct pcap_hdr) - bytes_read);
1147 snprintf(errmsg, errmsgl, "End of file on pipe during open");
1149 snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
1157 if (ld->byte_swapped) {
1158 /* Byte-swap the header fields about which we care. */
1159 hdr->version_major = BSWAP16(hdr->version_major);
1160 hdr->version_minor = BSWAP16(hdr->version_minor);
1161 hdr->snaplen = BSWAP32(hdr->snaplen);
1162 hdr->network = BSWAP32(hdr->network);
1165 if (hdr->version_major < 2) {
1166 snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1170 ld->pipe_state = STATE_EXPECT_REC_HDR;
1171 ld->pipe_err = PIPOK;
1175 ld->pipe_err = PIPERR;
1181 /* We read one record from the pipe, take care of byte order in the record
1182 * header, write the record in the capture file, and update capture statistics. */
1185 pipe_dispatch(int fd, loop_data *ld, struct pcap_hdr *hdr,
1186 struct pcaprec_modified_hdr *rechdr, guchar *data,
1187 char *errmsg, int errmsgl)
1189 struct pcap_pkthdr phdr;
1191 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1194 switch (ld->pipe_state) {
1196 case STATE_EXPECT_REC_HDR:
1197 ld->bytes_to_read = ld->modified ?
1198 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1200 ld->pipe_state = STATE_READ_REC_HDR;
1203 case STATE_READ_REC_HDR:
1204 b = read(fd, ((char *)rechdr)+ld->bytes_read,
1205 ld->bytes_to_read - ld->bytes_read);
1208 result = PD_PIPE_EOF;
1210 result = PD_PIPE_ERR;
1213 if ((ld->bytes_read += b) < ld->bytes_to_read)
1215 result = PD_REC_HDR_READ;
1218 case STATE_EXPECT_DATA:
1220 ld->pipe_state = STATE_READ_DATA;
1223 case STATE_READ_DATA:
1224 b = read(fd, data+ld->bytes_read, rechdr->hdr.incl_len - ld->bytes_read);
1227 result = PD_PIPE_EOF;
1229 result = PD_PIPE_ERR;
1232 if ((ld->bytes_read += b) < rechdr->hdr.incl_len)
1234 result = PD_DATA_READ;
1238 snprintf(errmsg, errmsgl, "pipe_dispatch: invalid state");
1241 } /* switch (ld->pipe_state) */
1244 * We've now read as much data as we were expecting, so process it.
1248 case PD_REC_HDR_READ:
1249 /* We've read the header. Take care of byte order. */
1250 adjust_header(ld, hdr, &rechdr->hdr);
1251 if (rechdr->hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1252 snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
1253 ld->counts.total+1, rechdr->hdr.incl_len);
1256 ld->pipe_state = STATE_EXPECT_DATA;
1260 /* Fill in a "struct pcap_pkthdr", and process the packet. */
1261 phdr.ts.tv_sec = rechdr->hdr.ts_sec;
1262 phdr.ts.tv_usec = rechdr->hdr.ts_usec;
1263 phdr.caplen = rechdr->hdr.incl_len;
1264 phdr.len = rechdr->hdr.orig_len;
1266 capture_pcap_cb((guchar *)ld, &phdr, data);
1268 ld->pipe_state = STATE_EXPECT_REC_HDR;
1272 ld->pipe_err = PIPEOF;
1276 snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
1283 ld->pipe_err = PIPERR;
1284 /* Return here rather than inside the switch to prevent GCC warning */
1290 * This needs to be static, so that the SIGUSR1 handler can clear the "go"
1293 static loop_data ld;
1295 /* Do the low-level work of a capture.
1296 Returns TRUE if it succeeds, FALSE otherwise. */
1298 capture(gboolean *stats_known, struct pcap_stat *stats)
1303 gchar open_err_str[PCAP_ERRBUF_SIZE];
1304 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
1305 bpf_u_int32 netnum, netmask;
1306 struct bpf_program fcode;
1307 const char *set_linktype_err_str;
1308 time_t upd_time, cur_time;
1311 condition *cnd_stop_capturesize = NULL;
1312 condition *cnd_stop_timeout = NULL;
1313 condition *cnd_ring_timeout = NULL;
1314 static const char capstart_msg = SP_CAPSTART;
1315 char errmsg[4096+1];
1318 capture_info capture_ui;
1321 WORD wVersionRequested;
1325 struct timeval timeout;
1326 static const char ppamsg[] = "can't find PPA for ";
1330 struct pcap_hdr hdr;
1331 struct pcaprec_modified_hdr rechdr;
1332 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1334 #ifdef MUST_DO_SELECT
1338 /* Size of buffer to hold decimal representation of
1339 signed/unsigned 64-bit int */
1342 /* Initialize Windows Socket if we are in a WIN32 OS
1343 This needs to be done before querying the interface for network/netmask */
1345 /* XXX - do we really require 1.1 or earlier?
1346 Are there any versions that support only 2.0 or higher? */
1347 wVersionRequested = MAKEWORD(1, 1);
1348 err = WSAStartup(wVersionRequested, &wsaData);
1352 case WSASYSNOTREADY:
1353 snprintf(errmsg, sizeof errmsg,
1354 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
1357 case WSAVERNOTSUPPORTED:
1358 snprintf(errmsg, sizeof errmsg,
1359 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
1360 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
1363 case WSAEINPROGRESS:
1364 snprintf(errmsg, sizeof errmsg,
1365 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
1369 snprintf(errmsg, sizeof errmsg,
1370 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
1374 snprintf(errmsg, sizeof errmsg,
1375 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
1379 snprintf(errmsg, sizeof errmsg,
1380 "Couldn't initialize Windows Sockets: error %d", err);
1389 ld.counts.total = 0;
1390 if (capture_opts.has_autostop_count)
1391 ld.max = capture_opts.autostop_count;
1393 ld.max = 0; /* no limit */
1394 ld.err = 0; /* no error seen yet */
1395 ld.linktype = WTAP_ENCAP_UNKNOWN;
1396 ld.pcap_err = FALSE;
1397 ld.from_pipe = FALSE;
1398 ld.sync_packets = 0;
1406 ld.counts.netbios = 0;
1407 ld.counts.vines = 0;
1408 ld.counts.other = 0;
1412 /* We haven't yet gotten the capture statistics. */
1413 *stats_known = FALSE;
1415 /* Open the network interface to capture from it.
1416 Some versions of libpcap may put warnings into the error buffer
1417 if they succeed; to tell if that's happened, we have to clear
1418 the error buffer, and check if it's still a null string. */
1419 open_err_str[0] = '\0';
1420 pch = pcap_open_live(cfile.iface,
1421 capture_opts.has_snaplen ? capture_opts.snaplen :
1422 WTAP_MAX_PACKET_SIZE,
1423 capture_opts.promisc_mode, CAP_READ_TIMEOUT,
1427 /* setting the data link type only works on real interfaces */
1428 if (capture_opts.linktype != -1) {
1429 set_linktype_err_str = set_pcap_linktype(pch, cfile.iface,
1430 capture_opts.linktype);
1431 if (set_linktype_err_str != NULL) {
1432 snprintf(errmsg, sizeof errmsg, "Unable to set data link type (%s).",
1433 set_linktype_err_str);
1438 /* We couldn't open "cfile.iface" as a network device. */
1440 /* On Windows, we don't support capturing on pipes, so we give up.
1441 If this is a child process that does the capturing in sync
1442 mode or fork mode, it shouldn't do any UI stuff until we pop up the
1443 capture-progress window, and, since we couldn't start the
1444 capture, we haven't popped it up. */
1445 if (!capture_child) {
1446 main_window_update();
1449 /* On Win32 OSes, the capture devices are probably available to all
1450 users; don't warn about permissions problems.
1452 Do, however, warn that WAN devices aren't supported. */
1453 snprintf(errmsg, sizeof errmsg,
1454 "The capture session could not be initiated (%s).\n"
1455 "Please check that you have the proper interface specified.\n"
1457 "Note that the WinPcap 2.x version of the driver Ethereal uses for packet\n"
1458 "capture on Windows doesn't support capturing on PPP/WAN interfaces in\n"
1459 "Windows NT/2000/XP/2003 Server, and that the WinPcap 3.0 and later versions\n"
1460 "don't support capturing on PPP/WAN interfaces at all.",
1464 /* try to open cfile.iface as a pipe */
1465 pipe_fd = pipe_open_live(cfile.iface, &hdr, &ld, errmsg, sizeof errmsg);
1467 if (pipe_fd == -1) {
1469 /* If this is a child process that does the capturing in sync
1470 * mode or fork mode, it shouldn't do any UI stuff until we pop up the
1471 * capture-progress window, and, since we couldn't start the
1472 * capture, we haven't popped it up.
1474 if (!capture_child) {
1475 main_window_update();
1478 if (ld.pipe_err == PIPNEXIST) {
1479 /* Pipe doesn't exist, so output message for interface */
1481 /* If we got a "can't find PPA for XXX" message, warn the user (who
1482 is running Ethereal on HP-UX) that they don't have a version
1483 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1484 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1485 PPA for XXX" rather than "can't find PPA for XXX"). */
1486 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1489 "You are running Ethereal with a version of the libpcap library\n"
1490 "that doesn't handle HP-UX network devices well; this means that\n"
1491 "Ethereal may not be able to capture packets.\n"
1493 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1494 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1495 "packaged binary form from the Software Porting And Archive Centre\n"
1496 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1497 "at the URL lists a number of mirror sites.";
1500 snprintf(errmsg, sizeof errmsg,
1501 "The capture session could not be initiated (%s).\n"
1502 "Please check to make sure you have sufficient permissions, and that\n"
1503 "you have the proper interface or pipe specified.%s", open_err_str,
1507 * Else pipe (or file) does exist and pipe_open_live() has
1512 /* pipe_open_live() succeeded; don't want
1513 error message from pcap_open_live() */
1514 open_err_str[0] = '\0';
1518 /* capture filters only work on real interfaces */
1519 if (cfile.cfilter && !ld.from_pipe) {
1520 /* A capture filter was specified; set it up. */
1521 if (pcap_lookupnet(cfile.iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1523 * Well, we can't get the netmask for this interface; it's used
1524 * only for filters that check for broadcast IP addresses, so
1525 * we just punt and use 0. It might be nice to warn the user,
1526 * but that's a pain in a GUI application, as it'd involve popping
1527 * up a message box, and it's not clear how often this would make
1528 * a difference (only filters that check for IP broadcast addresses
1533 if (pcap_compile(pch, &fcode, cfile.cfilter, 1, netmask) < 0) {
1534 dfilter_t *rfcode = NULL;
1535 if (dfilter_compile(cfile.cfilter, &rfcode) && rfcode != NULL) {
1536 snprintf(errmsg, sizeof errmsg,
1537 "Unable to parse capture filter string (%s).\n"
1539 " That string looks like a valid display filter; note that display filters\n"
1540 " and capture filters don't have the same syntax, so you can't use\n"
1541 " most display filter expressions as capture filters.",
1543 dfilter_free(rfcode);
1545 snprintf(errmsg, sizeof errmsg,
1546 "Unable to parse capture filter string (%s).",
1551 if (pcap_setfilter(pch, &fcode) < 0) {
1552 snprintf(errmsg, sizeof errmsg, "Can't install filter (%s).",
1558 /* Set up to write to the capture file. */
1561 pcap_encap = hdr.network;
1562 file_snaplen = hdr.snaplen;
1566 pcap_encap = get_pcap_linktype(pch, cfile.iface);
1567 file_snaplen = pcap_snapshot(pch);
1569 ld.linktype = wtap_pcap_encap_to_wtap_encap(pcap_encap);
1570 if (ld.linktype == WTAP_ENCAP_UNKNOWN) {
1571 snprintf(errmsg, sizeof errmsg,
1572 "The network you're capturing from is of a type"
1573 " that Ethereal doesn't support (data link type %d).", pcap_encap);
1576 if (capture_opts.ringbuffer_on) {
1577 ld.pdh = ringbuf_init_wtap_dump_fdopen(WTAP_FILE_PCAP, ld.linktype,
1578 file_snaplen, &err);
1580 ld.pdh = wtap_dump_fdopen(cfile.save_file_fd, WTAP_FILE_PCAP,
1581 ld.linktype, file_snaplen, &err);
1584 if (ld.pdh == NULL) {
1585 /* We couldn't set up to write to the capture file. */
1588 case WTAP_ERR_CANT_OPEN:
1589 strcpy(errmsg, "The file to which the capture would be saved"
1590 " couldn't be created for some unknown reason.");
1593 case WTAP_ERR_SHORT_WRITE:
1594 strcpy(errmsg, "A full header couldn't be written to the file"
1595 " to which the capture would be saved.");
1600 snprintf(errmsg, sizeof(errmsg),
1601 "The file to which the capture would be"
1602 " saved (\"%s\") could not be opened: Error %d.",
1603 cfile.save_file, err);
1605 snprintf(errmsg, sizeof(errmsg),
1606 "The file to which the capture would be"
1607 " saved (\"%s\") could not be opened: %s.",
1608 cfile.save_file, strerror(err));
1615 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1616 returned a warning; print it, but keep capturing. */
1617 if (open_err_str[0] != '\0')
1618 g_warning("%s.", open_err_str);
1620 /* XXX - capture SIGTERM and close the capture, in case we're on a
1621 Linux 2.0[.x] system and you have to explicitly close the capture
1622 stream in order to turn promiscuous mode off? We need to do that
1623 in other places as well - and I don't think that works all the
1624 time in any case, due to libpcap bugs. */
1626 if (capture_child) {
1627 /* Well, we should be able to start capturing.
1629 This is the child process for a sync mode capture, so sync out
1630 the capture file, so the header makes it to the file system,
1631 and send a "capture started successfully and capture file created"
1632 message to our parent so that they'll open the capture file and
1633 update its windows to indicate that we have a live capture in
1635 fflush(wtap_dump_file(ld.pdh));
1636 write(1, &capstart_msg, 1);
1639 /* start capture info dialog */
1640 capture_ui.callback_data = &ld;
1641 capture_ui.counts = &ld.counts;
1642 capture_info_create(&capture_ui);
1644 start_time = time(NULL);
1645 upd_time = time(NULL);
1646 #ifdef MUST_DO_SELECT
1647 if (!ld.from_pipe) pcap_fd = pcap_fileno(pch);
1652 * Catch SIGUSR1, so that we exit cleanly if the parent process
1653 * kills us with it due to the user selecting "Capture->Stop".
1656 signal(SIGUSR1, stop_capture);
1658 /* initialize capture stop conditions */
1659 init_capture_stop_conditions();
1660 /* create stop conditions */
1661 if (capture_opts.has_autostop_filesize)
1662 cnd_stop_capturesize =
1663 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts.autostop_filesize * 1000);
1664 if (capture_opts.has_autostop_duration)
1666 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts.autostop_duration);
1668 if (capture_opts.ringbuffer_on && capture_opts.has_ring_duration)
1670 cnd_new(CND_CLASS_TIMEOUT, capture_opts.ringbuffer_duration);
1673 /* WOW, everything is prepared! */
1674 /* please fasten your seat belts, we will enter now the actual capture loop */
1676 main_window_update();
1681 FD_SET(pipe_fd, &set1);
1683 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1684 sel_ret = select(pipe_fd+1, &set1, NULL, NULL, &timeout);
1687 if (sel_ret < 0 && errno != EINTR) {
1688 snprintf(errmsg, sizeof(errmsg),
1689 "Unexpected error from select: %s", strerror(errno));
1690 popup_errmsg(errmsg);
1695 * "select()" says we can read from the pipe without blocking
1697 inpkts = pipe_dispatch(pipe_fd, &ld, &hdr, &rechdr, pcap_data,
1698 errmsg, sizeof errmsg);
1707 #ifdef MUST_DO_SELECT
1709 * Sigh. The semantics of the read timeout argument to
1710 * "pcap_open_live()" aren't particularly well specified by
1711 * the "pcap" man page - at least with the BSD BPF code, the
1712 * intent appears to be, at least in part, a way of cutting
1713 * down the number of reads done on a capture, by blocking
1714 * until the buffer fills or a timer expires - and the Linux
1715 * libpcap doesn't actually support it, so we can't use it
1716 * to break out of the "pcap_dispatch()" every 1/4 of a second
1717 * or so. Linux's libpcap is not the only libpcap that doesn't
1718 * support the read timeout.
1720 * Furthermore, at least on Solaris, the bufmod STREAMS module's
1721 * read timeout won't go off if no data has arrived, i.e. it cannot
1722 * be used to guarantee that a read from a DLPI stream will return
1723 * within a specified amount of time regardless of whether any
1724 * data arrives or not.
1726 * Thus, on all platforms other than BSD, we do a "select()" on the
1727 * file descriptor for the capture, with a timeout of CAP_READ_TIMEOUT
1728 * milliseconds, or CAP_READ_TIMEOUT*1000 microseconds.
1730 * "select()", on BPF devices, doesn't work as you might expect;
1731 * at least on some versions of some flavors of BSD, the timer
1732 * doesn't start until a read is done, so it won't expire if
1733 * only a "select()" or "poll()" is posted.
1736 FD_SET(pcap_fd, &set1);
1738 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1739 sel_ret = select(pcap_fd+1, &set1, NULL, NULL, &timeout);
1742 * "select()" says we can read from it without blocking; go for
1745 inpkts = pcap_dispatch(pch, 1, capture_pcap_cb, (guchar *) &ld);
1752 if (sel_ret < 0 && errno != EINTR) {
1753 snprintf(errmsg, sizeof(errmsg),
1754 "Unexpected error from select: %s", strerror(errno));
1755 popup_errmsg(errmsg);
1760 inpkts = pcap_dispatch(pch, 1, capture_pcap_cb, (guchar *) &ld);
1769 ld.sync_packets += inpkts;
1770 /* check capture stop conditons */
1771 if (cnd_stop_capturesize != NULL && cnd_eval(cnd_stop_capturesize,
1772 (guint32)wtap_get_bytes_dumped(ld.pdh))){
1773 /* Capture file reached its maximum size. */
1774 if (capture_opts.ringbuffer_on) {
1775 /* Switch to the next ringbuffer file */
1776 if (ringbuf_switch_file(&cfile, &ld.pdh, &ld.err)) {
1777 /* File switch succeeded: reset the condition */
1778 cnd_reset(cnd_stop_capturesize);
1779 if (cnd_ring_timeout) {
1780 cnd_reset(cnd_ring_timeout);
1783 /* File switch failed: stop here */
1788 /* no ringbuffer - just stop */
1794 /* Only update once a second so as not to overload slow displays */
1795 cur_time = time(NULL);
1796 if (cur_time > upd_time) {
1797 upd_time = cur_time;
1799 /*if (pcap_stats(pch, stats) >= 0) {
1800 *stats_known = TRUE;
1803 /* Let the parent process know. */
1804 /* calculate and display running time */
1805 cur_time -= start_time;
1806 capture_ui.running_time = cur_time;
1807 capture_ui.new_packets = ld.sync_packets;
1808 capture_info_update(&capture_ui);
1810 if (ld.sync_packets) {
1812 fflush(wtap_dump_file(ld.pdh));
1814 if (capture_child) {
1815 /* This is the child process for a sync mode capture, so send
1816 our parent a message saying we've written out "ld.sync_packets"
1817 packets to the capture file. */
1818 char tmp[DECISIZE+1+1];
1819 sprintf(tmp, "%d%c", ld.sync_packets, SP_PACKET_COUNT);
1820 write(1, tmp, strlen(tmp));
1823 ld.sync_packets = 0;
1827 if (cnd_stop_timeout != NULL && cnd_eval(cnd_stop_timeout)) {
1828 /* The specified capture time has elapsed; stop the capture. */
1830 } else if (cnd_ring_timeout != NULL && cnd_eval(cnd_ring_timeout)) {
1831 /* time elasped for this ring file, swith to the next */
1832 if (ringbuf_switch_file(&cfile, &ld.pdh, &ld.err)) {
1833 /* File switch succeeded: reset the condition */
1834 cnd_reset(cnd_ring_timeout);
1836 /* File switch failed: stop here */
1842 } /* while (ld.go) */
1844 /* delete stop conditions */
1845 if (cnd_stop_capturesize != NULL)
1846 cnd_delete(cnd_stop_capturesize);
1847 if (cnd_stop_timeout != NULL)
1848 cnd_delete(cnd_stop_timeout);
1849 if (cnd_ring_timeout != NULL)
1850 cnd_delete(cnd_ring_timeout);
1853 snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
1855 popup_errmsg(errmsg);
1859 } else if (ld.from_pipe && ld.pipe_err == PIPERR)
1860 popup_errmsg(errmsg);
1866 get_capture_file_io_error(errmsg, sizeof(errmsg), cfile.save_file, ld.err,
1868 popup_errmsg(errmsg);
1872 if (capture_opts.ringbuffer_on) {
1873 close_ok = ringbuf_wtap_dump_close(&cfile, &err);
1875 close_ok = wtap_dump_close(ld.pdh, &err);
1877 /* If we've displayed a message about a write error, there's no point
1878 in displaying another message about an error on close. */
1879 if (!close_ok && write_ok) {
1880 get_capture_file_io_error(errmsg, sizeof(errmsg), cfile.save_file, err,
1882 popup_errmsg(errmsg);
1884 /* Set write_ok to mean the write and the close were successful. */
1885 write_ok = (write_ok && close_ok);
1889 * XXX We exhibit different behaviour between normal mode and sync mode
1890 * when the pipe is stdin and not already at EOF. If we're a child, the
1891 * parent's stdin isn't closed, so if the user starts another capture,
1892 * pipe_open_live() will very likely not see the expected magic bytes and
1893 * will say "Unrecognized libpcap format". On the other hand, in normal
1894 * mode, pipe_open_live() will say "End of file on pipe during open".
1896 if (ld.from_pipe && pipe_fd >= 0)
1901 /* Get the capture statistics, so we know how many packets were
1903 if (pcap_stats(pch, stats) >= 0) {
1904 *stats_known = TRUE;
1905 if (capture_child) {
1906 /* Let the parent process know. */
1907 char tmp[DECISIZE+1+1];
1908 sprintf(tmp, "%d%c", stats->ps_drop, SP_DROPS);
1909 write(1, tmp, strlen(tmp));
1912 snprintf(errmsg, sizeof(errmsg),
1913 "Can't get packet-drop statistics: %s",
1915 popup_errmsg(errmsg);
1921 /* Shut down windows sockets */
1925 capture_info_destroy(&capture_ui);
1930 if (capture_opts.ringbuffer_on) {
1931 /* cleanup ringbuffer */
1932 ringbuf_error_cleanup();
1934 /* We can't use the save file, and we have no wtap_dump stream
1935 to close in order to close it, so close the FD directly. */
1936 close(cfile.save_file_fd);
1938 /* We couldn't even start the capture, so get rid of the capture
1940 unlink(cfile.save_file); /* silently ignore error */
1941 g_free(cfile.save_file);
1943 cfile.save_file = NULL;
1944 popup_errmsg(errmsg);
1961 get_capture_file_io_error(char *errmsg, int errmsglen, const char *fname,
1962 int err, gboolean is_close)
1967 snprintf(errmsg, errmsglen,
1968 "Not all the packets could be written to the file"
1969 " to which the capture was being saved\n"
1970 "(\"%s\") because there is no space left on the file system\n"
1971 "on which that file resides.",
1977 snprintf(errmsg, errmsglen,
1978 "Not all the packets could be written to the file"
1979 " to which the capture was being saved\n"
1980 "(\"%s\") because you are too close to, or over,"
1981 " your disk quota\n"
1982 "on the file system on which that file resides.",
1987 case WTAP_ERR_CANT_CLOSE:
1988 snprintf(errmsg, errmsglen,
1989 "The file to which the capture was being saved"
1990 " couldn't be closed for some unknown reason.");
1993 case WTAP_ERR_SHORT_WRITE:
1994 snprintf(errmsg, errmsglen,
1995 "Not all the packets could be written to the file"
1996 " to which the capture was being saved\n"
2003 snprintf(errmsg, errmsglen,
2004 "The file to which the capture was being saved\n"
2005 "(\"%s\") could not be closed: %s.",
2006 fname, wtap_strerror(err));
2008 snprintf(errmsg, errmsglen,
2009 "An error occurred while writing to the file"
2010 " to which the capture was being saved\n"
2012 fname, wtap_strerror(err));
2019 popup_errmsg(const char *errmsg)
2021 if (capture_child) {
2022 /* This is the child process for a sync mode capture.
2023 Send the error message to our parent, so they can display a
2024 dialog box containing it. */
2025 send_errmsg_to_parent(errmsg);
2027 /* Display the dialog box ourselves; there's no parent. */
2028 simple_dialog(ESD_TYPE_ERROR, NULL, "%s", errmsg);
2033 send_errmsg_to_parent(const char *errmsg)
2035 int msglen = strlen(errmsg);
2036 char lenbuf[DECISIZE+1+1];
2038 sprintf(lenbuf, "%u%c", msglen, SP_ERROR_MSG);
2039 write(1, lenbuf, strlen(lenbuf));
2040 write(1, errmsg, msglen);
2044 stop_capture(int signo _U_)
2049 void capture_ui_stop_callback(
2050 gpointer callback_data)
2052 loop_data *ld = (loop_data *) callback_data;
2062 if (fork_child != -1)
2063 kill(fork_child, SIGUSR1);
2065 if (fork_child != -1) {
2066 /* XXX: this is not the preferred method of closing a process!
2067 * the clean way would be getting the process id of the child process,
2068 * then getting window handle hWnd of that process (using EnumChildWindows),
2069 * and then do a SendMessage(hWnd, WM_CLOSE, 0, 0)
2071 * Unfortunately, I don't know how to get the process id from the handle */
2072 /* Hint: OpenProcess will get an handle from the id, not vice versa :-(
2074 * Hint: GenerateConsoleCtrlEvent() will only work, if both processes are
2075 * running in the same console, I don't know if that is true for our case.
2076 * And this also will require to have the process id
2078 TerminateProcess((HANDLE) fork_child, 0);
2084 kill_capture_child(void)
2087 if (fork_child != -1)
2088 kill(fork_child, SIGTERM); /* SIGTERM so it can clean up if necessary */
2095 capture_pcap_cb(guchar *user, const struct pcap_pkthdr *phdr,
2098 struct wtap_pkthdr whdr;
2099 union wtap_pseudo_header pseudo_header;
2100 loop_data *ld = (loop_data *) user;
2103 if ((++ld->counts.total >= ld->max) && (ld->max > 0))
2108 /* Convert from libpcap to Wiretap format.
2109 If that fails, set "ld->go" to FALSE, to stop the capture, and set
2110 "ld->err" to the error. */
2111 pd = wtap_process_pcap_packet(ld->linktype, phdr, pd, &pseudo_header,
2120 /* We're supposed to write the packet to a file; do so.
2121 If this fails, set "ld->go" to FALSE, to stop the capture, and set
2122 "ld->err" to the error. */
2123 if (!wtap_dump(ld->pdh, &whdr, &pseudo_header, pd, &err)) {
2129 switch (ld->linktype) {
2130 case WTAP_ENCAP_ETHERNET:
2131 capture_eth(pd, 0, whdr.caplen, &ld->counts);
2133 case WTAP_ENCAP_FDDI:
2134 case WTAP_ENCAP_FDDI_BITSWAPPED:
2135 capture_fddi(pd, whdr.caplen, &ld->counts);
2137 case WTAP_ENCAP_PRISM_HEADER:
2138 capture_prism(pd, 0, whdr.caplen, &ld->counts);
2140 case WTAP_ENCAP_TOKEN_RING:
2141 capture_tr(pd, 0, whdr.caplen, &ld->counts);
2143 case WTAP_ENCAP_NULL:
2144 capture_null(pd, whdr.caplen, &ld->counts);
2146 case WTAP_ENCAP_PPP:
2147 capture_ppp_hdlc(pd, 0, whdr.caplen, &ld->counts);
2149 case WTAP_ENCAP_RAW_IP:
2150 capture_raw(pd, whdr.caplen, &ld->counts);
2152 case WTAP_ENCAP_SLL:
2153 capture_sll(pd, whdr.caplen, &ld->counts);
2155 case WTAP_ENCAP_LINUX_ATM_CLIP:
2156 capture_clip(pd, whdr.caplen, &ld->counts);
2158 case WTAP_ENCAP_IEEE_802_11:
2159 case WTAP_ENCAP_IEEE_802_11_WITH_RADIO:
2160 capture_ieee80211(pd, 0, whdr.caplen, &ld->counts);
2162 case WTAP_ENCAP_CHDLC:
2163 capture_chdlc(pd, 0, whdr.caplen, &ld->counts);
2165 case WTAP_ENCAP_LOCALTALK:
2166 capture_llap(&ld->counts);
2168 case WTAP_ENCAP_ATM_PDUS:
2169 capture_atm(&pseudo_header, pd, whdr.caplen, &ld->counts);
2171 case WTAP_ENCAP_IP_OVER_FC:
2172 capture_ipfc(pd, whdr.caplen, &ld->counts);
2174 case WTAP_ENCAP_ARCNET:
2175 capture_arcnet(pd, whdr.caplen, &ld->counts, FALSE, TRUE);
2177 case WTAP_ENCAP_ARCNET_LINUX:
2178 capture_arcnet(pd, whdr.caplen, &ld->counts, TRUE, FALSE);
2180 /* XXX - some ATM drivers on FreeBSD might prepend a 4-byte ATM
2181 pseudo-header to DLT_ATM_RFC1483, with LLC header following;
2182 we might have to implement that at some point. */
2186 #endif /* HAVE_LIBPCAP */