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