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