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