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