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