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