Make the bytes-written information from Wiretap a long, as we allow
[obnox/wireshark/wip.git] / capture.c
1 /* capture.c
2  * Routines for packet capture windows
3  *
4  * $Id: capture.c,v 1.163 2001/12/04 08:25:55 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_TYPES_H
32 # include <sys/types.h>
33 #endif
34
35 #ifdef HAVE_SYS_STAT_H
36 # include <sys/stat.h>
37 #endif
38
39 #ifdef HAVE_SYS_WAIT_H
40 # include <sys/wait.h>
41 #endif
42
43 #ifndef _WIN32
44 /*
45  * Define various POSIX macros (and, in the case of WCOREDUMP, non-POSIX
46  * macros) on UNIX systems that don't have them.
47  */
48 #ifndef WIFEXITED
49 # define WIFEXITED(status)      (((status) & 0177) == 0)
50 #endif
51 #ifndef WIFSTOPPED
52 # define WIFSTOPPED(status)     (((status) & 0177) == 0177)
53 #endif
54 #ifndef WIFSIGNALED
55 # define WIFSIGNALED(status)    (!WIFSTOPPED(status) && !WIFEXITED(status))
56 #endif
57 #ifndef WEXITSTATUS
58 # define WEXITSTATUS(status)    ((status) >> 8)
59 #endif
60 #ifndef WTERMSIG
61 # define WTERMSIG(status)       ((status) & 0177)
62 #endif
63 #ifndef WCOREDUMP
64 # define WCOREDUMP(status)      ((status) & 0200)
65 #endif
66 #ifndef WSTOPSIG
67 # define WSTOPSIG(status)       ((status) >> 8)
68 #endif
69 #endif /* _WIN32 */
70
71 #ifdef HAVE_IO_H
72 # include <io.h>
73 #endif
74
75 #include <gtk/gtk.h>
76 #include <stdlib.h>
77 #include <stdio.h>
78 #include <ctype.h>
79 #include <string.h>
80
81 #ifdef HAVE_FCNTL_H
82 #include <fcntl.h>
83 #endif
84
85 #ifdef HAVE_UNISTD_H
86 #include <unistd.h>
87 #endif
88
89 #include <time.h>
90
91 #ifdef HAVE_SYS_SOCKET_H
92 #include <sys/socket.h>
93 #endif
94
95 #ifdef HAVE_SYS_IOCTL_H
96 #include <sys/ioctl.h>
97 #endif
98
99 #include <signal.h>
100 #include <errno.h>
101
102 #include <pcap.h>
103
104 #ifdef NEED_SNPRINTF_H
105 # include "snprintf.h"
106 #endif
107
108 #ifdef _WIN32
109 #include <process.h>    /* For spawning child process */
110 #endif
111
112 /*
113  * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
114  * want to include it if it's not present on this platform, however.
115  */
116 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__bsdi__)
117 #ifndef BSD
118 #define BSD
119 #endif /* BSD */
120 #endif /* defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__bsdi__) */
121
122 /*
123  * We don't want to do a "select()" on the pcap_t's file descriptor on
124  * BSD (because "select()" doesn't work correctly on BPF devices on at
125  * least some releases of some flavors of BSD), and we don't want to do
126  * it on Windows (because "select()" is something for sockets, not for
127  * arbitrary handles).
128  *
129  * We *do* want to do it on other platforms, as, on other platforms (with
130  * the possible exception of Ultrix and Digital UNIX), the read timeout
131  * doesn't expire if no packets have arrived, so a "pcap_dispatch()" call
132  * will block until packets arrive, causing the UI to hang.
133  */
134 #if !defined(BSD) && !defined(_WIN32)
135 # define MUST_DO_SELECT
136 #endif
137
138 #include "gtk/main.h"
139 #include "gtk/gtkglobals.h"
140 #include "packet.h"
141 #include "file.h"
142 #include "capture.h"
143 #include "util.h"
144 #include "pcap-util.h"
145 #include "simple_dialog.h"
146 #include "prefs.h"
147 #include "globals.h"
148 #include "conditions.h"
149 #include "capture_stop_conditions.h"
150 #include "ringbuffer.h"
151
152 #include "wiretap/libpcap.h"
153 #include "wiretap/wtap.h"
154
155 #include "packet-atalk.h"
156 #include "packet-clip.h"
157 #include "packet-eth.h"
158 #include "packet-fddi.h"
159 #include "packet-null.h"
160 #include "packet-ppp.h"
161 #include "packet-raw.h"
162 #include "packet-sll.h"
163 #include "packet-tr.h"
164 #include "packet-ieee80211.h"
165 #include "packet-chdlc.h"
166 #include "packet-prism.h"
167
168 #ifdef WIN32
169 #include "capture-wpcap.h"
170 #endif
171
172 static int sync_pipe[2]; /* used to sync father */
173 enum PIPES { READ, WRITE }; /* Constants 0 and 1 for READ and WRITE */
174 int quit_after_cap; /* Makes a "capture only mode". Implies -k */
175 gboolean capture_child; /* if this is the child for "-S" */
176 static int fork_child;  /* In parent, process ID of child */
177 static guint cap_input_id;
178
179 /*
180  * Indications sent out on the sync pipe.
181  */
182 #define SP_CAPSTART     ';'     /* capture start message */
183 #define SP_PACKET_COUNT '*'     /* followed by count of packets captured since last message */
184 #define SP_ERROR_MSG    '!'     /* followed by length of error message that follows */
185 #define SP_DROPS        '#'     /* followed by count of packets dropped in capture */
186
187 #ifdef _WIN32
188 static guint cap_timer_id;
189 static int cap_timer_cb(gpointer); /* Win32 kludge to check for pipe input */
190 #endif
191
192 static void cap_file_input_cb(gpointer, gint, GdkInputCondition);
193 static void wait_for_child(gboolean);
194 #ifndef _WIN32
195 static char *signame(int);
196 #endif
197 static void capture_delete_cb(GtkWidget *, GdkEvent *, gpointer);
198 static void capture_stop_cb(GtkWidget *, gpointer);
199 static void capture_pcap_cb(u_char *, const struct pcap_pkthdr *,
200   const u_char *);
201 static void get_capture_file_io_error(char *, int, const char *, int, gboolean);
202 static void send_errmsg_to_parent(const char *);
203 static float pct(gint, gint);
204 static void stop_capture(int signo);
205
206 typedef struct _loop_data {
207   gint           go;           /* TRUE as long as we're supposed to keep capturing */
208   gint           max;          /* Number of packets we're supposed to capture - 0 means infinite */
209   int            err;          /* if non-zero, error seen while capturing */
210   gint           linktype;
211   gint           sync_packets;
212   gboolean       from_pipe;    /* TRUE if we are capturing data from a pipe */
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   packet_counts  counts;
216   wtap_dumper   *pdh;
217 } loop_data;
218
219 #ifndef _WIN32
220 static void adjust_header(loop_data *, struct pcap_hdr *, struct pcaprec_hdr *);
221 static int pipe_open_live(char *, struct pcap_hdr *, loop_data *, char *);
222 static int pipe_dispatch(int, loop_data *, struct pcap_hdr *);
223 #endif
224
225 /* Win32 needs the O_BINARY flag for open() */
226 #ifndef O_BINARY
227 #define O_BINARY        0
228 #endif
229
230 #ifdef _WIN32
231 /* Win32 needs a handle to the child capture process */
232 int child_process;
233 #endif
234
235 /* Add a string pointer to a NULL-terminated array of string pointers. */
236 static char **
237 add_arg(char **args, int *argc, char *arg)
238 {
239   /* Grow the array; "*argc" currently contains the number of string
240      pointers, *not* counting the NULL pointer at the end, so we have
241      to add 2 in order to get the new size of the array, including the
242      new pointer and the terminating NULL pointer. */
243   args = g_realloc(args, (*argc + 2) * sizeof (char *));
244
245   /* Stuff the pointer into the penultimate element of the array, which
246      is the one at the index specified by "*argc". */
247   args[*argc] = arg;
248
249   /* Now bump the count. */
250   (*argc)++;
251
252   /* We overwrite the NULL pointer; put it back right after the
253      element we added. */
254   args[*argc] = NULL;
255
256   return args;
257 }
258
259 #ifdef _WIN32
260 /* Given a string, return a pointer to a quote-encapsulated version of
261    the string, so we can pass it as an argument with "spawnvp" even
262    if it contains blanks. */
263 char *
264 quote_encapsulate(const char *string)
265 {
266   char *encapsulated_string;
267
268   encapsulated_string = g_new(char, strlen(string) + 3);
269   sprintf(encapsulated_string, "\"%s\"", string);
270   return encapsulated_string;
271 }
272 #endif
273
274 /* Open a specified file, or create a temporary file, and start a capture
275    to the file in question. */
276 void
277 do_capture(char *capfile_name)
278 {
279   char tmpname[128+1];
280   gboolean is_tempfile;
281   u_char c;
282   int i;
283   guint byte_count;
284   char *msg;
285   int err;
286   int capture_succeeded;
287   gboolean stats_known;
288   struct pcap_stat stats;
289
290   if (capfile_name != NULL) {
291     if (cfile.ringbuffer_on) {
292       /* ringbuffer is enabled */
293       cfile.save_file_fd = ringbuf_init(capfile_name, cfile.ringbuffer_num_files);
294     } else {
295       /* Try to open/create the specified file for use as a capture buffer. */
296       cfile.save_file_fd = open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT, 0600);
297     }
298     is_tempfile = FALSE;
299   } else {
300     /* Choose a random name for the capture buffer */
301     cfile.save_file_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
302     capfile_name = g_strdup(tmpname);
303     is_tempfile = TRUE;
304   }
305   if (cfile.save_file_fd == -1) {
306     if (is_tempfile) {
307       simple_dialog(ESD_TYPE_CRIT, NULL,
308         "The temporary file to which the capture would be saved (\"%s\")"
309         "could not be opened: %s.", capfile_name, strerror(errno));
310     } else {
311       if (cfile.ringbuffer_on) {
312         ringbuf_error_cleanup();
313       }
314       simple_dialog(ESD_TYPE_CRIT, NULL,
315         file_open_error_message(errno, TRUE), capfile_name);
316     }
317     return;
318   }
319   close_cap_file(&cfile);
320   g_assert(cfile.save_file == NULL);
321   cfile.save_file = capfile_name;
322
323   if (prefs.capture_real_time) {        /* do the capture in a child process */
324     char ssnap[24];
325     char scount[24];                    /* need a constant for len of numbers */
326     char sautostop_filesize[24];        /* need a constant for len of numbers */
327     char sautostop_duration[24];        /* need a constant for len of numbers */
328     char save_file_fd[24];
329     char errmsg[1024+1];
330     int error;
331     int argc;
332     char **argv;
333 #ifdef _WIN32
334     char sync_pipe_fd[24];
335     char *fontstring;
336     char *filterstring;
337 #endif
338
339     /* Allocate the string pointer array with enough space for the
340        terminating NULL pointer. */
341     argc = 0;
342     argv = g_malloc(sizeof (char *));
343     *argv = NULL;
344
345     /* Now add those arguments used on all platforms. */
346     argv = add_arg(argv, &argc, CHILD_NAME);
347
348     argv = add_arg(argv, &argc, "-i");
349     argv = add_arg(argv, &argc, cfile.iface);
350
351     argv = add_arg(argv, &argc, "-w");
352     argv = add_arg(argv, &argc, cfile.save_file);
353
354     argv = add_arg(argv, &argc, "-W");
355     sprintf(save_file_fd,"%d",cfile.save_file_fd);      /* in lieu of itoa */
356     argv = add_arg(argv, &argc, save_file_fd);
357
358     argv = add_arg(argv, &argc, "-c");
359     sprintf(scount,"%d",cfile.count);
360     argv = add_arg(argv, &argc, scount);
361
362     argv = add_arg(argv, &argc, "-s");
363     sprintf(ssnap,"%d",cfile.snap);
364     argv = add_arg(argv, &argc, ssnap);
365
366     argv = add_arg(argv, &argc, "-a");
367     sprintf(sautostop_filesize,"filesize:%d",cfile.autostop_filesize);
368     argv = add_arg(argv, &argc, sautostop_filesize);
369
370     argv = add_arg(argv, &argc, "-a");
371     sprintf(sautostop_duration,"duration:%d",cfile.autostop_duration);
372     argv = add_arg(argv, &argc, sautostop_duration);
373
374     if (!prefs.capture_prom_mode)
375       argv = add_arg(argv, &argc, "-p");
376
377 #ifdef _WIN32
378     /* Create a pipe for the child process */
379
380     if(_pipe(sync_pipe, 512, O_BINARY) < 0) {
381       /* Couldn't create the pipe between parent and child. */
382       error = errno;
383       unlink(cfile.save_file);
384       g_free(cfile.save_file);
385       cfile.save_file = NULL;
386       simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create sync pipe: %s",
387                         strerror(error));
388       return;
389     }
390
391     /* Convert font name to a quote-encapsulated string and pass to child */
392     argv = add_arg(argv, &argc, "-m");
393     fontstring = quote_encapsulate(prefs.gui_font_name);
394     argv = add_arg(argv, &argc, fontstring);
395
396     /* Convert pipe write handle to a string and pass to child */
397     argv = add_arg(argv, &argc, "-Z");
398     itoa(sync_pipe[WRITE], sync_pipe_fd, 10);
399     argv = add_arg(argv, &argc, sync_pipe_fd);
400
401     /* Convert filter string to a quote delimited string and pass to child */
402     if (cfile.cfilter != NULL && strlen(cfile.cfilter) != 0) {
403       argv = add_arg(argv, &argc, "-f");
404       filterstring = quote_encapsulate(cfile.cfilter);
405       argv = add_arg(argv, &argc, filterstring);
406     }
407
408     /* Spawn process */
409     fork_child = spawnvp(_P_NOWAIT, ethereal_path, argv);
410     g_free(fontstring);
411     g_free(filterstring);
412     /* Keep a copy for later evaluation by _cwait() */
413     child_process = fork_child;
414 #else
415     signal(SIGCHLD, SIG_IGN);
416     if (pipe(sync_pipe) < 0) {
417       /* Couldn't create the pipe between parent and child. */
418       error = errno;
419       unlink(cfile.save_file);
420       g_free(cfile.save_file);
421       cfile.save_file = NULL;
422       simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create sync pipe: %s",
423                         strerror(error));
424       return;
425     }
426
427     argv = add_arg(argv, &argc, "-m");
428     argv = add_arg(argv, &argc, prefs.gui_font_name);
429
430     if (cfile.cfilter != NULL && strlen(cfile.cfilter) != 0) {
431       argv = add_arg(argv, &argc, "-f");
432       argv = add_arg(argv, &argc, cfile.cfilter);
433     }
434
435     if ((fork_child = fork()) == 0) {
436       /*
437        * Child process - run Ethereal with the right arguments to make
438        * it just pop up the live capture dialog box and capture with
439        * the specified capture parameters, writing to the specified file.
440        *
441        * args: -i interface specification
442        * -w file to write
443        * -W file descriptor to write
444        * -c count to capture
445        * -s snaplen
446        * -m / -b fonts
447        * -f "filter expression"
448        */
449       close(1);
450       dup(sync_pipe[WRITE]);
451       close(sync_pipe[READ]);
452       execvp(ethereal_path, argv);
453       snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
454                 ethereal_path, strerror(errno));
455       send_errmsg_to_parent(errmsg);
456
457       /* Exit with "_exit()", so that we don't close the connection
458          to the X server (and cause stuff buffered up by our parent but
459          not yet sent to be sent, as that stuff should only be sent by
460          our parent). */
461       _exit(2);
462     }
463 #endif
464
465     /* Parent process - read messages from the child process over the
466        sync pipe. */
467     g_free(argv);       /* free up arg array */
468
469     /* Close the write side of the pipe, so that only the child has it
470        open, and thus it completely closes, and thus returns to us
471        an EOF indication, if the child closes it (either deliberately
472        or by exiting abnormally). */
473     close(sync_pipe[WRITE]);
474
475     /* Close the save file FD, as we won't be using it - we'll be opening
476        it and reading the save file through Wiretap. */
477     close(cfile.save_file_fd);
478
479     if (fork_child == -1) {
480       /* We couldn't even create the child process. */
481       error = errno;
482       close(sync_pipe[READ]);
483       unlink(cfile.save_file);
484       g_free(cfile.save_file);
485       cfile.save_file = NULL;
486       simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create child process: %s",
487                         strerror(error));
488       return;
489     }
490
491     /* Read a byte count from "sync_pipe[READ]", terminated with a
492        colon; if the count is 0, the child process created the
493        capture file and we should start reading from it, otherwise
494        the capture couldn't start and the count is a count of bytes
495        of error message, and we should display the message. */
496     byte_count = 0;
497     for (;;) {
498       i = read(sync_pipe[READ], &c, 1);
499       if (i == 0) {
500         /* EOF - the child process died.
501            Close the read side of the sync pipe, remove the capture file,
502            and report the failure. */
503         close(sync_pipe[READ]);
504         unlink(cfile.save_file);
505         g_free(cfile.save_file);
506         cfile.save_file = NULL;
507         wait_for_child(TRUE);
508         return;
509       }
510       if (c == SP_CAPSTART || c == SP_ERROR_MSG)
511         break;
512       if (!isdigit(c)) {
513         /* Child process handed us crap.
514            Close the read side of the sync pipe, remove the capture file,
515            and report the failure. */
516         close(sync_pipe[READ]);
517         unlink(cfile.save_file);
518         g_free(cfile.save_file);
519         cfile.save_file = NULL;
520         simple_dialog(ESD_TYPE_WARN, NULL,
521                         "Capture child process sent us a bad message");
522         return;
523       }
524       byte_count = byte_count*10 + c - '0';
525     }
526     if (c == SP_CAPSTART) {
527       /* Success.  Open the capture file, and set up to read it. */
528       err = start_tail_cap_file(cfile.save_file, is_tempfile, &cfile);
529       if (err == 0) {
530         /* We were able to open and set up to read the capture file;
531            arrange that our callback be called whenever it's possible
532            to read from the sync pipe, so that it's called when
533            the child process wants to tell us something. */
534 #ifdef _WIN32
535         /* Tricky to use pipes in win9x, as no concept of wait.  NT can
536            do this but that doesn't cover all win32 platforms.  GTK can do
537            this but doesn't seem to work over processes.  Attempt to do
538            something similar here, start a timer and check for data on every
539            timeout. */
540         cap_timer_id = gtk_timeout_add(1000, cap_timer_cb, NULL);
541 #else
542         cap_input_id = gtk_input_add_full(sync_pipe[READ],
543                                        GDK_INPUT_READ|GDK_INPUT_EXCEPTION,
544                                        cap_file_input_cb,
545                                        NULL,
546                                        (gpointer) &cfile,
547                                        NULL);
548 #endif
549       } else {
550         /* We weren't able to open the capture file; complain, and
551            close the sync pipe. */
552         simple_dialog(ESD_TYPE_CRIT, NULL,
553                         file_open_error_message(err, FALSE), cfile.save_file);
554
555         /* Close the sync pipe. */
556         close(sync_pipe[READ]);
557
558         /* Don't unlink the save file - leave it around, for debugging
559            purposes. */
560         g_free(cfile.save_file);
561         cfile.save_file = NULL;
562       }
563     } else {
564       /* Failure - the child process sent us a message indicating
565          what the problem was. */
566       if (byte_count == 0) {
567         /* Zero-length message? */
568         simple_dialog(ESD_TYPE_WARN, NULL,
569                 "Capture child process failed, but its error message was empty.");
570       } else {
571         msg = g_malloc(byte_count + 1);
572         if (msg == NULL) {
573           simple_dialog(ESD_TYPE_WARN, NULL,
574                 "Capture child process failed, but its error message was too big.");
575         } else {
576           i = read(sync_pipe[READ], msg, byte_count);
577           msg[byte_count] = '\0';
578           if (i < 0) {
579             simple_dialog(ESD_TYPE_WARN, NULL,
580                   "Capture child process failed: Error %s reading its error message.",
581                   strerror(errno));
582           } else if (i == 0) {
583             simple_dialog(ESD_TYPE_WARN, NULL,
584                   "Capture child process failed: EOF reading its error message.");
585             wait_for_child(FALSE);
586           } else
587             simple_dialog(ESD_TYPE_WARN, NULL, msg);
588           g_free(msg);
589         }
590
591         /* Close the sync pipe. */
592         close(sync_pipe[READ]);
593
594         /* Get rid of the save file - the capture never started. */
595         unlink(cfile.save_file);
596         g_free(cfile.save_file);
597         cfile.save_file = NULL;
598       }
599     }
600   } else {
601     /* Not sync mode. */
602     capture_succeeded = capture(&stats_known, &stats);
603     if (quit_after_cap) {
604       /* DON'T unlink the save file.  Presumably someone wants it. */
605       gtk_exit(0);
606     }
607     if (capture_succeeded) {
608       /* Capture succeeded; read in the capture file. */
609       if ((err = open_cap_file(cfile.save_file, is_tempfile, &cfile)) == 0) {
610         /* Set the read filter to NULL. */
611         cfile.rfcode = NULL;
612
613         /* Get the packet-drop statistics.
614
615            XXX - there are currently no packet-drop statistics stored
616            in libpcap captures, and that's what we're reading.
617
618            At some point, we will add support in Wiretap to return
619            packet-drop statistics for capture file formats that store it,
620            and will make "read_cap_file()" get those statistics from
621            Wiretap.  We clear the statistics (marking them as "not known")
622            in "open_cap_file()", and "read_cap_file()" will only fetch
623            them and mark them as known if Wiretap supplies them, so if
624            we get the statistics now, after calling "open_cap_file()" but
625            before calling "read_cap_file()", the values we store will
626            be used by "read_cap_file()".
627
628            If a future libpcap capture file format stores the statistics,
629            we'll put them into the capture file that we write, and will
630            thus not have to set them here - "read_cap_file()" will get
631            them from the file and use them. */
632         if (stats_known) {
633           cfile.drops_known = TRUE;
634
635           /* XXX - on some systems, libpcap doesn't bother filling in
636              "ps_ifdrop" - it doesn't even set it to zero - so we don't
637              bother looking at it.
638
639              Ideally, libpcap would have an interface that gave us
640              several statistics - perhaps including various interface
641              error statistics - and would tell us which of them it
642              supplies, allowing us to display only the ones it does. */
643           cfile.drops = stats.ps_drop;
644         }
645         switch (read_cap_file(&cfile, &err)) {
646
647         case READ_SUCCESS:
648         case READ_ERROR:
649           /* Just because we got an error, that doesn't mean we were unable
650              to read any of the file; we handle what we could get from the
651              file. */
652           break;
653
654         case READ_ABORTED:
655           /* Exit by leaving the main loop, so that any quit functions
656              we registered get called. */
657           gtk_main_quit();
658           return;
659         }
660       }
661     }
662     /* We're not doing a capture any more, so we don't have a save
663        file. */
664     if (cfile.ringbuffer_on) {
665       ringbuf_free();
666     } else {
667       g_free(cfile.save_file);
668     }
669     cfile.save_file = NULL;
670   }
671 }
672
673 #ifdef _WIN32
674 /* The timer has expired, see if there's stuff to read from the pipe,
675    if so call the cap_file_input_cb */
676 static gint
677 cap_timer_cb(gpointer data)
678 {
679   HANDLE handle;
680   DWORD avail = 0;
681   gboolean result, result1;
682   DWORD childstatus;
683
684   /* Oddly enough although Named pipes don't work on win9x,
685      PeekNamedPipe does !!! */
686   handle = (HANDLE) _get_osfhandle (sync_pipe[READ]);
687   result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
688
689   /* Get the child process exit status */
690   result1 = GetExitCodeProcess((HANDLE)child_process, &childstatus);
691
692   /* If the Peek returned an error, or there are bytes to be read
693      or the childwatcher thread has terminated then call the normal
694      callback */
695   if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
696
697     /* avoid reentrancy problems and stack overflow */
698     gtk_timeout_remove(cap_timer_id);
699
700     /* And call the real handler */
701     cap_file_input_cb((gpointer) &cfile, 0, 0);
702
703     /* Return false so that the timer is not run again */
704     return FALSE;
705   }
706   else {
707     /* No data so let timer run again */
708     return TRUE;
709   }
710 }
711 #endif
712
713 /* There's stuff to read from the sync pipe, meaning the child has sent
714    us a message, or the sync pipe has closed, meaning the child has
715    closed it (perhaps because it exited). */
716 static void 
717 cap_file_input_cb(gpointer data, gint source, GdkInputCondition condition)
718 {
719   capture_file *cf = (capture_file *)data;
720 #define BUFSIZE 4096
721   char buffer[BUFSIZE+1], *p = buffer, *q = buffer, *msg, *r;
722   int  nread, msglen, chars_to_copy;
723   int  to_read = 0;
724   int  err;
725
726 #ifndef _WIN32
727   /* avoid reentrancy problems and stack overflow */
728   gtk_input_remove(cap_input_id);
729 #endif
730
731   if ((nread = read(sync_pipe[READ], buffer, BUFSIZE)) <= 0) {
732     /* The child has closed the sync pipe, meaning it's not going to be
733        capturing any more packets.  Pick up its exit status, and
734        complain if it did anything other than exit with status 0. */
735     wait_for_child(FALSE);
736       
737     /* Read what remains of the capture file, and finish the capture.
738        XXX - do something if this fails? */
739     switch (finish_tail_cap_file(cf, &err)) {
740
741     case READ_SUCCESS:
742     case READ_ERROR:
743       /* Just because we got an error, that doesn't mean we were unable
744          to read any of the file; we handle what we could get from the
745          file. */
746       break;
747
748     case READ_ABORTED:
749       /* Exit by leaving the main loop, so that any quit functions
750          we registered get called. */
751       gtk_main_quit();
752       return;
753     }
754
755     /* We're not doing a capture any more, so we don't have a save
756        file. */
757     g_free(cf->save_file);
758     cf->save_file = NULL;
759
760     return;
761   }
762
763   buffer[nread] = '\0';
764
765   while (nread != 0) {
766     /* look for (possibly multiple) indications */
767     switch (*q) {
768     case SP_PACKET_COUNT :
769       to_read += atoi(p);
770       p = q + 1;
771       q++;
772       nread--;
773       break;
774     case SP_DROPS :
775       cf->drops_known = TRUE;
776       cf->drops = atoi(p);
777       p = q + 1;
778       q++;
779       nread--;
780       break;
781     case SP_ERROR_MSG :
782       msglen = atoi(p);
783       p = q + 1;
784       q++;
785       nread--;
786
787       /* Read the entire message.
788          XXX - if the child hasn't sent it all yet, this could cause us
789          to hang until they do. */
790       msg = g_malloc(msglen + 1);
791       r = msg;
792       while (msglen != 0) {
793         if (nread == 0) {
794           /* Read more. */
795           if ((nread = read(sync_pipe[READ], buffer, BUFSIZE)) <= 0)
796             break;
797           p = buffer;
798           q = buffer;
799         }
800         chars_to_copy = MIN(msglen, nread);
801         memcpy(r, q, chars_to_copy);
802         r += chars_to_copy;
803         q += chars_to_copy;
804         nread -= chars_to_copy;
805         msglen -= chars_to_copy;
806       }
807       *r = '\0';
808       simple_dialog(ESD_TYPE_WARN, NULL, msg);
809       g_free(msg);
810       break;
811     default :
812       q++;
813       nread--;
814       break;
815     } 
816   }
817
818   /* Read from the capture file the number of records the child told us
819      it added.
820      XXX - do something if this fails? */
821   switch (continue_tail_cap_file(cf, to_read, &err)) {
822
823   case READ_SUCCESS:
824   case READ_ERROR:
825     /* Just because we got an error, that doesn't mean we were unable
826        to read any of the file; we handle what we could get from the
827        file.
828
829        XXX - abort on a read error? */
830     break;
831
832   case READ_ABORTED:
833     /* Kill the child capture process; the user wants to exit, and we
834        shouldn't just leave it running. */
835 #ifdef _WIN32
836     /* XXX - kill it. */
837 #else
838     kill(fork_child, SIGTERM);  /* SIGTERM so it can clean up if necessary */
839 #endif
840     break;
841   }
842
843   /* restore pipe handler */
844 #ifdef _WIN32
845   cap_timer_id = gtk_timeout_add(1000, cap_timer_cb, NULL);
846 #else
847   cap_input_id = gtk_input_add_full (sync_pipe[READ],
848                                      GDK_INPUT_READ|GDK_INPUT_EXCEPTION,
849                                      cap_file_input_cb,
850                                      NULL,
851                                      (gpointer) cf,
852                                      NULL);
853 #endif
854 }
855
856 static void
857 wait_for_child(gboolean always_report)
858 {
859   int  wstatus;
860
861 #ifdef _WIN32
862   /* XXX - analyze the wait stuatus and display more information
863      in the dialog box? */
864   if (_cwait(&wstatus, child_process, _WAIT_CHILD) == -1) {
865     simple_dialog(ESD_TYPE_WARN, NULL, "Child capture process stopped unexpectedly");
866   }
867 #else
868   if (wait(&wstatus) != -1) {
869     if (WIFEXITED(wstatus)) {
870       /* The child exited; display its exit status, if it's not zero,
871          and even if it's zero if "always_report" is true. */
872       if (always_report || WEXITSTATUS(wstatus) != 0) {
873         simple_dialog(ESD_TYPE_WARN, NULL,
874                       "Child capture process exited: exit status %d",
875                       WEXITSTATUS(wstatus));
876       }
877     } else if (WIFSTOPPED(wstatus)) {
878       /* It stopped, rather than exiting.  "Should not happen." */
879       simple_dialog(ESD_TYPE_WARN, NULL,
880                     "Child capture process stopped: %s",
881                     signame(WSTOPSIG(wstatus)));
882     } else if (WIFSIGNALED(wstatus)) {
883       /* It died with a signal. */
884       simple_dialog(ESD_TYPE_WARN, NULL,
885                     "Child capture process died: %s%s",
886                     signame(WTERMSIG(wstatus)),
887                     WCOREDUMP(wstatus) ? " - core dumped" : "");
888     } else {
889       /* What?  It had to either have exited, or stopped, or died with
890          a signal; what happened here? */
891       simple_dialog(ESD_TYPE_WARN, NULL,
892                     "Child capture process died: wait status %#o", wstatus);
893     }
894   }
895 #endif
896 }
897
898 #ifndef _WIN32
899 static char *
900 signame(int sig)
901 {
902   char *sigmsg;
903   static char sigmsg_buf[6+1+3+1];
904
905   switch (sig) {
906
907   case SIGHUP:
908     sigmsg = "Hangup";
909     break;
910
911   case SIGINT:
912     sigmsg = "Interrupted";
913     break;
914
915   case SIGQUIT:
916     sigmsg = "Quit";
917     break;
918
919   case SIGILL:
920     sigmsg = "Illegal instruction";
921     break;
922
923   case SIGTRAP:
924     sigmsg = "Trace trap";
925     break;
926
927   case SIGABRT:
928     sigmsg = "Abort";
929     break;
930
931   case SIGFPE:
932     sigmsg = "Arithmetic exception";
933     break;
934
935   case SIGKILL:
936     sigmsg = "Killed";
937     break;
938
939   case SIGBUS:
940     sigmsg = "Bus error";
941     break;
942
943   case SIGSEGV:
944     sigmsg = "Segmentation violation";
945     break;
946
947   /* http://metalab.unc.edu/pub/Linux/docs/HOWTO/GCC-HOWTO 
948      Linux is POSIX compliant.  These are not POSIX-defined signals ---
949      ISO/IEC 9945-1:1990 (IEEE Std 1003.1-1990), paragraph B.3.3.1.1 sez:
950
951         ``The signals SIGBUS, SIGEMT, SIGIOT, SIGTRAP, and SIGSYS
952         were omitted from POSIX.1 because their behavior is
953         implementation dependent and could not be adequately catego-
954         rized.  Conforming implementations may deliver these sig-
955         nals, but must document the circumstances under which they
956         are delivered and note any restrictions concerning their
957         delivery.''
958
959      So we only check for SIGSYS on those systems that happen to
960      implement them (a system can be POSIX-compliant and implement
961      them, it's just that POSIX doesn't *require* a POSIX-compliant
962      system to implement them).
963    */
964
965 #ifdef SIGSYS
966   case SIGSYS:
967     sigmsg = "Bad system call";
968     break;
969 #endif
970
971   case SIGPIPE:
972     sigmsg = "Broken pipe";
973     break;
974
975   case SIGALRM:
976     sigmsg = "Alarm clock";
977     break;
978
979   case SIGTERM:
980     sigmsg = "Terminated";
981     break;
982
983   default:
984     sprintf(sigmsg_buf, "Signal %d", sig);
985     sigmsg = sigmsg_buf;
986     break;
987   }
988   return sigmsg;
989 }
990 #endif
991
992 /*
993  * Timeout, in milliseconds, for reads from the stream of captured packets.
994  */
995 #define CAP_READ_TIMEOUT        250
996
997 #ifndef _WIN32
998 /* Take carre of byte order in the libpcap headers read from pipes.
999  * (function taken from wiretap/libpcap.c) */
1000 static void
1001 adjust_header(loop_data *ld, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
1002 {
1003   if (ld->byte_swapped) {
1004     /* Byte-swap the record header fields. */
1005     rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
1006     rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
1007     rechdr->incl_len = BSWAP32(rechdr->incl_len);
1008     rechdr->orig_len = BSWAP32(rechdr->orig_len);
1009   }
1010
1011   /* In file format version 2.3, the "incl_len" and "orig_len" fields were
1012      swapped, in order to match the BPF header layout.
1013
1014      Unfortunately, some files were, according to a comment in the "libpcap"
1015      source, written with version 2.3 in their headers but without the
1016      interchanged fields, so if "incl_len" is greater than "orig_len" - which
1017      would make no sense - we assume that we need to swap them.  */
1018   if (hdr->version_major == 2 &&
1019       (hdr->version_minor < 3 ||
1020        (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
1021     guint32 temp;
1022
1023     temp = rechdr->orig_len;
1024     rechdr->orig_len = rechdr->incl_len;
1025     rechdr->incl_len = temp;
1026   }
1027 }
1028
1029 /* Mimic pcap_open_live() for pipe captures 
1030  * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
1031  * header.
1032  * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1033  * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1034 static int
1035 pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld, char *ebuf)
1036 {
1037   struct stat pipe_stat;
1038   int         fd;
1039   guint32     magic;
1040   int         bytes_read, b;
1041
1042   if (strcmp(pipename, "-") == 0) fd = 0; /* read from stdin */
1043   else if (stat(pipename, &pipe_stat) == 0 && S_ISFIFO(pipe_stat.st_mode)) {
1044     if ((fd = open(pipename, O_RDONLY)) == -1) return -1;
1045   } else return -1;
1046
1047   ld->from_pipe = TRUE;
1048   /* read the pcap header */
1049   if (read(fd, &magic, sizeof magic) != sizeof magic) {
1050     close(fd);
1051     return -1;
1052   }
1053
1054   switch (magic) {
1055   case PCAP_MAGIC:
1056     /* Host that wrote it has our byte order, and was running
1057        a program using either standard or ss990417 libpcap. */
1058     ld->byte_swapped = FALSE;
1059     ld->modified = FALSE;
1060     break;
1061   case PCAP_MODIFIED_MAGIC:
1062     /* Host that wrote it has our byte order, but was running
1063        a program using either ss990915 or ss991029 libpcap. */
1064     ld->byte_swapped = FALSE;
1065     ld->modified = TRUE;
1066     break;
1067   case PCAP_SWAPPED_MAGIC:
1068     /* Host that wrote it has a byte order opposite to ours,
1069        and was running a program using either standard or
1070        ss990417 libpcap. */
1071     ld->byte_swapped = TRUE;
1072     ld->modified = FALSE;
1073     break;
1074   case PCAP_SWAPPED_MODIFIED_MAGIC:
1075     /* Host that wrote it out has a byte order opposite to
1076        ours, and was running a program using either ss990915
1077        or ss991029 libpcap. */
1078     ld->byte_swapped = TRUE;
1079     ld->modified = TRUE;
1080     break;
1081   default:
1082     /* Not a "libpcap" type we know about. */
1083     close(fd);
1084     return -1;
1085   }
1086
1087   /* Read the rest of the header */
1088   bytes_read = read(fd, hdr, sizeof(struct pcap_hdr));
1089   if (bytes_read <= 0) {
1090     close(fd);
1091     return -1;
1092   }
1093   while ((unsigned) bytes_read < sizeof(struct pcap_hdr))
1094   {
1095     b = read(fd, ((char *)&hdr)+bytes_read, sizeof(struct pcap_hdr) - bytes_read);
1096     if (b <= 0) {
1097       close(fd);
1098       return -1;
1099     }
1100     bytes_read += b;
1101   }
1102   if (ld->byte_swapped) {
1103     /* Byte-swap the header fields about which we care. */
1104     hdr->version_major = BSWAP16(hdr->version_major);
1105     hdr->version_minor = BSWAP16(hdr->version_minor);
1106     hdr->snaplen = BSWAP32(hdr->snaplen);
1107     hdr->network = BSWAP32(hdr->network);
1108   }
1109   if (hdr->version_major < 2) {
1110     close(fd);
1111     return -1;
1112   }
1113
1114   return fd;
1115 }
1116
1117 /* We read one record from the pipe, take care of byte order in the record
1118  * header, write the record in the capture file, and update capture statistics. */
1119 static int
1120 pipe_dispatch(int fd, loop_data *ld, struct pcap_hdr *hdr)
1121 {
1122   struct wtap_pkthdr whdr;
1123   struct pcaprec_modified_hdr rechdr;
1124   int bytes_to_read, bytes_read, b;
1125   u_char pd[WTAP_MAX_PACKET_SIZE];
1126   int err;
1127
1128   /* read the record header */
1129   bytes_to_read = ld->modified ? sizeof rechdr : sizeof rechdr.hdr;
1130   bytes_read = read(fd, &rechdr, bytes_to_read);
1131   if (bytes_read <= 0) {
1132     close(fd);
1133     ld->go = FALSE;
1134     return 0;
1135   }
1136   while (bytes_read < bytes_to_read)
1137   {
1138     b = read(fd, ((char *)&rechdr)+bytes_read, bytes_to_read - bytes_read);
1139     if (b <= 0) {
1140       close(fd);
1141       ld->go = FALSE;
1142       return 0;
1143     }
1144     bytes_read += b;
1145   }
1146   /* take care of byte order */
1147   adjust_header(ld, hdr, &rechdr.hdr);
1148   if (rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1149     close(fd);
1150     ld->go = FALSE;
1151     return 0;
1152   }
1153   /* read the packet data */
1154   bytes_read = read(fd, pd, rechdr.hdr.incl_len);
1155   if (bytes_read <= 0) {
1156     close(fd);
1157     ld->go = FALSE;
1158     return 0;
1159   }
1160   while ((unsigned) bytes_read < rechdr.hdr.incl_len)
1161   {
1162     b = read(fd, pd+bytes_read, rechdr.hdr.incl_len - bytes_read);
1163     if (b <= 0) {
1164       close(fd);
1165       ld->go = FALSE;
1166       return 0;
1167     }
1168     bytes_read += b;
1169   }
1170   /* dump the packet data to the capture file */
1171   whdr.ts.tv_sec = rechdr.hdr.ts_sec;
1172   whdr.ts.tv_usec = rechdr.hdr.ts_usec;
1173   whdr.caplen = rechdr.hdr.incl_len;
1174   whdr.len = rechdr.hdr.orig_len;
1175   whdr.pkt_encap = ld->linktype;
1176   wtap_dump(ld->pdh, &whdr, NULL, pd, &err);
1177
1178   /* update capture statistics */
1179   switch (ld->linktype) {
1180     case WTAP_ENCAP_ETHERNET:
1181       capture_eth(pd, 0, whdr.caplen, &ld->counts);
1182       break;
1183     case WTAP_ENCAP_FDDI:
1184     case WTAP_ENCAP_FDDI_BITSWAPPED:
1185       capture_fddi(pd, whdr.caplen, &ld->counts);
1186       break;
1187     case WTAP_ENCAP_PRISM_HEADER:
1188       capture_prism(pd, 0, whdr.caplen, &ld->counts);
1189       break;
1190     case WTAP_ENCAP_TOKEN_RING:
1191       capture_tr(pd, 0, whdr.caplen, &ld->counts);
1192       break;
1193     case WTAP_ENCAP_NULL:
1194       capture_null(pd, whdr.caplen, &ld->counts);
1195       break;
1196     case WTAP_ENCAP_PPP:
1197       capture_ppp_hdlc(pd, 0, whdr.caplen, &ld->counts);
1198       break;
1199     case WTAP_ENCAP_RAW_IP:
1200       capture_raw(pd, whdr.caplen, &ld->counts);
1201       break;
1202     case WTAP_ENCAP_LINUX_ATM_CLIP:
1203       capture_clip(pd, whdr.caplen, &ld->counts);
1204       break;
1205     case WTAP_ENCAP_IEEE_802_11:
1206       capture_ieee80211(pd, 0, whdr.caplen, &ld->counts);
1207       break;
1208     case WTAP_ENCAP_CHDLC:
1209       capture_chdlc(pd, 0, whdr.caplen, &ld->counts);
1210       break;
1211     case WTAP_ENCAP_LOCALTALK:
1212       capture_llap(pd, whdr.caplen, &ld->counts);
1213       break;
1214     /* XXX - FreeBSD may append 4-byte ATM pseudo-header to DLT_ATM_RFC1483,
1215        with LLC header following; we should implement it at some
1216        point. */
1217   }
1218
1219   return 1;
1220 }
1221 #endif
1222
1223 /*
1224  * This needs to be static, so that the SIGUSR1 handler can clear the "go"
1225  * flag.
1226  */
1227 static loop_data   ld;
1228
1229 /* Do the low-level work of a capture.
1230    Returns TRUE if it succeeds, FALSE otherwise. */
1231 int
1232 capture(gboolean *stats_known, struct pcap_stat *stats)
1233 {
1234   GtkWidget  *cap_w, *main_vb, *stop_bt, *counts_tb;
1235   pcap_t     *pch;
1236   int         pcap_encap;
1237   int         snaplen;
1238   gchar       open_err_str[PCAP_ERRBUF_SIZE];
1239   gchar       lookup_net_err_str[PCAP_ERRBUF_SIZE];
1240   gchar       label_str[64];
1241   bpf_u_int32 netnum, netmask;
1242   struct bpf_program fcode;
1243   time_t      upd_time, cur_time;
1244   int         err, inpkts;
1245   condition *cnd_stop_capturesize;
1246   condition *cnd_stop_timeout;
1247   unsigned int i;
1248   static const char capstart_msg = SP_CAPSTART;
1249   char        errmsg[4096+1];
1250   gboolean    dump_ok;
1251 #ifndef _WIN32
1252   static const char ppamsg[] = "can't find PPA for ";
1253   char       *libpcap_warn;
1254 #endif
1255   fd_set      set1;
1256   struct timeval timeout;
1257 #ifdef MUST_DO_SELECT
1258   int         pcap_fd = 0;
1259 #endif
1260 #ifdef _WIN32 
1261   WORD wVersionRequested; 
1262   WSADATA wsaData; 
1263 #endif
1264 #ifndef _WIN32
1265   int         pipe_fd = -1;
1266   struct pcap_hdr hdr;
1267 #endif
1268   struct {
1269       const gchar *title;
1270       gint *value_ptr;
1271       GtkWidget *label, *value, *percent;
1272   } counts[] = {
1273       { "Total", &ld.counts.total, NULL, NULL, NULL },
1274       { "SCTP", &ld.counts.sctp, NULL, NULL, NULL },
1275       { "TCP", &ld.counts.tcp, NULL, NULL, NULL },
1276       { "UDP", &ld.counts.udp, NULL, NULL, NULL },
1277       { "ICMP", &ld.counts.icmp, NULL, NULL, NULL },
1278       { "OSPF", &ld.counts.ospf, NULL, NULL, NULL },
1279       { "GRE", &ld.counts.gre, NULL, NULL, NULL },
1280       { "NetBIOS", &ld.counts.netbios, NULL, NULL, NULL },
1281       { "IPX", &ld.counts.ipx, NULL, NULL, NULL },
1282       { "VINES", &ld.counts.vines, NULL, NULL, NULL },
1283       { "Other", &ld.counts.other, NULL, NULL, NULL }
1284   };
1285
1286 #define N_COUNTS (sizeof counts / sizeof counts[0])
1287
1288   /* Initialize Windows Socket if we are in a WIN32 OS 
1289      This needs to be done before querying the interface for network/netmask */
1290 #ifdef _WIN32 
1291   wVersionRequested = MAKEWORD( 1, 1 ); 
1292   err = WSAStartup( wVersionRequested, &wsaData ); 
1293   if (err!=0) { 
1294     snprintf(errmsg, sizeof errmsg, 
1295       "Couldn't initialize Windows Sockets."); 
1296         pch=NULL; 
1297     goto error; 
1298   } 
1299 #endif 
1300
1301   ld.go             = TRUE;
1302   ld.counts.total   = 0;
1303   ld.max            = cfile.count;
1304   ld.err            = 0;        /* no error seen yet */
1305   ld.linktype       = WTAP_ENCAP_UNKNOWN;
1306   ld.from_pipe      = FALSE;
1307   ld.sync_packets   = 0;
1308   ld.counts.sctp    = 0;
1309   ld.counts.tcp     = 0;
1310   ld.counts.udp     = 0;
1311   ld.counts.icmp    = 0;
1312   ld.counts.ospf    = 0;
1313   ld.counts.gre     = 0;
1314   ld.counts.ipx     = 0;
1315   ld.counts.netbios = 0;
1316   ld.counts.vines   = 0;
1317   ld.counts.other   = 0;
1318   ld.pdh            = NULL;
1319
1320   /* We haven't yet gotten the capture statistics. */
1321   *stats_known      = FALSE;
1322
1323   /* Open the network interface to capture from it.
1324      Some versions of libpcap may put warnings into the error buffer
1325      if they succeed; to tell if that's happened, we have to clear
1326      the error buffer, and check if it's still a null string.  */
1327   open_err_str[0] = '\0';
1328   pch = pcap_open_live(cfile.iface, cfile.snap, prefs.capture_prom_mode,
1329                        CAP_READ_TIMEOUT, open_err_str);
1330
1331   if (pch == NULL) {
1332 #ifdef _WIN32
1333     /* Well, we couldn't start the capture.
1334        If this is a child process that does the capturing in sync
1335        mode or fork mode, it shouldn't do any UI stuff until we pop up the
1336        capture-progress window, and, since we couldn't start the
1337        capture, we haven't popped it up. */
1338     if (!capture_child) {
1339       while (gtk_events_pending()) gtk_main_iteration();
1340     }
1341
1342     /* On Win32 OSes, the capture devices are probably available to all
1343        users; don't warn about permissions problems.
1344
1345        Do, however, warn that WAN devices aren't supported. */
1346     snprintf(errmsg, sizeof errmsg,
1347         "The capture session could not be initiated (%s).\n"
1348         "Please check that you have the proper interface specified.\n"
1349         "\n"
1350         "Note that the driver Ethereal uses for packet capture on Windows\n"
1351         "doesn't support capturing on PPP/WAN interfaces in Windows NT/2000.\n",
1352         open_err_str);
1353     goto error;
1354 #else
1355     /* try to open cfile.iface as a pipe */
1356     pipe_fd = pipe_open_live(cfile.iface, &hdr, &ld, open_err_str);
1357
1358     if (pipe_fd == -1) {
1359       /* Well, we couldn't start the capture.
1360          If this is a child process that does the capturing in sync
1361          mode or fork mode, it shouldn't do any UI stuff until we pop up the
1362          capture-progress window, and, since we couldn't start the
1363          capture, we haven't popped it up. */
1364       if (!capture_child) {
1365         while (gtk_events_pending()) gtk_main_iteration();
1366       }
1367
1368       /* If we got a "can't find PPA for XXX" message, warn the user (who
1369          is running Ethereal on HP-UX) that they don't have a version
1370          of libpcap that properly handles HP-UX (libpcap 0.6.x and later
1371          versions, which properly handle HP-UX, say "can't find /dev/dlpi
1372          PPA for XXX" rather than "can't find PPA for XXX"). */
1373       if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
1374         libpcap_warn =
1375           "\n\n"
1376           "You are running Ethereal with a version of the libpcap library\n"
1377           "that doesn't handle HP-UX network devices well; this means that\n"
1378           "Ethereal may not be able to capture packets.\n"
1379           "\n"
1380           "To fix this, you should install libpcap 0.6.2, or a later version\n"
1381           "of libpcap, rather than libpcap 0.4 or 0.5.x.  It is available in\n"
1382           "packaged binary form from the Software Porting And Archive Centre\n"
1383           "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
1384           "at the URL lists a number of mirror sites.";
1385       else
1386         libpcap_warn = "";
1387       snprintf(errmsg, sizeof errmsg,
1388           "The capture session could not be initiated (%s).\n"
1389           "Please check to make sure you have sufficient permissions, and that\n"
1390           "you have the proper interface or pipe specified.%s", open_err_str,
1391           libpcap_warn);
1392       goto error;
1393     }
1394 #endif
1395   }
1396
1397   /* capture filters only work on real interfaces */
1398   if (cfile.cfilter && !ld.from_pipe) {
1399     /* A capture filter was specified; set it up. */
1400     if (pcap_lookupnet(cfile.iface, &netnum, &netmask, lookup_net_err_str) < 0) {
1401       /*
1402        * Well, we can't get the netmask for this interface; it's used
1403        * only for filters that check for broadcast IP addresses, so
1404        * we just punt and use 0.  It might be nice to warn the user,
1405        * but that's a pain in a GUI application, as it'd involve popping
1406        * up a message box, and it's not clear how often this would make
1407        * a difference (only filters that check for IP broadcast addresses
1408        * use the netmask).
1409        */
1410       netmask = 0;
1411     }
1412     if (pcap_compile(pch, &fcode, cfile.cfilter, 1, netmask) < 0) {
1413       snprintf(errmsg, sizeof errmsg, "Unable to parse filter string (%s).",
1414         pcap_geterr(pch));
1415       goto error;
1416     }
1417     if (pcap_setfilter(pch, &fcode) < 0) {
1418       snprintf(errmsg, sizeof errmsg, "Can't install filter (%s).",
1419         pcap_geterr(pch));
1420       goto error;
1421     }
1422   }
1423
1424   /* Set up to write to the capture file. */
1425 #ifndef _WIN32
1426   if (ld.from_pipe) {
1427     pcap_encap = hdr.network;
1428     snaplen = hdr.snaplen;
1429   } else
1430 #endif
1431   {
1432     pcap_encap = get_pcap_linktype(pch, cfile.iface);
1433     snaplen = pcap_snapshot(pch);
1434   }
1435   ld.linktype = wtap_pcap_encap_to_wtap_encap(pcap_encap);
1436   if (ld.linktype == WTAP_ENCAP_UNKNOWN) {
1437     snprintf(errmsg, sizeof errmsg,
1438         "The network you're capturing from is of a type"
1439         " that Ethereal doesn't support (data link type %d).", pcap_encap);
1440     goto error;
1441   }
1442   if (cfile.ringbuffer_on) {
1443     ld.pdh = ringbuf_init_wtap_dump_fdopen(WTAP_FILE_PCAP, ld.linktype, 
1444       snaplen, &err);
1445   } else {
1446     ld.pdh = wtap_dump_fdopen(cfile.save_file_fd, WTAP_FILE_PCAP,
1447       ld.linktype, snaplen, &err);
1448   }
1449
1450   if (ld.pdh == NULL) {
1451     /* We couldn't set up to write to the capture file. */
1452     switch (err) {
1453
1454     case WTAP_ERR_CANT_OPEN:
1455       strcpy(errmsg, "The file to which the capture would be saved"
1456                " couldn't be created for some unknown reason.");
1457       break;
1458
1459     case WTAP_ERR_SHORT_WRITE:
1460       strcpy(errmsg, "A full header couldn't be written to the file"
1461                " to which the capture would be saved.");
1462       break;
1463
1464     default:
1465       if (err < 0) {
1466         snprintf(errmsg, sizeof(errmsg),
1467                      "The file to which the capture would be"
1468                      " saved (\"%s\") could not be opened: Error %d.",
1469                         cfile.save_file, err);
1470       } else {
1471         snprintf(errmsg, sizeof(errmsg),
1472                      "The file to which the capture would be"
1473                      " saved (\"%s\") could not be opened: %s.",
1474                         cfile.save_file, strerror(err));
1475       }
1476       break;
1477     }
1478     goto error;
1479   }
1480
1481   /* Does "open_err_str" contain a non-empty string?  If so, "pcap_open_live()"
1482      returned a warning; print it, but keep capturing. */
1483   if (open_err_str[0] != '\0')
1484     g_warning("%s.", open_err_str);
1485
1486   /* XXX - capture SIGTERM and close the capture, in case we're on a
1487      Linux 2.0[.x] system and you have to explicitly close the capture
1488      stream in order to turn promiscuous mode off?  We need to do that
1489      in other places as well - and I don't think that works all the
1490      time in any case, due to libpcap bugs. */
1491
1492   if (capture_child) {
1493     /* Well, we should be able to start capturing.
1494
1495        This is the child process for a sync mode capture, so sync out
1496        the capture file, so the header makes it to the file system,
1497        and send a "capture started successfully and capture file created"
1498        message to our parent so that they'll open the capture file and
1499        update its windows to indicate that we have a live capture in
1500        progress. */
1501     fflush(wtap_dump_file(ld.pdh));
1502     write(1, &capstart_msg, 1);
1503   }
1504
1505   cap_w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1506   gtk_window_set_title(GTK_WINDOW(cap_w), "Ethereal: Capture");
1507   gtk_window_set_modal(GTK_WINDOW(cap_w), TRUE);
1508
1509   /* Container for capture display widgets */
1510   main_vb = gtk_vbox_new(FALSE, 1);
1511   gtk_container_border_width(GTK_CONTAINER(main_vb), 5);
1512   gtk_container_add(GTK_CONTAINER(cap_w), main_vb);
1513   gtk_widget_show(main_vb);
1514
1515   /* Individual statistic elements */
1516   counts_tb = gtk_table_new(N_COUNTS, 3, TRUE);
1517   gtk_box_pack_start(GTK_BOX(main_vb), counts_tb, TRUE, TRUE, 3);
1518   gtk_widget_show(counts_tb);
1519
1520   for (i = 0; i < N_COUNTS; i++) {
1521       counts[i].label = gtk_label_new(counts[i].title);
1522       gtk_misc_set_alignment(GTK_MISC(counts[i].label), 0.0f, 0.0f);
1523
1524       counts[i].value = gtk_label_new("0");
1525       gtk_misc_set_alignment(GTK_MISC(counts[i].value), 0.0f, 0.0f);
1526
1527       counts[i].percent = gtk_label_new("0.0%");
1528       gtk_misc_set_alignment(GTK_MISC(counts[i].percent), 0.0f, 0.0f);
1529
1530       gtk_table_attach_defaults(GTK_TABLE(counts_tb),
1531                                 counts[i].label, 0, 1, i, i + 1);
1532
1533       gtk_table_attach(GTK_TABLE(counts_tb),
1534                        counts[i].value,
1535                        1, 2, i, i + 1, 0, 0, 5, 0);
1536
1537       gtk_table_attach_defaults(GTK_TABLE(counts_tb),
1538                                 counts[i].percent, 2, 3, i, i + 1);
1539
1540       gtk_widget_show(counts[i].label);
1541       gtk_widget_show(counts[i].value);
1542       gtk_widget_show(counts[i].percent);
1543   }
1544
1545   /* allow user to either click a stop button, or the close button on
1546         the window to stop a capture in progress. */
1547   stop_bt = gtk_button_new_with_label ("Stop");
1548   gtk_signal_connect(GTK_OBJECT(stop_bt), "clicked",
1549     GTK_SIGNAL_FUNC(capture_stop_cb), (gpointer) &ld);
1550   gtk_signal_connect(GTK_OBJECT(cap_w), "delete_event",
1551         GTK_SIGNAL_FUNC(capture_delete_cb), (gpointer) &ld);
1552   gtk_box_pack_end(GTK_BOX(main_vb), stop_bt, FALSE, FALSE, 3);
1553   GTK_WIDGET_SET_FLAGS(stop_bt, GTK_CAN_DEFAULT);
1554   gtk_widget_grab_default(stop_bt);
1555   GTK_WIDGET_SET_FLAGS(stop_bt, GTK_CAN_DEFAULT);
1556   gtk_widget_grab_default(stop_bt);
1557   gtk_widget_show(stop_bt);
1558
1559   gtk_widget_show(cap_w);
1560
1561   upd_time = time(NULL);
1562 #ifdef MUST_DO_SELECT
1563   if (!ld.from_pipe) pcap_fd = pcap_fileno(pch);
1564 #endif
1565
1566 #ifndef _WIN32
1567   /*
1568    * Catch SIGUSR1, so that we exit cleanly if the parent process
1569    * kills us with it due to the user selecting "Capture->Stop".
1570    */
1571   signal(SIGUSR1, stop_capture);
1572 #endif
1573   /* initialize capture stop conditions */ 
1574   init_capture_stop_conditions();
1575   /* create stop conditions */
1576   cnd_stop_capturesize = 
1577     cnd_new(CND_CLASS_CAPTURESIZE,(long)cfile.autostop_filesize * 1000); 
1578   cnd_stop_timeout = 
1579     cnd_new(CND_CLASS_TIMEOUT,(gint32)cfile.autostop_duration);
1580
1581   while (ld.go) {
1582     while (gtk_events_pending()) gtk_main_iteration();
1583
1584 #ifndef _WIN32
1585     if (ld.from_pipe) {
1586       FD_ZERO(&set1);
1587       FD_SET(pipe_fd, &set1);
1588       timeout.tv_sec = 0;
1589       timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1590       if (select(pipe_fd+1, &set1, NULL, NULL, &timeout) != 0) {
1591         /*
1592          * "select()" says we can read from the pipe without blocking; go for
1593          * it. We are not sure we can read a whole record, but at least the
1594          * begninning of one. pipe_dispatch() will block reading the whole
1595          * record.
1596          */
1597         inpkts = pipe_dispatch(pipe_fd, &ld, &hdr);
1598       } else
1599         inpkts = 0;
1600     }
1601     else
1602 #endif
1603     {
1604 #ifdef MUST_DO_SELECT
1605       /*
1606        * Sigh.  The semantics of the read timeout argument to
1607        * "pcap_open_live()" aren't particularly well specified by
1608        * the "pcap" man page - at least with the BSD BPF code, the
1609        * intent appears to be, at least in part, a way of cutting
1610        * down the number of reads done on a capture, by blocking
1611        * until the buffer fills or a timer expires - and the Linux
1612        * libpcap doesn't actually support it, so we can't use it
1613        * to break out of the "pcap_dispatch()" every 1/4 of a second
1614        * or so.  Linux's libpcap is not the only libpcap that doesn't
1615        * support the read timeout.
1616        *
1617        * Furthermore, at least on Solaris, the bufmod STREAMS module's
1618        * read timeout won't go off if no data has arrived, i.e. it cannot
1619        * be used to guarantee that a read from a DLPI stream will return
1620        * within a specified amount of time regardless of whether any
1621        * data arrives or not.
1622        *
1623        * Thus, on all platforms other than BSD, we do a "select()" on the
1624        * file descriptor for the capture, with a timeout of CAP_READ_TIMEOUT
1625        * milliseconds, or CAP_READ_TIMEOUT*1000 microseconds.
1626        *
1627        * "select()", on BPF devices, doesn't work as you might expect;
1628        * at least on some versions of some flavors of BSD, the timer
1629        * doesn't start until a read is done, so it won't expire if
1630        * only a "select()" or "poll()" is posted.
1631        */
1632       FD_ZERO(&set1);
1633       FD_SET(pcap_fd, &set1);
1634       timeout.tv_sec = 0;
1635       timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1636       if (select(pcap_fd+1, &set1, NULL, NULL, &timeout) != 0) {
1637         /*
1638          * "select()" says we can read from it without blocking; go for
1639          * it.
1640          */
1641         inpkts = pcap_dispatch(pch, 1, capture_pcap_cb, (u_char *) &ld);
1642       } else
1643         inpkts = 0;
1644 #else
1645       inpkts = pcap_dispatch(pch, 1, capture_pcap_cb, (u_char *) &ld);
1646 #endif
1647     }
1648     if (inpkts > 0)
1649       ld.sync_packets += inpkts;
1650     /* check capture stop conditons */
1651     if (cnd_eval(cnd_stop_timeout) == TRUE) {
1652       /* The specified capture time has elapsed; stop the capture. */
1653       ld.go = FALSE;
1654     } else if ((cnd_eval(cnd_stop_capturesize, 
1655                   (guint32)wtap_get_bytes_dumped(ld.pdh))) == TRUE){
1656       /* Capture file reached its maximum size. */
1657       if (cfile.ringbuffer_on) {
1658         /* Switch to the next ringbuffer file */
1659         if (ringbuf_switch_file(&cfile, &ld.pdh, &ld.err)) {
1660           /* File switch succeeded: reset the condition */
1661           cnd_reset(cnd_stop_capturesize);
1662         } else {
1663           /* File switch failed: stop here */
1664           ld.go = FALSE;
1665           continue;
1666         }
1667       } else {
1668         /* no ringbuffer - just stop */
1669         ld.go = FALSE;
1670       }
1671     }
1672     /* Only update once a second so as not to overload slow displays */
1673     cur_time = time(NULL);
1674     if (cur_time > upd_time) {
1675       upd_time = cur_time;
1676
1677       for (i = 0; i < N_COUNTS; i++) {
1678           snprintf(label_str, sizeof(label_str), "%d",
1679                    *counts[i].value_ptr);
1680
1681           gtk_label_set(GTK_LABEL(counts[i].value), label_str);
1682
1683           snprintf(label_str, sizeof(label_str), "(%.1f%%)",
1684                    pct(*counts[i].value_ptr, ld.counts.total));
1685
1686           gtk_label_set(GTK_LABEL(counts[i].percent), label_str);
1687       }
1688
1689       /* do sync here, too */
1690       fflush(wtap_dump_file(ld.pdh));
1691       if (capture_child && ld.sync_packets) {
1692         /* This is the child process for a sync mode capture, so send
1693            our parent a message saying we've written out "ld.sync_packets"
1694            packets to the capture file. */
1695         char tmp[20];
1696         sprintf(tmp, "%d%c", ld.sync_packets, SP_PACKET_COUNT);
1697         write(1, tmp, strlen(tmp));
1698         ld.sync_packets = 0;
1699       }
1700     }
1701   }
1702     
1703   /* delete stop conditions */
1704   cnd_delete(cnd_stop_capturesize);
1705   cnd_delete(cnd_stop_timeout);
1706
1707   if (ld.err != 0) {
1708     get_capture_file_io_error(errmsg, sizeof(errmsg), cfile.save_file, ld.err,
1709                               FALSE);
1710     if (capture_child) {
1711       /* Tell the parent, so that they can pop up the message;
1712          we're going to exit, so if we try to pop it up, either
1713          it won't pop up or it'll disappear as soon as we exit. */
1714       send_errmsg_to_parent(errmsg);
1715     } else {
1716      /* Just pop up the message ourselves. */
1717      simple_dialog(ESD_TYPE_WARN, NULL, "%s", errmsg);
1718     }
1719
1720     /* A write failed, so we've already told the user there's a problem;
1721        if the close fails, there's no point in telling them about that
1722        as well. */
1723     if (cfile.ringbuffer_on) {
1724       ringbuf_wtap_dump_close(&cfile, &err);
1725     } else {
1726       wtap_dump_close(ld.pdh, &err);
1727     }
1728    } else {
1729     if (cfile.ringbuffer_on) {
1730       dump_ok = ringbuf_wtap_dump_close(&cfile, &err);
1731     } else {
1732       dump_ok = wtap_dump_close(ld.pdh, &err);
1733     }
1734     if (!dump_ok) {
1735       get_capture_file_io_error(errmsg, sizeof(errmsg), cfile.save_file, err,
1736                                 TRUE);
1737       if (capture_child) {
1738         /* Tell the parent, so that they can pop up the message;
1739            we're going to exit, so if we try to pop it up, either
1740            it won't pop up or it'll disappear as soon as we exit. */
1741         send_errmsg_to_parent(errmsg);
1742       } else {
1743        /* Just pop up the message ourselves. */
1744        simple_dialog(ESD_TYPE_WARN, NULL, "%s", errmsg);
1745       }
1746     }
1747   }
1748 #ifndef _WIN32
1749   if (ld.from_pipe)
1750     close(pipe_fd);
1751   else
1752 #endif
1753   {
1754     /* Get the capture statistics, so we know how many packets were
1755        dropped. */
1756     if (pcap_stats(pch, stats) >= 0) {
1757       *stats_known = TRUE;
1758       if (capture_child) {
1759         /* Let the parent process know. */
1760         char tmp[20];
1761         sprintf(tmp, "%d%c", stats->ps_drop, SP_DROPS);
1762         write(1, tmp, strlen(tmp));
1763       }
1764     } else {
1765       snprintf(errmsg, sizeof(errmsg),
1766                 "Can't get packet-drop statistics: %s",
1767                 pcap_geterr(pch));
1768       if (capture_child) {
1769         /* Tell the parent, so that they can pop up the message;
1770            we're going to exit, so if we try to pop it up, either
1771            it won't pop up or it'll disappear as soon as we exit. */
1772         send_errmsg_to_parent(errmsg);
1773       } else {
1774        /* Just pop up the message ourselves. */
1775        simple_dialog(ESD_TYPE_WARN, NULL, "%s", errmsg);
1776       }
1777     }
1778     pcap_close(pch);
1779   }
1780
1781 #ifdef WIN32
1782   /* Shut down windows sockets */
1783   WSACleanup();
1784 #endif
1785
1786   gtk_grab_remove(GTK_WIDGET(cap_w));
1787   gtk_widget_destroy(GTK_WIDGET(cap_w));
1788
1789   return TRUE;
1790
1791 error:
1792   if (cfile.ringbuffer_on) {
1793     /* cleanup ringbuffer */
1794     ringbuf_error_cleanup();
1795   } else {
1796     /* We can't use the save file, and we have no wtap_dump stream
1797        to close in order to close it, so close the FD directly. */
1798     close(cfile.save_file_fd);
1799
1800     /* We couldn't even start the capture, so get rid of the capture
1801        file. */
1802     unlink(cfile.save_file); /* silently ignore error */
1803     g_free(cfile.save_file);
1804   }
1805   cfile.save_file = NULL;
1806   if (capture_child) {
1807     /* This is the child process for a sync mode capture.
1808        Send the error message to our parent, so they can display a
1809        dialog box containing it. */
1810     send_errmsg_to_parent(errmsg);
1811   } else {
1812     /* Display the dialog box ourselves; there's no parent. */
1813     simple_dialog(ESD_TYPE_CRIT, NULL, "%s", errmsg);
1814   }
1815   if (pch != NULL && !ld.from_pipe)
1816     pcap_close(pch);
1817
1818   return FALSE;
1819 }
1820
1821 static void
1822 get_capture_file_io_error(char *errmsg, int errmsglen, const char *fname,
1823                           int err, gboolean is_close)
1824 {
1825   switch (err) {
1826
1827   case ENOSPC:
1828     snprintf(errmsg, errmsglen,
1829                 "Not all the packets could be written to the file"
1830                 " to which the capture was being saved\n"
1831                 "(\"%s\") because there is no space left on the file system\n"
1832                 "on which that file resides.",
1833                 fname);
1834     break;
1835
1836 #ifdef EDQUOT
1837   case EDQUOT:
1838     snprintf(errmsg, errmsglen,
1839                 "Not all the packets could be written to the file"
1840                 " to which the capture was being saved\n"
1841                 "(\"%s\") because you are too close to, or over,"
1842                 " your disk quota\n"
1843                 "on the file system on which that file resides.",
1844                 fname);
1845   break;
1846 #endif
1847
1848   case WTAP_ERR_CANT_CLOSE:
1849     snprintf(errmsg, errmsglen,
1850                 "The file to which the capture was being saved"
1851                 " couldn't be closed for some unknown reason.");
1852     break;
1853
1854   case WTAP_ERR_SHORT_WRITE:
1855     snprintf(errmsg, errmsglen,
1856                 "Not all the packets could be written to the file"
1857                 " to which the capture was being saved\n"
1858                 "(\"%s\").",
1859                 fname);
1860     break;
1861
1862   default:
1863     if (is_close) {
1864       snprintf(errmsg, errmsglen,
1865                 "The file to which the capture was being saved\n"
1866                 "(\"%s\") could not be closed: %s.",
1867                 fname, wtap_strerror(err));
1868     } else {
1869       snprintf(errmsg, errmsglen,
1870                 "An error occurred while writing to the file"
1871                 " to which the capture was being saved\n"
1872                 "(\"%s\"): %s.",
1873                 fname, wtap_strerror(err));
1874     }
1875     break;
1876   }
1877 }
1878
1879 static void
1880 send_errmsg_to_parent(const char *errmsg)
1881 {
1882     int msglen = strlen(errmsg);
1883     char lenbuf[10+1+1];
1884
1885     sprintf(lenbuf, "%u%c", msglen, SP_ERROR_MSG);
1886     write(1, lenbuf, strlen(lenbuf));
1887     write(1, errmsg, msglen);
1888 }
1889
1890 static float
1891 pct(gint num, gint denom) {
1892   if (denom) {
1893     return (float) num * 100.0 / (float) denom;
1894   } else {
1895     return 0.0;
1896   }
1897 }
1898
1899 static void
1900 stop_capture(int signo)
1901 {
1902   ld.go = FALSE;
1903 }
1904
1905 static void
1906 capture_delete_cb(GtkWidget *w, GdkEvent *event, gpointer data) {
1907   capture_stop_cb(NULL, data);
1908 }
1909
1910 static void
1911 capture_stop_cb(GtkWidget *w, gpointer data) {
1912   loop_data *ld = (loop_data *) data;
1913   
1914   ld->go = FALSE;
1915 }
1916
1917 void
1918 capture_stop(void)
1919 {
1920   /*
1921    * XXX - find some way of signaling the child in Win32.
1922    */
1923 #ifndef _WIN32
1924   if (fork_child != -1)
1925       kill(fork_child, SIGUSR1);
1926 #endif
1927 }
1928
1929 static void
1930 capture_pcap_cb(u_char *user, const struct pcap_pkthdr *phdr,
1931   const u_char *pd) {
1932   struct wtap_pkthdr whdr;
1933   loop_data *ld = (loop_data *) user;
1934   int err;
1935
1936   if ((++ld->counts.total >= ld->max) && (ld->max > 0)) 
1937   {
1938      ld->go = FALSE;
1939   }
1940   if (ld->pdh) {
1941      /* "phdr->ts" may not necessarily be a "struct timeval" - it may
1942         be a "struct bpf_timeval", with member sizes wired to 32
1943         bits - and we may go that way ourselves in the future, so
1944         copy the members individually. */
1945      whdr.ts.tv_sec = phdr->ts.tv_sec;
1946      whdr.ts.tv_usec = phdr->ts.tv_usec;
1947      whdr.caplen = phdr->caplen;
1948      whdr.len = phdr->len;
1949      whdr.pkt_encap = ld->linktype;
1950
1951      /* If this fails, set "ld->go" to FALSE, to stop the capture, and set
1952         "ld->err" to the error. */
1953      if (!wtap_dump(ld->pdh, &whdr, NULL, pd, &err)) {
1954        ld->go = FALSE;
1955        ld->err = err;
1956      }
1957   }
1958
1959   switch (ld->linktype) {
1960     case WTAP_ENCAP_ETHERNET:
1961       capture_eth(pd, 0, phdr->len, &ld->counts);
1962       break;
1963     case WTAP_ENCAP_FDDI:
1964     case WTAP_ENCAP_FDDI_BITSWAPPED:
1965       capture_fddi(pd, phdr->len, &ld->counts);
1966       break;
1967     case WTAP_ENCAP_PRISM_HEADER:
1968       capture_prism(pd, 0, phdr->len, &ld->counts);
1969       break;
1970     case WTAP_ENCAP_TOKEN_RING:
1971       capture_tr(pd, 0, phdr->len, &ld->counts);
1972       break;
1973     case WTAP_ENCAP_NULL:
1974       capture_null(pd, phdr->len, &ld->counts);
1975       break;
1976     case WTAP_ENCAP_PPP:
1977       capture_ppp_hdlc(pd, 0, phdr->len, &ld->counts);
1978       break;
1979     case WTAP_ENCAP_RAW_IP:
1980       capture_raw(pd, phdr->len, &ld->counts);
1981       break;
1982     case WTAP_ENCAP_SLL:
1983       capture_sll(pd, phdr->len, &ld->counts);
1984       break;
1985     case WTAP_ENCAP_LINUX_ATM_CLIP:
1986       capture_clip(pd, phdr->len, &ld->counts);
1987       break;
1988     case WTAP_ENCAP_LOCALTALK:
1989       capture_llap(pd, phdr->len, &ld->counts);
1990       break;
1991     /* XXX - FreeBSD may append 4-byte ATM pseudo-header to DLT_ATM_RFC1483,
1992        with LLC header following; we should implement it at some
1993        point. */
1994   }
1995 }
1996
1997 #endif /* HAVE_LIBPCAP */