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