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