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