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