2 * Routines for packet capture windows
4 * $Id: capture.c,v 1.213 2003/11/01 02:30:14 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 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
110 * want to include it if it's not present on this platform, however.
112 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__bsdi__) || defined(__APPLE__)
116 #endif /* defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__bsdi__) || defined(__APPLE__) */
119 * We don't want to do a "select()" on the pcap_t's file descriptor on
120 * BSD (because "select()" doesn't work correctly on BPF devices on at
121 * least some releases of some flavors of BSD), and we don't want to do
122 * it on Windows (because "select()" is something for sockets, not for
123 * arbitrary handles).
125 * We *do* want to do it on other platforms, as, on other platforms (with
126 * the possible exception of Ultrix and Digital UNIX), the read timeout
127 * doesn't expire if no packets have arrived, so a "pcap_dispatch()" call
128 * will block until packets arrive, causing the UI to hang.
130 #if !defined(BSD) && !defined(_WIN32)
131 # define MUST_DO_SELECT
134 #include <epan/packet.h>
135 #include <epan/dfilter/dfilter.h>
139 #include "pcap-util.h"
140 #include "simple_dialog.h"
143 #include "conditions.h"
144 #include "capture_stop_conditions.h"
145 #include "ringbuffer.h"
147 #include "wiretap/libpcap.h"
148 #include "wiretap/wtap.h"
149 #include "wiretap/wtap-capture.h"
151 #include "packet-atalk.h"
152 #include "packet-atm.h"
153 #include "packet-clip.h"
154 #include "packet-eth.h"
155 #include "packet-fddi.h"
156 #include "packet-null.h"
157 #include "packet-ppp.h"
158 #include "packet-raw.h"
159 #include "packet-sll.h"
160 #include "packet-tr.h"
161 #include "packet-ieee80211.h"
162 #include "packet-chdlc.h"
163 #include "packet-prism.h"
164 #include "packet-ipfc.h"
165 #include "packet-arcnet.h"
168 #include "capture-wpcap.h"
174 capture_options capture_opts;
176 static int sync_pipe[2]; /* used to sync father */
177 enum PIPES { READ, WRITE }; /* Constants 0 and 1 for READ and WRITE */
178 int quit_after_cap; /* Makes a "capture only mode". Implies -k */
179 gboolean capture_child; /* if this is the child for "-S" */
180 static int fork_child = -1; /* If not -1, in parent, process ID of child */
181 static guint cap_input_id;
184 * Indications sent out on the sync pipe.
186 #define SP_CAPSTART ';' /* capture start message */
187 #define SP_PACKET_COUNT '*' /* followed by count of packets captured since last message */
188 #define SP_ERROR_MSG '!' /* followed by length of error message that follows */
189 #define SP_DROPS '#' /* followed by count of packets dropped in capture */
192 static guint cap_timer_id;
193 static int cap_timer_cb(gpointer); /* Win32 kludge to check for pipe input */
196 static void cap_file_input_cb(gpointer, gint, GdkInputCondition);
197 static void wait_for_child(gboolean);
199 static char *signame(int);
201 static void capture_delete_cb(GtkWidget *, GdkEvent *, gpointer);
202 static void capture_stop_cb(GtkWidget *, gpointer);
203 static void capture_pcap_cb(guchar *, const struct pcap_pkthdr *,
205 static void get_capture_file_io_error(char *, int, const char *, int, gboolean);
206 static void popup_errmsg(const char *);
207 static void send_errmsg_to_parent(const char *);
208 static float pct(gint, gint);
209 static void stop_capture(int signo);
211 typedef struct _loop_data {
212 gboolean go; /* TRUE as long as we're supposed to keep capturing */
213 gint max; /* Number of packets we're supposed to capture - 0 means infinite */
214 int err; /* if non-zero, error seen while capturing */
217 gboolean pcap_err; /* TRUE if error from pcap */
218 gboolean from_pipe; /* TRUE if we are capturing data from a pipe */
219 packet_counts counts;
222 gboolean modified; /* TRUE if data in the pipe uses modified pcap headers */
223 gboolean byte_swapped; /* TRUE if data in the pipe is byte swapped */
224 unsigned int bytes_to_read, bytes_read; /* Used by pipe_dispatch */
226 STATE_EXPECT_REC_HDR, STATE_READ_REC_HDR,
227 STATE_EXPECT_DATA, STATE_READ_DATA
230 enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } pipe_err;
235 static void adjust_header(loop_data *, struct pcap_hdr *, struct pcaprec_hdr *);
236 static int pipe_open_live(char *, struct pcap_hdr *, loop_data *, char *, int);
237 static int pipe_dispatch(int, loop_data *, struct pcap_hdr *, \
238 struct pcaprec_modified_hdr *, guchar *, char *, int);
241 /* Win32 needs the O_BINARY flag for open() */
247 /* Win32 needs a handle to the child capture process */
251 /* Add a string pointer to a NULL-terminated array of string pointers. */
253 add_arg(char **args, int *argc, char *arg)
255 /* Grow the array; "*argc" currently contains the number of string
256 pointers, *not* counting the NULL pointer at the end, so we have
257 to add 2 in order to get the new size of the array, including the
258 new pointer and the terminating NULL pointer. */
259 args = g_realloc(args, (*argc + 2) * sizeof (char *));
261 /* Stuff the pointer into the penultimate element of the array, which
262 is the one at the index specified by "*argc". */
265 /* Now bump the count. */
268 /* We overwrite the NULL pointer; put it back right after the
276 /* Given a string, return a pointer to a quote-encapsulated version of
277 the string, so we can pass it as an argument with "spawnvp" even
278 if it contains blanks. */
280 quote_encapsulate(const char *string)
282 char *encapsulated_string;
284 encapsulated_string = g_new(char, strlen(string) + 3);
285 sprintf(encapsulated_string, "\"%s\"", string);
286 return encapsulated_string;
290 /* Open a specified file, or create a temporary file, and start a capture
291 to the file in question. Returns TRUE if the capture starts
292 successfully, FALSE otherwise. */
294 do_capture(const char *save_file)
297 gboolean is_tempfile;
303 int capture_succeeded;
304 gboolean stats_known;
305 struct pcap_stat stats;
308 if (save_file != NULL) {
309 /* If the Sync option is set, we return to the caller while the capture
310 * is in progress. Therefore we need to take a copy of save_file in
311 * case the caller destroys it after we return.
313 capfile_name = g_strdup(save_file);
314 if (capture_opts.ringbuffer_on) {
315 /* ringbuffer is enabled */
316 cfile.save_file_fd = ringbuf_init(capfile_name,
317 capture_opts.ringbuffer_num_files);
319 /* Try to open/create the specified file for use as a capture buffer. */
320 cfile.save_file_fd = open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT,
325 /* Choose a random name for the capture buffer */
326 cfile.save_file_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
327 capfile_name = g_strdup(tmpname);
330 if (cfile.save_file_fd == -1) {
332 simple_dialog(ESD_TYPE_CRIT, NULL,
333 "The temporary file to which the capture would be saved (\"%s\")"
334 "could not be opened: %s.", capfile_name, strerror(errno));
336 if (capture_opts.ringbuffer_on) {
337 ringbuf_error_cleanup();
339 simple_dialog(ESD_TYPE_CRIT, NULL,
340 file_open_error_message(errno, TRUE, WTAP_FILE_PCAP), capfile_name);
342 g_free(capfile_name);
346 g_assert(cfile.save_file == NULL);
347 cfile.save_file = capfile_name;
348 /* cfile.save_file is "g_free"ed below, which is equivalent to
349 "g_free(capfile_name)". */
351 if (capture_opts.sync_mode) { /* do the capture in a child process */
353 char scount[24]; /* need a constant for len of numbers */
354 char sautostop_filesize[24]; /* need a constant for len of numbers */
355 char sautostop_duration[24]; /* need a constant for len of numbers */
356 char save_file_fd[24];
362 char sync_pipe_fd[24];
367 /* Allocate the string pointer array with enough space for the
368 terminating NULL pointer. */
370 argv = g_malloc(sizeof (char *));
373 /* Now add those arguments used on all platforms. */
374 argv = add_arg(argv, &argc, CHILD_NAME);
376 argv = add_arg(argv, &argc, "-i");
377 argv = add_arg(argv, &argc, cfile.iface);
379 argv = add_arg(argv, &argc, "-w");
380 argv = add_arg(argv, &argc, cfile.save_file);
382 argv = add_arg(argv, &argc, "-W");
383 sprintf(save_file_fd,"%d",cfile.save_file_fd); /* in lieu of itoa */
384 argv = add_arg(argv, &argc, save_file_fd);
386 if (capture_opts.has_autostop_count) {
387 argv = add_arg(argv, &argc, "-c");
388 sprintf(scount,"%d",capture_opts.autostop_count);
389 argv = add_arg(argv, &argc, scount);
392 if (capture_opts.has_snaplen) {
393 argv = add_arg(argv, &argc, "-s");
394 sprintf(ssnap,"%d",capture_opts.snaplen);
395 argv = add_arg(argv, &argc, ssnap);
398 if (capture_opts.linktype != -1) {
399 argv = add_arg(argv, &argc, "-y");
400 sprintf(ssnap,"%d",capture_opts.linktype);
401 argv = add_arg(argv, &argc, ssnap);
404 if (capture_opts.has_autostop_filesize) {
405 argv = add_arg(argv, &argc, "-a");
406 sprintf(sautostop_filesize,"filesize:%d",capture_opts.autostop_filesize);
407 argv = add_arg(argv, &argc, sautostop_filesize);
410 if (capture_opts.has_autostop_duration) {
411 argv = add_arg(argv, &argc, "-a");
412 sprintf(sautostop_duration,"duration:%d",capture_opts.autostop_duration);
413 argv = add_arg(argv, &argc, sautostop_duration);
416 if (!capture_opts.promisc_mode)
417 argv = add_arg(argv, &argc, "-p");
420 /* Create a pipe for the child process */
422 if(_pipe(sync_pipe, 512, O_BINARY) < 0) {
423 /* Couldn't create the pipe between parent and child. */
425 unlink(cfile.save_file);
426 g_free(cfile.save_file);
427 cfile.save_file = NULL;
428 simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create sync pipe: %s",
433 /* Convert font name to a quote-encapsulated string and pass to child */
434 argv = add_arg(argv, &argc, "-m");
435 fontstring = quote_encapsulate(prefs.gui_font_name);
436 argv = add_arg(argv, &argc, fontstring);
438 /* Convert pipe write handle to a string and pass to child */
439 argv = add_arg(argv, &argc, "-Z");
440 itoa(sync_pipe[WRITE], sync_pipe_fd, 10);
441 argv = add_arg(argv, &argc, sync_pipe_fd);
443 /* Convert filter string to a quote delimited string and pass to child */
445 if (cfile.cfilter != NULL && strlen(cfile.cfilter) != 0) {
446 argv = add_arg(argv, &argc, "-f");
447 filterstring = quote_encapsulate(cfile.cfilter);
448 argv = add_arg(argv, &argc, filterstring);
452 fork_child = spawnvp(_P_NOWAIT, ethereal_path, argv);
455 g_free(filterstring);
457 /* Keep a copy for later evaluation by _cwait() */
458 child_process = fork_child;
460 if (pipe(sync_pipe) < 0) {
461 /* Couldn't create the pipe between parent and child. */
463 unlink(cfile.save_file);
464 g_free(cfile.save_file);
465 cfile.save_file = NULL;
466 simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create sync pipe: %s",
471 argv = add_arg(argv, &argc, "-m");
472 argv = add_arg(argv, &argc, prefs.gui_font_name);
474 if (cfile.cfilter != NULL && strlen(cfile.cfilter) != 0) {
475 argv = add_arg(argv, &argc, "-f");
476 argv = add_arg(argv, &argc, cfile.cfilter);
479 if ((fork_child = fork()) == 0) {
481 * Child process - run Ethereal with the right arguments to make
482 * it just pop up the live capture dialog box and capture with
483 * the specified capture parameters, writing to the specified file.
485 * args: -i interface specification
487 * -W file descriptor to write
488 * -c count to capture
491 * -f "filter expression"
494 dup(sync_pipe[WRITE]);
495 close(sync_pipe[READ]);
496 execvp(ethereal_path, argv);
497 snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
498 ethereal_path, strerror(errno));
499 send_errmsg_to_parent(errmsg);
501 /* Exit with "_exit()", so that we don't close the connection
502 to the X server (and cause stuff buffered up by our parent but
503 not yet sent to be sent, as that stuff should only be sent by
509 /* Parent process - read messages from the child process over the
511 g_free(argv); /* free up arg array */
513 /* Close the write side of the pipe, so that only the child has it
514 open, and thus it completely closes, and thus returns to us
515 an EOF indication, if the child closes it (either deliberately
516 or by exiting abnormally). */
517 close(sync_pipe[WRITE]);
519 /* Close the save file FD, as we won't be using it - we'll be opening
520 it and reading the save file through Wiretap. */
521 close(cfile.save_file_fd);
523 if (fork_child == -1) {
524 /* We couldn't even create the child process. */
526 close(sync_pipe[READ]);
527 unlink(cfile.save_file);
528 g_free(cfile.save_file);
529 cfile.save_file = NULL;
530 simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create child process: %s",
535 /* Read a byte count from "sync_pipe[READ]", terminated with a
536 colon; if the count is 0, the child process created the
537 capture file and we should start reading from it, otherwise
538 the capture couldn't start and the count is a count of bytes
539 of error message, and we should display the message. */
542 i = read(sync_pipe[READ], &c, 1);
544 /* EOF - the child process died.
545 Close the read side of the sync pipe, remove the capture file,
546 and report the failure. */
547 close(sync_pipe[READ]);
548 unlink(cfile.save_file);
549 g_free(cfile.save_file);
550 cfile.save_file = NULL;
551 wait_for_child(TRUE);
554 if (c == SP_CAPSTART || c == SP_ERROR_MSG)
557 /* Child process handed us crap.
558 Close the read side of the sync pipe, remove the capture file,
559 and report the failure. */
560 close(sync_pipe[READ]);
561 unlink(cfile.save_file);
562 g_free(cfile.save_file);
563 cfile.save_file = NULL;
564 simple_dialog(ESD_TYPE_WARN, NULL,
565 "Capture child process sent us a bad message");
568 byte_count = byte_count*10 + c - '0';
570 if (c != SP_CAPSTART) {
571 /* Failure - the child process sent us a message indicating
572 what the problem was. */
573 if (byte_count == 0) {
574 /* Zero-length message? */
575 simple_dialog(ESD_TYPE_WARN, NULL,
576 "Capture child process failed, but its error message was empty.");
578 msg = g_malloc(byte_count + 1);
580 simple_dialog(ESD_TYPE_WARN, NULL,
581 "Capture child process failed, but its error message was too big.");
583 i = read(sync_pipe[READ], msg, byte_count);
584 msg[byte_count] = '\0';
586 simple_dialog(ESD_TYPE_WARN, NULL,
587 "Capture child process failed: Error %s reading its error message.",
590 simple_dialog(ESD_TYPE_WARN, NULL,
591 "Capture child process failed: EOF reading its error message.");
592 wait_for_child(FALSE);
594 simple_dialog(ESD_TYPE_CRIT, NULL, msg);
598 /* Close the sync pipe. */
599 close(sync_pipe[READ]);
601 /* Get rid of the save file - the capture never started. */
602 unlink(cfile.save_file);
603 g_free(cfile.save_file);
604 cfile.save_file = NULL;
609 /* The child process started a capture.
610 Attempt to open the capture file and set up to read it. */
611 err = cf_start_tail(cfile.save_file, is_tempfile, &cfile);
613 /* We weren't able to open the capture file; user has been
614 alerted. Close the sync pipe. */
616 close(sync_pipe[READ]);
618 /* Don't unlink the save file - leave it around, for debugging
620 g_free(cfile.save_file);
621 cfile.save_file = NULL;
624 /* We were able to open and set up to read the capture file;
625 arrange that our callback be called whenever it's possible
626 to read from the sync pipe, so that it's called when
627 the child process wants to tell us something. */
629 /* Tricky to use pipes in win9x, as no concept of wait. NT can
630 do this but that doesn't cover all win32 platforms. GTK can do
631 this but doesn't seem to work over processes. Attempt to do
632 something similar here, start a timer and check for data on every
634 cap_timer_id = gtk_timeout_add(1000, cap_timer_cb, NULL);
636 cap_input_id = gtk_input_add_full(sync_pipe[READ],
637 GDK_INPUT_READ|GDK_INPUT_EXCEPTION,
645 capture_succeeded = capture(&stats_known, &stats);
646 if (quit_after_cap) {
647 /* DON'T unlink the save file. Presumably someone wants it. */
650 if (!capture_succeeded) {
651 /* We didn't succeed in doing the capture, so we don't have a save
653 if (capture_opts.ringbuffer_on) {
656 g_free(cfile.save_file);
658 cfile.save_file = NULL;
661 /* Capture succeeded; attempt to read in the capture file. */
662 if ((err = cf_open(cfile.save_file, is_tempfile, &cfile)) != 0) {
663 /* We're not doing a capture any more, so we don't have a save
665 if (capture_opts.ringbuffer_on) {
668 g_free(cfile.save_file);
670 cfile.save_file = NULL;
674 /* Set the read filter to NULL. */
677 /* Get the packet-drop statistics.
679 XXX - there are currently no packet-drop statistics stored
680 in libpcap captures, and that's what we're reading.
682 At some point, we will add support in Wiretap to return
683 packet-drop statistics for capture file formats that store it,
684 and will make "cf_read()" get those statistics from Wiretap.
685 We clear the statistics (marking them as "not known") in
686 "cf_open()", and "cf_read()" will only fetch them and mark
687 them as known if Wiretap supplies them, so if we get the
688 statistics now, after calling "cf_open()" but before calling
689 "cf_read()", the values we store will be used by "cf_read()".
691 If a future libpcap capture file format stores the statistics,
692 we'll put them into the capture file that we write, and will
693 thus not have to set them here - "cf_read()" will get them from
694 the file and use them. */
696 cfile.drops_known = TRUE;
698 /* XXX - on some systems, libpcap doesn't bother filling in
699 "ps_ifdrop" - it doesn't even set it to zero - so we don't
700 bother looking at it.
702 Ideally, libpcap would have an interface that gave us
703 several statistics - perhaps including various interface
704 error statistics - and would tell us which of them it
705 supplies, allowing us to display only the ones it does. */
706 cfile.drops = stats.ps_drop;
708 switch (cf_read(&cfile, &err)) {
712 /* Just because we got an error, that doesn't mean we were unable
713 to read any of the file; we handle what we could get from the
718 /* Exit by leaving the main loop, so that any quit functions
719 we registered get called. */
720 if (gtk_main_level() > 0)
725 /* We're not doing a capture any more, so we don't have a save
727 if (capture_opts.ringbuffer_on) {
730 g_free(cfile.save_file);
732 cfile.save_file = NULL;
738 /* The timer has expired, see if there's stuff to read from the pipe,
739 if so call the cap_file_input_cb */
741 cap_timer_cb(gpointer data)
745 gboolean result, result1;
748 /* Oddly enough although Named pipes don't work on win9x,
749 PeekNamedPipe does !!! */
750 handle = (HANDLE) _get_osfhandle (sync_pipe[READ]);
751 result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
753 /* Get the child process exit status */
754 result1 = GetExitCodeProcess((HANDLE)child_process, &childstatus);
756 /* If the Peek returned an error, or there are bytes to be read
757 or the childwatcher thread has terminated then call the normal
759 if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
761 /* avoid reentrancy problems and stack overflow */
762 gtk_timeout_remove(cap_timer_id);
764 /* And call the real handler */
765 cap_file_input_cb((gpointer) &cfile, 0, 0);
767 /* Return false so that the timer is not run again */
771 /* No data so let timer run again */
777 /* There's stuff to read from the sync pipe, meaning the child has sent
778 us a message, or the sync pipe has closed, meaning the child has
779 closed it (perhaps because it exited). */
781 cap_file_input_cb(gpointer data, gint source _U_,
782 GdkInputCondition condition _U_)
784 capture_file *cf = (capture_file *)data;
786 char buffer[BUFSIZE+1], *p = buffer, *q = buffer, *msg, *r;
787 int nread, msglen, chars_to_copy;
792 /* avoid reentrancy problems and stack overflow */
793 gtk_input_remove(cap_input_id);
796 if ((nread = read(sync_pipe[READ], buffer, BUFSIZE)) <= 0) {
797 /* The child has closed the sync pipe, meaning it's not going to be
798 capturing any more packets. Pick up its exit status, and
799 complain if it did anything other than exit with status 0. */
800 wait_for_child(FALSE);
802 /* Read what remains of the capture file, and finish the capture.
803 XXX - do something if this fails? */
804 switch (cf_finish_tail(cf, &err)) {
808 /* Just because we got an error, that doesn't mean we were unable
809 to read any of the file; we handle what we could get from the
814 /* Exit by leaving the main loop, so that any quit functions
815 we registered get called. */
820 /* We're not doing a capture any more, so we don't have a save
822 g_free(cf->save_file);
823 cf->save_file = NULL;
828 buffer[nread] = '\0';
831 /* look for (possibly multiple) indications */
833 case SP_PACKET_COUNT :
840 cf->drops_known = TRUE;
852 /* Read the entire message.
853 XXX - if the child hasn't sent it all yet, this could cause us
854 to hang until they do. */
855 msg = g_malloc(msglen + 1);
857 while (msglen != 0) {
860 if ((nread = read(sync_pipe[READ], buffer, BUFSIZE)) <= 0)
865 chars_to_copy = MIN(msglen, nread);
866 memcpy(r, q, chars_to_copy);
869 nread -= chars_to_copy;
870 msglen -= chars_to_copy;
873 simple_dialog(ESD_TYPE_CRIT, NULL, msg);
883 /* Read from the capture file the number of records the child told us
885 XXX - do something if this fails? */
886 switch (cf_continue_tail(cf, to_read, &err)) {
890 /* Just because we got an error, that doesn't mean we were unable
891 to read any of the file; we handle what we could get from the
894 XXX - abort on a read error? */
898 /* Kill the child capture process; the user wants to exit, and we
899 shouldn't just leave it running. */
903 kill(fork_child, SIGTERM); /* SIGTERM so it can clean up if necessary */
908 /* restore pipe handler */
910 cap_timer_id = gtk_timeout_add(1000, cap_timer_cb, NULL);
912 cap_input_id = gtk_input_add_full (sync_pipe[READ],
913 GDK_INPUT_READ|GDK_INPUT_EXCEPTION,
922 wait_for_child(gboolean always_report)
927 /* XXX - analyze the wait stuatus and display more information
928 in the dialog box? */
929 if (_cwait(&wstatus, child_process, _WAIT_CHILD) == -1) {
930 simple_dialog(ESD_TYPE_WARN, NULL, "Child capture process stopped unexpectedly");
933 if (wait(&wstatus) != -1) {
934 if (WIFEXITED(wstatus)) {
935 /* The child exited; display its exit status, if it's not zero,
936 and even if it's zero if "always_report" is true. */
937 if (always_report || WEXITSTATUS(wstatus) != 0) {
938 simple_dialog(ESD_TYPE_WARN, NULL,
939 "Child capture process exited: exit status %d",
940 WEXITSTATUS(wstatus));
942 } else if (WIFSTOPPED(wstatus)) {
943 /* It stopped, rather than exiting. "Should not happen." */
944 simple_dialog(ESD_TYPE_WARN, NULL,
945 "Child capture process stopped: %s",
946 signame(WSTOPSIG(wstatus)));
947 } else if (WIFSIGNALED(wstatus)) {
948 /* It died with a signal. */
949 simple_dialog(ESD_TYPE_WARN, NULL,
950 "Child capture process died: %s%s",
951 signame(WTERMSIG(wstatus)),
952 WCOREDUMP(wstatus) ? " - core dumped" : "");
954 /* What? It had to either have exited, or stopped, or died with
955 a signal; what happened here? */
956 simple_dialog(ESD_TYPE_WARN, NULL,
957 "Child capture process died: wait status %#o", wstatus);
961 /* No more child process. */
971 static char sigmsg_buf[6+1+3+1];
980 sigmsg = "Interrupted";
988 sigmsg = "Illegal instruction";
992 sigmsg = "Trace trap";
1000 sigmsg = "Arithmetic exception";
1008 sigmsg = "Bus error";
1012 sigmsg = "Segmentation violation";
1015 /* http://metalab.unc.edu/pub/Linux/docs/HOWTO/GCC-HOWTO
1016 Linux is POSIX compliant. These are not POSIX-defined signals ---
1017 ISO/IEC 9945-1:1990 (IEEE Std 1003.1-1990), paragraph B.3.3.1.1 sez:
1019 ``The signals SIGBUS, SIGEMT, SIGIOT, SIGTRAP, and SIGSYS
1020 were omitted from POSIX.1 because their behavior is
1021 implementation dependent and could not be adequately catego-
1022 rized. Conforming implementations may deliver these sig-
1023 nals, but must document the circumstances under which they
1024 are delivered and note any restrictions concerning their
1027 So we only check for SIGSYS on those systems that happen to
1028 implement them (a system can be POSIX-compliant and implement
1029 them, it's just that POSIX doesn't *require* a POSIX-compliant
1030 system to implement them).
1035 sigmsg = "Bad system call";
1040 sigmsg = "Broken pipe";
1044 sigmsg = "Alarm clock";
1048 sigmsg = "Terminated";
1052 sprintf(sigmsg_buf, "Signal %d", sig);
1053 sigmsg = sigmsg_buf;
1061 * Timeout, in milliseconds, for reads from the stream of captured packets.
1063 #define CAP_READ_TIMEOUT 250
1066 /* Take care of byte order in the libpcap headers read from pipes.
1067 * (function taken from wiretap/libpcap.c) */
1069 adjust_header(loop_data *ld, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1071 if (ld->byte_swapped) {
1072 /* Byte-swap the record header fields. */
1073 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
1074 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
1075 rechdr->incl_len = BSWAP32(rechdr->incl_len);
1076 rechdr->orig_len = BSWAP32(rechdr->orig_len);
1079 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1080 swapped, in order to match the BPF header layout.
1082 Unfortunately, some files were, according to a comment in the "libpcap"
1083 source, written with version 2.3 in their headers but without the
1084 interchanged fields, so if "incl_len" is greater than "orig_len" - which
1085 would make no sense - we assume that we need to swap them. */
1086 if (hdr->version_major == 2 &&
1087 (hdr->version_minor < 3 ||
1088 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1091 temp = rechdr->orig_len;
1092 rechdr->orig_len = rechdr->incl_len;
1093 rechdr->incl_len = temp;
1097 /* Mimic pcap_open_live() for pipe captures
1098 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
1100 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1101 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1103 pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
1104 char *errmsg, int errmsgl)
1106 struct stat pipe_stat;
1110 unsigned int bytes_read;
1112 struct timeval timeout;
1115 * XXX Ethereal blocks until we return
1117 if (strcmp(pipename, "-") == 0)
1118 fd = 0; /* read from stdin */
1120 if (stat(pipename, &pipe_stat) < 0) {
1121 if (errno == ENOENT || errno == ENOTDIR)
1122 ld->pipe_err = PIPNEXIST;
1124 snprintf(errmsg, errmsgl,
1125 "The capture session could not be initiated "
1126 "due to error on pipe: %s", strerror(errno));
1127 ld->pipe_err = PIPERR;
1131 if (! S_ISFIFO(pipe_stat.st_mode)) {
1132 if (S_ISCHR(pipe_stat.st_mode)) {
1134 * Assume the user specified an interface on a system where
1135 * interfaces are in /dev. Pretend we haven't seen it.
1137 ld->pipe_err = PIPNEXIST;
1139 snprintf(errmsg, errmsgl,
1140 "The capture session could not be initiated because\n"
1141 "\"%s\" is neither an interface nor a pipe", pipename);
1142 ld->pipe_err = PIPERR;
1146 fd = open(pipename, O_RDONLY | O_NONBLOCK);
1148 snprintf(errmsg, errmsgl,
1149 "The capture session could not be initiated "
1150 "due to error on pipe open: %s", strerror(errno));
1151 ld->pipe_err = PIPERR;
1156 ld->from_pipe = TRUE;
1158 /* read the pcap header */
1161 while (bytes_read < sizeof magic) {
1164 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1165 sel_ret = select(fd+1, &rfds, NULL, NULL, &timeout);
1167 snprintf(errmsg, errmsgl,
1168 "Unexpected error from select: %s", strerror(errno));
1170 } else if (sel_ret > 0) {
1171 b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
1174 snprintf(errmsg, errmsgl, "End of file on pipe during open");
1176 snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
1186 /* Host that wrote it has our byte order, and was running
1187 a program using either standard or ss990417 libpcap. */
1188 ld->byte_swapped = FALSE;
1189 ld->modified = FALSE;
1191 case PCAP_MODIFIED_MAGIC:
1192 /* Host that wrote it has our byte order, but was running
1193 a program using either ss990915 or ss991029 libpcap. */
1194 ld->byte_swapped = FALSE;
1195 ld->modified = TRUE;
1197 case PCAP_SWAPPED_MAGIC:
1198 /* Host that wrote it has a byte order opposite to ours,
1199 and was running a program using either standard or
1200 ss990417 libpcap. */
1201 ld->byte_swapped = TRUE;
1202 ld->modified = FALSE;
1204 case PCAP_SWAPPED_MODIFIED_MAGIC:
1205 /* Host that wrote it out has a byte order opposite to
1206 ours, and was running a program using either ss990915
1207 or ss991029 libpcap. */
1208 ld->byte_swapped = TRUE;
1209 ld->modified = TRUE;
1212 /* Not a "libpcap" type we know about. */
1213 snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
1217 /* Read the rest of the header */
1219 while (bytes_read < sizeof(struct pcap_hdr)) {
1222 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1223 sel_ret = select(fd+1, &rfds, NULL, NULL, &timeout);
1225 snprintf(errmsg, errmsgl,
1226 "Unexpected error from select: %s", strerror(errno));
1228 } else if (sel_ret > 0) {
1229 b = read(fd, ((char *)hdr)+bytes_read,
1230 sizeof(struct pcap_hdr) - bytes_read);
1233 snprintf(errmsg, errmsgl, "End of file on pipe during open");
1235 snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
1243 if (ld->byte_swapped) {
1244 /* Byte-swap the header fields about which we care. */
1245 hdr->version_major = BSWAP16(hdr->version_major);
1246 hdr->version_minor = BSWAP16(hdr->version_minor);
1247 hdr->snaplen = BSWAP32(hdr->snaplen);
1248 hdr->network = BSWAP32(hdr->network);
1251 if (hdr->version_major < 2) {
1252 snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
1256 ld->pipe_state = STATE_EXPECT_REC_HDR;
1257 ld->pipe_err = PIPOK;
1261 ld->pipe_err = PIPERR;
1267 /* We read one record from the pipe, take care of byte order in the record
1268 * header, write the record in the capture file, and update capture statistics. */
1271 pipe_dispatch(int fd, loop_data *ld, struct pcap_hdr *hdr,
1272 struct pcaprec_modified_hdr *rechdr, guchar *data,
1273 char *errmsg, int errmsgl)
1275 struct pcap_pkthdr phdr;
1277 enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
1280 switch (ld->pipe_state) {
1282 case STATE_EXPECT_REC_HDR:
1283 ld->bytes_to_read = ld->modified ?
1284 sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
1286 ld->pipe_state = STATE_READ_REC_HDR;
1289 case STATE_READ_REC_HDR:
1290 b = read(fd, ((char *)rechdr)+ld->bytes_read,
1291 ld->bytes_to_read - ld->bytes_read);
1294 result = PD_PIPE_EOF;
1296 result = PD_PIPE_ERR;
1299 if ((ld->bytes_read += b) < ld->bytes_to_read)
1301 result = PD_REC_HDR_READ;
1304 case STATE_EXPECT_DATA:
1306 ld->pipe_state = STATE_READ_DATA;
1309 case STATE_READ_DATA:
1310 b = read(fd, data+ld->bytes_read, rechdr->hdr.incl_len - ld->bytes_read);
1313 result = PD_PIPE_EOF;
1315 result = PD_PIPE_ERR;
1318 if ((ld->bytes_read += b) < rechdr->hdr.incl_len)
1320 result = PD_DATA_READ;
1324 snprintf(errmsg, errmsgl, "pipe_dispatch: invalid state");
1327 } /* switch (ld->pipe_state) */
1330 * We've now read as much data as we were expecting, so process it.
1334 case PD_REC_HDR_READ:
1335 /* We've read the header. Take care of byte order. */
1336 adjust_header(ld, hdr, &rechdr->hdr);
1337 if (rechdr->hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1338 snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
1339 ld->counts.total+1, rechdr->hdr.incl_len);
1342 ld->pipe_state = STATE_EXPECT_DATA;
1346 /* Fill in a "struct pcap_pkthdr", and process the packet. */
1347 phdr.ts.tv_sec = rechdr->hdr.ts_sec;
1348 phdr.ts.tv_usec = rechdr->hdr.ts_usec;
1349 phdr.caplen = rechdr->hdr.incl_len;
1350 phdr.len = rechdr->hdr.orig_len;
1352 capture_pcap_cb((guchar *)ld, &phdr, data);
1354 ld->pipe_state = STATE_EXPECT_REC_HDR;
1358 ld->pipe_err = PIPEOF;
1362 snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
1369 ld->pipe_err = PIPERR;
1370 /* Return here rather than inside the switch to prevent GCC warning */
1376 * This needs to be static, so that the SIGUSR1 handler can clear the "go"
1379 static loop_data ld;
1381 /* Do the low-level work of a capture.
1382 Returns TRUE if it succeeds, FALSE otherwise. */
1384 capture(gboolean *stats_known, struct pcap_stat *stats)
1386 GtkWidget *cap_w, *main_vb, *stop_bt, *counts_tb;
1387 GtkWidget *counts_fr, *running_tb, *running_label, *running_time;
1391 gchar open_err_str[PCAP_ERRBUF_SIZE];
1392 gchar lookup_net_err_str[PCAP_ERRBUF_SIZE];
1393 gchar label_str[64];
1394 bpf_u_int32 netnum, netmask;
1395 struct bpf_program fcode;
1396 const char *set_linktype_err_str;
1397 time_t upd_time, cur_time;
1400 condition *cnd_stop_capturesize = NULL;
1401 condition *cnd_stop_timeout = NULL;
1402 condition *cnd_ring_timeout = NULL;
1404 static const char capstart_msg = SP_CAPSTART;
1405 char errmsg[4096+1];
1409 struct timeval timeout;
1413 GtkWidget *label, *value, *percent;
1415 { "Total", &ld.counts.total, NULL, NULL, NULL },
1416 { "SCTP", &ld.counts.sctp, NULL, NULL, NULL },
1417 { "TCP", &ld.counts.tcp, NULL, NULL, NULL },
1418 { "UDP", &ld.counts.udp, NULL, NULL, NULL },
1419 { "ICMP", &ld.counts.icmp, NULL, NULL, NULL },
1420 { "ARP", &ld.counts.arp, NULL, NULL, NULL },
1421 { "OSPF", &ld.counts.ospf, NULL, NULL, NULL },
1422 { "GRE", &ld.counts.gre, NULL, NULL, NULL },
1423 { "NetBIOS", &ld.counts.netbios, NULL, NULL, NULL },
1424 { "IPX", &ld.counts.ipx, NULL, NULL, NULL },
1425 { "VINES", &ld.counts.vines, NULL, NULL, NULL },
1426 { "Other", &ld.counts.other, NULL, NULL, NULL }
1429 #define N_COUNTS (sizeof counts / sizeof counts[0])
1432 WORD wVersionRequested;
1435 static const char ppamsg[] = "can't find PPA for ";
1439 struct pcap_hdr hdr;
1440 struct pcaprec_modified_hdr rechdr;
1441 guchar pcap_data[WTAP_MAX_PACKET_SIZE];
1443 #ifdef MUST_DO_SELECT
1447 /* Size of buffer to hold decimal representation of
1448 signed/unsigned 64-bit int */
1451 /* Initialize Windows Socket if we are in a WIN32 OS
1452 This needs to be done before querying the interface for network/netmask */
1454 /* XXX - do we really require 1.1 or earlier?
1455 Are there any versions that support only 2.0 or higher? */
1456 wVersionRequested = MAKEWORD(1, 1);
1457 err = WSAStartup(wVersionRequested, &wsaData);
1461 case WSASYSNOTREADY:
1462 snprintf(errmsg, sizeof errmsg,
1463 "Couldn't initialize Windows Sockets: Network system not ready for network communication");
1466 case WSAVERNOTSUPPORTED:
1467 snprintf(errmsg, sizeof errmsg,
1468 "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
1469 LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
1472 case WSAEINPROGRESS:
1473 snprintf(errmsg, sizeof errmsg,
1474 "Couldn't initialize Windows Sockets: Blocking operation is in progress");
1478 snprintf(errmsg, sizeof errmsg,
1479 "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
1483 snprintf(errmsg, sizeof errmsg,
1484 "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
1488 snprintf(errmsg, sizeof errmsg,
1489 "Couldn't initialize Windows Sockets: error %d", err);
1498 ld.counts.total = 0;
1499 if (capture_opts.has_autostop_count)
1500 ld.max = capture_opts.autostop_count;
1502 ld.max = 0; /* no limit */
1503 ld.err = 0; /* no error seen yet */
1504 ld.linktype = WTAP_ENCAP_UNKNOWN;
1505 ld.pcap_err = FALSE;
1506 ld.from_pipe = FALSE;
1507 ld.sync_packets = 0;
1515 ld.counts.netbios = 0;
1516 ld.counts.vines = 0;
1517 ld.counts.other = 0;
1521 /* We haven't yet gotten the capture statistics. */
1522 *stats_known = FALSE;
1524 /* Open the network interface to capture from it.
1525 Some versions of libpcap may put warnings into the error buffer
1526 if they succeed; to tell if that's happened, we have to clear
1527 the error buffer, and check if it's still a null string. */
1528 open_err_str[0] = '\0';
1529 pch = pcap_open_live(cfile.iface,
1530 capture_opts.has_snaplen ? capture_opts.snaplen :
1531 WTAP_MAX_PACKET_SIZE,
1532 capture_opts.promisc_mode, CAP_READ_TIMEOUT,
1536 /* setting the data link type only works on real interfaces */
1537 if (capture_opts.linktype != -1) {
1538 set_linktype_err_str = set_pcap_linktype(pch, cfile.iface,
1539 capture_opts.linktype);
1540 if (set_linktype_err_str != NULL) {
1541 snprintf(errmsg, sizeof errmsg, "Unable to set data link type (%s).",
1542 set_linktype_err_str);
1547 /* We couldn't open "cfile.iface" as a network device. */
1549 /* On Windows, we don't support capturing on pipes, so we give up.
1550 If this is a child process that does the capturing in sync
1551 mode or fork mode, it shouldn't do any UI stuff until we pop up the
1552 capture-progress window, and, since we couldn't start the
1553 capture, we haven't popped it up. */
1554 if (!capture_child) {
1555 while (gtk_events_pending()) gtk_main_iteration();
1558 /* On Win32 OSes, the capture devices are probably available to all
1559 users; don't warn about permissions problems.
1561 Do, however, warn that WAN devices aren't supported. */
1562 snprintf(errmsg, sizeof errmsg,
1563 "The capture session could not be initiated (%s).\n"
1564 "Please check that you have the proper interface specified.\n"
1566 "Note that the driver Ethereal uses for packet capture on Windows doesn't\n"
1567 "support capturing on PPP/WAN interfaces in Windows NT/2000/XP/.NET Server.\n",
1571 /* try to open cfile.iface as a pipe */
1572 pipe_fd = pipe_open_live(cfile.iface, &hdr, &ld, errmsg, sizeof errmsg);
1574 if (pipe_fd == -1) {
1576 /* If this is a child process that does the capturing in sync
1577 * mode or fork mode, it shouldn't do any UI stuff until we pop up the
1578 * capture-progress window, and, since we couldn't start the
1579 * capture, we haven't popped it up.
1581 if (!capture_child) {
1582 while (gtk_events_pending()) gtk_main_iteration();
1585 if (ld.pipe_err == PIPNEXIST) {
1586 /* Pipe doesn't exist, so output message for interface */
1588 /* If we got a "can't find PPA for XXX" message, warn the user (who
1589 is running Ethereal on HP-UX) that they don't have a version
1590 of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1591 versions, which properly handle HP-UX, say "can't find /dev/dlpi
1592 PPA for XXX" rather than "can't find PPA for XXX"). */
1593 if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1596 "You are running Ethereal with a version of the libpcap library\n"
1597 "that doesn't handle HP-UX network devices well; this means that\n"
1598 "Ethereal may not be able to capture packets.\n"
1600 "To fix this, you should install libpcap 0.6.2, or a later version\n"
1601 "of libpcap, rather than libpcap 0.4 or 0.5.x. It is available in\n"
1602 "packaged binary form from the Software Porting And Archive Centre\n"
1603 "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1604 "at the URL lists a number of mirror sites.";
1607 snprintf(errmsg, sizeof errmsg,
1608 "The capture session could not be initiated (%s).\n"
1609 "Please check to make sure you have sufficient permissions, and that\n"
1610 "you have the proper interface or pipe specified.%s", open_err_str,
1614 * Else pipe (or file) does exist and pipe_open_live() has
1619 /* pipe_open_live() succeeded; don't want
1620 error message from pcap_open_live() */
1621 open_err_str[0] = '\0';
1625 /* capture filters only work on real interfaces */
1626 if (cfile.cfilter && !ld.from_pipe) {
1627 /* A capture filter was specified; set it up. */
1628 if (pcap_lookupnet(cfile.iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1630 * Well, we can't get the netmask for this interface; it's used
1631 * only for filters that check for broadcast IP addresses, so
1632 * we just punt and use 0. It might be nice to warn the user,
1633 * but that's a pain in a GUI application, as it'd involve popping
1634 * up a message box, and it's not clear how often this would make
1635 * a difference (only filters that check for IP broadcast addresses
1640 if (pcap_compile(pch, &fcode, cfile.cfilter, 1, netmask) < 0) {
1641 dfilter_t *rfcode = NULL;
1642 if (dfilter_compile(cfile.cfilter, &rfcode)) {
1643 snprintf(errmsg, sizeof errmsg,
1644 "Unable to parse capture filter string (%s).\n"
1645 " Interestingly enough, this looks like a valid display filter\n"
1646 " Are you sure you didn't mix them up?",
1648 dfilter_free(rfcode);
1650 snprintf(errmsg, sizeof errmsg,
1651 "Unable to parse capture filter string (%s).",
1656 if (pcap_setfilter(pch, &fcode) < 0) {
1657 snprintf(errmsg, sizeof errmsg, "Can't install filter (%s).",
1663 /* Set up to write to the capture file. */
1666 pcap_encap = hdr.network;
1667 file_snaplen = hdr.snaplen;
1671 pcap_encap = get_pcap_linktype(pch, cfile.iface);
1672 file_snaplen = pcap_snapshot(pch);
1674 ld.linktype = wtap_pcap_encap_to_wtap_encap(pcap_encap);
1675 if (ld.linktype == WTAP_ENCAP_UNKNOWN) {
1676 snprintf(errmsg, sizeof errmsg,
1677 "The network you're capturing from is of a type"
1678 " that Ethereal doesn't support (data link type %d).", pcap_encap);
1681 if (capture_opts.ringbuffer_on) {
1682 ld.pdh = ringbuf_init_wtap_dump_fdopen(WTAP_FILE_PCAP, ld.linktype,
1683 file_snaplen, &err);
1685 ld.pdh = wtap_dump_fdopen(cfile.save_file_fd, WTAP_FILE_PCAP,
1686 ld.linktype, file_snaplen, &err);
1689 if (ld.pdh == NULL) {
1690 /* We couldn't set up to write to the capture file. */
1693 case WTAP_ERR_CANT_OPEN:
1694 strcpy(errmsg, "The file to which the capture would be saved"
1695 " couldn't be created for some unknown reason.");
1698 case WTAP_ERR_SHORT_WRITE:
1699 strcpy(errmsg, "A full header couldn't be written to the file"
1700 " to which the capture would be saved.");
1705 snprintf(errmsg, sizeof(errmsg),
1706 "The file to which the capture would be"
1707 " saved (\"%s\") could not be opened: Error %d.",
1708 cfile.save_file, err);
1710 snprintf(errmsg, sizeof(errmsg),
1711 "The file to which the capture would be"
1712 " saved (\"%s\") could not be opened: %s.",
1713 cfile.save_file, strerror(err));
1720 /* Does "open_err_str" contain a non-empty string? If so, "pcap_open_live()"
1721 returned a warning; print it, but keep capturing. */
1722 if (open_err_str[0] != '\0')
1723 g_warning("%s.", open_err_str);
1725 /* XXX - capture SIGTERM and close the capture, in case we're on a
1726 Linux 2.0[.x] system and you have to explicitly close the capture
1727 stream in order to turn promiscuous mode off? We need to do that
1728 in other places as well - and I don't think that works all the
1729 time in any case, due to libpcap bugs. */
1731 if (capture_child) {
1732 /* Well, we should be able to start capturing.
1734 This is the child process for a sync mode capture, so sync out
1735 the capture file, so the header makes it to the file system,
1736 and send a "capture started successfully and capture file created"
1737 message to our parent so that they'll open the capture file and
1738 update its windows to indicate that we have a live capture in
1740 fflush(wtap_dump_file(ld.pdh));
1741 write(1, &capstart_msg, 1);
1744 cap_w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1745 gtk_window_set_title(GTK_WINDOW(cap_w), "Ethereal: Capture");
1746 gtk_window_set_modal(GTK_WINDOW(cap_w), TRUE);
1748 /* Container for capture display widgets */
1749 main_vb = gtk_vbox_new(FALSE, 1);
1750 gtk_container_border_width(GTK_CONTAINER(main_vb), 5);
1751 gtk_container_add(GTK_CONTAINER(cap_w), main_vb);
1752 gtk_widget_show(main_vb);
1754 counts_fr = gtk_frame_new("Captured Frames");
1755 gtk_box_pack_start(GTK_BOX(main_vb), counts_fr, FALSE, FALSE, 3);
1756 gtk_widget_show(counts_fr);
1758 /* Individual statistic elements */
1759 counts_tb = gtk_table_new(N_COUNTS, 3, TRUE);
1760 gtk_container_add(GTK_CONTAINER(counts_fr), counts_tb);
1761 gtk_container_border_width(GTK_CONTAINER(counts_tb), 5);
1762 gtk_widget_show(counts_tb);
1764 for (i = 0; i < N_COUNTS; i++) {
1765 counts[i].label = gtk_label_new(counts[i].title);
1766 gtk_misc_set_alignment(GTK_MISC(counts[i].label), 0.0f, 0.0f);
1768 counts[i].value = gtk_label_new("0");
1769 gtk_misc_set_alignment(GTK_MISC(counts[i].value), 0.0f, 0.0f);
1771 counts[i].percent = gtk_label_new("0.0%");
1772 gtk_misc_set_alignment(GTK_MISC(counts[i].percent), 0.0f, 0.0f);
1774 gtk_table_attach_defaults(GTK_TABLE(counts_tb),
1775 counts[i].label, 0, 1, i, i + 1);
1777 gtk_table_attach(GTK_TABLE(counts_tb),
1779 1, 2, i, i + 1, 0, 0, 5, 0);
1781 gtk_table_attach_defaults(GTK_TABLE(counts_tb),
1782 counts[i].percent, 2, 3, i, i + 1);
1784 gtk_widget_show(counts[i].label);
1785 gtk_widget_show(counts[i].value);
1786 gtk_widget_show(counts[i].percent);
1790 running_tb = gtk_table_new(1, 3, TRUE);
1791 gtk_box_pack_start(GTK_BOX(main_vb), running_tb, FALSE, FALSE, 3);
1792 gtk_widget_show(running_tb);
1794 running_label = gtk_label_new("Running");
1795 gtk_misc_set_alignment(GTK_MISC(running_label), 0.0f, 0.0f);
1796 gtk_widget_show(running_label);
1797 gtk_table_attach_defaults(GTK_TABLE(running_tb),
1798 running_label, 0, 1, 0, 1);
1800 running_time = gtk_label_new("00:00:00");
1801 gtk_misc_set_alignment(GTK_MISC(running_time), 0.0f, 0.0f);
1802 gtk_widget_show(running_time);
1803 gtk_table_attach(GTK_TABLE(running_tb),
1805 1, 2, 0, 1, 0, 0, 5, 0);
1807 /* allow user to either click a stop button, or the close button on
1808 the window to stop a capture in progress. */
1809 stop_bt = gtk_button_new_with_label ("Stop");
1810 gtk_signal_connect(GTK_OBJECT(stop_bt), "clicked",
1811 GTK_SIGNAL_FUNC(capture_stop_cb), (gpointer) &ld);
1812 gtk_signal_connect(GTK_OBJECT(cap_w), "delete_event",
1813 GTK_SIGNAL_FUNC(capture_delete_cb), (gpointer) &ld);
1814 gtk_box_pack_start(GTK_BOX(main_vb), stop_bt, FALSE, FALSE, 3);
1815 GTK_WIDGET_SET_FLAGS(stop_bt, GTK_CAN_DEFAULT);
1816 gtk_widget_grab_default(stop_bt);
1817 GTK_WIDGET_SET_FLAGS(stop_bt, GTK_CAN_DEFAULT);
1818 gtk_widget_grab_default(stop_bt);
1819 gtk_widget_show(stop_bt);
1821 gtk_widget_show(cap_w);
1823 start_time = time(NULL);
1824 upd_time = time(NULL);
1825 #ifdef MUST_DO_SELECT
1826 if (!ld.from_pipe) pcap_fd = pcap_fileno(pch);
1831 * Catch SIGUSR1, so that we exit cleanly if the parent process
1832 * kills us with it due to the user selecting "Capture->Stop".
1835 signal(SIGUSR1, stop_capture);
1837 /* initialize capture stop conditions */
1838 init_capture_stop_conditions();
1839 /* create stop conditions */
1840 if (capture_opts.has_autostop_filesize)
1841 cnd_stop_capturesize =
1842 cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts.autostop_filesize * 1000);
1843 if (capture_opts.has_autostop_duration)
1845 cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts.autostop_duration);
1847 if (capture_opts.ringbuffer_on && capture_opts.has_ring_duration)
1849 cnd_new(CND_CLASS_TIMEOUT, capture_opts.ringbuffer_duration);
1852 while (gtk_events_pending()) gtk_main_iteration();
1857 FD_SET(pipe_fd, &set1);
1859 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1860 sel_ret = select(pipe_fd+1, &set1, NULL, NULL, &timeout);
1863 if (sel_ret < 0 && errno != EINTR) {
1864 snprintf(errmsg, sizeof(errmsg),
1865 "Unexpected error from select: %s", strerror(errno));
1866 popup_errmsg(errmsg);
1871 * "select()" says we can read from the pipe without blocking
1873 inpkts = pipe_dispatch(pipe_fd, &ld, &hdr, &rechdr, pcap_data,
1874 errmsg, sizeof errmsg);
1883 #ifdef MUST_DO_SELECT
1885 * Sigh. The semantics of the read timeout argument to
1886 * "pcap_open_live()" aren't particularly well specified by
1887 * the "pcap" man page - at least with the BSD BPF code, the
1888 * intent appears to be, at least in part, a way of cutting
1889 * down the number of reads done on a capture, by blocking
1890 * until the buffer fills or a timer expires - and the Linux
1891 * libpcap doesn't actually support it, so we can't use it
1892 * to break out of the "pcap_dispatch()" every 1/4 of a second
1893 * or so. Linux's libpcap is not the only libpcap that doesn't
1894 * support the read timeout.
1896 * Furthermore, at least on Solaris, the bufmod STREAMS module's
1897 * read timeout won't go off if no data has arrived, i.e. it cannot
1898 * be used to guarantee that a read from a DLPI stream will return
1899 * within a specified amount of time regardless of whether any
1900 * data arrives or not.
1902 * Thus, on all platforms other than BSD, we do a "select()" on the
1903 * file descriptor for the capture, with a timeout of CAP_READ_TIMEOUT
1904 * milliseconds, or CAP_READ_TIMEOUT*1000 microseconds.
1906 * "select()", on BPF devices, doesn't work as you might expect;
1907 * at least on some versions of some flavors of BSD, the timer
1908 * doesn't start until a read is done, so it won't expire if
1909 * only a "select()" or "poll()" is posted.
1912 FD_SET(pcap_fd, &set1);
1914 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1915 sel_ret = select(pcap_fd+1, &set1, NULL, NULL, &timeout);
1918 * "select()" says we can read from it without blocking; go for
1921 inpkts = pcap_dispatch(pch, 1, capture_pcap_cb, (guchar *) &ld);
1928 if (sel_ret < 0 && errno != EINTR) {
1929 snprintf(errmsg, sizeof(errmsg),
1930 "Unexpected error from select: %s", strerror(errno));
1931 popup_errmsg(errmsg);
1936 inpkts = pcap_dispatch(pch, 1, capture_pcap_cb, (guchar *) &ld);
1945 ld.sync_packets += inpkts;
1946 /* check capture stop conditons */
1947 if (cnd_stop_capturesize != NULL && cnd_eval(cnd_stop_capturesize,
1948 (guint32)wtap_get_bytes_dumped(ld.pdh))){
1949 /* Capture file reached its maximum size. */
1950 if (capture_opts.ringbuffer_on) {
1951 /* Switch to the next ringbuffer file */
1952 if (ringbuf_switch_file(&cfile, &ld.pdh, &ld.err)) {
1953 /* File switch succeeded: reset the condition */
1954 cnd_reset(cnd_stop_capturesize);
1955 if (cnd_ring_timeout) {
1956 cnd_reset(cnd_ring_timeout);
1959 /* File switch failed: stop here */
1964 /* no ringbuffer - just stop */
1970 /* Only update once a second so as not to overload slow displays */
1971 cur_time = time(NULL);
1972 if (cur_time > upd_time) {
1973 upd_time = cur_time;
1975 /* calculate and display running time */
1976 cur_time -= start_time;
1977 snprintf(label_str, sizeof(label_str), "%02ld:%02ld:%02ld",
1978 (long)(cur_time/3600), (long)((cur_time%3600)/60),
1979 (long)(cur_time%60));
1980 gtk_label_set(GTK_LABEL(running_time), label_str);
1982 if (ld.sync_packets) {
1984 for (i = 0; i < N_COUNTS; i++) {
1985 snprintf(label_str, sizeof(label_str), "%d",
1986 *counts[i].value_ptr);
1988 gtk_label_set(GTK_LABEL(counts[i].value), label_str);
1990 snprintf(label_str, sizeof(label_str), "(%.1f%%)",
1991 pct(*counts[i].value_ptr, ld.counts.total));
1993 gtk_label_set(GTK_LABEL(counts[i].percent), label_str);
1996 /* do sync here, too */
1997 fflush(wtap_dump_file(ld.pdh));
1999 if (capture_child) {
2000 /* This is the child process for a sync mode capture, so send
2001 our parent a message saying we've written out "ld.sync_packets"
2002 packets to the capture file. */
2003 char tmp[DECISIZE+1+1];
2004 sprintf(tmp, "%d%c", ld.sync_packets, SP_PACKET_COUNT);
2005 write(1, tmp, strlen(tmp));
2008 ld.sync_packets = 0;
2012 if (cnd_stop_timeout != NULL && cnd_eval(cnd_stop_timeout)) {
2013 /* The specified capture time has elapsed; stop the capture. */
2015 } else if (cnd_ring_timeout != NULL && cnd_eval(cnd_ring_timeout)) {
2016 /* time elasped for this ring file, swith to the next */
2017 if (ringbuf_switch_file(&cfile, &ld.pdh, &ld.err)) {
2018 /* File switch succeeded: reset the condition */
2019 cnd_reset(cnd_ring_timeout);
2021 /* File switch failed: stop here */
2027 } /* while (ld.go) */
2029 /* delete stop conditions */
2030 if (cnd_stop_capturesize != NULL)
2031 cnd_delete(cnd_stop_capturesize);
2032 if (cnd_stop_timeout != NULL)
2033 cnd_delete(cnd_stop_timeout);
2034 if (cnd_ring_timeout != NULL)
2035 cnd_delete(cnd_ring_timeout);
2038 snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
2040 popup_errmsg(errmsg);
2044 } else if (ld.from_pipe && ld.pipe_err == PIPERR)
2045 popup_errmsg(errmsg);
2051 get_capture_file_io_error(errmsg, sizeof(errmsg), cfile.save_file, ld.err,
2053 popup_errmsg(errmsg);
2057 if (capture_opts.ringbuffer_on) {
2058 close_ok = ringbuf_wtap_dump_close(&cfile, &err);
2060 close_ok = wtap_dump_close(ld.pdh, &err);
2062 /* If we've displayed a message about a write error, there's no point
2063 in displaying another message about an error on close. */
2064 if (!close_ok && write_ok) {
2065 get_capture_file_io_error(errmsg, sizeof(errmsg), cfile.save_file, err,
2067 popup_errmsg(errmsg);
2069 /* Set write_ok to mean the write and the close were successful. */
2070 write_ok = (write_ok && close_ok);
2074 * XXX We exhibit different behaviour between normal mode and sync mode
2075 * when the pipe is stdin and not already at EOF. If we're a child, the
2076 * parent's stdin isn't closed, so if the user starts another capture,
2077 * pipe_open_live() will very likely not see the expected magic bytes and
2078 * will say "Unrecognized libpcap format". On the other hand, in normal
2079 * mode, pipe_open_live() will say "End of file on pipe during open".
2081 if (ld.from_pipe && pipe_fd >= 0)
2086 /* Get the capture statistics, so we know how many packets were
2088 if (pcap_stats(pch, stats) >= 0) {
2089 *stats_known = TRUE;
2090 if (capture_child) {
2091 /* Let the parent process know. */
2092 char tmp[DECISIZE+1+1];
2093 sprintf(tmp, "%d%c", stats->ps_drop, SP_DROPS);
2094 write(1, tmp, strlen(tmp));
2097 snprintf(errmsg, sizeof(errmsg),
2098 "Can't get packet-drop statistics: %s",
2100 popup_errmsg(errmsg);
2106 /* Shut down windows sockets */
2110 gtk_grab_remove(GTK_WIDGET(cap_w));
2111 gtk_widget_destroy(GTK_WIDGET(cap_w));
2116 if (capture_opts.ringbuffer_on) {
2117 /* cleanup ringbuffer */
2118 ringbuf_error_cleanup();
2120 /* We can't use the save file, and we have no wtap_dump stream
2121 to close in order to close it, so close the FD directly. */
2122 close(cfile.save_file_fd);
2124 /* We couldn't even start the capture, so get rid of the capture
2126 unlink(cfile.save_file); /* silently ignore error */
2127 g_free(cfile.save_file);
2129 cfile.save_file = NULL;
2130 popup_errmsg(errmsg);
2147 get_capture_file_io_error(char *errmsg, int errmsglen, const char *fname,
2148 int err, gboolean is_close)
2153 snprintf(errmsg, errmsglen,
2154 "Not all the packets could be written to the file"
2155 " to which the capture was being saved\n"
2156 "(\"%s\") because there is no space left on the file system\n"
2157 "on which that file resides.",
2163 snprintf(errmsg, errmsglen,
2164 "Not all the packets could be written to the file"
2165 " to which the capture was being saved\n"
2166 "(\"%s\") because you are too close to, or over,"
2167 " your disk quota\n"
2168 "on the file system on which that file resides.",
2173 case WTAP_ERR_CANT_CLOSE:
2174 snprintf(errmsg, errmsglen,
2175 "The file to which the capture was being saved"
2176 " couldn't be closed for some unknown reason.");
2179 case WTAP_ERR_SHORT_WRITE:
2180 snprintf(errmsg, errmsglen,
2181 "Not all the packets could be written to the file"
2182 " to which the capture was being saved\n"
2189 snprintf(errmsg, errmsglen,
2190 "The file to which the capture was being saved\n"
2191 "(\"%s\") could not be closed: %s.",
2192 fname, wtap_strerror(err));
2194 snprintf(errmsg, errmsglen,
2195 "An error occurred while writing to the file"
2196 " to which the capture was being saved\n"
2198 fname, wtap_strerror(err));
2205 popup_errmsg(const char *errmsg)
2207 if (capture_child) {
2208 /* This is the child process for a sync mode capture.
2209 Send the error message to our parent, so they can display a
2210 dialog box containing it. */
2211 send_errmsg_to_parent(errmsg);
2213 /* Display the dialog box ourselves; there's no parent. */
2214 simple_dialog(ESD_TYPE_CRIT, NULL, "%s", errmsg);
2219 send_errmsg_to_parent(const char *errmsg)
2221 int msglen = strlen(errmsg);
2222 char lenbuf[DECISIZE+1+1];
2224 sprintf(lenbuf, "%u%c", msglen, SP_ERROR_MSG);
2225 write(1, lenbuf, strlen(lenbuf));
2226 write(1, errmsg, msglen);
2230 pct(gint num, gint denom) {
2232 return (float) num * 100.0 / (float) denom;
2239 stop_capture(int signo _U_)
2245 capture_delete_cb(GtkWidget *w _U_, GdkEvent *event _U_, gpointer data) {
2246 capture_stop_cb(NULL, data);
2250 capture_stop_cb(GtkWidget *w _U_, gpointer data) {
2251 loop_data *ld = (loop_data *) data;
2260 * XXX - find some way of signaling the child in Win32.
2263 if (fork_child != -1)
2264 kill(fork_child, SIGUSR1);
2269 kill_capture_child(void)
2272 * XXX - find some way of signaling the child in Win32.
2275 if (fork_child != -1)
2276 kill(fork_child, SIGTERM); /* SIGTERM so it can clean up if necessary */
2281 capture_pcap_cb(guchar *user, const struct pcap_pkthdr *phdr,
2284 struct wtap_pkthdr whdr;
2285 union wtap_pseudo_header pseudo_header;
2286 loop_data *ld = (loop_data *) user;
2289 if ((++ld->counts.total >= ld->max) && (ld->max > 0))
2294 /* Convert from libpcap to Wiretap format.
2295 If that fails, set "ld->go" to FALSE, to stop the capture, and set
2296 "ld->err" to the error. */
2297 pd = wtap_process_pcap_packet(ld->linktype, phdr, pd, &pseudo_header,
2306 /* We're supposed to write the packet to a file; do so.
2307 If this fails, set "ld->go" to FALSE, to stop the capture, and set
2308 "ld->err" to the error. */
2309 if (!wtap_dump(ld->pdh, &whdr, &pseudo_header, pd, &err)) {
2315 switch (ld->linktype) {
2316 case WTAP_ENCAP_ETHERNET:
2317 capture_eth(pd, 0, whdr.caplen, &ld->counts);
2319 case WTAP_ENCAP_FDDI:
2320 case WTAP_ENCAP_FDDI_BITSWAPPED:
2321 capture_fddi(pd, whdr.caplen, &ld->counts);
2323 case WTAP_ENCAP_PRISM_HEADER:
2324 capture_prism(pd, 0, whdr.caplen, &ld->counts);
2326 case WTAP_ENCAP_TOKEN_RING:
2327 capture_tr(pd, 0, whdr.caplen, &ld->counts);
2329 case WTAP_ENCAP_NULL:
2330 capture_null(pd, whdr.caplen, &ld->counts);
2332 case WTAP_ENCAP_PPP:
2333 capture_ppp_hdlc(pd, 0, whdr.caplen, &ld->counts);
2335 case WTAP_ENCAP_RAW_IP:
2336 capture_raw(pd, whdr.caplen, &ld->counts);
2338 case WTAP_ENCAP_SLL:
2339 capture_sll(pd, whdr.caplen, &ld->counts);
2341 case WTAP_ENCAP_LINUX_ATM_CLIP:
2342 capture_clip(pd, whdr.caplen, &ld->counts);
2344 case WTAP_ENCAP_IEEE_802_11:
2345 case WTAP_ENCAP_IEEE_802_11_WITH_RADIO:
2346 capture_ieee80211(pd, 0, whdr.caplen, &ld->counts);
2348 case WTAP_ENCAP_CHDLC:
2349 capture_chdlc(pd, 0, whdr.caplen, &ld->counts);
2351 case WTAP_ENCAP_LOCALTALK:
2352 capture_llap(&ld->counts);
2354 case WTAP_ENCAP_ATM_PDUS:
2355 capture_atm(&pseudo_header, pd, whdr.caplen, &ld->counts);
2357 case WTAP_ENCAP_IP_OVER_FC:
2358 capture_ipfc(pd, whdr.caplen, &ld->counts);
2360 case WTAP_ENCAP_ARCNET:
2361 capture_arcnet(pd, whdr.caplen, &ld->counts, FALSE, TRUE);
2363 case WTAP_ENCAP_ARCNET_LINUX:
2364 capture_arcnet(pd, whdr.caplen, &ld->counts, TRUE, FALSE);
2366 /* XXX - some ATM drivers on FreeBSD might prepend a 4-byte ATM
2367 pseudo-header to DLT_ATM_RFC1483, with LLC header following;
2368 we might have to implement that at some point. */
2372 #endif /* HAVE_LIBPCAP */