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