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