2 * Routines for packet capture windows
4 * $Id: capture.c,v 1.217 2003/11/17 19:40:09 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)
87 #ifdef HAVE_SYS_SOCKET_H
88 #include <sys/socket.h>
91 #ifdef HAVE_SYS_IOCTL_H
92 #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 "simple_dialog.h"
140 #include "conditions.h"
141 #include "capture_stop_conditions.h"
142 #include "ringbuffer.h"
144 #include "wiretap/libpcap.h"
145 #include "wiretap/wtap.h"
146 #include "wiretap/wtap-capture.h"
148 #include "packet-atalk.h"
149 #include "packet-atm.h"
150 #include "packet-clip.h"
151 #include "packet-eth.h"
152 #include "packet-fddi.h"
153 #include "packet-null.h"
154 #include "packet-ppp.h"
155 #include "packet-raw.h"
156 #include "packet-sll.h"
157 #include "packet-tr.h"
158 #include "packet-ieee80211.h"
159 #include "packet-chdlc.h"
160 #include "packet-prism.h"
161 #include "packet-ipfc.h"
162 #include "packet-arcnet.h"
165 #include "capture-wpcap.h"
171 capture_options capture_opts;
173 static int sync_pipe[2]; /* used to sync father */
174 enum PIPES { READ, WRITE }; /* Constants 0 and 1 for READ and WRITE */
175 int quit_after_cap; /* Makes a "capture only mode". Implies -k */
176 gboolean capture_child; /* if this is the child for "-S" */
177 static int fork_child = -1; /* If not -1, in parent, process ID of child */
178 static guint cap_input_id;
181 * Indications sent out on the sync pipe.
183 #define SP_CAPSTART ';' /* capture start message */
184 #define SP_PACKET_COUNT '*' /* followed by count of packets captured since last message */
185 #define SP_ERROR_MSG '!' /* followed by length of error message that follows */
186 #define SP_DROPS '#' /* followed by count of packets dropped in capture */
189 static guint cap_timer_id;
190 static int cap_timer_cb(gpointer); /* Win32 kludge to check for pipe input */
193 static void cap_file_input_cb(gpointer, gint, GdkInputCondition);
194 static void wait_for_child(gboolean);
196 static char *signame(int);
198 static void capture_pcap_cb(guchar *, const struct pcap_pkthdr *,
200 static void get_capture_file_io_error(char *, int, const char *, int, gboolean);
201 static void popup_errmsg(const char *);
202 static void send_errmsg_to_parent(const char *);
203 static void stop_capture(int signo);
205 typedef struct _loop_data {
206 gboolean go; /* TRUE as long as we're supposed to keep capturing */
207 gint max; /* Number of packets we're supposed to capture - 0 means infinite */
208 int err; /* if non-zero, error seen while capturing */
211 gboolean pcap_err; /* TRUE if error from pcap */
212 gboolean from_pipe; /* TRUE if we are capturing data from a pipe */
213 packet_counts counts;
216 gboolean modified; /* TRUE if data in the pipe uses modified pcap headers */
217 gboolean byte_swapped; /* TRUE if data in the pipe is byte swapped */
218 unsigned int bytes_to_read, bytes_read; /* Used by pipe_dispatch */
220 STATE_EXPECT_REC_HDR, STATE_READ_REC_HDR,
221 STATE_EXPECT_DATA, STATE_READ_DATA
224 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } pipe_err;
229 static void adjust_header(loop_data *, struct pcap_hdr *, struct pcaprec_hdr *);
230 static int pipe_open_live(char *, struct pcap_hdr *, loop_data *, char *, int);
231 static int pipe_dispatch(int, loop_data *, struct pcap_hdr *, \
232 struct pcaprec_modified_hdr *, guchar *, char *, int);
235 /* Win32 needs the O_BINARY flag for open() */
241 /* Win32 needs a handle to the child capture process */
245 /* Add a string pointer to a NULL-terminated array of string pointers. */
247 add_arg(char **args, int *argc, char *arg)
249 /* Grow the array; "*argc" currently contains the number of string
250 pointers, *not* counting the NULL pointer at the end, so we have
251 to add 2 in order to get the new size of the array, including the
252 new pointer and the terminating NULL pointer. */
253 args = g_realloc(args, (*argc + 2) * sizeof (char *));
255 /* Stuff the pointer into the penultimate element of the array, which
256 is the one at the index specified by "*argc". */
259 /* Now bump the count. */
262 /* We overwrite the NULL pointer; put it back right after the
270 /* Given a string, return a pointer to a quote-encapsulated version of
271 the string, so we can pass it as an argument with "spawnvp" even
272 if it contains blanks. */
274 quote_encapsulate(const char *string)
276 char *encapsulated_string;
278 encapsulated_string = g_new(char, strlen(string) + 3);
279 sprintf(encapsulated_string, "\"%s\"", string);
280 return encapsulated_string;
284 /* Open a specified file, or create a temporary file, and start a capture
285 to the file in question. Returns TRUE if the capture starts
286 successfully, FALSE otherwise. */
288 do_capture(const char *save_file)
291 gboolean is_tempfile;
297 int capture_succeeded;
298 gboolean stats_known;
299 struct pcap_stat stats;
302 if (save_file != NULL) {
303 /* If the Sync option is set, we return to the caller while the capture
304 * is in progress. Therefore we need to take a copy of save_file in
305 * case the caller destroys it after we return.
307 capfile_name = g_strdup(save_file);
308 if (capture_opts.ringbuffer_on) {
309 /* ringbuffer is enabled */
310 cfile.save_file_fd = ringbuf_init(capfile_name,
311 capture_opts.ringbuffer_num_files);
313 /* Try to open/create the specified file for use as a capture buffer. */
314 cfile.save_file_fd = open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
319 /* Choose a random name for the capture buffer */
320 cfile.save_file_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
321 capfile_name = g_strdup(tmpname);
324 if (cfile.save_file_fd == -1) {
326 simple_dialog(ESD_TYPE_CRIT, NULL,
327 "The temporary file to which the capture would be saved (\"%s\")"
328 "could not be opened: %s.", capfile_name, strerror(errno));
330 if (capture_opts.ringbuffer_on) {
331 ringbuf_error_cleanup();
333 simple_dialog(ESD_TYPE_CRIT, NULL,
334 file_open_error_message(errno, TRUE, WTAP_FILE_PCAP), capfile_name);
336 g_free(capfile_name);
340 g_assert(cfile.save_file == NULL);
341 cfile.save_file = capfile_name;
342 /* cfile.save_file is "g_free"ed below, which is equivalent to
343 "g_free(capfile_name)". */
345 if (capture_opts.sync_mode) { /* do the capture in a child process */
347 char scount[24]; /* need a constant for len of numbers */
348 char sautostop_filesize[24]; /* need a constant for len of numbers */
349 char sautostop_duration[24]; /* need a constant for len of numbers */
350 char save_file_fd[24];
356 char sync_pipe_fd[24];
361 /* Allocate the string pointer array with enough space for the
362 terminating NULL pointer. */
364 argv = g_malloc(sizeof (char *));
367 /* Now add those arguments used on all platforms. */
368 argv = add_arg(argv, &argc, CHILD_NAME);
370 argv = add_arg(argv, &argc, "-i");
371 argv = add_arg(argv, &argc, cfile.iface);
373 argv = add_arg(argv, &argc, "-w");
374 argv = add_arg(argv, &argc, cfile.save_file);
376 argv = add_arg(argv, &argc, "-W");
377 sprintf(save_file_fd,"%d",cfile.save_file_fd); /* in lieu of itoa */
378 argv = add_arg(argv, &argc, save_file_fd);
380 if (capture_opts.has_autostop_count) {
381 argv = add_arg(argv, &argc, "-c");
382 sprintf(scount,"%d",capture_opts.autostop_count);
383 argv = add_arg(argv, &argc, scount);
386 if (capture_opts.has_snaplen) {
387 argv = add_arg(argv, &argc, "-s");
388 sprintf(ssnap,"%d",capture_opts.snaplen);
389 argv = add_arg(argv, &argc, ssnap);
392 if (capture_opts.linktype != -1) {
393 argv = add_arg(argv, &argc, "-y");
394 sprintf(ssnap,"%d",capture_opts.linktype);
395 argv = add_arg(argv, &argc, ssnap);
398 if (capture_opts.has_autostop_filesize) {
399 argv = add_arg(argv, &argc, "-a");
400 sprintf(sautostop_filesize,"filesize:%d",capture_opts.autostop_filesize);
401 argv = add_arg(argv, &argc, sautostop_filesize);
404 if (capture_opts.has_autostop_duration) {
405 argv = add_arg(argv, &argc, "-a");
406 sprintf(sautostop_duration,"duration:%d",capture_opts.autostop_duration);
407 argv = add_arg(argv, &argc, sautostop_duration);
410 if (!capture_opts.promisc_mode)
411 argv = add_arg(argv, &argc, "-p");
414 /* Create a pipe for the child process */
416 if(_pipe(sync_pipe, 512, O_BINARY) < 0) {
417 /* Couldn't create the pipe between parent and child. */
419 unlink(cfile.save_file);
420 g_free(cfile.save_file);
421 cfile.save_file = NULL;
422 simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create sync pipe: %s",
427 /* Convert font name to a quote-encapsulated string and pass to child */
428 argv = add_arg(argv, &argc, "-m");
429 fontstring = quote_encapsulate(prefs.gui_font_name);
430 argv = add_arg(argv, &argc, fontstring);
432 /* Convert pipe write handle to a string and pass to child */
433 argv = add_arg(argv, &argc, "-Z");
434 itoa(sync_pipe[WRITE], sync_pipe_fd, 10);
435 argv = add_arg(argv, &argc, sync_pipe_fd);
437 /* Convert filter string to a quote delimited string and pass to child */
439 if (cfile.cfilter != NULL && strlen(cfile.cfilter) != 0) {
440 argv = add_arg(argv, &argc, "-f");
441 filterstring = quote_encapsulate(cfile.cfilter);
442 argv = add_arg(argv, &argc, filterstring);
446 fork_child = spawnvp(_P_NOWAIT, ethereal_path, argv);
449 g_free(filterstring);
451 /* Keep a copy for later evaluation by _cwait() */
452 child_process = fork_child;
454 if (pipe(sync_pipe) < 0) {
455 /* Couldn't create the pipe between parent and child. */
457 unlink(cfile.save_file);
458 g_free(cfile.save_file);
459 cfile.save_file = NULL;
460 simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create sync pipe: %s",
465 argv = add_arg(argv, &argc, "-m");
466 argv = add_arg(argv, &argc, prefs.gui_font_name);
468 if (cfile.cfilter != NULL && strlen(cfile.cfilter) != 0) {
469 argv = add_arg(argv, &argc, "-f");
470 argv = add_arg(argv, &argc, cfile.cfilter);
473 if ((fork_child = fork()) == 0) {
475 * Child process - run Ethereal with the right arguments to make
476 * it just pop up the live capture dialog box and capture with
477 * the specified capture parameters, writing to the specified file.
479 * args: -i interface specification
481 * -W file descriptor to write
482 * -c count to capture
485 * -f "filter expression"
488 dup(sync_pipe[WRITE]);
489 close(sync_pipe[READ]);
490 execvp(ethereal_path, argv);
491 snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
492 ethereal_path, strerror(errno));
493 send_errmsg_to_parent(errmsg);
495 /* Exit with "_exit()", so that we don't close the connection
496 to the X server (and cause stuff buffered up by our parent but
497 not yet sent to be sent, as that stuff should only be sent by
503 /* Parent process - read messages from the child process over the
505 g_free(argv); /* free up arg array */
507 /* Close the write side of the pipe, so that only the child has it
508 open, and thus it completely closes, and thus returns to us
509 an EOF indication, if the child closes it (either deliberately
510 or by exiting abnormally). */
511 close(sync_pipe[WRITE]);
513 /* Close the save file FD, as we won't be using it - we'll be opening
514 it and reading the save file through Wiretap. */
515 close(cfile.save_file_fd);
517 if (fork_child == -1) {
518 /* We couldn't even create the child process. */
520 close(sync_pipe[READ]);
521 unlink(cfile.save_file);
522 g_free(cfile.save_file);
523 cfile.save_file = NULL;
524 simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create child process: %s",
529 /* Read a byte count from "sync_pipe[READ]", terminated with a
530 colon; if the count is 0, the child process created the
531 capture file and we should start reading from it, otherwise
532 the capture couldn't start and the count is a count of bytes
533 of error message, and we should display the message. */
536 i = read(sync_pipe[READ], &c, 1);
538 /* EOF - the child process died.
539 Close the read side of the sync pipe, remove the capture file,
540 and report the failure. */
541 close(sync_pipe[READ]);
542 unlink(cfile.save_file);
543 g_free(cfile.save_file);
544 cfile.save_file = NULL;
545 wait_for_child(TRUE);
548 if (c == SP_CAPSTART || c == SP_ERROR_MSG)
551 /* Child process handed us crap.
552 Close the read side of the sync pipe, remove the capture file,
553 and report the failure. */
554 close(sync_pipe[READ]);
555 unlink(cfile.save_file);
556 g_free(cfile.save_file);
557 cfile.save_file = NULL;
558 simple_dialog(ESD_TYPE_WARN, NULL,
559 "Capture child process sent us a bad message");
562 byte_count = byte_count*10 + c - '0';
564 if (c != SP_CAPSTART) {
565 /* Failure - the child process sent us a message indicating
566 what the problem was. */
567 if (byte_count == 0) {
568 /* Zero-length message? */
569 simple_dialog(ESD_TYPE_WARN, NULL,
570 "Capture child process failed, but its error message was empty.");
572 msg = g_malloc(byte_count + 1);
574 simple_dialog(ESD_TYPE_WARN, NULL,
575 "Capture child process failed, but its error message was too big.");
577 i = read(sync_pipe[READ], msg, byte_count);
578 msg[byte_count] = '\0';
580 simple_dialog(ESD_TYPE_WARN, NULL,
581 "Capture child process failed: Error %s reading its error message.",
584 simple_dialog(ESD_TYPE_WARN, NULL,
585 "Capture child process failed: EOF reading its error message.");
586 wait_for_child(FALSE);
588 simple_dialog(ESD_TYPE_CRIT, NULL, msg);
592 /* Close the sync pipe. */
593 close(sync_pipe[READ]);
595 /* Get rid of the save file - the capture never started. */
596 unlink(cfile.save_file);
597 g_free(cfile.save_file);
598 cfile.save_file = NULL;
603 /* The child process started a capture.
604 Attempt to open the capture file and set up to read it. */
605 err = cf_start_tail(cfile.save_file, is_tempfile, &cfile);
607 /* We weren't able to open the capture file; user has been
608 alerted. Close the sync pipe. */
610 close(sync_pipe[READ]);
612 /* Don't unlink the save file - leave it around, for debugging
614 g_free(cfile.save_file);
615 cfile.save_file = NULL;
618 /* We were able to open and set up to read the capture file;
619 arrange that our callback be called whenever it's possible
620 to read from the sync pipe, so that it's called when
621 the child process wants to tell us something. */
623 /* Tricky to use pipes in win9x, as no concept of wait. NT can
624 do this but that doesn't cover all win32 platforms. GTK can do
625 this but doesn't seem to work over processes. Attempt to do
626 something similar here, start a timer and check for data on every
628 cap_timer_id = gtk_timeout_add(1000, cap_timer_cb, NULL);
630 cap_input_id = gtk_input_add_full(sync_pipe[READ],
631 GDK_INPUT_READ|GDK_INPUT_EXCEPTION,
639 capture_succeeded = capture(&stats_known, &stats);
640 if (quit_after_cap) {
641 /* DON'T unlink the save file. Presumably someone wants it. */
644 if (!capture_succeeded) {
645 /* We didn't succeed in doing the capture, so we don't have a save
647 if (capture_opts.ringbuffer_on) {
650 g_free(cfile.save_file);
652 cfile.save_file = NULL;
655 /* Capture succeeded; attempt to read in the capture file. */
656 if ((err = cf_open(cfile.save_file, is_tempfile, &cfile)) != 0) {
657 /* We're not doing a capture any more, so we don't have a save
659 if (capture_opts.ringbuffer_on) {
662 g_free(cfile.save_file);
664 cfile.save_file = NULL;
668 /* Set the read filter to NULL. */
671 /* Get the packet-drop statistics.
673 XXX - there are currently no packet-drop statistics stored
674 in libpcap captures, and that's what we're reading.
676 At some point, we will add support in Wiretap to return
677 packet-drop statistics for capture file formats that store it,
678 and will make "cf_read()" get those statistics from Wiretap.
679 We clear the statistics (marking them as "not known") in
680 "cf_open()", and "cf_read()" will only fetch them and mark
681 them as known if Wiretap supplies them, so if we get the
682 statistics now, after calling "cf_open()" but before calling
683 "cf_read()", the values we store will be used by "cf_read()".
685 If a future libpcap capture file format stores the statistics,
686 we'll put them into the capture file that we write, and will
687 thus not have to set them here - "cf_read()" will get them from
688 the file and use them. */
690 cfile.drops_known = TRUE;
692 /* XXX - on some systems, libpcap doesn't bother filling in
693 "ps_ifdrop" - it doesn't even set it to zero - so we don't
694 bother looking at it.
696 Ideally, libpcap would have an interface that gave us
697 several statistics - perhaps including various interface
698 error statistics - and would tell us which of them it
699 supplies, allowing us to display only the ones it does. */
700 cfile.drops = stats.ps_drop;
702 switch (cf_read(&cfile, &err)) {
706 /* Just because we got an error, that doesn't mean we were unable
707 to read any of the file; we handle what we could get from the
712 /* Exit by leaving the main loop, so that any quit functions
713 we registered get called. */
714 if (gtk_main_level() > 0)
719 /* We're not doing a capture any more, so we don't have a save
721 if (capture_opts.ringbuffer_on) {
724 g_free(cfile.save_file);
726 cfile.save_file = NULL;
732 /* The timer has expired, see if there's stuff to read from the pipe,
733 if so call the cap_file_input_cb */
735 cap_timer_cb(gpointer data)
739 gboolean result, result1;
742 /* Oddly enough although Named pipes don't work on win9x,
743 PeekNamedPipe does !!! */
744 handle = (HANDLE) _get_osfhandle (sync_pipe[READ]);
745 result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
747 /* Get the child process exit status */
748 result1 = GetExitCodeProcess((HANDLE)child_process, &childstatus);
750 /* If the Peek returned an error, or there are bytes to be read
751 or the childwatcher thread has terminated then call the normal
753 if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
755 /* avoid reentrancy problems and stack overflow */
756 gtk_timeout_remove(cap_timer_id);
758 /* And call the real handler */
759 cap_file_input_cb((gpointer) &cfile, 0, 0);
761 /* Return false so that the timer is not run again */
765 /* No data so let timer run again */
771 /* There's stuff to read from the sync pipe, meaning the child has sent
772 us a message, or the sync pipe has closed, meaning the child has
773 closed it (perhaps because it exited). */
775 cap_file_input_cb(gpointer data, gint source _U_,
776 GdkInputCondition condition _U_)
778 capture_file *cf = (capture_file *)data;
780 char buffer[BUFSIZE+1], *p = buffer, *q = buffer, *msg, *r;
781 int nread, msglen, chars_to_copy;
786 /* avoid reentrancy problems and stack overflow */
787 gtk_input_remove(cap_input_id);
790 if ((nread = read(sync_pipe[READ], buffer, BUFSIZE)) <= 0) {
791 /* The child has closed the sync pipe, meaning it's not going to be
792 capturing any more packets. Pick up its exit status, and
793 complain if it did anything other than exit with status 0. */
794 wait_for_child(FALSE);
796 /* Read what remains of the capture file, and finish the capture.
797 XXX - do something if this fails? */
798 switch (cf_finish_tail(cf, &err)) {
802 /* Just because we got an error, that doesn't mean we were unable
803 to read any of the file; we handle what we could get from the
808 /* Exit by leaving the main loop, so that any quit functions
809 we registered get called. */
814 /* We're not doing a capture any more, so we don't have a save
816 g_free(cf->save_file);
817 cf->save_file = NULL;
822 buffer[nread] = '\0';
825 /* look for (possibly multiple) indications */
827 case SP_PACKET_COUNT :
834 cf->drops_known = TRUE;
846 /* Read the entire message.
847 XXX - if the child hasn't sent it all yet, this could cause us
848 to hang until they do. */
849 msg = g_malloc(msglen + 1);
851 while (msglen != 0) {
854 if ((nread = read(sync_pipe[READ], buffer, BUFSIZE)) <= 0)
859 chars_to_copy = MIN(msglen, nread);
860 memcpy(r, q, chars_to_copy);
863 nread -= chars_to_copy;
864 msglen -= chars_to_copy;
867 simple_dialog(ESD_TYPE_CRIT, NULL, msg);
877 /* Read from the capture file the number of records the child told us
879 XXX - do something if this fails? */
880 switch (cf_continue_tail(cf, to_read, &err)) {
884 /* Just because we got an error, that doesn't mean we were unable
885 to read any of the file; we handle what we could get from the
888 XXX - abort on a read error? */
892 /* Kill the child capture process; the user wants to exit, and we
893 shouldn't just leave it running. */
897 kill(fork_child, SIGTERM); /* SIGTERM so it can clean up if necessary */
902 /* restore pipe handler */
904 cap_timer_id = gtk_timeout_add(1000, cap_timer_cb, NULL);
906 cap_input_id = gtk_input_add_full (sync_pipe[READ],
907 GDK_INPUT_READ|GDK_INPUT_EXCEPTION,
916 wait_for_child(gboolean always_report)
921 /* XXX - analyze the wait stuatus and display more information
922 in the dialog box? */
923 if (_cwait(&wstatus, child_process, _WAIT_CHILD) == -1) {
924 simple_dialog(ESD_TYPE_WARN, NULL, "Child capture process stopped unexpectedly");
927 if (wait(&wstatus) != -1) {
928 if (WIFEXITED(wstatus)) {
929 /* The child exited; display its exit status, if it's not zero,
930 and even if it's zero if "always_report" is true. */
931 if (always_report || WEXITSTATUS(wstatus) != 0) {
932 simple_dialog(ESD_TYPE_WARN, NULL,
933 "Child capture process exited: exit status %d",
934 WEXITSTATUS(wstatus));
936 } else if (WIFSTOPPED(wstatus)) {
937 /* It stopped, rather than exiting. "Should not happen." */
938 simple_dialog(ESD_TYPE_WARN, NULL,
939 "Child capture process stopped: %s",
940 signame(WSTOPSIG(wstatus)));
941 } else if (WIFSIGNALED(wstatus)) {
942 /* It died with a signal. */
943 simple_dialog(ESD_TYPE_WARN, NULL,
944 "Child capture process died: %s%s",
945 signame(WTERMSIG(wstatus)),
946 WCOREDUMP(wstatus) ? " - core dumped" : "");
948 /* What? It had to either have exited, or stopped, or died with
949 a signal; what happened here? */
950 simple_dialog(ESD_TYPE_WARN, NULL,
951 "Child capture process died: wait status %#o", wstatus);
955 /* No more child process. */
965 static char sigmsg_buf[6+1+3+1];
974 sigmsg = "Interrupted";
982 sigmsg = "Illegal instruction";
986 sigmsg = "Trace trap";
994 sigmsg = "Arithmetic exception";
1002 sigmsg = "Bus error";
1006 sigmsg = "Segmentation violation";
1009 /* http://metalab.unc.edu/pub/Linux/docs/HOWTO/GCC-HOWTO
1010 Linux is POSIX compliant. These are not POSIX-defined signals ---
1011 ISO/IEC 9945-1:1990 (IEEE Std 1003.1-1990), paragraph B.3.3.1.1 sez:
1013 ``The signals SIGBUS, SIGEMT, SIGIOT, SIGTRAP, and SIGSYS
1014 were omitted from POSIX.1 because their behavior is
1015 implementation dependent and could not be adequately catego-
1016 rized. Conforming implementations may deliver these sig-
1017 nals, but must document the circumstances under which they
1018 are delivered and note any restrictions concerning their
1021 So we only check for SIGSYS on those systems that happen to
1022 implement them (a system can be POSIX-compliant and implement
1023 them, it's just that POSIX doesn't *require* a POSIX-compliant
1024 system to implement them).
1029 sigmsg = "Bad system call";
1034 sigmsg = "Broken pipe";
1038 sigmsg = "Alarm clock";
1042 sigmsg = "Terminated";
1046 sprintf(sigmsg_buf, "Signal %d", sig);
1047 sigmsg = sigmsg_buf;
1055 * Timeout, in milliseconds, for reads from the stream of captured packets.
1057 #define CAP_READ_TIMEOUT 250
1060 /* Take care of byte order in the libpcap headers read from pipes.
1061 * (function taken from wiretap/libpcap.c) */
1063 adjust_header(loop_data *ld, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1065 if (ld->byte_swapped) {
1066 /* Byte-swap the record header fields. */
1067 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
1068 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
1069 rechdr->incl_len = BSWAP32(rechdr->incl_len);
1070 rechdr->orig_len = BSWAP32(rechdr->orig_len);
1073 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1074 swapped, in order to match the BPF header layout.
1076 Unfortunately, some files were, according to a comment in the "libpcap"
1077 source, written with version 2.3 in their headers but without the
1078 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1079 would make no sense - we assume that we need to swap them. */
1080 if (hdr->version_major == 2 &&
1081 (hdr->version_minor < 3 ||
1082 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1085 temp = rechdr->orig_len;
1086 rechdr->orig_len = rechdr->incl_len;
1087 rechdr->incl_len = temp;
1091 /* Mimic pcap_open_live() for pipe captures
1092 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
1094 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1095 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1097 pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
1098 char *errmsg, int errmsgl)
1100 struct stat pipe_stat;
1104 unsigned int bytes_read;
1106 struct timeval timeout;
1109 * XXX Ethereal blocks until we return
1111 if (strcmp(pipename, "-") == 0)
1112 fd = 0; /* read from stdin */
1114 if (stat(pipename, &pipe_stat) < 0) {
1115 if (errno == ENOENT || errno == ENOTDIR)
1116 ld->pipe_err = PIPNEXIST;
1118 snprintf(errmsg, errmsgl,
1119 "The capture session could not be initiated "
1120 "due to error on pipe: %s", strerror(errno));
1121 ld->pipe_err = PIPERR;
1125 if (! S_ISFIFO(pipe_stat.st_mode)) {
1126 if (S_ISCHR(pipe_stat.st_mode)) {
1128 * Assume the user specified an interface on a system where
1129 * interfaces are in /dev. Pretend we haven't seen it.
1131 ld->pipe_err = PIPNEXIST;
1133 snprintf(errmsg, errmsgl,
1134 "The capture session could not be initiated because\n"
1135 "\"%s\" is neither an interface nor a pipe", pipename);
1136 ld->pipe_err = PIPERR;
1140 fd = open(pipename, O_RDONLY | O_NONBLOCK);
1142 snprintf(errmsg, errmsgl,
1143 "The capture session could not be initiated "
1144 "due to error on pipe open: %s", strerror(errno));
1145 ld->pipe_err = PIPERR;
1150 ld->from_pipe = TRUE;
1152 /* read the pcap header */
1155 while (bytes_read < sizeof magic) {
1158 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1159 sel_ret = select(fd+1, &rfds, NULL, NULL, &timeout);
1161 snprintf(errmsg, errmsgl,
1162 "Unexpected error from select: %s", strerror(errno));
1164 } else if (sel_ret > 0) {
1165 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
1168 snprintf(errmsg, errmsgl, "End of file on pipe during open");
1170 snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
1180 /* Host that wrote it has our byte order, and was running
1181 a program using either standard or ss990417 libpcap. */
1182 ld->byte_swapped = FALSE;
1183 ld->modified = FALSE;
1185 case PCAP_MODIFIED_MAGIC:
1186 /* Host that wrote it has our byte order, but was running
1187 a program using either ss990915 or ss991029 libpcap. */
1188 ld->byte_swapped = FALSE;
1189 ld->modified = TRUE;
1191 case PCAP_SWAPPED_MAGIC:
1192 /* Host that wrote it has a byte order opposite to ours,
1193 and was running a program using either standard or
1194 ss990417 libpcap. */
1195 ld->byte_swapped = TRUE;
1196 ld->modified = FALSE;
1198 case PCAP_SWAPPED_MODIFIED_MAGIC:
1199 /* Host that wrote it out has a byte order opposite to
1200 ours, and was running a program using either ss990915
1201 or ss991029 libpcap. */
1202 ld->byte_swapped = TRUE;
1203 ld->modified = TRUE;
1206 /* Not a "libpcap" type we know about. */
1207 snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
1211 /* Read the rest of the header */
1213 while (bytes_read < sizeof(struct pcap_hdr)) {
1216 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1217 sel_ret = select(fd+1, &rfds, NULL, NULL, &timeout);
1219 snprintf(errmsg, errmsgl,
1220 "Unexpected error from select: %s", strerror(errno));
1222 } else if (sel_ret > 0) {
1223 b = read(fd, ((char *)hdr)+bytes_read,
1224 sizeof(struct pcap_hdr) - bytes_read);
1227 snprintf(errmsg, errmsgl, "End of file on pipe during open");
1229 snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
1237 if (ld->byte_swapped) {
1238 /* Byte-swap the header fields about which we care. */
1239 hdr->version_major = BSWAP16(hdr->version_major);
1240 hdr->version_minor = BSWAP16(hdr->version_minor);
1241 hdr->snaplen = BSWAP32(hdr->snaplen);
1242 hdr->network = BSWAP32(hdr->network);
1245 if (hdr->version_major < 2) {
1246 snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1250 ld->pipe_state = STATE_EXPECT_REC_HDR;
1251 ld->pipe_err = PIPOK;
1255 ld->pipe_err = PIPERR;
1261 /* We read one record from the pipe, take care of byte order in the record
1262 * header, write the record in the capture file, and update capture statistics. */
1265 pipe_dispatch(int fd, loop_data *ld, struct pcap_hdr *hdr,
1266 struct pcaprec_modified_hdr *rechdr, guchar *data,
1267 char *errmsg, int errmsgl)
1269 struct pcap_pkthdr phdr;
1271 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1274 switch (ld->pipe_state) {
1276 case STATE_EXPECT_REC_HDR:
1277 ld->bytes_to_read = ld->modified ?
1278 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1280 ld->pipe_state = STATE_READ_REC_HDR;
1283 case STATE_READ_REC_HDR:
1284 b = read(fd, ((char *)rechdr)+ld->bytes_read,
1285 ld->bytes_to_read - ld->bytes_read);
1288 result = PD_PIPE_EOF;
1290 result = PD_PIPE_ERR;
1293 if ((ld->bytes_read += b) < ld->bytes_to_read)
1295 result = PD_REC_HDR_READ;
1298 case STATE_EXPECT_DATA:
1300 ld->pipe_state = STATE_READ_DATA;
1303 case STATE_READ_DATA:
1304 b = read(fd, data+ld->bytes_read, rechdr->hdr.incl_len - ld->bytes_read);
1307 result = PD_PIPE_EOF;
1309 result = PD_PIPE_ERR;
1312 if ((ld->bytes_read += b) < rechdr->hdr.incl_len)
1314 result = PD_DATA_READ;
1318 snprintf(errmsg, errmsgl, "pipe_dispatch: invalid state");
1321 } /* switch (ld->pipe_state) */
1324 * We've now read as much data as we were expecting, so process it.
1328 case PD_REC_HDR_READ:
1329 /* We've read the header. Take care of byte order. */
1330 adjust_header(ld, hdr, &rechdr->hdr);
1331 if (rechdr->hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1332 snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
1333 ld->counts.total+1, rechdr->hdr.incl_len);
1336 ld->pipe_state = STATE_EXPECT_DATA;
1340 /* Fill in a "struct pcap_pkthdr", and process the packet. */
1341 phdr.ts.tv_sec = rechdr->hdr.ts_sec;
1342 phdr.ts.tv_usec = rechdr->hdr.ts_usec;
1343 phdr.caplen = rechdr->hdr.incl_len;
1344 phdr.len = rechdr->hdr.orig_len;
1346 capture_pcap_cb((guchar *)ld, &phdr, data);
1348 ld->pipe_state = STATE_EXPECT_REC_HDR;
1352 ld->pipe_err = PIPEOF;
1356 snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
1363 ld->pipe_err = PIPERR;
1364 /* Return here rather than inside the switch to prevent GCC warning */
1370 * This needs to be static, so that the SIGUSR1 handler can clear the "go"
1373 static loop_data ld;
1375 /* Do the low-level work of a capture.
1376 Returns TRUE if it succeeds, FALSE otherwise. */
1378 capture(gboolean *stats_known, struct pcap_stat *stats)
1383 gchar open_err_str[PCAP_ERRBUF_SIZE];
1384 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
1385 bpf_u_int32 netnum, netmask;
1386 struct bpf_program fcode;
1387 const char *set_linktype_err_str;
1388 time_t upd_time, cur_time;
1391 condition *cnd_stop_capturesize = NULL;
1392 condition *cnd_stop_timeout = NULL;
1393 condition *cnd_ring_timeout = NULL;
1394 static const char capstart_msg = SP_CAPSTART;
1395 char errmsg[4096+1];
1399 struct timeval timeout;
1400 capture_info capture_ui;
1403 WORD wVersionRequested;
1406 static const char ppamsg[] = "can't find PPA for ";
1410 struct pcap_hdr hdr;
1411 struct pcaprec_modified_hdr rechdr;
1412 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1414 #ifdef MUST_DO_SELECT
1418 /* Size of buffer to hold decimal representation of
1419 signed/unsigned 64-bit int */
1422 /* Initialize Windows Socket if we are in a WIN32 OS
1423 This needs to be done before querying the interface for network/netmask */
1425 /* XXX - do we really require 1.1 or earlier?
1426 Are there any versions that support only 2.0 or higher? */
1427 wVersionRequested = MAKEWORD(1, 1);
1428 err = WSAStartup(wVersionRequested, &wsaData);
1432 case WSASYSNOTREADY:
1433 snprintf(errmsg, sizeof errmsg,
1434 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
1437 case WSAVERNOTSUPPORTED:
1438 snprintf(errmsg, sizeof errmsg,
1439 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
1440 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
1443 case WSAEINPROGRESS:
1444 snprintf(errmsg, sizeof errmsg,
1445 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
1449 snprintf(errmsg, sizeof errmsg,
1450 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
1454 snprintf(errmsg, sizeof errmsg,
1455 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
1459 snprintf(errmsg, sizeof errmsg,
1460 "Couldn't initialize Windows Sockets: error %d", err);
1469 ld.counts.total = 0;
1470 if (capture_opts.has_autostop_count)
1471 ld.max = capture_opts.autostop_count;
1473 ld.max = 0; /* no limit */
1474 ld.err = 0; /* no error seen yet */
1475 ld.linktype = WTAP_ENCAP_UNKNOWN;
1476 ld.pcap_err = FALSE;
1477 ld.from_pipe = FALSE;
1478 ld.sync_packets = 0;
1486 ld.counts.netbios = 0;
1487 ld.counts.vines = 0;
1488 ld.counts.other = 0;
1492 /* We haven't yet gotten the capture statistics. */
1493 *stats_known = FALSE;
1495 /* Open the network interface to capture from it.
1496 Some versions of libpcap may put warnings into the error buffer
1497 if they succeed; to tell if that's happened, we have to clear
1498 the error buffer, and check if it's still a null string. */
1499 open_err_str[0] = '\0';
1500 pch = pcap_open_live(cfile.iface,
1501 capture_opts.has_snaplen ? capture_opts.snaplen :
1502 WTAP_MAX_PACKET_SIZE,
1503 capture_opts.promisc_mode, CAP_READ_TIMEOUT,
1507 /* setting the data link type only works on real interfaces */
1508 if (capture_opts.linktype != -1) {
1509 set_linktype_err_str = set_pcap_linktype(pch, cfile.iface,
1510 capture_opts.linktype);
1511 if (set_linktype_err_str != NULL) {
1512 snprintf(errmsg, sizeof errmsg, "Unable to set data link type (%s).",
1513 set_linktype_err_str);
1518 /* We couldn't open "cfile.iface" as a network device. */
1520 /* On Windows, we don't support capturing on pipes, so we give up.
1521 If this is a child process that does the capturing in sync
1522 mode or fork mode, it shouldn't do any UI stuff until we pop up the
1523 capture-progress window, and, since we couldn't start the
1524 capture, we haven't popped it up. */
1525 if (!capture_child) {
1526 while (gtk_events_pending()) gtk_main_iteration();
1529 /* On Win32 OSes, the capture devices are probably available to all
1530 users; don't warn about permissions problems.
1532 Do, however, warn that WAN devices aren't supported. */
1533 snprintf(errmsg, sizeof errmsg,
1534 "The capture session could not be initiated (%s).\n"
1535 "Please check that you have the proper interface specified.\n"
1537 "Note that the driver Ethereal uses for packet capture on Windows doesn't\n"
1538 "support capturing on PPP/WAN interfaces in Windows NT/2000/XP/.NET Server.\n",
1542 /* try to open cfile.iface as a pipe */
1543 pipe_fd = pipe_open_live(cfile.iface, &hdr, &ld, errmsg, sizeof errmsg);
1545 if (pipe_fd == -1) {
1547 /* If this is a child process that does the capturing in sync
1548 * mode or fork mode, it shouldn't do any UI stuff until we pop up the
1549 * capture-progress window, and, since we couldn't start the
1550 * capture, we haven't popped it up.
1552 if (!capture_child) {
1553 while (gtk_events_pending()) gtk_main_iteration();
1556 if (ld.pipe_err == PIPNEXIST) {
1557 /* Pipe doesn't exist, so output message for interface */
1559 /* If we got a "can't find PPA for XXX" message, warn the user (who
1560 is running Ethereal on HP-UX) that they don't have a version
1561 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1562 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1563 PPA for XXX" rather than "can't find PPA for XXX"). */
1564 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1567 "You are running Ethereal with a version of the libpcap library\n"
1568 "that doesn't handle HP-UX network devices well; this means that\n"
1569 "Ethereal may not be able to capture packets.\n"
1571 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1572 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1573 "packaged binary form from the Software Porting And Archive Centre\n"
1574 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1575 "at the URL lists a number of mirror sites.";
1578 snprintf(errmsg, sizeof errmsg,
1579 "The capture session could not be initiated (%s).\n"
1580 "Please check to make sure you have sufficient permissions, and that\n"
1581 "you have the proper interface or pipe specified.%s", open_err_str,
1585 * Else pipe (or file) does exist and pipe_open_live() has
1590 /* pipe_open_live() succeeded; don't want
1591 error message from pcap_open_live() */
1592 open_err_str[0] = '\0';
1596 /* capture filters only work on real interfaces */
1597 if (cfile.cfilter && !ld.from_pipe) {
1598 /* A capture filter was specified; set it up. */
1599 if (pcap_lookupnet(cfile.iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1601 * Well, we can't get the netmask for this interface; it's used
1602 * only for filters that check for broadcast IP addresses, so
1603 * we just punt and use 0. It might be nice to warn the user,
1604 * but that's a pain in a GUI application, as it'd involve popping
1605 * up a message box, and it's not clear how often this would make
1606 * a difference (only filters that check for IP broadcast addresses
1611 if (pcap_compile(pch, &fcode, cfile.cfilter, 1, netmask) < 0) {
1612 dfilter_t *rfcode = NULL;
1613 if (dfilter_compile(cfile.cfilter, &rfcode)) {
1614 snprintf(errmsg, sizeof errmsg,
1615 "Unable to parse capture filter string (%s).\n"
1616 " Interestingly enough, this looks like a valid display filter\n"
1617 " Are you sure you didn't mix them up?",
1619 dfilter_free(rfcode);
1621 snprintf(errmsg, sizeof errmsg,
1622 "Unable to parse capture filter string (%s).",
1627 if (pcap_setfilter(pch, &fcode) < 0) {
1628 snprintf(errmsg, sizeof errmsg, "Can't install filter (%s).",
1634 /* Set up to write to the capture file. */
1637 pcap_encap = hdr.network;
1638 file_snaplen = hdr.snaplen;
1642 pcap_encap = get_pcap_linktype(pch, cfile.iface);
1643 file_snaplen = pcap_snapshot(pch);
1645 ld.linktype = wtap_pcap_encap_to_wtap_encap(pcap_encap);
1646 if (ld.linktype == WTAP_ENCAP_UNKNOWN) {
1647 snprintf(errmsg, sizeof errmsg,
1648 "The network you're capturing from is of a type"
1649 " that Ethereal doesn't support (data link type %d).", pcap_encap);
1652 if (capture_opts.ringbuffer_on) {
1653 ld.pdh = ringbuf_init_wtap_dump_fdopen(WTAP_FILE_PCAP, ld.linktype,
1654 file_snaplen, &err);
1656 ld.pdh = wtap_dump_fdopen(cfile.save_file_fd, WTAP_FILE_PCAP,
1657 ld.linktype, file_snaplen, &err);
1660 if (ld.pdh == NULL) {
1661 /* We couldn't set up to write to the capture file. */
1664 case WTAP_ERR_CANT_OPEN:
1665 strcpy(errmsg, "The file to which the capture would be saved"
1666 " couldn't be created for some unknown reason.");
1669 case WTAP_ERR_SHORT_WRITE:
1670 strcpy(errmsg, "A full header couldn't be written to the file"
1671 " to which the capture would be saved.");
1676 snprintf(errmsg, sizeof(errmsg),
1677 "The file to which the capture would be"
1678 " saved (\"%s\") could not be opened: Error %d.",
1679 cfile.save_file, err);
1681 snprintf(errmsg, sizeof(errmsg),
1682 "The file to which the capture would be"
1683 " saved (\"%s\") could not be opened: %s.",
1684 cfile.save_file, strerror(err));
1691 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1692 returned a warning; print it, but keep capturing. */
1693 if (open_err_str[0] != '\0')
1694 g_warning("%s.", open_err_str);
1696 /* XXX - capture SIGTERM and close the capture, in case we're on a
1697 Linux 2.0[.x] system and you have to explicitly close the capture
1698 stream in order to turn promiscuous mode off? We need to do that
1699 in other places as well - and I don't think that works all the
1700 time in any case, due to libpcap bugs. */
1702 if (capture_child) {
1703 /* Well, we should be able to start capturing.
1705 This is the child process for a sync mode capture, so sync out
1706 the capture file, so the header makes it to the file system,
1707 and send a "capture started successfully and capture file created"
1708 message to our parent so that they'll open the capture file and
1709 update its windows to indicate that we have a live capture in
1711 fflush(wtap_dump_file(ld.pdh));
1712 write(1, &capstart_msg, 1);
1715 /* start capture info dialog */
1716 capture_ui.callback_data = &ld;
1717 capture_ui.counts = &ld.counts;
1718 capture_info_create(&capture_ui);
1720 start_time = time(NULL);
1721 upd_time = time(NULL);
1722 #ifdef MUST_DO_SELECT
1723 if (!ld.from_pipe) pcap_fd = pcap_fileno(pch);
1728 * Catch SIGUSR1, so that we exit cleanly if the parent process
1729 * kills us with it due to the user selecting "Capture->Stop".
1732 signal(SIGUSR1, stop_capture);
1734 /* initialize capture stop conditions */
1735 init_capture_stop_conditions();
1736 /* create stop conditions */
1737 if (capture_opts.has_autostop_filesize)
1738 cnd_stop_capturesize =
1739 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts.autostop_filesize * 1000);
1740 if (capture_opts.has_autostop_duration)
1742 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts.autostop_duration);
1744 if (capture_opts.ringbuffer_on && capture_opts.has_ring_duration)
1746 cnd_new(CND_CLASS_TIMEOUT, capture_opts.ringbuffer_duration);
1749 /* WOW, everything is prepared! */
1750 /* please fasten your seat belts, we will enter now the actual capture loop */
1752 while (gtk_events_pending()) gtk_main_iteration();
1757 FD_SET(pipe_fd, &set1);
1759 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1760 sel_ret = select(pipe_fd+1, &set1, NULL, NULL, &timeout);
1763 if (sel_ret < 0 && errno != EINTR) {
1764 snprintf(errmsg, sizeof(errmsg),
1765 "Unexpected error from select: %s", strerror(errno));
1766 popup_errmsg(errmsg);
1771 * "select()" says we can read from the pipe without blocking
1773 inpkts = pipe_dispatch(pipe_fd, &ld, &hdr, &rechdr, pcap_data,
1774 errmsg, sizeof errmsg);
1783 #ifdef MUST_DO_SELECT
1785 * Sigh. The semantics of the read timeout argument to
1786 * "pcap_open_live()" aren't particularly well specified by
1787 * the "pcap" man page - at least with the BSD BPF code, the
1788 * intent appears to be, at least in part, a way of cutting
1789 * down the number of reads done on a capture, by blocking
1790 * until the buffer fills or a timer expires - and the Linux
1791 * libpcap doesn't actually support it, so we can't use it
1792 * to break out of the "pcap_dispatch()" every 1/4 of a second
1793 * or so. Linux's libpcap is not the only libpcap that doesn't
1794 * support the read timeout.
1796 * Furthermore, at least on Solaris, the bufmod STREAMS module's
1797 * read timeout won't go off if no data has arrived, i.e. it cannot
1798 * be used to guarantee that a read from a DLPI stream will return
1799 * within a specified amount of time regardless of whether any
1800 * data arrives or not.
1802 * Thus, on all platforms other than BSD, we do a "select()" on the
1803 * file descriptor for the capture, with a timeout of CAP_READ_TIMEOUT
1804 * milliseconds, or CAP_READ_TIMEOUT*1000 microseconds.
1806 * "select()", on BPF devices, doesn't work as you might expect;
1807 * at least on some versions of some flavors of BSD, the timer
1808 * doesn't start until a read is done, so it won't expire if
1809 * only a "select()" or "poll()" is posted.
1812 FD_SET(pcap_fd, &set1);
1814 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1815 sel_ret = select(pcap_fd+1, &set1, NULL, NULL, &timeout);
1818 * "select()" says we can read from it without blocking; go for
1821 inpkts = pcap_dispatch(pch, 1, capture_pcap_cb, (guchar *) &ld);
1828 if (sel_ret < 0 && errno != EINTR) {
1829 snprintf(errmsg, sizeof(errmsg),
1830 "Unexpected error from select: %s", strerror(errno));
1831 popup_errmsg(errmsg);
1836 inpkts = pcap_dispatch(pch, 1, capture_pcap_cb, (guchar *) &ld);
1845 ld.sync_packets += inpkts;
1846 /* check capture stop conditons */
1847 if (cnd_stop_capturesize != NULL && cnd_eval(cnd_stop_capturesize,
1848 (guint32)wtap_get_bytes_dumped(ld.pdh))){
1849 /* Capture file reached its maximum size. */
1850 if (capture_opts.ringbuffer_on) {
1851 /* Switch to the next ringbuffer file */
1852 if (ringbuf_switch_file(&cfile, &ld.pdh, &ld.err)) {
1853 /* File switch succeeded: reset the condition */
1854 cnd_reset(cnd_stop_capturesize);
1855 if (cnd_ring_timeout) {
1856 cnd_reset(cnd_ring_timeout);
1859 /* File switch failed: stop here */
1864 /* no ringbuffer - just stop */
1870 /* Only update once a second so as not to overload slow displays */
1871 cur_time = time(NULL);
1872 if (cur_time > upd_time) {
1873 upd_time = cur_time;
1875 /*if (pcap_stats(pch, stats) >= 0) {
1876 *stats_known = TRUE;
1879 /* Let the parent process know. */
1880 /* calculate and display running time */
1881 cur_time -= start_time;
1882 capture_ui.running_time = cur_time;
1883 capture_ui.new_packets = ld.sync_packets;
1884 capture_info_update(&capture_ui);
1886 if (ld.sync_packets) {
1888 fflush(wtap_dump_file(ld.pdh));
1890 if (capture_child) {
1891 /* This is the child process for a sync mode capture, so send
1892 our parent a message saying we've written out "ld.sync_packets"
1893 packets to the capture file. */
1894 char tmp[DECISIZE+1+1];
1895 sprintf(tmp, "%d%c", ld.sync_packets, SP_PACKET_COUNT);
1896 write(1, tmp, strlen(tmp));
1899 ld.sync_packets = 0;
1903 if (cnd_stop_timeout != NULL && cnd_eval(cnd_stop_timeout)) {
1904 /* The specified capture time has elapsed; stop the capture. */
1906 } else if (cnd_ring_timeout != NULL && cnd_eval(cnd_ring_timeout)) {
1907 /* time elasped for this ring file, swith to the next */
1908 if (ringbuf_switch_file(&cfile, &ld.pdh, &ld.err)) {
1909 /* File switch succeeded: reset the condition */
1910 cnd_reset(cnd_ring_timeout);
1912 /* File switch failed: stop here */
1918 } /* while (ld.go) */
1920 /* delete stop conditions */
1921 if (cnd_stop_capturesize != NULL)
1922 cnd_delete(cnd_stop_capturesize);
1923 if (cnd_stop_timeout != NULL)
1924 cnd_delete(cnd_stop_timeout);
1925 if (cnd_ring_timeout != NULL)
1926 cnd_delete(cnd_ring_timeout);
1929 snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
1931 popup_errmsg(errmsg);
1935 } else if (ld.from_pipe && ld.pipe_err == PIPERR)
1936 popup_errmsg(errmsg);
1942 get_capture_file_io_error(errmsg, sizeof(errmsg), cfile.save_file, ld.err,
1944 popup_errmsg(errmsg);
1948 if (capture_opts.ringbuffer_on) {
1949 close_ok = ringbuf_wtap_dump_close(&cfile, &err);
1951 close_ok = wtap_dump_close(ld.pdh, &err);
1953 /* If we've displayed a message about a write error, there's no point
1954 in displaying another message about an error on close. */
1955 if (!close_ok && write_ok) {
1956 get_capture_file_io_error(errmsg, sizeof(errmsg), cfile.save_file, err,
1958 popup_errmsg(errmsg);
1960 /* Set write_ok to mean the write and the close were successful. */
1961 write_ok = (write_ok && close_ok);
1965 * XXX We exhibit different behaviour between normal mode and sync mode
1966 * when the pipe is stdin and not already at EOF. If we're a child, the
1967 * parent's stdin isn't closed, so if the user starts another capture,
1968 * pipe_open_live() will very likely not see the expected magic bytes and
1969 * will say "Unrecognized libpcap format". On the other hand, in normal
1970 * mode, pipe_open_live() will say "End of file on pipe during open".
1972 if (ld.from_pipe && pipe_fd >= 0)
1977 /* Get the capture statistics, so we know how many packets were
1979 if (pcap_stats(pch, stats) >= 0) {
1980 *stats_known = TRUE;
1981 if (capture_child) {
1982 /* Let the parent process know. */
1983 char tmp[DECISIZE+1+1];
1984 sprintf(tmp, "%d%c", stats->ps_drop, SP_DROPS);
1985 write(1, tmp, strlen(tmp));
1988 snprintf(errmsg, sizeof(errmsg),
1989 "Can't get packet-drop statistics: %s",
1991 popup_errmsg(errmsg);
1997 /* Shut down windows sockets */
2001 capture_info_destroy(&capture_ui);
2006 if (capture_opts.ringbuffer_on) {
2007 /* cleanup ringbuffer */
2008 ringbuf_error_cleanup();
2010 /* We can't use the save file, and we have no wtap_dump stream
2011 to close in order to close it, so close the FD directly. */
2012 close(cfile.save_file_fd);
2014 /* We couldn't even start the capture, so get rid of the capture
2016 unlink(cfile.save_file); /* silently ignore error */
2017 g_free(cfile.save_file);
2019 cfile.save_file = NULL;
2020 popup_errmsg(errmsg);
2037 get_capture_file_io_error(char *errmsg, int errmsglen, const char *fname,
2038 int err, gboolean is_close)
2043 snprintf(errmsg, errmsglen,
2044 "Not all the packets could be written to the file"
2045 " to which the capture was being saved\n"
2046 "(\"%s\") because there is no space left on the file system\n"
2047 "on which that file resides.",
2053 snprintf(errmsg, errmsglen,
2054 "Not all the packets could be written to the file"
2055 " to which the capture was being saved\n"
2056 "(\"%s\") because you are too close to, or over,"
2057 " your disk quota\n"
2058 "on the file system on which that file resides.",
2063 case WTAP_ERR_CANT_CLOSE:
2064 snprintf(errmsg, errmsglen,
2065 "The file to which the capture was being saved"
2066 " couldn't be closed for some unknown reason.");
2069 case WTAP_ERR_SHORT_WRITE:
2070 snprintf(errmsg, errmsglen,
2071 "Not all the packets could be written to the file"
2072 " to which the capture was being saved\n"
2079 snprintf(errmsg, errmsglen,
2080 "The file to which the capture was being saved\n"
2081 "(\"%s\") could not be closed: %s.",
2082 fname, wtap_strerror(err));
2084 snprintf(errmsg, errmsglen,
2085 "An error occurred while writing to the file"
2086 " to which the capture was being saved\n"
2088 fname, wtap_strerror(err));
2095 popup_errmsg(const char *errmsg)
2097 if (capture_child) {
2098 /* This is the child process for a sync mode capture.
2099 Send the error message to our parent, so they can display a
2100 dialog box containing it. */
2101 send_errmsg_to_parent(errmsg);
2103 /* Display the dialog box ourselves; there's no parent. */
2104 simple_dialog(ESD_TYPE_CRIT, NULL, "%s", errmsg);
2109 send_errmsg_to_parent(const char *errmsg)
2111 int msglen = strlen(errmsg);
2112 char lenbuf[DECISIZE+1+1];
2114 sprintf(lenbuf, "%u%c", msglen, SP_ERROR_MSG);
2115 write(1, lenbuf, strlen(lenbuf));
2116 write(1, errmsg, msglen);
2120 stop_capture(int signo _U_)
2125 void capture_ui_stop_callback(
2126 gpointer callback_data)
2128 loop_data *ld = (loop_data *) callback_data;
2138 * XXX - find some way of signaling the child in Win32.
2141 if (fork_child != -1)
2142 kill(fork_child, SIGUSR1);
2147 kill_capture_child(void)
2150 * XXX - find some way of signaling the child in Win32.
2153 if (fork_child != -1)
2154 kill(fork_child, SIGTERM); /* SIGTERM so it can clean up if necessary */
2159 capture_pcap_cb(guchar *user, const struct pcap_pkthdr *phdr,
2162 struct wtap_pkthdr whdr;
2163 union wtap_pseudo_header pseudo_header;
2164 loop_data *ld = (loop_data *) user;
2167 if ((++ld->counts.total >= ld->max) && (ld->max > 0))
2172 /* Convert from libpcap to Wiretap format.
2173 If that fails, set "ld->go" to FALSE, to stop the capture, and set
2174 "ld->err" to the error. */
2175 pd = wtap_process_pcap_packet(ld->linktype, phdr, pd, &pseudo_header,
2184 /* We're supposed to write the packet to a file; do so.
2185 If this fails, set "ld->go" to FALSE, to stop the capture, and set
2186 "ld->err" to the error. */
2187 if (!wtap_dump(ld->pdh, &whdr, &pseudo_header, pd, &err)) {
2193 switch (ld->linktype) {
2194 case WTAP_ENCAP_ETHERNET:
2195 capture_eth(pd, 0, whdr.caplen, &ld->counts);
2197 case WTAP_ENCAP_FDDI:
2198 case WTAP_ENCAP_FDDI_BITSWAPPED:
2199 capture_fddi(pd, whdr.caplen, &ld->counts);
2201 case WTAP_ENCAP_PRISM_HEADER:
2202 capture_prism(pd, 0, whdr.caplen, &ld->counts);
2204 case WTAP_ENCAP_TOKEN_RING:
2205 capture_tr(pd, 0, whdr.caplen, &ld->counts);
2207 case WTAP_ENCAP_NULL:
2208 capture_null(pd, whdr.caplen, &ld->counts);
2210 case WTAP_ENCAP_PPP:
2211 capture_ppp_hdlc(pd, 0, whdr.caplen, &ld->counts);
2213 case WTAP_ENCAP_RAW_IP:
2214 capture_raw(pd, whdr.caplen, &ld->counts);
2216 case WTAP_ENCAP_SLL:
2217 capture_sll(pd, whdr.caplen, &ld->counts);
2219 case WTAP_ENCAP_LINUX_ATM_CLIP:
2220 capture_clip(pd, whdr.caplen, &ld->counts);
2222 case WTAP_ENCAP_IEEE_802_11:
2223 case WTAP_ENCAP_IEEE_802_11_WITH_RADIO:
2224 capture_ieee80211(pd, 0, whdr.caplen, &ld->counts);
2226 case WTAP_ENCAP_CHDLC:
2227 capture_chdlc(pd, 0, whdr.caplen, &ld->counts);
2229 case WTAP_ENCAP_LOCALTALK:
2230 capture_llap(&ld->counts);
2232 case WTAP_ENCAP_ATM_PDUS:
2233 capture_atm(&pseudo_header, pd, whdr.caplen, &ld->counts);
2235 case WTAP_ENCAP_IP_OVER_FC:
2236 capture_ipfc(pd, whdr.caplen, &ld->counts);
2238 case WTAP_ENCAP_ARCNET:
2239 capture_arcnet(pd, whdr.caplen, &ld->counts, FALSE, TRUE);
2241 case WTAP_ENCAP_ARCNET_LINUX:
2242 capture_arcnet(pd, whdr.caplen, &ld->counts, TRUE, FALSE);
2244 /* XXX - some ATM drivers on FreeBSD might prepend a 4-byte ATM
2245 pseudo-header to DLT_ATM_RFC1483, with LLC header following;
2246 we might have to implement that at some point. */
2250 #endif /* HAVE_LIBPCAP */