2 * Routines for packet capture windows
4 * $Id: capture.c,v 1.132 2000/11/15 05:41:41 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.
33 #ifdef HAVE_SYS_TYPES_H
34 # include <sys/types.h>
37 #ifdef HAVE_SYS_STAT_H
38 # include <sys/stat.h>
41 #ifdef HAVE_SYS_WAIT_H
42 # include <sys/wait.h>
64 #ifdef HAVE_SYS_SOCKET_H
65 #include <sys/socket.h>
68 #ifdef HAVE_SYS_IOCTL_H
69 #include <sys/ioctl.h>
75 #ifdef NEED_SNPRINTF_H
76 # include "snprintf.h"
84 #include <process.h> /* For spawning child process */
88 #include "gtk/gtkglobals.h"
93 #include "simple_dialog.h"
97 #include "wiretap/libpcap.h"
98 #include "wiretap/wtap.h"
100 #include "packet-clip.h"
101 #include "packet-eth.h"
102 #include "packet-fddi.h"
103 #include "packet-null.h"
104 #include "packet-ppp.h"
105 #include "packet-raw.h"
106 #include "packet-tr.h"
107 #include "packet-ieee80211.h"
109 int promisc_mode = TRUE; /* capture in promiscuous mode */
110 int sync_mode; /* fork a child to do the capture, and sync between them */
111 static int sync_pipe[2]; /* used to sync father */
112 enum PIPES { READ, WRITE }; /* Constants 0 and 1 for READ and WRITE */
113 int quit_after_cap; /* Makes a "capture only mode". Implies -k */
114 gboolean capture_child; /* if this is the child for "-S" */
115 static int fork_child; /* In parent, process ID of child */
116 static guint cap_input_id;
119 static guint cap_timer_id;
120 static int cap_timer_cb(gpointer); /* Win32 kludge to check for pipe input */
123 static void cap_file_input_cb(gpointer, gint, GdkInputCondition);
124 static void capture_delete_cb(GtkWidget *, GdkEvent *, gpointer);
125 static void capture_stop_cb(GtkWidget *, gpointer);
126 static void capture_pcap_cb(u_char *, const struct pcap_pkthdr *,
128 static void send_errmsg_to_parent(const char *);
129 static float pct(gint, gint);
130 static void stop_capture(int signo);
132 typedef struct _loop_data {
137 gboolean from_pipe; /* TRUE if we are capturing data from a pipe */
138 gboolean modified; /* TRUE if data in the pipe uses modified pcap headers */
139 gboolean byte_swapped; /* TRUE if data in the pipe is byte swapped */
140 packet_counts counts;
145 static void adjust_header(loop_data *, struct pcap_hdr *, struct pcaprec_hdr *);
146 static int pipe_open_live(char *, struct pcap_hdr *, loop_data *, char *);
147 static int pipe_dispatch(int, loop_data *, struct pcap_hdr *);
150 /* Win32 needs the O_BINARY flag for open() */
156 /* Win32 needs a handle to the child capture process */
160 /* Add a string pointer to a NULL-terminated array of string pointers. */
162 add_arg(char **args, int *argc, char *arg)
164 /* Grow the array; "*argc" currently contains the number of string
165 pointers, *not* counting the NULL pointer at the end, so we have
166 to add 2 in order to get the new size of the array, including the
167 new pointer and the terminating NULL pointer. */
168 args = g_realloc(args, (*argc + 2) * sizeof (char *));
170 /* Stuff the pointer into the penultimate element of the array, which
171 is the one at the index specified by "*argc". */
174 /* Now bump the count. */
177 /* We overwrite the NULL pointer; put it back right after the
185 /* Given a string, return a pointer to a quote-encapsulated version of
186 the string, so we can pass it as an argument with "spawnvp" even
187 if it contains blanks. */
189 quote_encapsulate(const char *string)
191 char *encapsulated_string;
193 encapsulated_string = g_new(char, strlen(string) + 3);
194 sprintf(encapsulated_string, "\"%s\"", string);
195 return encapsulated_string;
199 /* Open a specified file, or create a temporary file, and start a capture
200 to the file in question. */
202 do_capture(char *capfile_name)
205 gboolean is_tempfile;
211 int capture_succeeded;
213 if (capfile_name != NULL) {
214 /* Try to open/create the specified file for use as a capture buffer. */
215 cfile.save_file_fd = open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT, 0600);
218 /* Choose a random name for the capture buffer */
219 cfile.save_file_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
220 capfile_name = g_strdup(tmpname);
223 if (cfile.save_file_fd == -1) {
225 simple_dialog(ESD_TYPE_CRIT, NULL,
226 "The temporary file to which the capture would be saved (\"%s\")"
227 "could not be opened: %s.", capfile_name, strerror(errno));
229 simple_dialog(ESD_TYPE_CRIT, NULL,
230 file_open_error_message(errno, TRUE), capfile_name);
234 close_cap_file(&cfile, info_bar);
235 g_assert(cfile.save_file == NULL);
236 cfile.save_file = capfile_name;
238 if (sync_mode) { /* do the capture in a child process */
240 char scount[24]; /* need a constant for len of numbers */
241 char save_file_fd[24];
247 char sync_pipe_fd[24];
252 /* Allocate the string pointer array with enough space for the
253 terminating NULL pointer. */
255 argv = g_malloc(sizeof (char *));
258 /* Now add those arguments used on all platforms. */
259 argv = add_arg(argv, &argc, CHILD_NAME);
261 argv = add_arg(argv, &argc, "-i");
262 argv = add_arg(argv, &argc, cfile.iface);
264 argv = add_arg(argv, &argc, "-w");
265 argv = add_arg(argv, &argc, cfile.save_file);
267 argv = add_arg(argv, &argc, "-W");
268 sprintf(save_file_fd,"%d",cfile.save_file_fd); /* in lieu of itoa */
269 argv = add_arg(argv, &argc, save_file_fd);
271 argv = add_arg(argv, &argc, "-c");
272 sprintf(scount,"%d",cfile.count);
273 argv = add_arg(argv, &argc, scount);
275 argv = add_arg(argv, &argc, "-s");
276 sprintf(ssnap,"%d",cfile.snap);
277 argv = add_arg(argv, &argc, ssnap);
280 argv = add_arg(argv, &argc, "-p");
283 /* Create a pipe for the child process */
285 if(_pipe(sync_pipe, 512, O_BINARY) < 0) {
286 /* Couldn't create the pipe between parent and child. */
288 unlink(cfile.save_file);
289 g_free(cfile.save_file);
290 cfile.save_file = NULL;
291 simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create sync pipe: %s",
296 /* Convert font name to a quote-encapsulated string and pass to child */
297 argv = add_arg(argv, &argc, "-m");
298 fontstring = quote_encapsulate(prefs.gui_font_name);
299 argv = add_arg(argv, &argc, fontstring);
301 /* Convert pipe write handle to a string and pass to child */
302 argv = add_arg(argv, &argc, "-Z");
303 itoa(sync_pipe[WRITE], sync_pipe_fd, 10);
304 argv = add_arg(argv, &argc, sync_pipe_fd);
306 /* Convert filter string to a quote delimited string and pass to child */
307 if (cfile.cfilter != NULL && strlen(cfile.cfilter) != 0) {
308 argv = add_arg(argv, &argc, "-f");
309 filterstring = quote_encapsulate(cfile.cfilter);
310 argv = add_arg(argv, &argc, filterstring);
314 fork_child = spawnvp(_P_NOWAIT, ethereal_path, argv);
316 g_free(filterstring);
317 /* Keep a copy for later evaluation by _cwait() */
318 child_process = fork_child;
320 signal(SIGCHLD, SIG_IGN);
321 if (pipe(sync_pipe) < 0) {
322 /* Couldn't create the pipe between parent and child. */
324 unlink(cfile.save_file);
325 g_free(cfile.save_file);
326 cfile.save_file = NULL;
327 simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create sync pipe: %s",
332 argv = add_arg(argv, &argc, "-m");
333 argv = add_arg(argv, &argc, prefs.gui_font_name);
335 if (cfile.cfilter != NULL && strlen(cfile.cfilter) != 0) {
336 argv = add_arg(argv, &argc, "-f");
337 argv = add_arg(argv, &argc, cfile.cfilter);
340 if ((fork_child = fork()) == 0) {
342 * Child process - run Ethereal with the right arguments to make
343 * it just pop up the live capture dialog box and capture with
344 * the specified capture parameters, writing to the specified file.
346 * args: -i interface specification
348 * -W file descriptor to write
349 * -c count to capture
352 * -f "filter expression"
355 dup(sync_pipe[WRITE]);
356 close(sync_pipe[READ]);
357 execvp(ethereal_path, argv);
358 snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
359 ethereal_path, strerror(errno));
360 send_errmsg_to_parent(errmsg);
362 /* Exit with "_exit()", so that we don't close the connection
363 to the X server (and cause stuff buffered up by our parent but
364 not yet sent to be sent, as that stuff should only be sent by
370 /* Parent process - read messages from the child process over the
372 g_free(argv); /* free up arg array */
374 /* Close the write side of the pipe, so that only the child has it
375 open, and thus it completely closes, and thus returns to us
376 an EOF indication, if the child closes it (either deliberately
377 or by exiting abnormally). */
378 close(sync_pipe[WRITE]);
380 /* Close the save file FD, as we won't be using it - we'll be opening
381 it and reading the save file through Wiretap. */
382 close(cfile.save_file_fd);
384 if (fork_child == -1) {
385 /* We couldn't even create the child process. */
387 close(sync_pipe[READ]);
388 unlink(cfile.save_file);
389 g_free(cfile.save_file);
390 cfile.save_file = NULL;
391 simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create child process: %s",
396 /* Read a byte count from "sync_pipe[READ]", terminated with a
397 colon; if the count is 0, the child process created the
398 capture file and we should start reading from it, otherwise
399 the capture couldn't start and the count is a count of bytes
400 of error message, and we should display the message. */
403 i = read(sync_pipe[READ], &c, 1);
405 /* EOF - the child process died.
406 Close the read side of the sync pipe, remove the capture file,
407 and report the failure.
408 XXX - reap the child process and report the status in detail. */
409 close(sync_pipe[READ]);
410 unlink(cfile.save_file);
411 g_free(cfile.save_file);
412 cfile.save_file = NULL;
413 simple_dialog(ESD_TYPE_WARN, NULL, "Capture child process died");
419 /* Child process handed us crap.
420 Close the read side of the sync pipe, remove the capture file,
421 and report the failure. */
422 close(sync_pipe[READ]);
423 unlink(cfile.save_file);
424 g_free(cfile.save_file);
425 cfile.save_file = NULL;
426 simple_dialog(ESD_TYPE_WARN, NULL,
427 "Capture child process sent us a bad message");
430 byte_count = byte_count*10 + c - '0';
432 if (byte_count == 0) {
433 /* Success. Open the capture file, and set up to read it. */
434 err = start_tail_cap_file(cfile.save_file, is_tempfile, &cfile);
436 /* We were able to open and set up to read the capture file;
437 arrange that our callback be called whenever it's possible
438 to read from the sync pipe, so that it's called when
439 the child process wants to tell us something. */
441 /* Tricky to use pipes in win9x, as no concept of wait. NT can
442 do this but that doesn't cover all win32 platforms. GTK can do
443 this but doesn't seem to work over processes. Attempt to do
444 something similar here, start a timer and check for data on every
446 cap_timer_id = gtk_timeout_add(1000, cap_timer_cb, NULL);
448 cap_input_id = gtk_input_add_full(sync_pipe[READ],
449 GDK_INPUT_READ|GDK_INPUT_EXCEPTION,
456 /* We weren't able to open the capture file; complain, and
457 close the sync pipe. */
458 simple_dialog(ESD_TYPE_CRIT, NULL,
459 file_open_error_message(err, FALSE), cfile.save_file);
461 /* Close the sync pipe. */
462 close(sync_pipe[READ]);
464 /* Don't unlink the save file - leave it around, for debugging
466 g_free(cfile.save_file);
467 cfile.save_file = NULL;
470 /* Failure - the child process sent us a message indicating
471 what the problem was. */
472 msg = g_malloc(byte_count + 1);
474 simple_dialog(ESD_TYPE_WARN, NULL,
475 "Capture child process failed, but its error message was too big.");
477 i = read(sync_pipe[READ], msg, byte_count);
479 simple_dialog(ESD_TYPE_WARN, NULL,
480 "Capture child process failed: Error %s reading its error message.",
483 simple_dialog(ESD_TYPE_WARN, NULL,
484 "Capture child process failed: EOF reading its error message.");
486 simple_dialog(ESD_TYPE_WARN, NULL, msg);
489 /* Close the sync pipe. */
490 close(sync_pipe[READ]);
492 /* Get rid of the save file - the capture never started. */
493 unlink(cfile.save_file);
494 g_free(cfile.save_file);
495 cfile.save_file = NULL;
500 capture_succeeded = capture();
501 if (quit_after_cap) {
502 /* DON'T unlink the save file. Presumably someone wants it. */
505 if (capture_succeeded) {
506 /* Capture succeeded; read in the capture file. */
507 if ((err = open_cap_file(cfile.save_file, is_tempfile, &cfile)) == 0) {
508 /* Set the read filter to NULL. */
510 switch (read_cap_file(&cfile, &err)) {
514 /* Just because we got an error, that doesn't mean we were unable
515 to read any of the file; we handle what we could get from the
520 /* Exit by leaving the main loop, so that any quit functions
521 we registered get called. */
527 /* We're not doing a capture any more, so we don't have a save
529 g_free(cfile.save_file);
530 cfile.save_file = NULL;
535 /* The timer has expired, see if there's stuff to read from the pipe,
536 if so call the cap_file_input_cb */
538 cap_timer_cb(gpointer data)
542 gboolean result, result1;
545 /* Oddly enough although Named pipes don't work on win9x,
546 PeekNamedPipe does !!! */
547 handle = (HANDLE) _get_osfhandle (sync_pipe[READ]);
548 result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
550 /* Get the child process exit status */
551 result1 = GetExitCodeProcess((HANDLE)child_process, &childstatus);
553 /* If the Peek returned an error, or there are bytes to be read
554 or the childwatcher thread has terminated then call the normal
556 if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
558 /* avoid reentrancy problems and stack overflow */
559 gtk_timeout_remove(cap_timer_id);
561 /* And call the real handler */
562 cap_file_input_cb((gpointer) &cfile, 0, 0);
564 /* Return false so that the timer is not run again */
568 /* No data so let timer run again */
574 /* There's stuff to read from the sync pipe, meaning the child has sent
575 us a message, or the sync pipe has closed, meaning the child has
576 closed it (perhaps because it exited). */
578 cap_file_input_cb(gpointer data, gint source, GdkInputCondition condition)
580 capture_file *cf = (capture_file *)data;
581 char buffer[256+1], *p = buffer, *q = buffer;
584 gboolean exit_loop = FALSE;
590 char sigmsg_buf[6+1+3+1];
594 /* avoid reentrancy problems and stack overflow */
595 gtk_input_remove(cap_input_id);
598 if ((nread = read(sync_pipe[READ], buffer, 256)) <= 0) {
599 /* The child has closed the sync pipe, meaning it's not going to be
600 capturing any more packets. Pick up its exit status, and
601 complain if it died of a signal. */
603 /* XXX - analyze the wait stuatus and display more information
604 in the dialog box? */
605 if (_cwait(&wstatus, child_process, _WAIT_CHILD) == -1) {
606 simple_dialog(ESD_TYPE_WARN, NULL, "Child capture process stopped unexpectedly");
609 if (wait(&wstatus) != -1) {
610 /* XXX - are there any platforms on which we can run that *don't*
611 support POSIX.1's <sys/wait.h> and macros therein? */
612 wsignal = wstatus & 0177;
614 if (wstatus == 0177) {
615 /* It stopped, rather than exiting. "Should not happen." */
617 wsignal = (wstatus >> 8) & 0xFF;
621 coredumped = " - core dumped";
631 sigmsg = "Interrupted";
639 sigmsg = "Illegal instruction";
643 sigmsg = "Trace trap";
651 sigmsg = "Arithmetic exception";
659 sigmsg = "Bus error";
663 sigmsg = "Segmentation violation";
666 /* http://metalab.unc.edu/pub/Linux/docs/HOWTO/GCC-HOWTO
667 Linux is POSIX compliant. These are not POSIX-defined signals ---
668 ISO/IEC 9945-1:1990 (IEEE Std 1003.1-1990), paragraph B.3.3.1.1 sez:
670 ``The signals SIGBUS, SIGEMT, SIGIOT, SIGTRAP, and SIGSYS
671 were omitted from POSIX.1 because their behavior is
672 implementation dependent and could not be adequately catego-
673 rized. Conforming implementations may deliver these sig-
674 nals, but must document the circumstances under which they
675 are delivered and note any restrictions concerning their
681 sigmsg = "Bad system call";
686 sigmsg = "Broken pipe";
690 sigmsg = "Alarm clock";
694 sigmsg = "Terminated";
698 sprintf(sigmsg_buf, "Signal %d", wsignal);
702 simple_dialog(ESD_TYPE_WARN, NULL,
703 "Child capture process %s: %s%s", msg, sigmsg, coredumped);
708 /* Read what remains of the capture file, and finish the capture.
709 XXX - do something if this fails? */
710 switch (finish_tail_cap_file(cf, &err)) {
714 /* Just because we got an error, that doesn't mean we were unable
715 to read any of the file; we handle what we could get from the
720 /* Exit by leaving the main loop, so that any quit functions
721 we registered get called. */
726 /* We're not doing a capture any more, so we don't have a save
728 g_free(cf->save_file);
729 cf->save_file = NULL;
734 buffer[nread] = '\0';
737 /* look for (possibly multiple) '*' */
745 /* XXX should handle the case of a pipe full (i.e. no star found) */
754 /* Read from the capture file the number of records the child told us
756 XXX - do something if this fails? */
757 switch (continue_tail_cap_file(cf, to_read, &err)) {
761 /* Just because we got an error, that doesn't mean we were unable
762 to read any of the file; we handle what we could get from the
765 XXX - abort on a read error? */
769 /* Kill the child capture process; the user wants to exit, and we
770 shouldn't just leave it running. */
774 kill(fork_child, SIGTERM); /* SIGTERM so it can clean up if necessary */
779 /* restore pipe handler */
781 cap_timer_id = gtk_timeout_add(1000, cap_timer_cb, NULL);
783 cap_input_id = gtk_input_add_full (sync_pipe[READ],
784 GDK_INPUT_READ|GDK_INPUT_EXCEPTION,
793 * Timeout, in milliseconds, for reads from the stream of captured packets.
795 #define CAP_READ_TIMEOUT 250
798 /* Take carre of byte order in the libpcap headers read from pipes.
799 * (function taken from wiretap/libpcap.c) */
801 adjust_header(loop_data *ld, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
803 if (ld->byte_swapped) {
804 /* Byte-swap the record header fields. */
805 rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
806 rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
807 rechdr->incl_len = BSWAP32(rechdr->incl_len);
808 rechdr->orig_len = BSWAP32(rechdr->orig_len);
811 /* In file format version 2.3, the "incl_len" and "orig_len" fields were
812 swapped, in order to match the BPF header layout.
814 Unfortunately, some files were, according to a comment in the "libpcap"
815 source, written with version 2.3 in their headers but without the
816 interchanged fields, so if "incl_len" is greater than "orig_len" - which
817 would make no sense - we assume that we need to swap them. */
818 if (hdr->version_major == 2 &&
819 (hdr->version_minor < 3 ||
820 (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
823 temp = rechdr->orig_len;
824 rechdr->orig_len = rechdr->incl_len;
825 rechdr->incl_len = temp;
829 /* Mimic pcap_open_live() for pipe captures
830 * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
832 * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
833 * because we can't seek on pipes (see wiretap/libpcap.c for details) */
835 pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld, char *ebuf)
837 struct stat pipe_stat;
842 if (strcmp(pipename, "-") == 0) fd = 0; /* read from stdin */
843 else if (stat(pipename, &pipe_stat) == 0 && S_ISFIFO(pipe_stat.st_mode)) {
844 if ((fd = open(pipename, O_RDONLY)) == -1) return -1;
847 ld->from_pipe = TRUE;
848 /* read the pcap header */
849 if (read(fd, &magic, sizeof magic) != sizeof magic) {
856 /* Host that wrote it has our byte order, and was running
857 a program using either standard or ss990417 libpcap. */
858 ld->byte_swapped = FALSE;
859 ld->modified = FALSE;
861 case PCAP_MODIFIED_MAGIC:
862 /* Host that wrote it has our byte order, but was running
863 a program using either ss990915 or ss991029 libpcap. */
864 ld->byte_swapped = FALSE;
867 case PCAP_SWAPPED_MAGIC:
868 /* Host that wrote it has a byte order opposite to ours,
869 and was running a program using either standard or
871 ld->byte_swapped = TRUE;
872 ld->modified = FALSE;
874 case PCAP_SWAPPED_MODIFIED_MAGIC:
875 /* Host that wrote it out has a byte order opposite to
876 ours, and was running a program using either ss990915
877 or ss991029 libpcap. */
878 ld->byte_swapped = TRUE;
882 /* Not a "libpcap" type we know about. */
887 /* Read the rest of the header */
888 bytes_read = read(fd, hdr, sizeof(struct pcap_hdr));
889 if (bytes_read <= 0) {
893 while (bytes_read < sizeof(struct pcap_hdr))
895 b = read(fd, ((char *)&hdr)+bytes_read, sizeof(struct pcap_hdr) - bytes_read);
902 if (ld->byte_swapped) {
903 /* Byte-swap the header fields about which we care. */
904 hdr->version_major = BSWAP16(hdr->version_major);
905 hdr->version_minor = BSWAP16(hdr->version_minor);
906 hdr->snaplen = BSWAP32(hdr->snaplen);
907 hdr->network = BSWAP32(hdr->network);
909 if (hdr->version_major < 2) {
917 /* We read one record from the pipe, take care of byte order in the record
918 * header, write the record in the capture file, and update capture statistics. */
920 pipe_dispatch(int fd, loop_data *ld, struct pcap_hdr *hdr)
922 struct wtap_pkthdr whdr;
923 struct pcaprec_modified_hdr rechdr;
924 int bytes_to_read, bytes_read, b;
925 u_char pd[WTAP_MAX_PACKET_SIZE];
928 /* read the record header */
929 bytes_to_read = ld->modified ? sizeof rechdr : sizeof rechdr.hdr;
930 bytes_read = read(fd, &rechdr, bytes_to_read);
931 if (bytes_read <= 0) {
936 while (bytes_read < bytes_to_read)
938 b = read(fd, ((char *)&rechdr)+bytes_read, bytes_to_read - bytes_read);
946 /* take care of byte order */
947 adjust_header(ld, hdr, &rechdr.hdr);
948 if (rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
953 /* read the packet data */
954 bytes_read = read(fd, pd, rechdr.hdr.incl_len);
955 if (bytes_read <= 0) {
960 while (bytes_read < rechdr.hdr.incl_len)
962 b = read(fd, pd+bytes_read, rechdr.hdr.incl_len - bytes_read);
970 /* dump the packet data to the capture file */
971 whdr.ts.tv_sec = rechdr.hdr.ts_sec;
972 whdr.ts.tv_usec = rechdr.hdr.ts_usec;
973 whdr.caplen = rechdr.hdr.incl_len;
974 whdr.len = rechdr.hdr.orig_len;
975 whdr.pkt_encap = ld->linktype;
976 wtap_dump(ld->pdh, &whdr, NULL, pd, &err);
978 /* Set the initial payload to the packet length, and the initial
979 captured payload to the capture length (other protocols may
980 reduce them if their headers say they're less). */
982 pi.captured_len = whdr.caplen;
984 /* update capture statistics */
985 switch (ld->linktype) {
986 case WTAP_ENCAP_ETHERNET:
987 capture_eth(pd, 0, &ld->counts);
989 case WTAP_ENCAP_FDDI:
990 case WTAP_ENCAP_FDDI_BITSWAPPED:
991 capture_fddi(pd, &ld->counts);
993 case WTAP_ENCAP_TOKEN_RING:
994 capture_tr(pd, 0, &ld->counts);
996 case WTAP_ENCAP_NULL:
997 capture_null(pd, &ld->counts);
1000 capture_ppp(pd, 0, &ld->counts);
1002 case WTAP_ENCAP_RAW_IP:
1003 capture_raw(pd, &ld->counts);
1005 case WTAP_ENCAP_LINUX_ATM_CLIP:
1006 capture_clip(pd, &ld->counts);
1008 case WTAP_ENCAP_IEEE_802_11:
1009 capture_ieee80211(pd,0,&ld->counts);
1011 /* XXX - FreeBSD may append 4-byte ATM pseudo-header to DLT_ATM_RFC1483,
1012 with LLC header following; we should implement it at some
1021 * This needs to be static, so that the SIGUSR1 handler can clear the "go"
1024 static loop_data ld;
1026 /* Do the low-level work of a capture.
1027 Returns TRUE if it succeeds, FALSE otherwise. */
1031 GtkWidget *cap_w, *main_vb, *stop_bt, *counts_tb;
1035 gchar err_str[PCAP_ERRBUF_SIZE], label_str[64];
1036 bpf_u_int32 netnum, netmask;
1037 time_t upd_time, cur_time;
1039 char errmsg[4096+1];
1041 static const char ppamsg[] = "can't find PPA for ";
1045 struct timeval timeout;
1050 WORD wVersionRequested;
1055 struct pcap_hdr hdr;
1060 GtkWidget *label, *value, *percent;
1062 { "Total", &ld.counts.total },
1063 { "SCTP", &ld.counts.sctp },
1064 { "TCP", &ld.counts.tcp },
1065 { "UDP", &ld.counts.udp },
1066 { "ICMP", &ld.counts.icmp },
1067 { "OSPF", &ld.counts.ospf },
1068 { "GRE", &ld.counts.gre },
1069 { "NetBIOS", &ld.counts.netbios },
1070 { "IPX", &ld.counts.ipx },
1071 { "VINES", &ld.counts.vines },
1072 { "Other", &ld.counts.other }
1075 #define N_STATS (sizeof stats / sizeof stats[0])
1077 /* Initialize Windows Socket if we are in a WIN32 OS
1078 This needs to be done before querying the interface for network/netmask */
1080 wVersionRequested = MAKEWORD( 1, 1 );
1081 err = WSAStartup( wVersionRequested, &wsaData );
1083 snprintf(errmsg, sizeof errmsg,
1084 "Couldn't initialize Windows Sockets.");
1091 ld.counts.total = 0;
1092 ld.max = cfile.count;
1093 ld.linktype = WTAP_ENCAP_UNKNOWN;
1094 ld.from_pipe = FALSE;
1095 ld.sync_packets = 0;
1103 ld.counts.netbios = 0;
1104 ld.counts.vines = 0;
1105 ld.counts.other = 0;
1108 /* Open the network interface to capture from it. */
1109 pch = pcap_open_live(cfile.iface, cfile.snap, promisc_mode,
1110 CAP_READ_TIMEOUT, err_str);
1114 /* Well, we couldn't start the capture.
1115 If this is a child process that does the capturing in sync
1116 mode or fork mode, it shouldn't do any UI stuff until we pop up the
1117 capture-progress window, and, since we couldn't start the
1118 capture, we haven't popped it up. */
1119 if (!capture_child) {
1120 while (gtk_events_pending()) gtk_main_iteration();
1123 /* On Win32 OSes, the capture devices are probably available to all
1124 users; don't warn about permissions problems.
1126 Do, however, warn that Token Ring and PPP devices aren't supported. */
1127 snprintf(errmsg, sizeof errmsg,
1128 "The capture session could not be initiated (%s).\n"
1129 "Please check that you have the proper interface specified.\n"
1131 "Note that the driver Ethereal uses for packet capture on Windows\n"
1132 "doesn't support capturing on Token Ring interfaces, and doesn't\n"
1133 "support capturing on PPP/WAN interfaces in Windows NT/2000.\n",
1137 /* try to open cfile.iface as a pipe */
1138 pipe_fd = pipe_open_live(cfile.iface, &hdr, &ld, err_str);
1140 if (pipe_fd == -1) {
1141 /* Well, we couldn't start the capture.
1142 If this is a child process that does the capturing in sync
1143 mode or fork mode, it shouldn't do any UI stuff until we pop up the
1144 capture-progress window, and, since we couldn't start the
1145 capture, we haven't popped it up. */
1146 if (!capture_child) {
1147 while (gtk_events_pending()) gtk_main_iteration();
1150 /* If we got a "can't find PPA for XXX" message, warn the user (who
1151 is running Ethereal on HP-UX) that they don't have a version
1152 of libpcap patched to properly handle HP-UX (the patched version
1153 says "can't find /dev/dlpi PPA for XXX" rather than "can't find
1155 if (strncmp(err_str, ppamsg, sizeof ppamsg - 1) == 0)
1158 "You are running Ethereal with a version of the libpcap library\n"
1159 "that doesn't handle HP-UX network devices well; this means that\n"
1160 "Ethereal may not be able to capture packets.\n"
1162 "To fix this, you will need to download the source to Ethereal\n"
1163 "from www.ethereal.com if you have not already done so, read\n"
1164 "the instructions in the \"README.hpux\" file in the source\n"
1165 "distribution, download the source to libpcap if you have not\n"
1166 "already done so, patch libpcap as per the instructions, rebuild\n"
1167 "and install libpcap, and then build Ethereal (if you have already\n"
1168 "built Ethereal from source, do a \"make distclean\" and re-run\n"
1169 "configure before building).";
1172 snprintf(errmsg, sizeof errmsg,
1173 "The capture session could not be initiated (%s).\n"
1174 "Please check to make sure you have sufficient permissions, and that\n"
1175 "you have the proper interface or pipe specified.%s", err_str,
1182 /* capture filters only work on real interfaces */
1183 if (cfile.cfilter && !ld.from_pipe) {
1184 /* A capture filter was specified; set it up. */
1185 if (pcap_lookupnet (cfile.iface, &netnum, &netmask, err_str) < 0) {
1187 * Well, we can't get the netmask for this interface; it's used
1188 * only for filters that check for broadcast IP addresses, so
1189 * we just punt and use 0. It might be nice to warn the user,
1190 * but that's a pain in a GUI application, as it'd involve popping
1191 * up a message box, and it's not clear how often this would make
1192 * a difference (only filters that check for IP broadcast addresses
1197 if (pcap_compile(pch, &cfile.fcode, cfile.cfilter, 1, netmask) < 0) {
1198 snprintf(errmsg, sizeof errmsg, "Unable to parse filter string (%s).",
1202 if (pcap_setfilter(pch, &cfile.fcode) < 0) {
1203 snprintf(errmsg, sizeof errmsg, "Can't install filter (%s).",
1209 /* Set up to write to the capture file. */
1212 pcap_encap = hdr.network;
1213 snaplen = hdr.snaplen;
1217 pcap_encap = pcap_datalink(pch);
1218 snaplen = pcap_snapshot(pch);
1220 ld.linktype = wtap_pcap_encap_to_wtap_encap(pcap_encap);
1221 if (ld.linktype == WTAP_ENCAP_UNKNOWN) {
1222 snprintf(errmsg, sizeof errmsg,
1223 "The network you're capturing from is of a type"
1224 " that Ethereal doesn't support (data link type %d).", pcap_encap);
1227 ld.pdh = wtap_dump_fdopen(cfile.save_file_fd, WTAP_FILE_PCAP,
1228 ld.linktype, snaplen, &err);
1230 if (ld.pdh == NULL) {
1231 /* We couldn't set up to write to the capture file. */
1234 case WTAP_ERR_CANT_OPEN:
1235 strcpy(errmsg, "The file to which the capture would be saved"
1236 " couldn't be created for some unknown reason.");
1239 case WTAP_ERR_SHORT_WRITE:
1240 strcpy(errmsg, "A full header couldn't be written to the file"
1241 " to which the capture would be saved.");
1246 snprintf(errmsg, sizeof(errmsg),
1247 "The file to which the capture would be"
1248 " saved (\"%s\") could not be opened: Error %d.",
1249 cfile.save_file, err);
1251 snprintf(errmsg, sizeof(errmsg),
1252 "The file to which the capture would be"
1253 " saved (\"%s\") could not be opened: %s.",
1254 cfile.save_file, strerror(err));
1261 /* XXX - capture SIGTERM and close the capture, in case we're on a
1262 Linux 2.0[.x] system and you have to explicitly close the capture
1263 stream in order to turn promiscuous mode off? We need to do that
1264 in other places as well - and I don't think that works all the
1265 time in any case, due to libpcap bugs. */
1267 if (capture_child) {
1268 /* Well, we should be able to start capturing.
1270 This is the child process for a sync mode capture, so sync out
1271 the capture file, so the header makes it to the file system,
1272 and send a "capture started successfully and capture file created"
1273 message to our parent so that they'll open the capture file and
1274 update its windows to indicate that we have a live capture in
1276 fflush(wtap_dump_file(ld.pdh));
1280 cap_w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1281 gtk_window_set_title(GTK_WINDOW(cap_w), "Ethereal: Capture");
1282 gtk_window_set_modal(GTK_WINDOW(cap_w), TRUE);
1284 /* Container for capture display widgets */
1285 main_vb = gtk_vbox_new(FALSE, 1);
1286 gtk_container_border_width(GTK_CONTAINER(main_vb), 5);
1287 gtk_container_add(GTK_CONTAINER(cap_w), main_vb);
1288 gtk_widget_show(main_vb);
1290 /* Individual statistic elements */
1291 counts_tb = gtk_table_new(N_STATS, 3, TRUE);
1292 gtk_box_pack_start(GTK_BOX(main_vb), counts_tb, TRUE, TRUE, 3);
1293 gtk_widget_show(counts_tb);
1295 for (i = 0; i < N_STATS; i++) {
1296 stats[i].label = gtk_label_new(stats[i].title);
1297 gtk_misc_set_alignment(GTK_MISC(stats[i].label), 0.0f, 0.0f);
1299 stats[i].value = gtk_label_new("0");
1300 gtk_misc_set_alignment(GTK_MISC(stats[i].value), 0.0f, 0.0f);
1302 stats[i].percent = gtk_label_new("0.0%");
1303 gtk_misc_set_alignment(GTK_MISC(stats[i].percent), 0.0f, 0.0f);
1305 gtk_table_attach_defaults(GTK_TABLE(counts_tb),
1306 stats[i].label, 0, 1, i, i + 1);
1308 gtk_table_attach(GTK_TABLE(counts_tb),
1310 1, 2, i, i + 1, 0, 0, 5, 0);
1312 gtk_table_attach_defaults(GTK_TABLE(counts_tb),
1313 stats[i].percent, 2, 3, i, i + 1);
1315 gtk_widget_show(stats[i].label);
1316 gtk_widget_show(stats[i].value);
1317 gtk_widget_show(stats[i].percent);
1320 /* allow user to either click a stop button, or the close button on
1321 the window to stop a capture in progress. */
1322 stop_bt = gtk_button_new_with_label ("Stop");
1323 gtk_signal_connect(GTK_OBJECT(stop_bt), "clicked",
1324 GTK_SIGNAL_FUNC(capture_stop_cb), (gpointer) &ld);
1325 gtk_signal_connect(GTK_OBJECT(cap_w), "delete_event",
1326 GTK_SIGNAL_FUNC(capture_delete_cb), (gpointer) &ld);
1327 gtk_box_pack_end(GTK_BOX(main_vb), stop_bt, FALSE, FALSE, 3);
1328 GTK_WIDGET_SET_FLAGS(stop_bt, GTK_CAN_DEFAULT);
1329 gtk_widget_grab_default(stop_bt);
1330 GTK_WIDGET_SET_FLAGS(stop_bt, GTK_CAN_DEFAULT);
1331 gtk_widget_grab_default(stop_bt);
1332 gtk_widget_show(stop_bt);
1334 gtk_widget_show(cap_w);
1336 upd_time = time(NULL);
1338 if (!ld.from_pipe) pcap_fd = pcap_fileno(pch);
1343 * Catch SIGUSR1, so that we exit cleanly if the parent process
1344 * kills us with it due to the user selecting "Capture->Stop".
1346 signal(SIGUSR1, stop_capture);
1349 while (gtk_events_pending()) gtk_main_iteration();
1354 FD_SET(pipe_fd, &set1);
1356 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1357 if (select(pipe_fd+1, &set1, NULL, NULL, &timeout) != 0) {
1359 * "select()" says we can read from the pipe without blocking; go for
1360 * it. We are not sure we can read a whole record, but at least the
1361 * begninning of one. pipe_dispatch() will block reading the whole
1364 inpkts = pipe_dispatch(pipe_fd, &ld, &hdr);
1373 * Sigh. The semantics of the read timeout argument to
1374 * "pcap_open_live()" aren't particularly well specified by
1375 * the "pcap" man page - at least with the BSD BPF code, the
1376 * intent appears to be, at least in part, a way of cutting
1377 * down the number of reads done on a capture, by blocking
1378 * until the buffer fills or a timer expires - and the Linux
1379 * libpcap doesn't actually support it, so we can't use it
1380 * to break out of the "pcap_dispatch()" every 1/4 of a second
1383 * Thus, on Linux, we do a "select()" on the file descriptor for the
1384 * capture, with a timeout of CAP_READ_TIMEOUT milliseconds, or
1385 * CAP_READ_TIMEOUT*1000 microseconds.
1388 FD_SET(pcap_fd, &set1);
1390 timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1391 if (select(pcap_fd+1, &set1, NULL, NULL, &timeout) != 0) {
1393 * "select()" says we can read from it without blocking; go for
1396 inpkts = pcap_dispatch(pch, 1, capture_pcap_cb, (u_char *) &ld);
1400 inpkts = pcap_dispatch(pch, 1, capture_pcap_cb, (u_char *) &ld);
1404 ld.sync_packets += inpkts;
1405 /* Only update once a second so as not to overload slow displays */
1406 cur_time = time(NULL);
1407 if (cur_time > upd_time) {
1408 upd_time = cur_time;
1410 for (i = 0; i < N_STATS; i++) {
1411 snprintf(label_str, sizeof(label_str), "%d",
1412 *stats[i].value_ptr);
1414 gtk_label_set(GTK_LABEL(stats[i].value), label_str);
1416 snprintf(label_str, sizeof(label_str), "(%.1f%%)",
1417 pct(*stats[i].value_ptr, ld.counts.total));
1419 gtk_label_set(GTK_LABEL(stats[i].percent), label_str);
1422 /* do sync here, too */
1423 fflush(wtap_dump_file(ld.pdh));
1424 if (capture_child && ld.sync_packets) {
1425 /* This is the child process for a sync mode capture, so send
1426 our parent a message saying we've written out "ld.sync_packets"
1427 packets to the capture file. */
1429 sprintf(tmp, "%d*", ld.sync_packets);
1430 write(1, tmp, strlen(tmp));
1431 ld.sync_packets = 0;
1436 if (!wtap_dump_close(ld.pdh, &err)) {
1437 /* XXX - in fork mode, this may not pop up, or, if it does,
1438 it may disappear as soon as we exit.
1440 We should have the parent process, while it's reading
1441 the packet count update messages, catch error messages
1442 and pop up a message box if it sees one. */
1445 case WTAP_ERR_CANT_CLOSE:
1446 simple_dialog(ESD_TYPE_WARN, NULL,
1447 "The file to which the capture was being saved"
1448 " couldn't be closed for some unknown reason.");
1451 case WTAP_ERR_SHORT_WRITE:
1452 simple_dialog(ESD_TYPE_WARN, NULL,
1453 "Not all the data could be written to the file"
1454 " to which the capture was being saved.");
1458 simple_dialog(ESD_TYPE_WARN, NULL,
1459 "The file to which the capture was being"
1460 " saved (\"%s\") could not be closed: %s.",
1461 cfile.save_file, wtap_strerror(err));
1473 /* Shut down windows sockets */
1477 gtk_grab_remove(GTK_WIDGET(cap_w));
1478 gtk_widget_destroy(GTK_WIDGET(cap_w));
1483 /* We can't use the save file, and we have no wtap_dump stream
1484 to close in order to close it, so close the FD directly. */
1485 close(cfile.save_file_fd);
1487 /* We couldn't even start the capture, so get rid of the capture
1489 unlink(cfile.save_file); /* silently ignore error */
1490 g_free(cfile.save_file);
1491 cfile.save_file = NULL;
1492 if (capture_child) {
1493 /* This is the child process for a sync mode capture.
1494 Send the error message to our parent, so they can display a
1495 dialog box containing it. */
1496 send_errmsg_to_parent(errmsg);
1498 /* Display the dialog box ourselves; there's no parent. */
1499 simple_dialog(ESD_TYPE_CRIT, NULL, errmsg);
1501 if (pch != NULL && !ld.from_pipe)
1508 send_errmsg_to_parent(const char *errmsg)
1510 int msglen = strlen(errmsg);
1511 char lenbuf[10+1+1];
1513 sprintf(lenbuf, "%u;", msglen);
1514 write(1, lenbuf, strlen(lenbuf));
1515 write(1, errmsg, msglen);
1519 pct(gint num, gint denom) {
1521 return (float) num * 100.0 / (float) denom;
1528 stop_capture(int signo)
1534 capture_delete_cb(GtkWidget *w, GdkEvent *event, gpointer data) {
1535 capture_stop_cb(NULL, data);
1539 capture_stop_cb(GtkWidget *w, gpointer data) {
1540 loop_data *ld = (loop_data *) data;
1549 * XXX - find some way of signaling the child in Win32.
1552 if (fork_child != -1)
1553 kill(fork_child, SIGUSR1);
1558 capture_pcap_cb(u_char *user, const struct pcap_pkthdr *phdr,
1560 struct wtap_pkthdr whdr;
1561 loop_data *ld = (loop_data *) user;
1564 if ((++ld->counts.total >= ld->max) && (ld->max > 0))
1569 /* "phdr->ts" may not necessarily be a "struct timeval" - it may
1570 be a "struct bpf_timeval", with member sizes wired to 32
1571 bits - and we may go that way ourselves in the future, so
1572 copy the members individually. */
1573 whdr.ts.tv_sec = phdr->ts.tv_sec;
1574 whdr.ts.tv_usec = phdr->ts.tv_usec;
1575 whdr.caplen = phdr->caplen;
1576 whdr.len = phdr->len;
1577 whdr.pkt_encap = ld->linktype;
1579 /* XXX - do something if this fails */
1580 wtap_dump(ld->pdh, &whdr, NULL, pd, &err);
1583 /* Set the initial payload to the packet length, and the initial
1584 captured payload to the capture length (other protocols may
1585 reduce them if their headers say they're less). */
1587 pi.captured_len = phdr->caplen;
1589 switch (ld->linktype) {
1590 case WTAP_ENCAP_ETHERNET:
1591 capture_eth(pd, 0, &ld->counts);
1593 case WTAP_ENCAP_FDDI:
1594 case WTAP_ENCAP_FDDI_BITSWAPPED:
1595 capture_fddi(pd, &ld->counts);
1597 case WTAP_ENCAP_TOKEN_RING:
1598 capture_tr(pd, 0, &ld->counts);
1600 case WTAP_ENCAP_NULL:
1601 capture_null(pd, &ld->counts);
1603 case WTAP_ENCAP_PPP:
1604 capture_ppp(pd, 0, &ld->counts);
1606 case WTAP_ENCAP_RAW_IP:
1607 capture_raw(pd, &ld->counts);
1609 case WTAP_ENCAP_LINUX_ATM_CLIP:
1610 capture_clip(pd, &ld->counts);
1612 /* XXX - FreeBSD may append 4-byte ATM pseudo-header to DLT_ATM_RFC1483,
1613 with LLC header following; we should implement it at some
1618 #endif /* HAVE_LIBPCAP */