2 * Routines for packet capture windows
4 * $Id: capture.c,v 1.134 2000/12/28 01:44:19 guy Exp $
6 * Ethereal - Network traffic analyzer
7 * By Gerald Combs <gerald@zing.org>
8 * Copyright 1998 Gerald Combs
11 * This program is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU General Public License
13 * as published by the Free Software Foundation; either version 2
14 * of the License, or (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
32 #ifdef HAVE_SYS_TYPES_H
33 # include <sys/types.h>
36 #ifdef HAVE_SYS_STAT_H
37 # include <sys/stat.h>
40 #ifdef HAVE_SYS_WAIT_H
41 # include <sys/wait.h>
46 * Define various POSIX macros (and, in the case of WCOREDUMP, non-POSIX
47 * macros) on UNIX systems that don't have them.
50 # define WIFEXITED(status) (((status) & 0177) == 0)
53 # define WIFSTOPPED(status) (((status) & 0177) == 0177)
56 # define WIFSIGNALED(status) (!WIFSTOPPED(status) && !WIFEXITED(status))
59 # define WEXITSTATUS(status) ((status) >> 8)
62 # define WTERMSIG(status) ((status) & 0177)
65 # define WCOREDUMP(status) ((status) & 0200)
68 # define WSTOPSIG(status) ((status) >> 8)
92 #ifdef HAVE_SYS_SOCKET_H
93 #include <sys/socket.h>
96 #ifdef HAVE_SYS_IOCTL_H
97 #include <sys/ioctl.h>
103 #ifdef NEED_SNPRINTF_H
104 # include "snprintf.h"
112 #include <process.h> /* For spawning child process */
116 * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
117 * want to include it if it's not present on this platform, however.
119 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__bsdi__)
123 #endif /* defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__bsdi__) */
125 #include "gtk/main.h"
126 #include "gtk/gtkglobals.h"
131 #include "simple_dialog.h"
135 #include "wiretap/libpcap.h"
136 #include "wiretap/wtap.h"
138 #include "packet-clip.h"
139 #include "packet-eth.h"
140 #include "packet-fddi.h"
141 #include "packet-null.h"
142 #include "packet-ppp.h"
143 #include "packet-raw.h"
144 #include "packet-tr.h"
145 #include "packet-ieee80211.h"
147 int promisc_mode = TRUE; /* capture in promiscuous mode */
148 int sync_mode; /* fork a child to do the capture, and sync between them */
149 static int sync_pipe[2]; /* used to sync father */
150 enum PIPES { READ, WRITE }; /* Constants 0 and 1 for READ and WRITE */
151 int quit_after_cap; /* Makes a "capture only mode". Implies -k */
152 gboolean capture_child; /* if this is the child for "-S" */
153 static int fork_child; /* In parent, process ID of child */
154 static guint cap_input_id;
157 static guint cap_timer_id;
158 static int cap_timer_cb(gpointer); /* Win32 kludge to check for pipe input */
161 static void cap_file_input_cb(gpointer, gint, GdkInputCondition);
162 static void wait_for_child(gboolean);
164 static char *signame(int);
166 static void capture_delete_cb(GtkWidget *, GdkEvent *, gpointer);
167 static void capture_stop_cb(GtkWidget *, gpointer);
168 static void capture_pcap_cb(u_char *, const struct pcap_pkthdr *,
170 static void send_errmsg_to_parent(const char *);
171 static float pct(gint, gint);
172 static void stop_capture(int signo);
174 typedef struct _loop_data {
179 gboolean from_pipe; /* TRUE if we are capturing data from a pipe */
180 gboolean modified; /* TRUE if data in the pipe uses modified pcap headers */
181 gboolean byte_swapped; /* TRUE if data in the pipe is byte swapped */
182 packet_counts counts;
187 static void adjust_header(loop_data *, struct pcap_hdr *, struct pcaprec_hdr *);
188 static int pipe_open_live(char *, struct pcap_hdr *, loop_data *, char *);
189 static int pipe_dispatch(int, loop_data *, struct pcap_hdr *);
192 /* Win32 needs the O_BINARY flag for open() */
198 /* Win32 needs a handle to the child capture process */
202 /* Add a string pointer to a NULL-terminated array of string pointers. */
204 add_arg(char **args, int *argc, char *arg)
206 /* Grow the array; "*argc" currently contains the number of string
207 pointers, *not* counting the NULL pointer at the end, so we have
208 to add 2 in order to get the new size of the array, including the
209 new pointer and the terminating NULL pointer. */
210 args = g_realloc(args, (*argc + 2) * sizeof (char *));
212 /* Stuff the pointer into the penultimate element of the array, which
213 is the one at the index specified by "*argc". */
216 /* Now bump the count. */
219 /* We overwrite the NULL pointer; put it back right after the
227 /* Given a string, return a pointer to a quote-encapsulated version of
228 the string, so we can pass it as an argument with "spawnvp" even
229 if it contains blanks. */
231 quote_encapsulate(const char *string)
233 char *encapsulated_string;
235 encapsulated_string = g_new(char, strlen(string) + 3);
236 sprintf(encapsulated_string, "\"%s\"", string);
237 return encapsulated_string;
241 /* Open a specified file, or create a temporary file, and start a capture
242 to the file in question. */
244 do_capture(char *capfile_name)
247 gboolean is_tempfile;
253 int capture_succeeded;
255 if (capfile_name != NULL) {
256 /* Try to open/create the specified file for use as a capture buffer. */
257 cfile.save_file_fd = open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT, 0600);
260 /* Choose a random name for the capture buffer */
261 cfile.save_file_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
262 capfile_name = g_strdup(tmpname);
265 if (cfile.save_file_fd == -1) {
267 simple_dialog(ESD_TYPE_CRIT, NULL,
268 "The temporary file to which the capture would be saved (\"%s\")"
269 "could not be opened: %s.", capfile_name, strerror(errno));
271 simple_dialog(ESD_TYPE_CRIT, NULL,
272 file_open_error_message(errno, TRUE), capfile_name);
276 close_cap_file(&cfile, info_bar);
277 g_assert(cfile.save_file == NULL);
278 cfile.save_file = capfile_name;
280 if (sync_mode) { /* do the capture in a child process */
282 char scount[24]; /* need a constant for len of numbers */
283 char save_file_fd[24];
289 char sync_pipe_fd[24];
294 /* Allocate the string pointer array with enough space for the
295 terminating NULL pointer. */
297 argv = g_malloc(sizeof (char *));
300 /* Now add those arguments used on all platforms. */
301 argv = add_arg(argv, &argc, CHILD_NAME);
303 argv = add_arg(argv, &argc, "-i");
304 argv = add_arg(argv, &argc, cfile.iface);
306 argv = add_arg(argv, &argc, "-w");
307 argv = add_arg(argv, &argc, cfile.save_file);
309 argv = add_arg(argv, &argc, "-W");
310 sprintf(save_file_fd,"%d",cfile.save_file_fd); /* in lieu of itoa */
311 argv = add_arg(argv, &argc, save_file_fd);
313 argv = add_arg(argv, &argc, "-c");
314 sprintf(scount,"%d",cfile.count);
315 argv = add_arg(argv, &argc, scount);
317 argv = add_arg(argv, &argc, "-s");
318 sprintf(ssnap,"%d",cfile.snap);
319 argv = add_arg(argv, &argc, ssnap);
322 argv = add_arg(argv, &argc, "-p");
325 /* Create a pipe for the child process */
327 if(_pipe(sync_pipe, 512, O_BINARY) < 0) {
328 /* Couldn't create the pipe between parent and child. */
330 unlink(cfile.save_file);
331 g_free(cfile.save_file);
332 cfile.save_file = NULL;
333 simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create sync pipe: %s",
338 /* Convert font name to a quote-encapsulated string and pass to child */
339 argv = add_arg(argv, &argc, "-m");
340 fontstring = quote_encapsulate(prefs.gui_font_name);
341 argv = add_arg(argv, &argc, fontstring);
343 /* Convert pipe write handle to a string and pass to child */
344 argv = add_arg(argv, &argc, "-Z");
345 itoa(sync_pipe[WRITE], sync_pipe_fd, 10);
346 argv = add_arg(argv, &argc, sync_pipe_fd);
348 /* Convert filter string to a quote delimited string and pass to child */
349 if (cfile.cfilter != NULL && strlen(cfile.cfilter) != 0) {
350 argv = add_arg(argv, &argc, "-f");
351 filterstring = quote_encapsulate(cfile.cfilter);
352 argv = add_arg(argv, &argc, filterstring);
356 fork_child = spawnvp(_P_NOWAIT, ethereal_path, argv);
358 g_free(filterstring);
359 /* Keep a copy for later evaluation by _cwait() */
360 child_process = fork_child;
362 signal(SIGCHLD, SIG_IGN);
363 if (pipe(sync_pipe) < 0) {
364 /* Couldn't create the pipe between parent and child. */
366 unlink(cfile.save_file);
367 g_free(cfile.save_file);
368 cfile.save_file = NULL;
369 simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create sync pipe: %s",
374 argv = add_arg(argv, &argc, "-m");
375 argv = add_arg(argv, &argc, prefs.gui_font_name);
377 if (cfile.cfilter != NULL && strlen(cfile.cfilter) != 0) {
378 argv = add_arg(argv, &argc, "-f");
379 argv = add_arg(argv, &argc, cfile.cfilter);
382 if ((fork_child = fork()) == 0) {
384 * Child process - run Ethereal with the right arguments to make
385 * it just pop up the live capture dialog box and capture with
386 * the specified capture parameters, writing to the specified file.
388 * args: -i interface specification
390 * -W file descriptor to write
391 * -c count to capture
394 * -f "filter expression"
397 dup(sync_pipe[WRITE]);
398 close(sync_pipe[READ]);
399 execvp(ethereal_path, argv);
400 snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
401 ethereal_path, strerror(errno));
402 send_errmsg_to_parent(errmsg);
404 /* Exit with "_exit()", so that we don't close the connection
405 to the X server (and cause stuff buffered up by our parent but
406 not yet sent to be sent, as that stuff should only be sent by
412 /* Parent process - read messages from the child process over the
414 g_free(argv); /* free up arg array */
416 /* Close the write side of the pipe, so that only the child has it
417 open, and thus it completely closes, and thus returns to us
418 an EOF indication, if the child closes it (either deliberately
419 or by exiting abnormally). */
420 close(sync_pipe[WRITE]);
422 /* Close the save file FD, as we won't be using it - we'll be opening
423 it and reading the save file through Wiretap. */
424 close(cfile.save_file_fd);
426 if (fork_child == -1) {
427 /* We couldn't even create the child process. */
429 close(sync_pipe[READ]);
430 unlink(cfile.save_file);
431 g_free(cfile.save_file);
432 cfile.save_file = NULL;
433 simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create child process: %s",
438 /* Read a byte count from "sync_pipe[READ]", terminated with a
439 colon; if the count is 0, the child process created the
440 capture file and we should start reading from it, otherwise
441 the capture couldn't start and the count is a count of bytes
442 of error message, and we should display the message. */
445 i = read(sync_pipe[READ], &c, 1);
447 /* EOF - the child process died.
448 Close the read side of the sync pipe, remove the capture file,
449 and report the failure. */
450 close(sync_pipe[READ]);
451 unlink(cfile.save_file);
452 g_free(cfile.save_file);
453 cfile.save_file = NULL;
454 wait_for_child(TRUE);
460 /* Child process handed us crap.
461 Close the read side of the sync pipe, remove the capture file,
462 and report the failure. */
463 close(sync_pipe[READ]);
464 unlink(cfile.save_file);
465 g_free(cfile.save_file);
466 cfile.save_file = NULL;
467 simple_dialog(ESD_TYPE_WARN, NULL,
468 "Capture child process sent us a bad message");
471 byte_count = byte_count*10 + c - '0';
473 if (byte_count == 0) {
474 /* Success. Open the capture file, and set up to read it. */
475 err = start_tail_cap_file(cfile.save_file, is_tempfile, &cfile);
477 /* We were able to open and set up to read the capture file;
478 arrange that our callback be called whenever it's possible
479 to read from the sync pipe, so that it's called when
480 the child process wants to tell us something. */
482 /* Tricky to use pipes in win9x, as no concept of wait. NT can
483 do this but that doesn't cover all win32 platforms. GTK can do
484 this but doesn't seem to work over processes. Attempt to do
485 something similar here, start a timer and check for data on every
487 cap_timer_id = gtk_timeout_add(1000, cap_timer_cb, NULL);
489 cap_input_id = gtk_input_add_full(sync_pipe[READ],
490 GDK_INPUT_READ|GDK_INPUT_EXCEPTION,
497 /* We weren't able to open the capture file; complain, and
498 close the sync pipe. */
499 simple_dialog(ESD_TYPE_CRIT, NULL,
500 file_open_error_message(err, FALSE), cfile.save_file);
502 /* Close the sync pipe. */
503 close(sync_pipe[READ]);
505 /* Don't unlink the save file - leave it around, for debugging
507 g_free(cfile.save_file);
508 cfile.save_file = NULL;
511 /* Failure - the child process sent us a message indicating
512 what the problem was. */
513 msg = g_malloc(byte_count + 1);
515 simple_dialog(ESD_TYPE_WARN, NULL,
516 "Capture child process failed, but its error message was too big.");
518 i = read(sync_pipe[READ], msg, byte_count);
520 simple_dialog(ESD_TYPE_WARN, NULL,
521 "Capture child process failed: Error %s reading its error message.",
524 simple_dialog(ESD_TYPE_WARN, NULL,
525 "Capture child process failed: EOF reading its error message.");
526 wait_for_child(FALSE);
528 simple_dialog(ESD_TYPE_WARN, NULL, msg);
531 /* Close the sync pipe. */
532 close(sync_pipe[READ]);
534 /* Get rid of the save file - the capture never started. */
535 unlink(cfile.save_file);
536 g_free(cfile.save_file);
537 cfile.save_file = NULL;
542 capture_succeeded = capture();
543 if (quit_after_cap) {
544 /* DON'T unlink the save file. Presumably someone wants it. */
547 if (capture_succeeded) {
548 /* Capture succeeded; read in the capture file. */
549 if ((err = open_cap_file(cfile.save_file, is_tempfile, &cfile)) == 0) {
550 /* Set the read filter to NULL. */
552 switch (read_cap_file(&cfile, &err)) {
556 /* Just because we got an error, that doesn't mean we were unable
557 to read any of the file; we handle what we could get from the
562 /* Exit by leaving the main loop, so that any quit functions
563 we registered get called. */
569 /* We're not doing a capture any more, so we don't have a save
571 g_free(cfile.save_file);
572 cfile.save_file = NULL;
577 /* The timer has expired, see if there's stuff to read from the pipe,
578 if so call the cap_file_input_cb */
580 cap_timer_cb(gpointer data)
584 gboolean result, result1;
587 /* Oddly enough although Named pipes don't work on win9x,
588 PeekNamedPipe does !!! */
589 handle = (HANDLE) _get_osfhandle (sync_pipe[READ]);
590 result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
592 /* Get the child process exit status */
593 result1 = GetExitCodeProcess((HANDLE)child_process, &childstatus);
595 /* If the Peek returned an error, or there are bytes to be read
596 or the childwatcher thread has terminated then call the normal
598 if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
600 /* avoid reentrancy problems and stack overflow */
601 gtk_timeout_remove(cap_timer_id);
603 /* And call the real handler */
604 cap_file_input_cb((gpointer) &cfile, 0, 0);
606 /* Return false so that the timer is not run again */
610 /* No data so let timer run again */
616 /* There's stuff to read from the sync pipe, meaning the child has sent
617 us a message, or the sync pipe has closed, meaning the child has
618 closed it (perhaps because it exited). */
620 cap_file_input_cb(gpointer data, gint source, GdkInputCondition condition)
622 capture_file *cf = (capture_file *)data;
623 char buffer[256+1], *p = buffer, *q = buffer;
626 gboolean exit_loop = FALSE;
630 /* avoid reentrancy problems and stack overflow */
631 gtk_input_remove(cap_input_id);
634 if ((nread = read(sync_pipe[READ], buffer, 256)) <= 0) {
635 /* The child has closed the sync pipe, meaning it's not going to be
636 capturing any more packets. Pick up its exit status, and
637 complain if it did anything other than exit with status 0. */
638 wait_for_child(FALSE);
640 /* Read what remains of the capture file, and finish the capture.
641 XXX - do something if this fails? */
642 switch (finish_tail_cap_file(cf, &err)) {
646 /* Just because we got an error, that doesn't mean we were unable
647 to read any of the file; we handle what we could get from the
652 /* Exit by leaving the main loop, so that any quit functions
653 we registered get called. */
658 /* We're not doing a capture any more, so we don't have a save
660 g_free(cf->save_file);
661 cf->save_file = NULL;
666 buffer[nread] = '\0';
669 /* look for (possibly multiple) '*' */
677 /* XXX should handle the case of a pipe full (i.e. no star found) */
686 /* Read from the capture file the number of records the child told us
688 XXX - do something if this fails? */
689 switch (continue_tail_cap_file(cf, to_read, &err)) {
693 /* Just because we got an error, that doesn't mean we were unable
694 to read any of the file; we handle what we could get from the
697 XXX - abort on a read error? */
701 /* Kill the child capture process; the user wants to exit, and we
702 shouldn't just leave it running. */
706 kill(fork_child, SIGTERM); /* SIGTERM so it can clean up if necessary */
711 /* restore pipe handler */
713 cap_timer_id = gtk_timeout_add(1000, cap_timer_cb, NULL);
715 cap_input_id = gtk_input_add_full (sync_pipe[READ],
716 GDK_INPUT_READ|GDK_INPUT_EXCEPTION,
725 wait_for_child(gboolean always_report)
730 /* XXX - analyze the wait stuatus and display more information
731 in the dialog box? */
732 if (_cwait(&wstatus, child_process, _WAIT_CHILD) == -1) {
733 simple_dialog(ESD_TYPE_WARN, NULL, "Child capture process stopped unexpectedly");
736 if (wait(&wstatus) != -1) {
737 if (WIFEXITED(wstatus)) {
738 /* The child exited; display its exit status, if it's not zero,
739 and even if it's zero if "always_report" is true. */
740 if (always_report || WEXITSTATUS(wstatus) != 0) {
741 simple_dialog(ESD_TYPE_WARN, NULL,
742 "Child capture process exited: exit status %d",
743 WEXITSTATUS(wstatus));
745 } else if (WIFSTOPPED(wstatus)) {
746 /* It stopped, rather than exiting. "Should not happen." */
747 simple_dialog(ESD_TYPE_WARN, NULL,
748 "Child capture process stopped: %s",
749 signame(WSTOPSIG(wstatus)));
750 } else if (WIFSIGNALED(wstatus)) {
751 /* It died with a signal. */
752 simple_dialog(ESD_TYPE_WARN, NULL,
753 "Child capture process died: %s%s",
754 signame(WTERMSIG(wstatus)),
755 WCOREDUMP(wstatus) ? " - core dumped" : "");
757 /* What? It had to either have exited, or stopped, or died with
758 a signal; what happened here? */
759 simple_dialog(ESD_TYPE_WARN, NULL,
760 "Child capture process died: wait status %#o", wstatus);
771 static char sigmsg_buf[6+1+3+1];
780 sigmsg = "Interrupted";
788 sigmsg = "Illegal instruction";
792 sigmsg = "Trace trap";
800 sigmsg = "Arithmetic exception";
808 sigmsg = "Bus error";
812 sigmsg = "Segmentation violation";
815 /* http://metalab.unc.edu/pub/Linux/docs/HOWTO/GCC-HOWTO
816 Linux is POSIX compliant. These are not POSIX-defined signals ---
817 ISO/IEC 9945-1:1990 (IEEE Std 1003.1-1990), paragraph B.3.3.1.1 sez:
819 ``The signals SIGBUS, SIGEMT, SIGIOT, SIGTRAP, and SIGSYS
820 were omitted from POSIX.1 because their behavior is
821 implementation dependent and could not be adequately catego-
822 rized. Conforming implementations may deliver these sig-
823 nals, but must document the circumstances under which they
824 are delivered and note any restrictions concerning their
827 So we only check for SIGSYS on those systems that happen to
828 implement them (a system can be POSIX-compliant and implement
829 them, it's just that POSIX doesn't *require* a POSIX-compliant
830 system to implement them).
835 sigmsg = "Bad system call";
840 sigmsg = "Broken pipe";
844 sigmsg = "Alarm clock";
848 sigmsg = "Terminated";
852 sprintf(sigmsg_buf, "Signal %d", sig);
861 * Timeout, in milliseconds, for reads from the stream of captured packets.
863 #define CAP_READ_TIMEOUT 250
866 /* Take carre of byte order in the libpcap headers read from pipes.
867 * (function taken from wiretap/libpcap.c) */
869 adjust_header(loop_data *ld, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
871 if (ld->byte_swapped) {
872 /* Byte-swap the record header fields. */
873 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
874 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
875 rechdr->incl_len = BSWAP32(rechdr->incl_len);
876 rechdr->orig_len = BSWAP32(rechdr->orig_len);
879 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
880 swapped, in order to match the BPF header layout.
882 Unfortunately, some files were, according to a comment in the "libpcap"
883 source, written with version 2.3 in their headers but without the
884 interchanged fields, so if "incl_len" is greater than "orig_len" - which
885 would make no sense - we assume that we need to swap them. */
886 if (hdr->version_major == 2 &&
887 (hdr->version_minor < 3 ||
888 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
891 temp = rechdr->orig_len;
892 rechdr->orig_len = rechdr->incl_len;
893 rechdr->incl_len = temp;
897 /* Mimic pcap_open_live() for pipe captures
898 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
900 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
901 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
903 pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld, char *ebuf)
905 struct stat pipe_stat;
910 if (strcmp(pipename, "-") == 0) fd = 0; /* read from stdin */
911 else if (stat(pipename, &pipe_stat) == 0 && S_ISFIFO(pipe_stat.st_mode)) {
912 if ((fd = open(pipename, O_RDONLY)) == -1) return -1;
915 ld->from_pipe = TRUE;
916 /* read the pcap header */
917 if (read(fd, &magic, sizeof magic) != sizeof magic) {
924 /* Host that wrote it has our byte order, and was running
925 a program using either standard or ss990417 libpcap. */
926 ld->byte_swapped = FALSE;
927 ld->modified = FALSE;
929 case PCAP_MODIFIED_MAGIC:
930 /* Host that wrote it has our byte order, but was running
931 a program using either ss990915 or ss991029 libpcap. */
932 ld->byte_swapped = FALSE;
935 case PCAP_SWAPPED_MAGIC:
936 /* Host that wrote it has a byte order opposite to ours,
937 and was running a program using either standard or
939 ld->byte_swapped = TRUE;
940 ld->modified = FALSE;
942 case PCAP_SWAPPED_MODIFIED_MAGIC:
943 /* Host that wrote it out has a byte order opposite to
944 ours, and was running a program using either ss990915
945 or ss991029 libpcap. */
946 ld->byte_swapped = TRUE;
950 /* Not a "libpcap" type we know about. */
955 /* Read the rest of the header */
956 bytes_read = read(fd, hdr, sizeof(struct pcap_hdr));
957 if (bytes_read <= 0) {
961 while (bytes_read < sizeof(struct pcap_hdr))
963 b = read(fd, ((char *)&hdr)+bytes_read, sizeof(struct pcap_hdr) - bytes_read);
970 if (ld->byte_swapped) {
971 /* Byte-swap the header fields about which we care. */
972 hdr->version_major = BSWAP16(hdr->version_major);
973 hdr->version_minor = BSWAP16(hdr->version_minor);
974 hdr->snaplen = BSWAP32(hdr->snaplen);
975 hdr->network = BSWAP32(hdr->network);
977 if (hdr->version_major < 2) {
985 /* We read one record from the pipe, take care of byte order in the record
986 * header, write the record in the capture file, and update capture statistics. */
988 pipe_dispatch(int fd, loop_data *ld, struct pcap_hdr *hdr)
990 struct wtap_pkthdr whdr;
991 struct pcaprec_modified_hdr rechdr;
992 int bytes_to_read, bytes_read, b;
993 u_char pd[WTAP_MAX_PACKET_SIZE];
996 /* read the record header */
997 bytes_to_read = ld->modified ? sizeof rechdr : sizeof rechdr.hdr;
998 bytes_read = read(fd, &rechdr, bytes_to_read);
999 if (bytes_read <= 0) {
1004 while (bytes_read < bytes_to_read)
1006 b = read(fd, ((char *)&rechdr)+bytes_read, bytes_to_read - bytes_read);
1014 /* take care of byte order */
1015 adjust_header(ld, hdr, &rechdr.hdr);
1016 if (rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1021 /* read the packet data */
1022 bytes_read = read(fd, pd, rechdr.hdr.incl_len);
1023 if (bytes_read <= 0) {
1028 while (bytes_read < rechdr.hdr.incl_len)
1030 b = read(fd, pd+bytes_read, rechdr.hdr.incl_len - bytes_read);
1038 /* dump the packet data to the capture file */
1039 whdr.ts.tv_sec = rechdr.hdr.ts_sec;
1040 whdr.ts.tv_usec = rechdr.hdr.ts_usec;
1041 whdr.caplen = rechdr.hdr.incl_len;
1042 whdr.len = rechdr.hdr.orig_len;
1043 whdr.pkt_encap = ld->linktype;
1044 wtap_dump(ld->pdh, &whdr, NULL, pd, &err);
1046 /* Set the initial payload to the packet length, and the initial
1047 captured payload to the capture length (other protocols may
1048 reduce them if their headers say they're less). */
1050 pi.captured_len = whdr.caplen;
1052 /* update capture statistics */
1053 switch (ld->linktype) {
1054 case WTAP_ENCAP_ETHERNET:
1055 capture_eth(pd, 0, &ld->counts);
1057 case WTAP_ENCAP_FDDI:
1058 case WTAP_ENCAP_FDDI_BITSWAPPED:
1059 capture_fddi(pd, &ld->counts);
1061 case WTAP_ENCAP_TOKEN_RING:
1062 capture_tr(pd, 0, &ld->counts);
1064 case WTAP_ENCAP_NULL:
1065 capture_null(pd, &ld->counts);
1067 case WTAP_ENCAP_PPP:
1068 capture_ppp(pd, 0, &ld->counts);
1070 case WTAP_ENCAP_RAW_IP:
1071 capture_raw(pd, &ld->counts);
1073 case WTAP_ENCAP_LINUX_ATM_CLIP:
1074 capture_clip(pd, &ld->counts);
1076 case WTAP_ENCAP_IEEE_802_11:
1077 capture_ieee80211(pd,0,&ld->counts);
1079 /* XXX - FreeBSD may append 4-byte ATM pseudo-header to DLT_ATM_RFC1483,
1080 with LLC header following; we should implement it at some
1089 * This needs to be static, so that the SIGUSR1 handler can clear the "go"
1092 static loop_data ld;
1094 /* Do the low-level work of a capture.
1095 Returns TRUE if it succeeds, FALSE otherwise. */
1099 GtkWidget *cap_w, *main_vb, *stop_bt, *counts_tb;
1103 gchar err_str[PCAP_ERRBUF_SIZE], label_str[64];
1104 bpf_u_int32 netnum, netmask;
1105 time_t upd_time, cur_time;
1107 char errmsg[4096+1];
1109 static const char ppamsg[] = "can't find PPA for ";
1113 struct timeval timeout;
1118 WORD wVersionRequested;
1123 struct pcap_hdr hdr;
1128 GtkWidget *label, *value, *percent;
1130 { "Total", &ld.counts.total },
1131 { "SCTP", &ld.counts.sctp },
1132 { "TCP", &ld.counts.tcp },
1133 { "UDP", &ld.counts.udp },
1134 { "ICMP", &ld.counts.icmp },
1135 { "OSPF", &ld.counts.ospf },
1136 { "GRE", &ld.counts.gre },
1137 { "NetBIOS", &ld.counts.netbios },
1138 { "IPX", &ld.counts.ipx },
1139 { "VINES", &ld.counts.vines },
1140 { "Other", &ld.counts.other }
1143 #define N_STATS (sizeof stats / sizeof stats[0])
1145 /* Initialize Windows Socket if we are in a WIN32 OS
1146 This needs to be done before querying the interface for network/netmask */
1148 wVersionRequested = MAKEWORD( 1, 1 );
1149 err = WSAStartup( wVersionRequested, &wsaData );
1151 snprintf(errmsg, sizeof errmsg,
1152 "Couldn't initialize Windows Sockets.");
1159 ld.counts.total = 0;
1160 ld.max = cfile.count;
1161 ld.linktype = WTAP_ENCAP_UNKNOWN;
1162 ld.from_pipe = FALSE;
1163 ld.sync_packets = 0;
1171 ld.counts.netbios = 0;
1172 ld.counts.vines = 0;
1173 ld.counts.other = 0;
1176 /* Open the network interface to capture from it. */
1177 pch = pcap_open_live(cfile.iface, cfile.snap, promisc_mode,
1178 CAP_READ_TIMEOUT, err_str);
1182 /* Well, we couldn't start the capture.
1183 If this is a child process that does the capturing in sync
1184 mode or fork mode, it shouldn't do any UI stuff until we pop up the
1185 capture-progress window, and, since we couldn't start the
1186 capture, we haven't popped it up. */
1187 if (!capture_child) {
1188 while (gtk_events_pending()) gtk_main_iteration();
1191 /* On Win32 OSes, the capture devices are probably available to all
1192 users; don't warn about permissions problems.
1194 Do, however, warn that Token Ring and PPP devices aren't supported. */
1195 snprintf(errmsg, sizeof errmsg,
1196 "The capture session could not be initiated (%s).\n"
1197 "Please check that you have the proper interface specified.\n"
1199 "Note that the driver Ethereal uses for packet capture on Windows\n"
1200 "doesn't support capturing on Token Ring interfaces, and doesn't\n"
1201 "support capturing on PPP/WAN interfaces in Windows NT/2000.\n",
1205 /* try to open cfile.iface as a pipe */
1206 pipe_fd = pipe_open_live(cfile.iface, &hdr, &ld, err_str);
1208 if (pipe_fd == -1) {
1209 /* Well, we couldn't start the capture.
1210 If this is a child process that does the capturing in sync
1211 mode or fork mode, it shouldn't do any UI stuff until we pop up the
1212 capture-progress window, and, since we couldn't start the
1213 capture, we haven't popped it up. */
1214 if (!capture_child) {
1215 while (gtk_events_pending()) gtk_main_iteration();
1218 /* If we got a "can't find PPA for XXX" message, warn the user (who
1219 is running Ethereal on HP-UX) that they don't have a version
1220 of libpcap patched to properly handle HP-UX (the patched version
1221 says "can't find /dev/dlpi PPA for XXX" rather than "can't find
1223 if (strncmp(err_str, ppamsg, sizeof ppamsg - 1) == 0)
1226 "You are running Ethereal with a version of the libpcap library\n"
1227 "that doesn't handle HP-UX network devices well; this means that\n"
1228 "Ethereal may not be able to capture packets.\n"
1230 "To fix this, you will need to download the source to Ethereal\n"
1231 "from www.ethereal.com if you have not already done so, read\n"
1232 "the instructions in the \"README.hpux\" file in the source\n"
1233 "distribution, download the source to libpcap if you have not\n"
1234 "already done so, patch libpcap as per the instructions, rebuild\n"
1235 "and install libpcap, and then build Ethereal (if you have already\n"
1236 "built Ethereal from source, do a \"make distclean\" and re-run\n"
1237 "configure before building).";
1240 snprintf(errmsg, sizeof errmsg,
1241 "The capture session could not be initiated (%s).\n"
1242 "Please check to make sure you have sufficient permissions, and that\n"
1243 "you have the proper interface or pipe specified.%s", err_str,
1250 /* capture filters only work on real interfaces */
1251 if (cfile.cfilter && !ld.from_pipe) {
1252 /* A capture filter was specified; set it up. */
1253 if (pcap_lookupnet (cfile.iface, &netnum, &netmask, err_str) < 0) {
1255 * Well, we can't get the netmask for this interface; it's used
1256 * only for filters that check for broadcast IP addresses, so
1257 * we just punt and use 0. It might be nice to warn the user,
1258 * but that's a pain in a GUI application, as it'd involve popping
1259 * up a message box, and it's not clear how often this would make
1260 * a difference (only filters that check for IP broadcast addresses
1265 if (pcap_compile(pch, &cfile.fcode, cfile.cfilter, 1, netmask) < 0) {
1266 snprintf(errmsg, sizeof errmsg, "Unable to parse filter string (%s).",
1270 if (pcap_setfilter(pch, &cfile.fcode) < 0) {
1271 snprintf(errmsg, sizeof errmsg, "Can't install filter (%s).",
1277 /* Set up to write to the capture file. */
1280 pcap_encap = hdr.network;
1281 snaplen = hdr.snaplen;
1285 pcap_encap = pcap_datalink(pch);
1286 snaplen = pcap_snapshot(pch);
1288 ld.linktype = wtap_pcap_encap_to_wtap_encap(pcap_encap);
1289 if (ld.linktype == WTAP_ENCAP_UNKNOWN) {
1290 snprintf(errmsg, sizeof errmsg,
1291 "The network you're capturing from is of a type"
1292 " that Ethereal doesn't support (data link type %d).", pcap_encap);
1295 ld.pdh = wtap_dump_fdopen(cfile.save_file_fd, WTAP_FILE_PCAP,
1296 ld.linktype, snaplen, &err);
1298 if (ld.pdh == NULL) {
1299 /* We couldn't set up to write to the capture file. */
1302 case WTAP_ERR_CANT_OPEN:
1303 strcpy(errmsg, "The file to which the capture would be saved"
1304 " couldn't be created for some unknown reason.");
1307 case WTAP_ERR_SHORT_WRITE:
1308 strcpy(errmsg, "A full header couldn't be written to the file"
1309 " to which the capture would be saved.");
1314 snprintf(errmsg, sizeof(errmsg),
1315 "The file to which the capture would be"
1316 " saved (\"%s\") could not be opened: Error %d.",
1317 cfile.save_file, err);
1319 snprintf(errmsg, sizeof(errmsg),
1320 "The file to which the capture would be"
1321 " saved (\"%s\") could not be opened: %s.",
1322 cfile.save_file, strerror(err));
1329 /* XXX - capture SIGTERM and close the capture, in case we're on a
1330 Linux 2.0[.x] system and you have to explicitly close the capture
1331 stream in order to turn promiscuous mode off? We need to do that
1332 in other places as well - and I don't think that works all the
1333 time in any case, due to libpcap bugs. */
1335 if (capture_child) {
1336 /* Well, we should be able to start capturing.
1338 This is the child process for a sync mode capture, so sync out
1339 the capture file, so the header makes it to the file system,
1340 and send a "capture started successfully and capture file created"
1341 message to our parent so that they'll open the capture file and
1342 update its windows to indicate that we have a live capture in
1344 fflush(wtap_dump_file(ld.pdh));
1348 cap_w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1349 gtk_window_set_title(GTK_WINDOW(cap_w), "Ethereal: Capture");
1350 gtk_window_set_modal(GTK_WINDOW(cap_w), TRUE);
1352 /* Container for capture display widgets */
1353 main_vb = gtk_vbox_new(FALSE, 1);
1354 gtk_container_border_width(GTK_CONTAINER(main_vb), 5);
1355 gtk_container_add(GTK_CONTAINER(cap_w), main_vb);
1356 gtk_widget_show(main_vb);
1358 /* Individual statistic elements */
1359 counts_tb = gtk_table_new(N_STATS, 3, TRUE);
1360 gtk_box_pack_start(GTK_BOX(main_vb), counts_tb, TRUE, TRUE, 3);
1361 gtk_widget_show(counts_tb);
1363 for (i = 0; i < N_STATS; i++) {
1364 stats[i].label = gtk_label_new(stats[i].title);
1365 gtk_misc_set_alignment(GTK_MISC(stats[i].label), 0.0f, 0.0f);
1367 stats[i].value = gtk_label_new("0");
1368 gtk_misc_set_alignment(GTK_MISC(stats[i].value), 0.0f, 0.0f);
1370 stats[i].percent = gtk_label_new("0.0%");
1371 gtk_misc_set_alignment(GTK_MISC(stats[i].percent), 0.0f, 0.0f);
1373 gtk_table_attach_defaults(GTK_TABLE(counts_tb),
1374 stats[i].label, 0, 1, i, i + 1);
1376 gtk_table_attach(GTK_TABLE(counts_tb),
1378 1, 2, i, i + 1, 0, 0, 5, 0);
1380 gtk_table_attach_defaults(GTK_TABLE(counts_tb),
1381 stats[i].percent, 2, 3, i, i + 1);
1383 gtk_widget_show(stats[i].label);
1384 gtk_widget_show(stats[i].value);
1385 gtk_widget_show(stats[i].percent);
1388 /* allow user to either click a stop button, or the close button on
1389 the window to stop a capture in progress. */
1390 stop_bt = gtk_button_new_with_label ("Stop");
1391 gtk_signal_connect(GTK_OBJECT(stop_bt), "clicked",
1392 GTK_SIGNAL_FUNC(capture_stop_cb), (gpointer) &ld);
1393 gtk_signal_connect(GTK_OBJECT(cap_w), "delete_event",
1394 GTK_SIGNAL_FUNC(capture_delete_cb), (gpointer) &ld);
1395 gtk_box_pack_end(GTK_BOX(main_vb), stop_bt, FALSE, FALSE, 3);
1396 GTK_WIDGET_SET_FLAGS(stop_bt, GTK_CAN_DEFAULT);
1397 gtk_widget_grab_default(stop_bt);
1398 GTK_WIDGET_SET_FLAGS(stop_bt, GTK_CAN_DEFAULT);
1399 gtk_widget_grab_default(stop_bt);
1400 gtk_widget_show(stop_bt);
1402 gtk_widget_show(cap_w);
1404 upd_time = time(NULL);
1406 if (!ld.from_pipe) pcap_fd = pcap_fileno(pch);
1411 * Catch SIGUSR1, so that we exit cleanly if the parent process
1412 * kills us with it due to the user selecting "Capture->Stop".
1414 signal(SIGUSR1, stop_capture);
1417 while (gtk_events_pending()) gtk_main_iteration();
1422 FD_SET(pipe_fd, &set1);
1424 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1425 if (select(pipe_fd+1, &set1, NULL, NULL, &timeout) != 0) {
1427 * "select()" says we can read from the pipe without blocking; go for
1428 * it. We are not sure we can read a whole record, but at least the
1429 * begninning of one. pipe_dispatch() will block reading the whole
1432 inpkts = pipe_dispatch(pipe_fd, &ld, &hdr);
1441 * Sigh. The semantics of the read timeout argument to
1442 * "pcap_open_live()" aren't particularly well specified by
1443 * the "pcap" man page - at least with the BSD BPF code, the
1444 * intent appears to be, at least in part, a way of cutting
1445 * down the number of reads done on a capture, by blocking
1446 * until the buffer fills or a timer expires - and the Linux
1447 * libpcap doesn't actually support it, so we can't use it
1448 * to break out of the "pcap_dispatch()" every 1/4 of a second
1449 * or so. Linux's libpcap is not the only libpcap that doesn't
1450 * support the read timeout.
1452 * Furthermore, at least on Solaris, the bufmod STREAMS module's
1453 * read timeout won't go off if no data has arrived, i.e. it cannot
1454 * be used to guarantee that a read from a DLPI stream will return
1455 * within a specified amount of time regardless of whether any
1456 * data arrives or not.
1458 * Thus, on all platforms other than BSD, we do a "select()" on the
1459 * file descriptor for the capture, with a timeout of CAP_READ_TIMEOUT
1460 * milliseconds, or CAP_READ_TIMEOUT*1000 microseconds.
1462 * "select()", on BPF devices, doesn't work as you might expect;
1463 * at least on some versions of some flavors of BSD, the timer
1464 * doesn't start until a read is done, so it won't expire if
1465 * only a "select()" or "poll()" is posted.
1468 FD_SET(pcap_fd, &set1);
1470 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1471 if (select(pcap_fd+1, &set1, NULL, NULL, &timeout) != 0) {
1473 * "select()" says we can read from it without blocking; go for
1476 inpkts = pcap_dispatch(pch, 1, capture_pcap_cb, (u_char *) &ld);
1480 inpkts = pcap_dispatch(pch, 1, capture_pcap_cb, (u_char *) &ld);
1484 ld.sync_packets += inpkts;
1485 /* Only update once a second so as not to overload slow displays */
1486 cur_time = time(NULL);
1487 if (cur_time > upd_time) {
1488 upd_time = cur_time;
1490 for (i = 0; i < N_STATS; i++) {
1491 snprintf(label_str, sizeof(label_str), "%d",
1492 *stats[i].value_ptr);
1494 gtk_label_set(GTK_LABEL(stats[i].value), label_str);
1496 snprintf(label_str, sizeof(label_str), "(%.1f%%)",
1497 pct(*stats[i].value_ptr, ld.counts.total));
1499 gtk_label_set(GTK_LABEL(stats[i].percent), label_str);
1502 /* do sync here, too */
1503 fflush(wtap_dump_file(ld.pdh));
1504 if (capture_child && ld.sync_packets) {
1505 /* This is the child process for a sync mode capture, so send
1506 our parent a message saying we've written out "ld.sync_packets"
1507 packets to the capture file. */
1509 sprintf(tmp, "%d*", ld.sync_packets);
1510 write(1, tmp, strlen(tmp));
1511 ld.sync_packets = 0;
1516 if (!wtap_dump_close(ld.pdh, &err)) {
1517 /* XXX - in fork mode, this may not pop up, or, if it does,
1518 it may disappear as soon as we exit.
1520 We should have the parent process, while it's reading
1521 the packet count update messages, catch error messages
1522 and pop up a message box if it sees one. */
1525 case WTAP_ERR_CANT_CLOSE:
1526 simple_dialog(ESD_TYPE_WARN, NULL,
1527 "The file to which the capture was being saved"
1528 " couldn't be closed for some unknown reason.");
1531 case WTAP_ERR_SHORT_WRITE:
1532 simple_dialog(ESD_TYPE_WARN, NULL,
1533 "Not all the data could be written to the file"
1534 " to which the capture was being saved.");
1538 simple_dialog(ESD_TYPE_WARN, NULL,
1539 "The file to which the capture was being"
1540 " saved (\"%s\") could not be closed: %s.",
1541 cfile.save_file, wtap_strerror(err));
1553 /* Shut down windows sockets */
1557 gtk_grab_remove(GTK_WIDGET(cap_w));
1558 gtk_widget_destroy(GTK_WIDGET(cap_w));
1563 /* We can't use the save file, and we have no wtap_dump stream
1564 to close in order to close it, so close the FD directly. */
1565 close(cfile.save_file_fd);
1567 /* We couldn't even start the capture, so get rid of the capture
1569 unlink(cfile.save_file); /* silently ignore error */
1570 g_free(cfile.save_file);
1571 cfile.save_file = NULL;
1572 if (capture_child) {
1573 /* This is the child process for a sync mode capture.
1574 Send the error message to our parent, so they can display a
1575 dialog box containing it. */
1576 send_errmsg_to_parent(errmsg);
1578 /* Display the dialog box ourselves; there's no parent. */
1579 simple_dialog(ESD_TYPE_CRIT, NULL, errmsg);
1581 if (pch != NULL && !ld.from_pipe)
1588 send_errmsg_to_parent(const char *errmsg)
1590 int msglen = strlen(errmsg);
1591 char lenbuf[10+1+1];
1593 sprintf(lenbuf, "%u;", msglen);
1594 write(1, lenbuf, strlen(lenbuf));
1595 write(1, errmsg, msglen);
1599 pct(gint num, gint denom) {
1601 return (float) num * 100.0 / (float) denom;
1608 stop_capture(int signo)
1614 capture_delete_cb(GtkWidget *w, GdkEvent *event, gpointer data) {
1615 capture_stop_cb(NULL, data);
1619 capture_stop_cb(GtkWidget *w, gpointer data) {
1620 loop_data *ld = (loop_data *) data;
1629 * XXX - find some way of signaling the child in Win32.
1632 if (fork_child != -1)
1633 kill(fork_child, SIGUSR1);
1638 capture_pcap_cb(u_char *user, const struct pcap_pkthdr *phdr,
1640 struct wtap_pkthdr whdr;
1641 loop_data *ld = (loop_data *) user;
1644 if ((++ld->counts.total >= ld->max) && (ld->max > 0))
1649 /* "phdr->ts" may not necessarily be a "struct timeval" - it may
1650 be a "struct bpf_timeval", with member sizes wired to 32
1651 bits - and we may go that way ourselves in the future, so
1652 copy the members individually. */
1653 whdr.ts.tv_sec = phdr->ts.tv_sec;
1654 whdr.ts.tv_usec = phdr->ts.tv_usec;
1655 whdr.caplen = phdr->caplen;
1656 whdr.len = phdr->len;
1657 whdr.pkt_encap = ld->linktype;
1659 /* XXX - do something if this fails */
1660 wtap_dump(ld->pdh, &whdr, NULL, pd, &err);
1663 /* Set the initial payload to the packet length, and the initial
1664 captured payload to the capture length (other protocols may
1665 reduce them if their headers say they're less). */
1667 pi.captured_len = phdr->caplen;
1669 switch (ld->linktype) {
1670 case WTAP_ENCAP_ETHERNET:
1671 capture_eth(pd, 0, &ld->counts);
1673 case WTAP_ENCAP_FDDI:
1674 case WTAP_ENCAP_FDDI_BITSWAPPED:
1675 capture_fddi(pd, &ld->counts);
1677 case WTAP_ENCAP_TOKEN_RING:
1678 capture_tr(pd, 0, &ld->counts);
1680 case WTAP_ENCAP_NULL:
1681 capture_null(pd, &ld->counts);
1683 case WTAP_ENCAP_PPP:
1684 capture_ppp(pd, 0, &ld->counts);
1686 case WTAP_ENCAP_RAW_IP:
1687 capture_raw(pd, &ld->counts);
1689 case WTAP_ENCAP_LINUX_ATM_CLIP:
1690 capture_clip(pd, &ld->counts);
1692 /* XXX - FreeBSD may append 4-byte ATM pseudo-header to DLT_ATM_RFC1483,
1693 with LLC header following; we should implement it at some
1698 #endif /* HAVE_LIBPCAP */