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