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