c90f451bff72c2453b46d4b836ea73b26fcbad50
[obnox/wireshark/wip.git] / capture.c
1 /* capture.c
2  * Routines for packet capture windows
3  *
4  * $Id: capture.c,v 1.167 2002/01/10 11:05:48 guy Exp $
5  *
6  * Ethereal - Network traffic analyzer
7  * By Gerald Combs <gerald@ethereal.com>
8  * Copyright 1998 Gerald Combs
9  * 
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.
14  * 
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.
19  * 
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.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #ifdef HAVE_LIBPCAP
30
31 #ifdef HAVE_SYS_TYPES_H
32 # include <sys/types.h>
33 #endif
34
35 #ifdef HAVE_SYS_STAT_H
36 # include <sys/stat.h>
37 #endif
38
39 #ifdef HAVE_SYS_WAIT_H
40 # include <sys/wait.h>
41 #endif
42
43 #ifndef _WIN32
44 /*
45  * Define various POSIX macros (and, in the case of WCOREDUMP, non-POSIX
46  * macros) on UNIX systems that don't have them.
47  */
48 #ifndef WIFEXITED
49 # define WIFEXITED(status)      (((status) & 0177) == 0)
50 #endif
51 #ifndef WIFSTOPPED
52 # define WIFSTOPPED(status)     (((status) & 0177) == 0177)
53 #endif
54 #ifndef WIFSIGNALED
55 # define WIFSIGNALED(status)    (!WIFSTOPPED(status) && !WIFEXITED(status))
56 #endif
57 #ifndef WEXITSTATUS
58 # define WEXITSTATUS(status)    ((status) >> 8)
59 #endif
60 #ifndef WTERMSIG
61 # define WTERMSIG(status)       ((status) & 0177)
62 #endif
63 #ifndef WCOREDUMP
64 # define WCOREDUMP(status)      ((status) & 0200)
65 #endif
66 #ifndef WSTOPSIG
67 # define WSTOPSIG(status)       ((status) >> 8)
68 #endif
69 #endif /* _WIN32 */
70
71 #ifdef HAVE_IO_H
72 # include <io.h>
73 #endif
74
75 #include <gtk/gtk.h>
76 #include <stdlib.h>
77 #include <stdio.h>
78 #include <ctype.h>
79 #include <string.h>
80
81 #ifdef HAVE_FCNTL_H
82 #include <fcntl.h>
83 #endif
84
85 #ifdef HAVE_UNISTD_H
86 #include <unistd.h>
87 #endif
88
89 #include <time.h>
90
91 #ifdef HAVE_SYS_SOCKET_H
92 #include <sys/socket.h>
93 #endif
94
95 #ifdef HAVE_SYS_IOCTL_H
96 #include <sys/ioctl.h>
97 #endif
98
99 #include <signal.h>
100 #include <errno.h>
101
102 #include <pcap.h>
103
104 #ifdef NEED_SNPRINTF_H
105 # include "snprintf.h"
106 #endif
107
108 #ifdef _WIN32
109 #include <process.h>    /* For spawning child process */
110 #endif
111
112 /*
113  * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
114  * want to include it if it's not present on this platform, however.
115  */
116 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__bsdi__)
117 #ifndef BSD
118 #define BSD
119 #endif /* BSD */
120 #endif /* defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__bsdi__) */
121
122 /*
123  * We don't want to do a "select()" on the pcap_t's file descriptor on
124  * BSD (because "select()" doesn't work correctly on BPF devices on at
125  * least some releases of some flavors of BSD), and we don't want to do
126  * it on Windows (because "select()" is something for sockets, not for
127  * arbitrary handles).
128  *
129  * We *do* want to do it on other platforms, as, on other platforms (with
130  * the possible exception of Ultrix and Digital UNIX), the read timeout
131  * doesn't expire if no packets have arrived, so a "pcap_dispatch()" call
132  * will block until packets arrive, causing the UI to hang.
133  */
134 #if !defined(BSD) && !defined(_WIN32)
135 # define MUST_DO_SELECT
136 #endif
137
138 #include "gtk/main.h"
139 #include "gtk/gtkglobals.h"
140 #include "packet.h"
141 #include "file.h"
142 #include "capture.h"
143 #include "util.h"
144 #include "pcap-util.h"
145 #include "simple_dialog.h"
146 #include "prefs.h"
147 #include "globals.h"
148 #include "conditions.h"
149 #include "capture_stop_conditions.h"
150 #include "ringbuffer.h"
151
152 #include "wiretap/libpcap.h"
153 #include "wiretap/wtap.h"
154
155 #include "packet-atalk.h"
156 #include "packet-clip.h"
157 #include "packet-eth.h"
158 #include "packet-fddi.h"
159 #include "packet-null.h"
160 #include "packet-ppp.h"
161 #include "packet-raw.h"
162 #include "packet-sll.h"
163 #include "packet-tr.h"
164 #include "packet-ieee80211.h"
165 #include "packet-chdlc.h"
166 #include "packet-prism.h"
167
168 #ifdef WIN32
169 #include "capture-wpcap.h"
170 #endif
171
172 int promisc_mode; /* capture in promiscuous mode */
173 int sync_mode;  /* fork a child to do the capture, and sync between them */
174 static int sync_pipe[2]; /* used to sync father */
175 enum PIPES { READ, WRITE }; /* Constants 0 and 1 for READ and WRITE */
176 int quit_after_cap; /* Makes a "capture only mode". Implies -k */
177 gboolean capture_child; /* if this is the child for "-S" */
178 static int fork_child = -1;     /* If not -1, in parent, process ID of child */
179 static guint cap_input_id;
180
181 /*
182  * Indications sent out on the sync pipe.
183  */
184 #define SP_CAPSTART     ';'     /* capture start message */
185 #define SP_PACKET_COUNT '*'     /* followed by count of packets captured since last message */
186 #define SP_ERROR_MSG    '!'     /* followed by length of error message that follows */
187 #define SP_DROPS        '#'     /* followed by count of packets dropped in capture */
188
189 #ifdef _WIN32
190 static guint cap_timer_id;
191 static int cap_timer_cb(gpointer); /* Win32 kludge to check for pipe input */
192 #endif
193
194 static void cap_file_input_cb(gpointer, gint, GdkInputCondition);
195 static void wait_for_child(gboolean);
196 #ifndef _WIN32
197 static char *signame(int);
198 #endif
199 static void capture_delete_cb(GtkWidget *, GdkEvent *, gpointer);
200 static void capture_stop_cb(GtkWidget *, gpointer);
201 static void capture_pcap_cb(u_char *, const struct pcap_pkthdr *,
202   const u_char *);
203 static void get_capture_file_io_error(char *, int, const char *, int, gboolean);
204 static void send_errmsg_to_parent(const char *);
205 static float pct(gint, gint);
206 static void stop_capture(int signo);
207
208 typedef struct _loop_data {
209   gboolean       go;           /* TRUE as long as we're supposed to keep capturing */
210   gint           max;          /* Number of packets we're supposed to capture - 0 means infinite */
211   int            err;          /* if non-zero, error seen while capturing */
212   gint           linktype;
213   gint           sync_packets;
214   gboolean       pcap_err;     /* TRUE if error from pcap */
215   gboolean       from_pipe;    /* TRUE if we are capturing data from a pipe */
216   gboolean       modified;     /* TRUE if data in the pipe uses modified pcap headers */
217   gboolean       byte_swapped; /* TRUE if data in the pipe is byte swapped */
218   packet_counts  counts;
219   wtap_dumper   *pdh;
220 } loop_data;
221
222 #ifndef _WIN32
223 static void adjust_header(loop_data *, struct pcap_hdr *, struct pcaprec_hdr *);
224 static int pipe_open_live(char *, struct pcap_hdr *, loop_data *, char *);
225 static int pipe_dispatch(int, loop_data *, struct pcap_hdr *);
226 #endif
227
228 /* Win32 needs the O_BINARY flag for open() */
229 #ifndef O_BINARY
230 #define O_BINARY        0
231 #endif
232
233 #ifdef _WIN32
234 /* Win32 needs a handle to the child capture process */
235 int child_process;
236 #endif
237
238 /* Add a string pointer to a NULL-terminated array of string pointers. */
239 static char **
240 add_arg(char **args, int *argc, char *arg)
241 {
242   /* Grow the array; "*argc" currently contains the number of string
243      pointers, *not* counting the NULL pointer at the end, so we have
244      to add 2 in order to get the new size of the array, including the
245      new pointer and the terminating NULL pointer. */
246   args = g_realloc(args, (*argc + 2) * sizeof (char *));
247
248   /* Stuff the pointer into the penultimate element of the array, which
249      is the one at the index specified by "*argc". */
250   args[*argc] = arg;
251
252   /* Now bump the count. */
253   (*argc)++;
254
255   /* We overwrite the NULL pointer; put it back right after the
256      element we added. */
257   args[*argc] = NULL;
258
259   return args;
260 }
261
262 #ifdef _WIN32
263 /* Given a string, return a pointer to a quote-encapsulated version of
264    the string, so we can pass it as an argument with "spawnvp" even
265    if it contains blanks. */
266 char *
267 quote_encapsulate(const char *string)
268 {
269   char *encapsulated_string;
270
271   encapsulated_string = g_new(char, strlen(string) + 3);
272   sprintf(encapsulated_string, "\"%s\"", string);
273   return encapsulated_string;
274 }
275 #endif
276
277 /* Open a specified file, or create a temporary file, and start a capture
278    to the file in question. */
279 void
280 do_capture(char *capfile_name)
281 {
282   char tmpname[128+1];
283   gboolean is_tempfile;
284   u_char c;
285   int i;
286   guint byte_count;
287   char *msg;
288   int err;
289   int capture_succeeded;
290   gboolean stats_known;
291   struct pcap_stat stats;
292
293   if (capfile_name != NULL) {
294     if (cfile.ringbuffer_on) {
295       /* ringbuffer is enabled */
296       cfile.save_file_fd = ringbuf_init(capfile_name, cfile.ringbuffer_num_files);
297     } else {
298       /* Try to open/create the specified file for use as a capture buffer. */
299       cfile.save_file_fd = open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT, 0600);
300     }
301     is_tempfile = FALSE;
302   } else {
303     /* Choose a random name for the capture buffer */
304     cfile.save_file_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
305     capfile_name = g_strdup(tmpname);
306     is_tempfile = TRUE;
307   }
308   if (cfile.save_file_fd == -1) {
309     if (is_tempfile) {
310       simple_dialog(ESD_TYPE_CRIT, NULL,
311         "The temporary file to which the capture would be saved (\"%s\")"
312         "could not be opened: %s.", capfile_name, strerror(errno));
313     } else {
314       if (cfile.ringbuffer_on) {
315         ringbuf_error_cleanup();
316       }
317       simple_dialog(ESD_TYPE_CRIT, NULL,
318         file_open_error_message(errno, TRUE), capfile_name);
319     }
320     return;
321   }
322   close_cap_file(&cfile);
323   g_assert(cfile.save_file == NULL);
324   cfile.save_file = capfile_name;
325
326   if (sync_mode) {      /* do the capture in a child process */
327     char ssnap[24];
328     char scount[24];                    /* need a constant for len of numbers */
329     char sautostop_filesize[24];        /* need a constant for len of numbers */
330     char sautostop_duration[24];        /* need a constant for len of numbers */
331     char save_file_fd[24];
332     char errmsg[1024+1];
333     int error;
334     int argc;
335     char **argv;
336 #ifdef _WIN32
337     char sync_pipe_fd[24];
338     char *fontstring;
339     char *filterstring;
340 #endif
341
342     /* Allocate the string pointer array with enough space for the
343        terminating NULL pointer. */
344     argc = 0;
345     argv = g_malloc(sizeof (char *));
346     *argv = NULL;
347
348     /* Now add those arguments used on all platforms. */
349     argv = add_arg(argv, &argc, CHILD_NAME);
350
351     argv = add_arg(argv, &argc, "-i");
352     argv = add_arg(argv, &argc, cfile.iface);
353
354     argv = add_arg(argv, &argc, "-w");
355     argv = add_arg(argv, &argc, cfile.save_file);
356
357     argv = add_arg(argv, &argc, "-W");
358     sprintf(save_file_fd,"%d",cfile.save_file_fd);      /* in lieu of itoa */
359     argv = add_arg(argv, &argc, save_file_fd);
360
361     argv = add_arg(argv, &argc, "-c");
362     sprintf(scount,"%d",cfile.count);
363     argv = add_arg(argv, &argc, scount);
364
365     argv = add_arg(argv, &argc, "-s");
366     sprintf(ssnap,"%d",cfile.snap);
367     argv = add_arg(argv, &argc, ssnap);
368
369     argv = add_arg(argv, &argc, "-a");
370     sprintf(sautostop_filesize,"filesize:%d",cfile.autostop_filesize);
371     argv = add_arg(argv, &argc, sautostop_filesize);
372
373     argv = add_arg(argv, &argc, "-a");
374     sprintf(sautostop_duration,"duration:%d",cfile.autostop_duration);
375     argv = add_arg(argv, &argc, sautostop_duration);
376
377     if (!promisc_mode)
378       argv = add_arg(argv, &argc, "-p");
379
380 #ifdef _WIN32
381     /* Create a pipe for the child process */
382
383     if(_pipe(sync_pipe, 512, O_BINARY) < 0) {
384       /* Couldn't create the pipe between parent and child. */
385       error = errno;
386       unlink(cfile.save_file);
387       g_free(cfile.save_file);
388       cfile.save_file = NULL;
389       simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create sync pipe: %s",
390                         strerror(error));
391       return;
392     }
393
394     /* Convert font name to a quote-encapsulated string and pass to child */
395     argv = add_arg(argv, &argc, "-m");
396     fontstring = quote_encapsulate(prefs.gui_font_name);
397     argv = add_arg(argv, &argc, fontstring);
398
399     /* Convert pipe write handle to a string and pass to child */
400     argv = add_arg(argv, &argc, "-Z");
401     itoa(sync_pipe[WRITE], sync_pipe_fd, 10);
402     argv = add_arg(argv, &argc, sync_pipe_fd);
403
404     /* Convert filter string to a quote delimited string and pass to child */
405     if (cfile.cfilter != NULL && strlen(cfile.cfilter) != 0) {
406       argv = add_arg(argv, &argc, "-f");
407       filterstring = quote_encapsulate(cfile.cfilter);
408       argv = add_arg(argv, &argc, filterstring);
409     }
410
411     /* Spawn process */
412     fork_child = spawnvp(_P_NOWAIT, ethereal_path, argv);
413     g_free(fontstring);
414     g_free(filterstring);
415     /* Keep a copy for later evaluation by _cwait() */
416     child_process = fork_child;
417 #else
418     signal(SIGCHLD, SIG_IGN);
419     if (pipe(sync_pipe) < 0) {
420       /* Couldn't create the pipe between parent and child. */
421       error = errno;
422       unlink(cfile.save_file);
423       g_free(cfile.save_file);
424       cfile.save_file = NULL;
425       simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create sync pipe: %s",
426                         strerror(error));
427       return;
428     }
429
430     argv = add_arg(argv, &argc, "-m");
431     argv = add_arg(argv, &argc, prefs.gui_font_name);
432
433     if (cfile.cfilter != NULL && strlen(cfile.cfilter) != 0) {
434       argv = add_arg(argv, &argc, "-f");
435       argv = add_arg(argv, &argc, cfile.cfilter);
436     }
437
438     if ((fork_child = fork()) == 0) {
439       /*
440        * Child process - run Ethereal with the right arguments to make
441        * it just pop up the live capture dialog box and capture with
442        * the specified capture parameters, writing to the specified file.
443        *
444        * args: -i interface specification
445        * -w file to write
446        * -W file descriptor to write
447        * -c count to capture
448        * -s snaplen
449        * -m / -b fonts
450        * -f "filter expression"
451        */
452       close(1);
453       dup(sync_pipe[WRITE]);
454       close(sync_pipe[READ]);
455       execvp(ethereal_path, argv);
456       snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
457                 ethereal_path, strerror(errno));
458       send_errmsg_to_parent(errmsg);
459
460       /* Exit with "_exit()", so that we don't close the connection
461          to the X server (and cause stuff buffered up by our parent but
462          not yet sent to be sent, as that stuff should only be sent by
463          our parent). */
464       _exit(2);
465     }
466 #endif
467
468     /* Parent process - read messages from the child process over the
469        sync pipe. */
470     g_free(argv);       /* free up arg array */
471
472     /* Close the write side of the pipe, so that only the child has it
473        open, and thus it completely closes, and thus returns to us
474        an EOF indication, if the child closes it (either deliberately
475        or by exiting abnormally). */
476     close(sync_pipe[WRITE]);
477
478     /* Close the save file FD, as we won't be using it - we'll be opening
479        it and reading the save file through Wiretap. */
480     close(cfile.save_file_fd);
481
482     if (fork_child == -1) {
483       /* We couldn't even create the child process. */
484       error = errno;
485       close(sync_pipe[READ]);
486       unlink(cfile.save_file);
487       g_free(cfile.save_file);
488       cfile.save_file = NULL;
489       simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create child process: %s",
490                         strerror(error));
491       return;
492     }
493
494     /* Read a byte count from "sync_pipe[READ]", terminated with a
495        colon; if the count is 0, the child process created the
496        capture file and we should start reading from it, otherwise
497        the capture couldn't start and the count is a count of bytes
498        of error message, and we should display the message. */
499     byte_count = 0;
500     for (;;) {
501       i = read(sync_pipe[READ], &c, 1);
502       if (i == 0) {
503         /* EOF - the child process died.
504            Close the read side of the sync pipe, remove the capture file,
505            and report the failure. */
506         close(sync_pipe[READ]);
507         unlink(cfile.save_file);
508         g_free(cfile.save_file);
509         cfile.save_file = NULL;
510         wait_for_child(TRUE);
511         return;
512       }
513       if (c == SP_CAPSTART || c == SP_ERROR_MSG)
514         break;
515       if (!isdigit(c)) {
516         /* Child process handed us crap.
517            Close the read side of the sync pipe, remove the capture file,
518            and report the failure. */
519         close(sync_pipe[READ]);
520         unlink(cfile.save_file);
521         g_free(cfile.save_file);
522         cfile.save_file = NULL;
523         simple_dialog(ESD_TYPE_WARN, NULL,
524                         "Capture child process sent us a bad message");
525         return;
526       }
527       byte_count = byte_count*10 + c - '0';
528     }
529     if (c == SP_CAPSTART) {
530       /* Success.  Open the capture file, and set up to read it. */
531       err = start_tail_cap_file(cfile.save_file, is_tempfile, &cfile);
532       if (err == 0) {
533         /* We were able to open and set up to read the capture file;
534            arrange that our callback be called whenever it's possible
535            to read from the sync pipe, so that it's called when
536            the child process wants to tell us something. */
537 #ifdef _WIN32
538         /* Tricky to use pipes in win9x, as no concept of wait.  NT can
539            do this but that doesn't cover all win32 platforms.  GTK can do
540            this but doesn't seem to work over processes.  Attempt to do
541            something similar here, start a timer and check for data on every
542            timeout. */
543         cap_timer_id = gtk_timeout_add(1000, cap_timer_cb, NULL);
544 #else
545         cap_input_id = gtk_input_add_full(sync_pipe[READ],
546                                        GDK_INPUT_READ|GDK_INPUT_EXCEPTION,
547                                        cap_file_input_cb,
548                                        NULL,
549                                        (gpointer) &cfile,
550                                        NULL);
551 #endif
552       } else {
553         /* We weren't able to open the capture file; complain, and
554            close the sync pipe. */
555         simple_dialog(ESD_TYPE_CRIT, NULL,
556                         file_open_error_message(err, FALSE), cfile.save_file);
557
558         /* Close the sync pipe. */
559         close(sync_pipe[READ]);
560
561         /* Don't unlink the save file - leave it around, for debugging
562            purposes. */
563         g_free(cfile.save_file);
564         cfile.save_file = NULL;
565       }
566     } else {
567       /* Failure - the child process sent us a message indicating
568          what the problem was. */
569       if (byte_count == 0) {
570         /* Zero-length message? */
571         simple_dialog(ESD_TYPE_WARN, NULL,
572                 "Capture child process failed, but its error message was empty.");
573       } else {
574         msg = g_malloc(byte_count + 1);
575         if (msg == NULL) {
576           simple_dialog(ESD_TYPE_WARN, NULL,
577                 "Capture child process failed, but its error message was too big.");
578         } else {
579           i = read(sync_pipe[READ], msg, byte_count);
580           msg[byte_count] = '\0';
581           if (i < 0) {
582             simple_dialog(ESD_TYPE_WARN, NULL,
583                   "Capture child process failed: Error %s reading its error message.",
584                   strerror(errno));
585           } else if (i == 0) {
586             simple_dialog(ESD_TYPE_WARN, NULL,
587                   "Capture child process failed: EOF reading its error message.");
588             wait_for_child(FALSE);
589           } else
590             simple_dialog(ESD_TYPE_WARN, NULL, msg);
591           g_free(msg);
592         }
593
594         /* Close the sync pipe. */
595         close(sync_pipe[READ]);
596
597         /* Get rid of the save file - the capture never started. */
598         unlink(cfile.save_file);
599         g_free(cfile.save_file);
600         cfile.save_file = NULL;
601       }
602     }
603   } else {
604     /* Not sync mode. */
605     capture_succeeded = capture(&stats_known, &stats);
606     if (quit_after_cap) {
607       /* DON'T unlink the save file.  Presumably someone wants it. */
608       gtk_exit(0);
609     }
610     if (capture_succeeded) {
611       /* Capture succeeded; read in the capture file. */
612       if ((err = open_cap_file(cfile.save_file, is_tempfile, &cfile)) == 0) {
613         /* Set the read filter to NULL. */
614         cfile.rfcode = NULL;
615
616         /* Get the packet-drop statistics.
617
618            XXX - there are currently no packet-drop statistics stored
619            in libpcap captures, and that's what we're reading.
620
621            At some point, we will add support in Wiretap to return
622            packet-drop statistics for capture file formats that store it,
623            and will make "read_cap_file()" get those statistics from
624            Wiretap.  We clear the statistics (marking them as "not known")
625            in "open_cap_file()", and "read_cap_file()" will only fetch
626            them and mark them as known if Wiretap supplies them, so if
627            we get the statistics now, after calling "open_cap_file()" but
628            before calling "read_cap_file()", the values we store will
629            be used by "read_cap_file()".
630
631            If a future libpcap capture file format stores the statistics,
632            we'll put them into the capture file that we write, and will
633            thus not have to set them here - "read_cap_file()" will get
634            them from the file and use them. */
635         if (stats_known) {
636           cfile.drops_known = TRUE;
637
638           /* XXX - on some systems, libpcap doesn't bother filling in
639              "ps_ifdrop" - it doesn't even set it to zero - so we don't
640              bother looking at it.
641
642              Ideally, libpcap would have an interface that gave us
643              several statistics - perhaps including various interface
644              error statistics - and would tell us which of them it
645              supplies, allowing us to display only the ones it does. */
646           cfile.drops = stats.ps_drop;
647         }
648         switch (read_cap_file(&cfile, &err)) {
649
650         case READ_SUCCESS:
651         case READ_ERROR:
652           /* Just because we got an error, that doesn't mean we were unable
653              to read any of the file; we handle what we could get from the
654              file. */
655           break;
656
657         case READ_ABORTED:
658           /* Exit by leaving the main loop, so that any quit functions
659              we registered get called. */
660           gtk_main_quit();
661           return;
662         }
663       }
664     }
665     /* We're not doing a capture any more, so we don't have a save
666        file. */
667     if (cfile.ringbuffer_on) {
668       ringbuf_free();
669     } else {
670       g_free(cfile.save_file);
671     }
672     cfile.save_file = NULL;
673   }
674 }
675
676 #ifdef _WIN32
677 /* The timer has expired, see if there's stuff to read from the pipe,
678    if so call the cap_file_input_cb */
679 static gint
680 cap_timer_cb(gpointer data)
681 {
682   HANDLE handle;
683   DWORD avail = 0;
684   gboolean result, result1;
685   DWORD childstatus;
686
687   /* Oddly enough although Named pipes don't work on win9x,
688      PeekNamedPipe does !!! */
689   handle = (HANDLE) _get_osfhandle (sync_pipe[READ]);
690   result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
691
692   /* Get the child process exit status */
693   result1 = GetExitCodeProcess((HANDLE)child_process, &childstatus);
694
695   /* If the Peek returned an error, or there are bytes to be read
696      or the childwatcher thread has terminated then call the normal
697      callback */
698   if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
699
700     /* avoid reentrancy problems and stack overflow */
701     gtk_timeout_remove(cap_timer_id);
702
703     /* And call the real handler */
704     cap_file_input_cb((gpointer) &cfile, 0, 0);
705
706     /* Return false so that the timer is not run again */
707     return FALSE;
708   }
709   else {
710     /* No data so let timer run again */
711     return TRUE;
712   }
713 }
714 #endif
715
716 /* There's stuff to read from the sync pipe, meaning the child has sent
717    us a message, or the sync pipe has closed, meaning the child has
718    closed it (perhaps because it exited). */
719 static void 
720 cap_file_input_cb(gpointer data, gint source, GdkInputCondition condition)
721 {
722   capture_file *cf = (capture_file *)data;
723 #define BUFSIZE 4096
724   char buffer[BUFSIZE+1], *p = buffer, *q = buffer, *msg, *r;
725   int  nread, msglen, chars_to_copy;
726   int  to_read = 0;
727   int  err;
728
729 #ifndef _WIN32
730   /* avoid reentrancy problems and stack overflow */
731   gtk_input_remove(cap_input_id);
732 #endif
733
734   if ((nread = read(sync_pipe[READ], buffer, BUFSIZE)) <= 0) {
735     /* The child has closed the sync pipe, meaning it's not going to be
736        capturing any more packets.  Pick up its exit status, and
737        complain if it did anything other than exit with status 0. */
738     wait_for_child(FALSE);
739       
740     /* Read what remains of the capture file, and finish the capture.
741        XXX - do something if this fails? */
742     switch (finish_tail_cap_file(cf, &err)) {
743
744     case READ_SUCCESS:
745     case READ_ERROR:
746       /* Just because we got an error, that doesn't mean we were unable
747          to read any of the file; we handle what we could get from the
748          file. */
749       break;
750
751     case READ_ABORTED:
752       /* Exit by leaving the main loop, so that any quit functions
753          we registered get called. */
754       gtk_main_quit();
755       return;
756     }
757
758     /* We're not doing a capture any more, so we don't have a save
759        file. */
760     g_free(cf->save_file);
761     cf->save_file = NULL;
762
763     return;
764   }
765
766   buffer[nread] = '\0';
767
768   while (nread != 0) {
769     /* look for (possibly multiple) indications */
770     switch (*q) {
771     case SP_PACKET_COUNT :
772       to_read += atoi(p);
773       p = q + 1;
774       q++;
775       nread--;
776       break;
777     case SP_DROPS :
778       cf->drops_known = TRUE;
779       cf->drops = atoi(p);
780       p = q + 1;
781       q++;
782       nread--;
783       break;
784     case SP_ERROR_MSG :
785       msglen = atoi(p);
786       p = q + 1;
787       q++;
788       nread--;
789
790       /* Read the entire message.
791          XXX - if the child hasn't sent it all yet, this could cause us
792          to hang until they do. */
793       msg = g_malloc(msglen + 1);
794       r = msg;
795       while (msglen != 0) {
796         if (nread == 0) {
797           /* Read more. */
798           if ((nread = read(sync_pipe[READ], buffer, BUFSIZE)) <= 0)
799             break;
800           p = buffer;
801           q = buffer;
802         }
803         chars_to_copy = MIN(msglen, nread);
804         memcpy(r, q, chars_to_copy);
805         r += chars_to_copy;
806         q += chars_to_copy;
807         nread -= chars_to_copy;
808         msglen -= chars_to_copy;
809       }
810       *r = '\0';
811       simple_dialog(ESD_TYPE_WARN, NULL, msg);
812       g_free(msg);
813       break;
814     default :
815       q++;
816       nread--;
817       break;
818     } 
819   }
820
821   /* Read from the capture file the number of records the child told us
822      it added.
823      XXX - do something if this fails? */
824   switch (continue_tail_cap_file(cf, to_read, &err)) {
825
826   case READ_SUCCESS:
827   case READ_ERROR:
828     /* Just because we got an error, that doesn't mean we were unable
829        to read any of the file; we handle what we could get from the
830        file.
831
832        XXX - abort on a read error? */
833     break;
834
835   case READ_ABORTED:
836     /* Kill the child capture process; the user wants to exit, and we
837        shouldn't just leave it running. */
838 #ifdef _WIN32
839     /* XXX - kill it. */
840 #else
841     kill(fork_child, SIGTERM);  /* SIGTERM so it can clean up if necessary */
842 #endif
843     break;
844   }
845
846   /* restore pipe handler */
847 #ifdef _WIN32
848   cap_timer_id = gtk_timeout_add(1000, cap_timer_cb, NULL);
849 #else
850   cap_input_id = gtk_input_add_full (sync_pipe[READ],
851                                      GDK_INPUT_READ|GDK_INPUT_EXCEPTION,
852                                      cap_file_input_cb,
853                                      NULL,
854                                      (gpointer) cf,
855                                      NULL);
856 #endif
857 }
858
859 static void
860 wait_for_child(gboolean always_report)
861 {
862   int  wstatus;
863
864 #ifdef _WIN32
865   /* XXX - analyze the wait stuatus and display more information
866      in the dialog box? */
867   if (_cwait(&wstatus, child_process, _WAIT_CHILD) == -1) {
868     simple_dialog(ESD_TYPE_WARN, NULL, "Child capture process stopped unexpectedly");
869   }
870 #else
871   if (wait(&wstatus) != -1) {
872     if (WIFEXITED(wstatus)) {
873       /* The child exited; display its exit status, if it's not zero,
874          and even if it's zero if "always_report" is true. */
875       if (always_report || WEXITSTATUS(wstatus) != 0) {
876         simple_dialog(ESD_TYPE_WARN, NULL,
877                       "Child capture process exited: exit status %d",
878                       WEXITSTATUS(wstatus));
879       }
880     } else if (WIFSTOPPED(wstatus)) {
881       /* It stopped, rather than exiting.  "Should not happen." */
882       simple_dialog(ESD_TYPE_WARN, NULL,
883                     "Child capture process stopped: %s",
884                     signame(WSTOPSIG(wstatus)));
885     } else if (WIFSIGNALED(wstatus)) {
886       /* It died with a signal. */
887       simple_dialog(ESD_TYPE_WARN, NULL,
888                     "Child capture process died: %s%s",
889                     signame(WTERMSIG(wstatus)),
890                     WCOREDUMP(wstatus) ? " - core dumped" : "");
891     } else {
892       /* What?  It had to either have exited, or stopped, or died with
893          a signal; what happened here? */
894       simple_dialog(ESD_TYPE_WARN, NULL,
895                     "Child capture process died: wait status %#o", wstatus);
896     }
897   }
898
899   /* No more child process. */
900   fork_child = -1;
901 #endif
902 }
903
904 #ifndef _WIN32
905 static char *
906 signame(int sig)
907 {
908   char *sigmsg;
909   static char sigmsg_buf[6+1+3+1];
910
911   switch (sig) {
912
913   case SIGHUP:
914     sigmsg = "Hangup";
915     break;
916
917   case SIGINT:
918     sigmsg = "Interrupted";
919     break;
920
921   case SIGQUIT:
922     sigmsg = "Quit";
923     break;
924
925   case SIGILL:
926     sigmsg = "Illegal instruction";
927     break;
928
929   case SIGTRAP:
930     sigmsg = "Trace trap";
931     break;
932
933   case SIGABRT:
934     sigmsg = "Abort";
935     break;
936
937   case SIGFPE:
938     sigmsg = "Arithmetic exception";
939     break;
940
941   case SIGKILL:
942     sigmsg = "Killed";
943     break;
944
945   case SIGBUS:
946     sigmsg = "Bus error";
947     break;
948
949   case SIGSEGV:
950     sigmsg = "Segmentation violation";
951     break;
952
953   /* http://metalab.unc.edu/pub/Linux/docs/HOWTO/GCC-HOWTO 
954      Linux is POSIX compliant.  These are not POSIX-defined signals ---
955      ISO/IEC 9945-1:1990 (IEEE Std 1003.1-1990), paragraph B.3.3.1.1 sez:
956
957         ``The signals SIGBUS, SIGEMT, SIGIOT, SIGTRAP, and SIGSYS
958         were omitted from POSIX.1 because their behavior is
959         implementation dependent and could not be adequately catego-
960         rized.  Conforming implementations may deliver these sig-
961         nals, but must document the circumstances under which they
962         are delivered and note any restrictions concerning their
963         delivery.''
964
965      So we only check for SIGSYS on those systems that happen to
966      implement them (a system can be POSIX-compliant and implement
967      them, it's just that POSIX doesn't *require* a POSIX-compliant
968      system to implement them).
969    */
970
971 #ifdef SIGSYS
972   case SIGSYS:
973     sigmsg = "Bad system call";
974     break;
975 #endif
976
977   case SIGPIPE:
978     sigmsg = "Broken pipe";
979     break;
980
981   case SIGALRM:
982     sigmsg = "Alarm clock";
983     break;
984
985   case SIGTERM:
986     sigmsg = "Terminated";
987     break;
988
989   default:
990     sprintf(sigmsg_buf, "Signal %d", sig);
991     sigmsg = sigmsg_buf;
992     break;
993   }
994   return sigmsg;
995 }
996 #endif
997
998 /*
999  * Timeout, in milliseconds, for reads from the stream of captured packets.
1000  *
1001  * XXX - Michael Tuexen says MacOS X's BPF appears to be broken, in that
1002  * if you use a timeout of 250 in "pcap_open_live()", you don't see
1003  * packets until a large number of packets arrive; the timeout doesn't
1004  * cause a smaller number of packets to be delivered.  Perhaps a timeout
1005  * that's less than 1 second acts like no timeout at all, so that you
1006  * don't see packets until the BPF buffer fills up?
1007  *
1008  * The workaround is to use a timeout of 1000 seconds on MacOS X.
1009  */
1010 #ifdef __APPLE__
1011 #define CAP_READ_TIMEOUT        1000
1012 #else
1013 #define CAP_READ_TIMEOUT        250
1014 #endif
1015
1016 #ifndef _WIN32
1017 /* Take carre of byte order in the libpcap headers read from pipes.
1018  * (function taken from wiretap/libpcap.c) */
1019 static void
1020 adjust_header(loop_data *ld, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1021 {
1022   if (ld->byte_swapped) {
1023     /* Byte-swap the record header fields. */
1024     rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
1025     rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
1026     rechdr->incl_len = BSWAP32(rechdr->incl_len);
1027     rechdr->orig_len = BSWAP32(rechdr->orig_len);
1028   }
1029
1030   /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1031      swapped, in order to match the BPF header layout.
1032
1033      Unfortunately, some files were, according to a comment in the "libpcap"
1034      source, written with version 2.3 in their headers but without the
1035      interchanged fields, so if "incl_len" is greater than "orig_len" - which
1036      would make no sense - we assume that we need to swap them.  */
1037   if (hdr->version_major == 2 &&
1038       (hdr->version_minor < 3 ||
1039        (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1040     guint32 temp;
1041
1042     temp = rechdr->orig_len;
1043     rechdr->orig_len = rechdr->incl_len;
1044     rechdr->incl_len = temp;
1045   }
1046 }
1047
1048 /* Mimic pcap_open_live() for pipe captures 
1049  * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
1050  * header.
1051  * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1052  * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1053 static int
1054 pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld, char *ebuf)
1055 {
1056   struct stat pipe_stat;
1057   int         fd;
1058   guint32     magic;
1059   int         bytes_read, b;
1060
1061   if (strcmp(pipename, "-") == 0) fd = 0; /* read from stdin */
1062   else if (stat(pipename, &pipe_stat) == 0 && S_ISFIFO(pipe_stat.st_mode)) {
1063     if ((fd = open(pipename, O_RDONLY)) == -1) return -1;
1064   } else return -1;
1065
1066   ld->from_pipe = TRUE;
1067   /* read the pcap header */
1068   if (read(fd, &magic, sizeof magic) != sizeof magic) {
1069     close(fd);
1070     return -1;
1071   }
1072
1073   switch (magic) {
1074   case PCAP_MAGIC:
1075     /* Host that wrote it has our byte order, and was running
1076        a program using either standard or ss990417 libpcap. */
1077     ld->byte_swapped = FALSE;
1078     ld->modified = FALSE;
1079     break;
1080   case PCAP_MODIFIED_MAGIC:
1081     /* Host that wrote it has our byte order, but was running
1082        a program using either ss990915 or ss991029 libpcap. */
1083     ld->byte_swapped = FALSE;
1084     ld->modified = TRUE;
1085     break;
1086   case PCAP_SWAPPED_MAGIC:
1087     /* Host that wrote it has a byte order opposite to ours,
1088        and was running a program using either standard or
1089        ss990417 libpcap. */
1090     ld->byte_swapped = TRUE;
1091     ld->modified = FALSE;
1092     break;
1093   case PCAP_SWAPPED_MODIFIED_MAGIC:
1094     /* Host that wrote it out has a byte order opposite to
1095        ours, and was running a program using either ss990915
1096        or ss991029 libpcap. */
1097     ld->byte_swapped = TRUE;
1098     ld->modified = TRUE;
1099     break;
1100   default:
1101     /* Not a "libpcap" type we know about. */
1102     close(fd);
1103     return -1;
1104   }
1105
1106   /* Read the rest of the header */
1107   bytes_read = read(fd, hdr, sizeof(struct pcap_hdr));
1108   if (bytes_read <= 0) {
1109     close(fd);
1110     return -1;
1111   }
1112   while ((unsigned) bytes_read < sizeof(struct pcap_hdr))
1113   {
1114     b = read(fd, ((char *)&hdr)+bytes_read, sizeof(struct pcap_hdr) - bytes_read);
1115     if (b <= 0) {
1116       close(fd);
1117       return -1;
1118     }
1119     bytes_read += b;
1120   }
1121   if (ld->byte_swapped) {
1122     /* Byte-swap the header fields about which we care. */
1123     hdr->version_major = BSWAP16(hdr->version_major);
1124     hdr->version_minor = BSWAP16(hdr->version_minor);
1125     hdr->snaplen = BSWAP32(hdr->snaplen);
1126     hdr->network = BSWAP32(hdr->network);
1127   }
1128   if (hdr->version_major < 2) {
1129     close(fd);
1130     return -1;
1131   }
1132
1133   return fd;
1134 }
1135
1136 /* We read one record from the pipe, take care of byte order in the record
1137  * header, write the record in the capture file, and update capture statistics. */
1138 static int
1139 pipe_dispatch(int fd, loop_data *ld, struct pcap_hdr *hdr)
1140 {
1141   struct wtap_pkthdr whdr;
1142   struct pcaprec_modified_hdr rechdr;
1143   int bytes_to_read, bytes_read, b;
1144   u_char pd[WTAP_MAX_PACKET_SIZE];
1145   int err;
1146
1147   /* read the record header */
1148   bytes_to_read = ld->modified ? sizeof rechdr : sizeof rechdr.hdr;
1149   bytes_read = read(fd, &rechdr, bytes_to_read);
1150   if (bytes_read <= 0) {
1151     close(fd);
1152     ld->go = FALSE;
1153     return 0;
1154   }
1155   while (bytes_read < bytes_to_read)
1156   {
1157     b = read(fd, ((char *)&rechdr)+bytes_read, bytes_to_read - bytes_read);
1158     if (b <= 0) {
1159       close(fd);
1160       ld->go = FALSE;
1161       return 0;
1162     }
1163     bytes_read += b;
1164   }
1165   /* take care of byte order */
1166   adjust_header(ld, hdr, &rechdr.hdr);
1167   if (rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1168     close(fd);
1169     ld->go = FALSE;
1170     return 0;
1171   }
1172   /* read the packet data */
1173   bytes_read = read(fd, pd, rechdr.hdr.incl_len);
1174   if (bytes_read <= 0) {
1175     close(fd);
1176     ld->go = FALSE;
1177     return 0;
1178   }
1179   while ((unsigned) bytes_read < rechdr.hdr.incl_len)
1180   {
1181     b = read(fd, pd+bytes_read, rechdr.hdr.incl_len - bytes_read);
1182     if (b <= 0) {
1183       close(fd);
1184       ld->go = FALSE;
1185       return 0;
1186     }
1187     bytes_read += b;
1188   }
1189   /* dump the packet data to the capture file */
1190   whdr.ts.tv_sec = rechdr.hdr.ts_sec;
1191   whdr.ts.tv_usec = rechdr.hdr.ts_usec;
1192   whdr.caplen = rechdr.hdr.incl_len;
1193   whdr.len = rechdr.hdr.orig_len;
1194   whdr.pkt_encap = ld->linktype;
1195   wtap_dump(ld->pdh, &whdr, NULL, pd, &err);
1196
1197   /* update capture statistics */
1198   switch (ld->linktype) {
1199     case WTAP_ENCAP_ETHERNET:
1200       capture_eth(pd, 0, whdr.caplen, &ld->counts);
1201       break;
1202     case WTAP_ENCAP_FDDI:
1203     case WTAP_ENCAP_FDDI_BITSWAPPED:
1204       capture_fddi(pd, whdr.caplen, &ld->counts);
1205       break;
1206     case WTAP_ENCAP_PRISM_HEADER:
1207       capture_prism(pd, 0, whdr.caplen, &ld->counts);
1208       break;
1209     case WTAP_ENCAP_TOKEN_RING:
1210       capture_tr(pd, 0, whdr.caplen, &ld->counts);
1211       break;
1212     case WTAP_ENCAP_NULL:
1213       capture_null(pd, whdr.caplen, &ld->counts);
1214       break;
1215     case WTAP_ENCAP_PPP:
1216       capture_ppp_hdlc(pd, 0, whdr.caplen, &ld->counts);
1217       break;
1218     case WTAP_ENCAP_RAW_IP:
1219       capture_raw(pd, whdr.caplen, &ld->counts);
1220       break;
1221     case WTAP_ENCAP_LINUX_ATM_CLIP:
1222       capture_clip(pd, whdr.caplen, &ld->counts);
1223       break;
1224     case WTAP_ENCAP_IEEE_802_11:
1225       capture_ieee80211(pd, 0, whdr.caplen, &ld->counts);
1226       break;
1227     case WTAP_ENCAP_CHDLC:
1228       capture_chdlc(pd, 0, whdr.caplen, &ld->counts);
1229       break;
1230     case WTAP_ENCAP_LOCALTALK:
1231       capture_llap(pd, whdr.caplen, &ld->counts);
1232       break;
1233     /* XXX - FreeBSD may append 4-byte ATM pseudo-header to DLT_ATM_RFC1483,
1234        with LLC header following; we should implement it at some
1235        point. */
1236   }
1237
1238   return 1;
1239 }
1240 #endif
1241
1242 /*
1243  * This needs to be static, so that the SIGUSR1 handler can clear the "go"
1244  * flag.
1245  */
1246 static loop_data   ld;
1247
1248 /* Do the low-level work of a capture.
1249    Returns TRUE if it succeeds, FALSE otherwise. */
1250 int
1251 capture(gboolean *stats_known, struct pcap_stat *stats)
1252 {
1253   GtkWidget  *cap_w, *main_vb, *stop_bt, *counts_tb;
1254   pcap_t     *pch;
1255   int         pcap_encap;
1256   int         snaplen;
1257   gchar       open_err_str[PCAP_ERRBUF_SIZE];
1258   gchar       lookup_net_err_str[PCAP_ERRBUF_SIZE];
1259   gchar       label_str[64];
1260   bpf_u_int32 netnum, netmask;
1261   struct bpf_program fcode;
1262   time_t      upd_time, cur_time;
1263   int         err, inpkts;
1264   condition *cnd_stop_capturesize;
1265   condition *cnd_stop_timeout;
1266   unsigned int i;
1267   static const char capstart_msg = SP_CAPSTART;
1268   char        errmsg[4096+1];
1269   gboolean    dump_ok;
1270 #ifndef _WIN32
1271   static const char ppamsg[] = "can't find PPA for ";
1272   char       *libpcap_warn;
1273 #endif
1274   fd_set      set1;
1275   struct timeval timeout;
1276 #ifdef MUST_DO_SELECT
1277   int         pcap_fd = 0;
1278 #endif
1279 #ifdef _WIN32 
1280   WORD wVersionRequested; 
1281   WSADATA wsaData; 
1282 #endif
1283 #ifndef _WIN32
1284   int         pipe_fd = -1;
1285   struct pcap_hdr hdr;
1286 #endif
1287   struct {
1288       const gchar *title;
1289       gint *value_ptr;
1290       GtkWidget *label, *value, *percent;
1291   } counts[] = {
1292       { "Total", &ld.counts.total, NULL, NULL, NULL },
1293       { "SCTP", &ld.counts.sctp, NULL, NULL, NULL },
1294       { "TCP", &ld.counts.tcp, NULL, NULL, NULL },
1295       { "UDP", &ld.counts.udp, NULL, NULL, NULL },
1296       { "ICMP", &ld.counts.icmp, NULL, NULL, NULL },
1297       { "OSPF", &ld.counts.ospf, NULL, NULL, NULL },
1298       { "GRE", &ld.counts.gre, NULL, NULL, NULL },
1299       { "NetBIOS", &ld.counts.netbios, NULL, NULL, NULL },
1300       { "IPX", &ld.counts.ipx, NULL, NULL, NULL },
1301       { "VINES", &ld.counts.vines, NULL, NULL, NULL },
1302       { "Other", &ld.counts.other, NULL, NULL, NULL }
1303   };
1304
1305 #define N_COUNTS (sizeof counts / sizeof counts[0])
1306
1307   /* Initialize Windows Socket if we are in a WIN32 OS 
1308      This needs to be done before querying the interface for network/netmask */
1309 #ifdef _WIN32 
1310   wVersionRequested = MAKEWORD( 1, 1 ); 
1311   err = WSAStartup( wVersionRequested, &wsaData ); 
1312   if (err!=0) { 
1313     snprintf(errmsg, sizeof errmsg, 
1314       "Couldn't initialize Windows Sockets."); 
1315         pch=NULL; 
1316     goto error; 
1317   } 
1318 #endif 
1319
1320   ld.go             = TRUE;
1321   ld.counts.total   = 0;
1322   ld.max            = cfile.count;
1323   ld.err            = 0;        /* no error seen yet */
1324   ld.linktype       = WTAP_ENCAP_UNKNOWN;
1325   ld.pcap_err       = FALSE;
1326   ld.from_pipe      = FALSE;
1327   ld.sync_packets   = 0;
1328   ld.counts.sctp    = 0;
1329   ld.counts.tcp     = 0;
1330   ld.counts.udp     = 0;
1331   ld.counts.icmp    = 0;
1332   ld.counts.ospf    = 0;
1333   ld.counts.gre     = 0;
1334   ld.counts.ipx     = 0;
1335   ld.counts.netbios = 0;
1336   ld.counts.vines   = 0;
1337   ld.counts.other   = 0;
1338   ld.pdh            = NULL;
1339
1340   /* We haven't yet gotten the capture statistics. */
1341   *stats_known      = FALSE;
1342
1343   /* Open the network interface to capture from it.
1344      Some versions of libpcap may put warnings into the error buffer
1345      if they succeed; to tell if that's happened, we have to clear
1346      the error buffer, and check if it's still a null string.  */
1347   open_err_str[0] = '\0';
1348   pch = pcap_open_live(cfile.iface, cfile.snap, promisc_mode,
1349                        CAP_READ_TIMEOUT, open_err_str);
1350
1351   if (pch == NULL) {
1352 #ifdef _WIN32
1353     /* Well, we couldn't start the capture.
1354        If this is a child process that does the capturing in sync
1355        mode or fork mode, it shouldn't do any UI stuff until we pop up the
1356        capture-progress window, and, since we couldn't start the
1357        capture, we haven't popped it up. */
1358     if (!capture_child) {
1359       while (gtk_events_pending()) gtk_main_iteration();
1360     }
1361
1362     /* On Win32 OSes, the capture devices are probably available to all
1363        users; don't warn about permissions problems.
1364
1365        Do, however, warn that WAN devices aren't supported. */
1366     snprintf(errmsg, sizeof errmsg,
1367         "The capture session could not be initiated (%s).\n"
1368         "Please check that you have the proper interface specified.\n"
1369         "\n"
1370         "Note that the driver Ethereal uses for packet capture on Windows\n"
1371         "doesn't support capturing on PPP/WAN interfaces in Windows NT/2000.\n",
1372         open_err_str);
1373     goto error;
1374 #else
1375     /* try to open cfile.iface as a pipe */
1376     pipe_fd = pipe_open_live(cfile.iface, &hdr, &ld, open_err_str);
1377
1378     if (pipe_fd == -1) {
1379       /* Well, we couldn't start the capture.
1380          If this is a child process that does the capturing in sync
1381          mode or fork mode, it shouldn't do any UI stuff until we pop up the
1382          capture-progress window, and, since we couldn't start the
1383          capture, we haven't popped it up. */
1384       if (!capture_child) {
1385         while (gtk_events_pending()) gtk_main_iteration();
1386       }
1387
1388       /* If we got a "can't find PPA for XXX" message, warn the user (who
1389          is running Ethereal on HP-UX) that they don't have a version
1390          of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1391          versions, which properly handle HP-UX, say "can't find /dev/dlpi
1392          PPA for XXX" rather than "can't find PPA for XXX"). */
1393       if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1394         libpcap_warn =
1395           "\n\n"
1396           "You are running Ethereal with a version of the libpcap library\n"
1397           "that doesn't handle HP-UX network devices well; this means that\n"
1398           "Ethereal may not be able to capture packets.\n"
1399           "\n"
1400           "To fix this, you should install libpcap 0.6.2, or a later version\n"
1401           "of libpcap, rather than libpcap 0.4 or 0.5.x.  It is available in\n"
1402           "packaged binary form from the Software Porting And Archive Centre\n"
1403           "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1404           "at the URL lists a number of mirror sites.";
1405       else
1406         libpcap_warn = "";
1407       snprintf(errmsg, sizeof errmsg,
1408           "The capture session could not be initiated (%s).\n"
1409           "Please check to make sure you have sufficient permissions, and that\n"
1410           "you have the proper interface or pipe specified.%s", open_err_str,
1411           libpcap_warn);
1412       goto error;
1413     }
1414 #endif
1415   }
1416
1417   /* capture filters only work on real interfaces */
1418   if (cfile.cfilter && !ld.from_pipe) {
1419     /* A capture filter was specified; set it up. */
1420     if (pcap_lookupnet(cfile.iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1421       /*
1422        * Well, we can't get the netmask for this interface; it's used
1423        * only for filters that check for broadcast IP addresses, so
1424        * we just punt and use 0.  It might be nice to warn the user,
1425        * but that's a pain in a GUI application, as it'd involve popping
1426        * up a message box, and it's not clear how often this would make
1427        * a difference (only filters that check for IP broadcast addresses
1428        * use the netmask).
1429        */
1430       netmask = 0;
1431     }
1432     if (pcap_compile(pch, &fcode, cfile.cfilter, 1, netmask) < 0) {
1433       snprintf(errmsg, sizeof errmsg, "Unable to parse filter string (%s).",
1434         pcap_geterr(pch));
1435       goto error;
1436     }
1437     if (pcap_setfilter(pch, &fcode) < 0) {
1438       snprintf(errmsg, sizeof errmsg, "Can't install filter (%s).",
1439         pcap_geterr(pch));
1440       goto error;
1441     }
1442   }
1443
1444   /* Set up to write to the capture file. */
1445 #ifndef _WIN32
1446   if (ld.from_pipe) {
1447     pcap_encap = hdr.network;
1448     snaplen = hdr.snaplen;
1449   } else
1450 #endif
1451   {
1452     pcap_encap = get_pcap_linktype(pch, cfile.iface);
1453     snaplen = pcap_snapshot(pch);
1454   }
1455   ld.linktype = wtap_pcap_encap_to_wtap_encap(pcap_encap);
1456   if (ld.linktype == WTAP_ENCAP_UNKNOWN) {
1457     snprintf(errmsg, sizeof errmsg,
1458         "The network you're capturing from is of a type"
1459         " that Ethereal doesn't support (data link type %d).", pcap_encap);
1460     goto error;
1461   }
1462   if (cfile.ringbuffer_on) {
1463     ld.pdh = ringbuf_init_wtap_dump_fdopen(WTAP_FILE_PCAP, ld.linktype, 
1464       snaplen, &err);
1465   } else {
1466     ld.pdh = wtap_dump_fdopen(cfile.save_file_fd, WTAP_FILE_PCAP,
1467       ld.linktype, snaplen, &err);
1468   }
1469
1470   if (ld.pdh == NULL) {
1471     /* We couldn't set up to write to the capture file. */
1472     switch (err) {
1473
1474     case WTAP_ERR_CANT_OPEN:
1475       strcpy(errmsg, "The file to which the capture would be saved"
1476                " couldn't be created for some unknown reason.");
1477       break;
1478
1479     case WTAP_ERR_SHORT_WRITE:
1480       strcpy(errmsg, "A full header couldn't be written to the file"
1481                " to which the capture would be saved.");
1482       break;
1483
1484     default:
1485       if (err < 0) {
1486         snprintf(errmsg, sizeof(errmsg),
1487                      "The file to which the capture would be"
1488                      " saved (\"%s\") could not be opened: Error %d.",
1489                         cfile.save_file, err);
1490       } else {
1491         snprintf(errmsg, sizeof(errmsg),
1492                      "The file to which the capture would be"
1493                      " saved (\"%s\") could not be opened: %s.",
1494                         cfile.save_file, strerror(err));
1495       }
1496       break;
1497     }
1498     goto error;
1499   }
1500
1501   /* Does "open_err_str" contain a non-empty string?  If so, "pcap_open_live()"
1502      returned a warning; print it, but keep capturing. */
1503   if (open_err_str[0] != '\0')
1504     g_warning("%s.", open_err_str);
1505
1506   /* XXX - capture SIGTERM and close the capture, in case we're on a
1507      Linux 2.0[.x] system and you have to explicitly close the capture
1508      stream in order to turn promiscuous mode off?  We need to do that
1509      in other places as well - and I don't think that works all the
1510      time in any case, due to libpcap bugs. */
1511
1512   if (capture_child) {
1513     /* Well, we should be able to start capturing.
1514
1515        This is the child process for a sync mode capture, so sync out
1516        the capture file, so the header makes it to the file system,
1517        and send a "capture started successfully and capture file created"
1518        message to our parent so that they'll open the capture file and
1519        update its windows to indicate that we have a live capture in
1520        progress. */
1521     fflush(wtap_dump_file(ld.pdh));
1522     write(1, &capstart_msg, 1);
1523   }
1524
1525   cap_w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1526   gtk_window_set_title(GTK_WINDOW(cap_w), "Ethereal: Capture");
1527   gtk_window_set_modal(GTK_WINDOW(cap_w), TRUE);
1528
1529   /* Container for capture display widgets */
1530   main_vb = gtk_vbox_new(FALSE, 1);
1531   gtk_container_border_width(GTK_CONTAINER(main_vb), 5);
1532   gtk_container_add(GTK_CONTAINER(cap_w), main_vb);
1533   gtk_widget_show(main_vb);
1534
1535   /* Individual statistic elements */
1536   counts_tb = gtk_table_new(N_COUNTS, 3, TRUE);
1537   gtk_box_pack_start(GTK_BOX(main_vb), counts_tb, TRUE, TRUE, 3);
1538   gtk_widget_show(counts_tb);
1539
1540   for (i = 0; i < N_COUNTS; i++) {
1541       counts[i].label = gtk_label_new(counts[i].title);
1542       gtk_misc_set_alignment(GTK_MISC(counts[i].label), 0.0f, 0.0f);
1543
1544       counts[i].value = gtk_label_new("0");
1545       gtk_misc_set_alignment(GTK_MISC(counts[i].value), 0.0f, 0.0f);
1546
1547       counts[i].percent = gtk_label_new("0.0%");
1548       gtk_misc_set_alignment(GTK_MISC(counts[i].percent), 0.0f, 0.0f);
1549
1550       gtk_table_attach_defaults(GTK_TABLE(counts_tb),
1551                                 counts[i].label, 0, 1, i, i + 1);
1552
1553       gtk_table_attach(GTK_TABLE(counts_tb),
1554                        counts[i].value,
1555                        1, 2, i, i + 1, 0, 0, 5, 0);
1556
1557       gtk_table_attach_defaults(GTK_TABLE(counts_tb),
1558                                 counts[i].percent, 2, 3, i, i + 1);
1559
1560       gtk_widget_show(counts[i].label);
1561       gtk_widget_show(counts[i].value);
1562       gtk_widget_show(counts[i].percent);
1563   }
1564
1565   /* allow user to either click a stop button, or the close button on
1566         the window to stop a capture in progress. */
1567   stop_bt = gtk_button_new_with_label ("Stop");
1568   gtk_signal_connect(GTK_OBJECT(stop_bt), "clicked",
1569     GTK_SIGNAL_FUNC(capture_stop_cb), (gpointer) &ld);
1570   gtk_signal_connect(GTK_OBJECT(cap_w), "delete_event",
1571         GTK_SIGNAL_FUNC(capture_delete_cb), (gpointer) &ld);
1572   gtk_box_pack_end(GTK_BOX(main_vb), stop_bt, FALSE, FALSE, 3);
1573   GTK_WIDGET_SET_FLAGS(stop_bt, GTK_CAN_DEFAULT);
1574   gtk_widget_grab_default(stop_bt);
1575   GTK_WIDGET_SET_FLAGS(stop_bt, GTK_CAN_DEFAULT);
1576   gtk_widget_grab_default(stop_bt);
1577   gtk_widget_show(stop_bt);
1578
1579   gtk_widget_show(cap_w);
1580
1581   upd_time = time(NULL);
1582 #ifdef MUST_DO_SELECT
1583   if (!ld.from_pipe) pcap_fd = pcap_fileno(pch);
1584 #endif
1585
1586 #ifndef _WIN32
1587   /*
1588    * Catch SIGUSR1, so that we exit cleanly if the parent process
1589    * kills us with it due to the user selecting "Capture->Stop".
1590    */
1591   signal(SIGUSR1, stop_capture);
1592 #endif
1593   /* initialize capture stop conditions */ 
1594   init_capture_stop_conditions();
1595   /* create stop conditions */
1596   cnd_stop_capturesize = 
1597     cnd_new(CND_CLASS_CAPTURESIZE,(long)cfile.autostop_filesize * 1000); 
1598   cnd_stop_timeout = 
1599     cnd_new(CND_CLASS_TIMEOUT,(gint32)cfile.autostop_duration);
1600
1601   while (ld.go) {
1602     while (gtk_events_pending()) gtk_main_iteration();
1603
1604 #ifndef _WIN32
1605     if (ld.from_pipe) {
1606       FD_ZERO(&set1);
1607       FD_SET(pipe_fd, &set1);
1608       timeout.tv_sec = 0;
1609       timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1610       if (select(pipe_fd+1, &set1, NULL, NULL, &timeout) != 0) {
1611         /*
1612          * "select()" says we can read from the pipe without blocking; go for
1613          * it. We are not sure we can read a whole record, but at least the
1614          * begninning of one. pipe_dispatch() will block reading the whole
1615          * record.
1616          */
1617         inpkts = pipe_dispatch(pipe_fd, &ld, &hdr);
1618       } else
1619         inpkts = 0;
1620     }
1621     else
1622 #endif
1623     {
1624 #ifdef MUST_DO_SELECT
1625       /*
1626        * Sigh.  The semantics of the read timeout argument to
1627        * "pcap_open_live()" aren't particularly well specified by
1628        * the "pcap" man page - at least with the BSD BPF code, the
1629        * intent appears to be, at least in part, a way of cutting
1630        * down the number of reads done on a capture, by blocking
1631        * until the buffer fills or a timer expires - and the Linux
1632        * libpcap doesn't actually support it, so we can't use it
1633        * to break out of the "pcap_dispatch()" every 1/4 of a second
1634        * or so.  Linux's libpcap is not the only libpcap that doesn't
1635        * support the read timeout.
1636        *
1637        * Furthermore, at least on Solaris, the bufmod STREAMS module's
1638        * read timeout won't go off if no data has arrived, i.e. it cannot
1639        * be used to guarantee that a read from a DLPI stream will return
1640        * within a specified amount of time regardless of whether any
1641        * data arrives or not.
1642        *
1643        * Thus, on all platforms other than BSD, we do a "select()" on the
1644        * file descriptor for the capture, with a timeout of CAP_READ_TIMEOUT
1645        * milliseconds, or CAP_READ_TIMEOUT*1000 microseconds.
1646        *
1647        * "select()", on BPF devices, doesn't work as you might expect;
1648        * at least on some versions of some flavors of BSD, the timer
1649        * doesn't start until a read is done, so it won't expire if
1650        * only a "select()" or "poll()" is posted.
1651        */
1652       FD_ZERO(&set1);
1653       FD_SET(pcap_fd, &set1);
1654       timeout.tv_sec = 0;
1655       timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1656       if (select(pcap_fd+1, &set1, NULL, NULL, &timeout) != 0) {
1657         /*
1658          * "select()" says we can read from it without blocking; go for
1659          * it.
1660          */
1661         inpkts = pcap_dispatch(pch, 1, capture_pcap_cb, (u_char *) &ld);
1662         if (inpkts < 0) {
1663           ld.pcap_err = TRUE;
1664           ld.go = FALSE;
1665         }
1666       } else
1667         inpkts = 0;
1668 #else
1669       inpkts = pcap_dispatch(pch, 1, capture_pcap_cb, (u_char *) &ld);
1670       if (inpkts < 0) {
1671         ld.pcap_err = TRUE;
1672         ld.go = FALSE;
1673       }
1674 #endif
1675     }
1676     if (inpkts > 0)
1677       ld.sync_packets += inpkts;
1678     /* check capture stop conditons */
1679     if (cnd_eval(cnd_stop_timeout) == TRUE) {
1680       /* The specified capture time has elapsed; stop the capture. */
1681       ld.go = FALSE;
1682     } else if ((cnd_eval(cnd_stop_capturesize, 
1683                   (guint32)wtap_get_bytes_dumped(ld.pdh))) == TRUE){
1684       /* Capture file reached its maximum size. */
1685       if (cfile.ringbuffer_on) {
1686         /* Switch to the next ringbuffer file */
1687         if (ringbuf_switch_file(&cfile, &ld.pdh, &ld.err)) {
1688           /* File switch succeeded: reset the condition */
1689           cnd_reset(cnd_stop_capturesize);
1690         } else {
1691           /* File switch failed: stop here */
1692           ld.go = FALSE;
1693           continue;
1694         }
1695       } else {
1696         /* no ringbuffer - just stop */
1697         ld.go = FALSE;
1698       }
1699     }
1700     /* Only update once a second so as not to overload slow displays */
1701     cur_time = time(NULL);
1702     if (cur_time > upd_time) {
1703       upd_time = cur_time;
1704
1705       for (i = 0; i < N_COUNTS; i++) {
1706           snprintf(label_str, sizeof(label_str), "%d",
1707                    *counts[i].value_ptr);
1708
1709           gtk_label_set(GTK_LABEL(counts[i].value), label_str);
1710
1711           snprintf(label_str, sizeof(label_str), "(%.1f%%)",
1712                    pct(*counts[i].value_ptr, ld.counts.total));
1713
1714           gtk_label_set(GTK_LABEL(counts[i].percent), label_str);
1715       }
1716
1717       /* do sync here, too */
1718       fflush(wtap_dump_file(ld.pdh));
1719       if (capture_child && ld.sync_packets) {
1720         /* This is the child process for a sync mode capture, so send
1721            our parent a message saying we've written out "ld.sync_packets"
1722            packets to the capture file. */
1723         char tmp[20];
1724         sprintf(tmp, "%d%c", ld.sync_packets, SP_PACKET_COUNT);
1725         write(1, tmp, strlen(tmp));
1726         ld.sync_packets = 0;
1727       }
1728     }
1729   }
1730     
1731   /* delete stop conditions */
1732   cnd_delete(cnd_stop_capturesize);
1733   cnd_delete(cnd_stop_timeout);
1734
1735   if (ld.pcap_err) {
1736     snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
1737       pcap_geterr(pch));
1738     if (capture_child) {
1739       /* Tell the parent, so that they can pop up the message;
1740          we're going to exit, so if we try to pop it up, either
1741          it won't pop up or it'll disappear as soon as we exit. */
1742       send_errmsg_to_parent(errmsg);
1743     } else {
1744      /* Just pop up the message ourselves. */
1745      simple_dialog(ESD_TYPE_WARN, NULL, "%s", errmsg);
1746     }
1747   }
1748
1749   if (ld.err != 0) {
1750     get_capture_file_io_error(errmsg, sizeof(errmsg), cfile.save_file, ld.err,
1751                               FALSE);
1752     if (capture_child) {
1753       /* Tell the parent, so that they can pop up the message;
1754          we're going to exit, so if we try to pop it up, either
1755          it won't pop up or it'll disappear as soon as we exit. */
1756       send_errmsg_to_parent(errmsg);
1757     } else {
1758      /* Just pop up the message ourselves. */
1759      simple_dialog(ESD_TYPE_WARN, NULL, "%s", errmsg);
1760     }
1761
1762     /* A write failed, so we've already told the user there's a problem;
1763        if the close fails, there's no point in telling them about that
1764        as well. */
1765     if (cfile.ringbuffer_on) {
1766       ringbuf_wtap_dump_close(&cfile, &err);
1767     } else {
1768       wtap_dump_close(ld.pdh, &err);
1769     }
1770    } else {
1771     if (cfile.ringbuffer_on) {
1772       dump_ok = ringbuf_wtap_dump_close(&cfile, &err);
1773     } else {
1774       dump_ok = wtap_dump_close(ld.pdh, &err);
1775     }
1776     if (!dump_ok) {
1777       get_capture_file_io_error(errmsg, sizeof(errmsg), cfile.save_file, err,
1778                                 TRUE);
1779       if (capture_child) {
1780         /* Tell the parent, so that they can pop up the message;
1781            we're going to exit, so if we try to pop it up, either
1782            it won't pop up or it'll disappear as soon as we exit. */
1783         send_errmsg_to_parent(errmsg);
1784       } else {
1785        /* Just pop up the message ourselves. */
1786        simple_dialog(ESD_TYPE_WARN, NULL, "%s", errmsg);
1787       }
1788     }
1789   }
1790 #ifndef _WIN32
1791   if (ld.from_pipe)
1792     close(pipe_fd);
1793   else
1794 #endif
1795   {
1796     /* Get the capture statistics, so we know how many packets were
1797        dropped. */
1798     if (pcap_stats(pch, stats) >= 0) {
1799       *stats_known = TRUE;
1800       if (capture_child) {
1801         /* Let the parent process know. */
1802         char tmp[20];
1803         sprintf(tmp, "%d%c", stats->ps_drop, SP_DROPS);
1804         write(1, tmp, strlen(tmp));
1805       }
1806     } else {
1807       snprintf(errmsg, sizeof(errmsg),
1808                 "Can't get packet-drop statistics: %s",
1809                 pcap_geterr(pch));
1810       if (capture_child) {
1811         /* Tell the parent, so that they can pop up the message;
1812            we're going to exit, so if we try to pop it up, either
1813            it won't pop up or it'll disappear as soon as we exit. */
1814         send_errmsg_to_parent(errmsg);
1815       } else {
1816        /* Just pop up the message ourselves. */
1817        simple_dialog(ESD_TYPE_WARN, NULL, "%s", errmsg);
1818       }
1819     }
1820     pcap_close(pch);
1821   }
1822
1823 #ifdef WIN32
1824   /* Shut down windows sockets */
1825   WSACleanup();
1826 #endif
1827
1828   gtk_grab_remove(GTK_WIDGET(cap_w));
1829   gtk_widget_destroy(GTK_WIDGET(cap_w));
1830
1831   return TRUE;
1832
1833 error:
1834   if (cfile.ringbuffer_on) {
1835     /* cleanup ringbuffer */
1836     ringbuf_error_cleanup();
1837   } else {
1838     /* We can't use the save file, and we have no wtap_dump stream
1839        to close in order to close it, so close the FD directly. */
1840     close(cfile.save_file_fd);
1841
1842     /* We couldn't even start the capture, so get rid of the capture
1843        file. */
1844     unlink(cfile.save_file); /* silently ignore error */
1845     g_free(cfile.save_file);
1846   }
1847   cfile.save_file = NULL;
1848   if (capture_child) {
1849     /* This is the child process for a sync mode capture.
1850        Send the error message to our parent, so they can display a
1851        dialog box containing it. */
1852     send_errmsg_to_parent(errmsg);
1853   } else {
1854     /* Display the dialog box ourselves; there's no parent. */
1855     simple_dialog(ESD_TYPE_CRIT, NULL, "%s", errmsg);
1856   }
1857   if (pch != NULL && !ld.from_pipe)
1858     pcap_close(pch);
1859
1860   return FALSE;
1861 }
1862
1863 static void
1864 get_capture_file_io_error(char *errmsg, int errmsglen, const char *fname,
1865                           int err, gboolean is_close)
1866 {
1867   switch (err) {
1868
1869   case ENOSPC:
1870     snprintf(errmsg, errmsglen,
1871                 "Not all the packets could be written to the file"
1872                 " to which the capture was being saved\n"
1873                 "(\"%s\") because there is no space left on the file system\n"
1874                 "on which that file resides.",
1875                 fname);
1876     break;
1877
1878 #ifdef EDQUOT
1879   case EDQUOT:
1880     snprintf(errmsg, errmsglen,
1881                 "Not all the packets could be written to the file"
1882                 " to which the capture was being saved\n"
1883                 "(\"%s\") because you are too close to, or over,"
1884                 " your disk quota\n"
1885                 "on the file system on which that file resides.",
1886                 fname);
1887   break;
1888 #endif
1889
1890   case WTAP_ERR_CANT_CLOSE:
1891     snprintf(errmsg, errmsglen,
1892                 "The file to which the capture was being saved"
1893                 " couldn't be closed for some unknown reason.");
1894     break;
1895
1896   case WTAP_ERR_SHORT_WRITE:
1897     snprintf(errmsg, errmsglen,
1898                 "Not all the packets could be written to the file"
1899                 " to which the capture was being saved\n"
1900                 "(\"%s\").",
1901                 fname);
1902     break;
1903
1904   default:
1905     if (is_close) {
1906       snprintf(errmsg, errmsglen,
1907                 "The file to which the capture was being saved\n"
1908                 "(\"%s\") could not be closed: %s.",
1909                 fname, wtap_strerror(err));
1910     } else {
1911       snprintf(errmsg, errmsglen,
1912                 "An error occurred while writing to the file"
1913                 " to which the capture was being saved\n"
1914                 "(\"%s\"): %s.",
1915                 fname, wtap_strerror(err));
1916     }
1917     break;
1918   }
1919 }
1920
1921 static void
1922 send_errmsg_to_parent(const char *errmsg)
1923 {
1924     int msglen = strlen(errmsg);
1925     char lenbuf[10+1+1];
1926
1927     sprintf(lenbuf, "%u%c", msglen, SP_ERROR_MSG);
1928     write(1, lenbuf, strlen(lenbuf));
1929     write(1, errmsg, msglen);
1930 }
1931
1932 static float
1933 pct(gint num, gint denom) {
1934   if (denom) {
1935     return (float) num * 100.0 / (float) denom;
1936   } else {
1937     return 0.0;
1938   }
1939 }
1940
1941 static void
1942 stop_capture(int signo)
1943 {
1944   ld.go = FALSE;
1945 }
1946
1947 static void
1948 capture_delete_cb(GtkWidget *w, GdkEvent *event, gpointer data) {
1949   capture_stop_cb(NULL, data);
1950 }
1951
1952 static void
1953 capture_stop_cb(GtkWidget *w, gpointer data) {
1954   loop_data *ld = (loop_data *) data;
1955   
1956   ld->go = FALSE;
1957 }
1958
1959 void
1960 capture_stop(void)
1961 {
1962   /*
1963    * XXX - find some way of signaling the child in Win32.
1964    */
1965 #ifndef _WIN32
1966   if (fork_child != -1)
1967       kill(fork_child, SIGUSR1);
1968 #endif
1969 }
1970
1971 void
1972 kill_capture_child(void)
1973 {
1974   /*
1975    * XXX - find some way of signaling the child in Win32.
1976    */
1977 #ifndef _WIN32
1978   if (fork_child != -1)
1979     kill(fork_child, SIGTERM);  /* SIGTERM so it can clean up if necessary */
1980 #endif
1981 }
1982
1983 static void
1984 capture_pcap_cb(u_char *user, const struct pcap_pkthdr *phdr,
1985   const u_char *pd) {
1986   struct wtap_pkthdr whdr;
1987   loop_data *ld = (loop_data *) user;
1988   int err;
1989
1990   if ((++ld->counts.total >= ld->max) && (ld->max > 0)) 
1991   {
1992      ld->go = FALSE;
1993   }
1994   if (ld->pdh) {
1995      /* "phdr->ts" may not necessarily be a "struct timeval" - it may
1996         be a "struct bpf_timeval", with member sizes wired to 32
1997         bits - and we may go that way ourselves in the future, so
1998         copy the members individually. */
1999      whdr.ts.tv_sec = phdr->ts.tv_sec;
2000      whdr.ts.tv_usec = phdr->ts.tv_usec;
2001      whdr.caplen = phdr->caplen;
2002      whdr.len = phdr->len;
2003      whdr.pkt_encap = ld->linktype;
2004
2005      /* If this fails, set "ld->go" to FALSE, to stop the capture, and set
2006         "ld->err" to the error. */
2007      if (!wtap_dump(ld->pdh, &whdr, NULL, pd, &err)) {
2008        ld->go = FALSE;
2009        ld->err = err;
2010      }
2011   }
2012
2013   switch (ld->linktype) {
2014     case WTAP_ENCAP_ETHERNET:
2015       capture_eth(pd, 0, phdr->len, &ld->counts);
2016       break;
2017     case WTAP_ENCAP_FDDI:
2018     case WTAP_ENCAP_FDDI_BITSWAPPED:
2019       capture_fddi(pd, phdr->len, &ld->counts);
2020       break;
2021     case WTAP_ENCAP_PRISM_HEADER:
2022       capture_prism(pd, 0, phdr->len, &ld->counts);
2023       break;
2024     case WTAP_ENCAP_TOKEN_RING:
2025       capture_tr(pd, 0, phdr->len, &ld->counts);
2026       break;
2027     case WTAP_ENCAP_NULL:
2028       capture_null(pd, phdr->len, &ld->counts);
2029       break;
2030     case WTAP_ENCAP_PPP:
2031       capture_ppp_hdlc(pd, 0, phdr->len, &ld->counts);
2032       break;
2033     case WTAP_ENCAP_RAW_IP:
2034       capture_raw(pd, phdr->len, &ld->counts);
2035       break;
2036     case WTAP_ENCAP_SLL:
2037       capture_sll(pd, phdr->len, &ld->counts);
2038       break;
2039     case WTAP_ENCAP_LINUX_ATM_CLIP:
2040       capture_clip(pd, phdr->len, &ld->counts);
2041       break;
2042     case WTAP_ENCAP_LOCALTALK:
2043       capture_llap(pd, phdr->len, &ld->counts);
2044       break;
2045     /* XXX - FreeBSD may append 4-byte ATM pseudo-header to DLT_ATM_RFC1483,
2046        with LLC header following; we should implement it at some
2047        point. */
2048   }
2049 }
2050
2051 #endif /* HAVE_LIBPCAP */