fdad9599b48167387fc208458598ac2e9066456a
[obnox/wireshark/wip.git] / capture_loop.c
1 /* capture_loop.c
2  * The actual capturing loop, getting packets and storing it
3  *
4  * $Id$
5  *
6  * Ethereal - Network traffic analyzer
7  * By Gerald Combs <gerald@ethereal.com>
8  * Copyright 1998 Gerald Combs
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
23  */
24
25
26 /** @file
27  *  
28  * Capture loop (internal interface).
29  *
30  * It will open the input and output files, capture the packets, 
31  * change ringbuffer output files while capturing and close all files again.
32  * 
33  * The input file can be a network interface or capture pipe (unix only).
34  * The output file can be a single or a ringbuffer file handled by wiretap.
35  *
36  */
37
38 #ifdef HAVE_CONFIG_H
39 # include "config.h"
40 #endif
41
42 #ifdef HAVE_LIBPCAP
43
44 #include <string.h>
45
46 #ifdef HAVE_FCNTL_H
47 #include <fcntl.h>
48 #endif
49
50 #ifdef HAVE_UNISTD_H
51 #include <unistd.h>
52 #endif
53
54 #ifdef HAVE_SYS_TYPES_H
55 # include <sys/types.h>
56 #endif
57
58 #ifdef HAVE_SYS_STAT_H
59 # include <sys/stat.h>
60 #endif
61
62 #include <signal.h>
63 #include <errno.h>
64
65 #include <pcap.h>
66
67 #include <glib.h>
68
69 #include <epan/packet.h>
70 #include "capture.h"
71 #include "capture_sync.h"
72 #include "pcap-util.h"
73
74 #include "simple_dialog.h"
75 #include "globals.h"
76 #include "conditions.h"
77 #include "capture_stop_conditions.h"
78 #include "ringbuffer.h"
79
80 #include "wiretap/libpcap.h"
81 #include "wiretap/wtap.h"
82 #include "wiretap/wtap-capture.h"
83
84 #include <epan/prefs.h>
85 /* XXX - try to remove this later */
86 #include "ui_util.h"
87 /* XXX - try to remove this later */
88
89
90 #include <epan/dissectors/packet-ap1394.h>
91 #include <epan/dissectors/packet-atalk.h>
92 #include <epan/dissectors/packet-atm.h>
93 #include <epan/dissectors/packet-clip.h>
94 #include <epan/dissectors/packet-eth.h>
95 #include <epan/dissectors/packet-fddi.h>
96 #include <epan/dissectors/packet-null.h>
97 #include <epan/dissectors/packet-ppp.h>
98 #include <epan/dissectors/packet-raw.h>
99 #include <epan/dissectors/packet-sll.h>
100 #include <epan/dissectors/packet-tr.h>
101 #include <epan/dissectors/packet-ieee80211.h>
102 #include <epan/dissectors/packet-chdlc.h>
103 #include <epan/dissectors/packet-prism.h>
104 #include <epan/dissectors/packet-ipfc.h>
105 #include <epan/dissectors/packet-arcnet.h>
106
107
108
109
110 /*
111  * We don't want to do a "select()" on the pcap_t's file descriptor on
112  * BSD (because "select()" doesn't work correctly on BPF devices on at
113  * least some releases of some flavors of BSD), and we don't want to do
114  * it on Windows (because "select()" is something for sockets, not for
115  * arbitrary handles).  (Note that "Windows" here includes Cygwin;
116  * even in its pretend-it's-UNIX environment, we're using WinPcap, not
117  * a UNIX libpcap.)
118  *
119  * We *do* want to do it on other platforms, as, on other platforms (with
120  * the possible exception of Ultrix and Digital UNIX), the read timeout
121  * doesn't expire if no packets have arrived, so a "pcap_dispatch()" call
122  * will block until packets arrive, causing the UI to hang.
123  *
124  * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
125  * want to include it if it's not present on this platform, however.
126  */
127 #if !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && \
128     !defined(__bsdi__) && !defined(__APPLE__) && !defined(_WIN32) && \
129     !defined(__CYGWIN__)
130 # define MUST_DO_SELECT
131 #endif
132
133
134 typedef struct _loop_data {
135   /* common */
136   gboolean       go;                    /* TRUE as long as we're supposed to keep capturing */
137   int            err;                   /* if non-zero, error seen while capturing */
138   gint           packets_max;           /* Number of packets we're supposed to capture - 0 means infinite */
139   gint           packets_sync_pipe;     /* packets not already send out to the sync_pipe */
140   packet_counts  counts;                /* several packet type counters */
141
142   /* pcap "input file" */
143   pcap_t        *pcap_h;                /* pcap handle */
144   gboolean       pcap_err;              /* TRUE if error from pcap */
145 #ifdef MUST_DO_SELECT
146   int            pcap_fd;               /* pcap file descriptor */
147 #endif
148
149   /* capture pipe (unix only "input file") */
150   gboolean       from_cap_pipe;         /* TRUE if we are capturing data from a capture pipe */
151 #ifndef _WIN32
152   struct pcap_hdr cap_pipe_hdr;
153   int            cap_pipe_fd;           /* the file descriptor of the capture pipe */
154   gboolean       cap_pipe_modified;     /* TRUE if data in the pipe uses modified pcap headers */
155   gboolean       cap_pipe_byte_swapped; /* TRUE if data in the pipe is byte swapped */
156   unsigned int   cap_pipe_bytes_to_read;/* Used by cap_pipe_dispatch */
157   unsigned int   cap_pipe_bytes_read;   /* Used by cap_pipe_dispatch */
158   enum {
159          STATE_EXPECT_REC_HDR,
160          STATE_READ_REC_HDR,
161          STATE_EXPECT_DATA,
162          STATE_READ_DATA
163        } cap_pipe_state;
164
165   enum { PIPOK, PIPEOF, PIPERR, PIPNEXIST } cap_pipe_err;
166 #endif
167
168   /* wiretap (output file) */
169   wtap_dumper   *wtap_pdh;
170   gint           wtap_linktype;
171
172 } loop_data;
173
174
175 /*
176  * Timeout, in milliseconds, for reads from the stream of captured packets.
177  */
178 #define CAP_READ_TIMEOUT        250
179
180 static void capture_loop_packet_cb(guchar *user, const struct pcap_pkthdr *phdr,
181   const guchar *pd);
182 static void capture_loop_popup_errmsg(capture_options *capture_opts, const char *errmsg);
183 static void capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
184                           int err, gboolean is_close);
185
186
187
188 #ifndef _WIN32
189 /* Take care of byte order in the libpcap headers read from pipes.
190  * (function taken from wiretap/libpcap.c) */
191 static void
192 cap_pipe_adjust_header(loop_data *ld, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
193 {
194   if (ld->cap_pipe_byte_swapped) {
195     /* Byte-swap the record header fields. */
196     rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
197     rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
198     rechdr->incl_len = BSWAP32(rechdr->incl_len);
199     rechdr->orig_len = BSWAP32(rechdr->orig_len);
200   }
201
202   /* In file format version 2.3, the "incl_len" and "orig_len" fields were
203      swapped, in order to match the BPF header layout.
204
205      Unfortunately, some files were, according to a comment in the "libpcap"
206      source, written with version 2.3 in their headers but without the
207      interchanged fields, so if "incl_len" is greater than "orig_len" - which
208      would make no sense - we assume that we need to swap them.  */
209   if (hdr->version_major == 2 &&
210       (hdr->version_minor < 3 ||
211        (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
212     guint32 temp;
213
214     temp = rechdr->orig_len;
215     rechdr->orig_len = rechdr->incl_len;
216     rechdr->incl_len = temp;
217   }
218 }
219
220 /* Mimic pcap_open_live() for pipe captures
221  * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
222  * header.
223  * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
224  * because we can't seek on pipes (see wiretap/libpcap.c for details) */
225 static int
226 cap_pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld,
227                  char *errmsg, int errmsgl)
228 {
229   struct stat pipe_stat;
230   int         fd;
231   guint32     magic;
232   int         b, sel_ret;
233   unsigned int bytes_read;
234   fd_set      rfds;
235   struct timeval timeout;
236
237   /*
238    * XXX Ethereal blocks until we return
239    */
240   if (strcmp(pipename, "-") == 0)
241     fd = 0; /* read from stdin */
242   else {
243     if (stat(pipename, &pipe_stat) < 0) {
244       if (errno == ENOENT || errno == ENOTDIR)
245         ld->cap_pipe_err = PIPNEXIST;
246       else {
247         g_snprintf(errmsg, errmsgl,
248           "The capture session could not be initiated "
249           "due to error on pipe: %s", strerror(errno));
250         ld->cap_pipe_err = PIPERR;
251       }
252       return -1;
253     }
254     if (! S_ISFIFO(pipe_stat.st_mode)) {
255       if (S_ISCHR(pipe_stat.st_mode)) {
256         /*
257          * Assume the user specified an interface on a system where
258          * interfaces are in /dev.  Pretend we haven't seen it.
259          */
260          ld->cap_pipe_err = PIPNEXIST;
261       } else {
262         g_snprintf(errmsg, errmsgl,
263             "The capture session could not be initiated because\n"
264             "\"%s\" is neither an interface nor a pipe", pipename);
265         ld->cap_pipe_err = PIPERR;
266       }
267       return -1;
268     }
269     fd = open(pipename, O_RDONLY | O_NONBLOCK);
270     if (fd == -1) {
271       g_snprintf(errmsg, errmsgl,
272           "The capture session could not be initiated "
273           "due to error on pipe open: %s", strerror(errno));
274       ld->cap_pipe_err = PIPERR;
275       return -1;
276     }
277   }
278
279   ld->from_cap_pipe = TRUE;
280
281   /* read the pcap header */
282   FD_ZERO(&rfds);
283   bytes_read = 0;
284   while (bytes_read < sizeof magic) {
285     FD_SET(fd, &rfds);
286     timeout.tv_sec = 0;
287     timeout.tv_usec = CAP_READ_TIMEOUT*1000;
288     sel_ret = select(fd+1, &rfds, NULL, NULL, &timeout);
289     if (sel_ret < 0) {
290       g_snprintf(errmsg, errmsgl,
291         "Unexpected error from select: %s", strerror(errno));
292       goto error;
293     } else if (sel_ret > 0) {
294       b = read(fd, ((char *)&magic)+bytes_read, sizeof magic-bytes_read);
295       if (b <= 0) {
296         if (b == 0)
297           g_snprintf(errmsg, errmsgl, "End of file on pipe during open");
298         else
299           g_snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
300             strerror(errno));
301         goto error;
302       }
303       bytes_read += b;
304     }
305   }
306
307   switch (magic) {
308   case PCAP_MAGIC:
309     /* Host that wrote it has our byte order, and was running
310        a program using either standard or ss990417 libpcap. */
311     ld->cap_pipe_byte_swapped = FALSE;
312     ld->cap_pipe_modified = FALSE;
313     break;
314   case PCAP_MODIFIED_MAGIC:
315     /* Host that wrote it has our byte order, but was running
316        a program using either ss990915 or ss991029 libpcap. */
317     ld->cap_pipe_byte_swapped = FALSE;
318     ld->cap_pipe_modified = TRUE;
319     break;
320   case PCAP_SWAPPED_MAGIC:
321     /* Host that wrote it has a byte order opposite to ours,
322        and was running a program using either standard or
323        ss990417 libpcap. */
324     ld->cap_pipe_byte_swapped = TRUE;
325     ld->cap_pipe_modified = FALSE;
326     break;
327   case PCAP_SWAPPED_MODIFIED_MAGIC:
328     /* Host that wrote it out has a byte order opposite to
329        ours, and was running a program using either ss990915
330        or ss991029 libpcap. */
331     ld->cap_pipe_byte_swapped = TRUE;
332     ld->cap_pipe_modified = TRUE;
333     break;
334   default:
335     /* Not a "libpcap" type we know about. */
336     g_snprintf(errmsg, errmsgl, "Unrecognized libpcap format");
337     goto error;
338   }
339
340   /* Read the rest of the header */
341   bytes_read = 0;
342   while (bytes_read < sizeof(struct pcap_hdr)) {
343     FD_SET(fd, &rfds);
344     timeout.tv_sec = 0;
345     timeout.tv_usec = CAP_READ_TIMEOUT*1000;
346     sel_ret = select(fd+1, &rfds, NULL, NULL, &timeout);
347     if (sel_ret < 0) {
348       g_snprintf(errmsg, errmsgl,
349         "Unexpected error from select: %s", strerror(errno));
350       goto error;
351     } else if (sel_ret > 0) {
352       b = read(fd, ((char *)hdr)+bytes_read,
353             sizeof(struct pcap_hdr) - bytes_read);
354       if (b <= 0) {
355         if (b == 0)
356           g_snprintf(errmsg, errmsgl, "End of file on pipe during open");
357         else
358           g_snprintf(errmsg, errmsgl, "Error on pipe during open: %s",
359             strerror(errno));
360         goto error;
361       }
362       bytes_read += b;
363     }
364   }
365
366   if (ld->cap_pipe_byte_swapped) {
367     /* Byte-swap the header fields about which we care. */
368     hdr->version_major = BSWAP16(hdr->version_major);
369     hdr->version_minor = BSWAP16(hdr->version_minor);
370     hdr->snaplen = BSWAP32(hdr->snaplen);
371     hdr->network = BSWAP32(hdr->network);
372   }
373
374   if (hdr->version_major < 2) {
375     g_snprintf(errmsg, errmsgl, "Unable to read old libpcap format");
376     goto error;
377   }
378
379   ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
380   ld->cap_pipe_err = PIPOK;
381   return fd;
382
383 error:
384   ld->cap_pipe_err = PIPERR;
385   close(fd);
386   return -1;
387
388 }
389
390
391 /* We read one record from the pipe, take care of byte order in the record
392  * header, write the record to the capture file, and update capture statistics. */
393 static int
394 cap_pipe_dispatch(int fd, loop_data *ld, struct pcap_hdr *hdr,
395                 struct pcaprec_modified_hdr *rechdr, guchar *data,
396                 char *errmsg, int errmsgl)
397 {
398   struct pcap_pkthdr phdr;
399   int b;
400   enum { PD_REC_HDR_READ, PD_DATA_READ, PD_PIPE_EOF, PD_PIPE_ERR,
401           PD_ERR } result;
402
403   switch (ld->cap_pipe_state) {
404
405   case STATE_EXPECT_REC_HDR:
406     ld->cap_pipe_bytes_to_read = ld->cap_pipe_modified ?
407       sizeof(struct pcaprec_modified_hdr) : sizeof(struct pcaprec_hdr);
408     ld->cap_pipe_bytes_read = 0;
409     ld->cap_pipe_state = STATE_READ_REC_HDR;
410     /* Fall through */
411
412   case STATE_READ_REC_HDR:
413     b = read(fd, ((char *)rechdr)+ld->cap_pipe_bytes_read,
414       ld->cap_pipe_bytes_to_read - ld->cap_pipe_bytes_read);
415     if (b <= 0) {
416       if (b == 0)
417         result = PD_PIPE_EOF;
418       else
419         result = PD_PIPE_ERR;
420       break;
421     }
422     if ((ld->cap_pipe_bytes_read += b) < ld->cap_pipe_bytes_to_read)
423         return 0;
424     result = PD_REC_HDR_READ;
425     break;
426
427   case STATE_EXPECT_DATA:
428     ld->cap_pipe_bytes_read = 0;
429     ld->cap_pipe_state = STATE_READ_DATA;
430     /* Fall through */
431
432   case STATE_READ_DATA:
433     b = read(fd, data+ld->cap_pipe_bytes_read, rechdr->hdr.incl_len - ld->cap_pipe_bytes_read);
434     if (b <= 0) {
435       if (b == 0)
436         result = PD_PIPE_EOF;
437       else
438         result = PD_PIPE_ERR;
439       break;
440     }
441     if ((ld->cap_pipe_bytes_read += b) < rechdr->hdr.incl_len)
442       return 0;
443     result = PD_DATA_READ;
444     break;
445
446   default:
447     g_snprintf(errmsg, errmsgl, "cap_pipe_dispatch: invalid state");
448     result = PD_ERR;
449
450   } /* switch (ld->cap_pipe_state) */
451
452   /*
453    * We've now read as much data as we were expecting, so process it.
454    */
455   switch (result) {
456
457   case PD_REC_HDR_READ:
458     /* We've read the header. Take care of byte order. */
459     cap_pipe_adjust_header(ld, hdr, &rechdr->hdr);
460     if (rechdr->hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
461       g_snprintf(errmsg, errmsgl, "Frame %u too long (%d bytes)",
462         ld->counts.total+1, rechdr->hdr.incl_len);
463       break;
464     }
465     ld->cap_pipe_state = STATE_EXPECT_DATA;
466     return 0;
467
468   case PD_DATA_READ:
469     /* Fill in a "struct pcap_pkthdr", and process the packet. */
470     phdr.ts.tv_sec = rechdr->hdr.ts_sec;
471     phdr.ts.tv_usec = rechdr->hdr.ts_usec;
472     phdr.caplen = rechdr->hdr.incl_len;
473     phdr.len = rechdr->hdr.orig_len;
474
475     capture_loop_packet_cb((guchar *)ld, &phdr, data);
476
477     ld->cap_pipe_state = STATE_EXPECT_REC_HDR;
478     return 1;
479
480   case PD_PIPE_EOF:
481     ld->cap_pipe_err = PIPEOF;
482     return -1;
483
484   case PD_PIPE_ERR:
485     g_snprintf(errmsg, errmsgl, "Error reading from pipe: %s",
486       strerror(errno));
487     /* Fall through */
488   case PD_ERR:
489     break;
490   }
491
492   ld->cap_pipe_err = PIPERR;
493   /* Return here rather than inside the switch to prevent GCC warning */
494   return -1;
495 }
496 #endif /* not _WIN32 */
497
498
499 /* open the capture input file (pcap or capture pipe) */
500 static int capture_loop_open_input(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len) {
501   gchar       open_err_str[PCAP_ERRBUF_SIZE];
502   const char *set_linktype_err_str;
503 #ifdef _WIN32
504   int         err;
505   WORD        wVersionRequested;
506   WSADATA     wsaData;
507 #else
508   static const char ppamsg[] = "can't find PPA for ";
509   char       *libpcap_warn;
510 #endif
511
512   /* Initialize Windows Socket if we are in a WIN32 OS
513      This needs to be done before querying the interface for network/netmask */
514 #ifdef _WIN32
515   /* XXX - do we really require 1.1 or earlier?
516      Are there any versions that support only 2.0 or higher? */
517   wVersionRequested = MAKEWORD(1, 1);
518   err = WSAStartup(wVersionRequested, &wsaData);
519   if (err != 0) {
520     switch (err) {
521
522     case WSASYSNOTREADY:
523       g_snprintf(errmsg, errmsg_len,
524         "Couldn't initialize Windows Sockets: Network system not ready for network communication");
525       break;
526
527     case WSAVERNOTSUPPORTED:
528       g_snprintf(errmsg, errmsg_len,
529         "Couldn't initialize Windows Sockets: Windows Sockets version %u.%u not supported",
530         LOBYTE(wVersionRequested), HIBYTE(wVersionRequested));
531       break;
532
533     case WSAEINPROGRESS:
534       g_snprintf(errmsg, errmsg_len,
535         "Couldn't initialize Windows Sockets: Blocking operation is in progress");
536       break;
537
538     case WSAEPROCLIM:
539       g_snprintf(errmsg, errmsg_len,
540         "Couldn't initialize Windows Sockets: Limit on the number of tasks supported by this WinSock implementation has been reached");
541       break;
542
543     case WSAEFAULT:
544       g_snprintf(errmsg, errmsg_len,
545         "Couldn't initialize Windows Sockets: Bad pointer passed to WSAStartup");
546       break;
547
548     default:
549       g_snprintf(errmsg, errmsg_len,
550         "Couldn't initialize Windows Sockets: error %d", err);
551       break;
552     }
553     return FALSE;
554   }
555 #endif
556
557   /* Open the network interface to capture from it.
558      Some versions of libpcap may put warnings into the error buffer
559      if they succeed; to tell if that's happened, we have to clear
560      the error buffer, and check if it's still a null string.  */
561   open_err_str[0] = '\0';
562   ld->pcap_h = pcap_open_live(cfile.iface,
563                        capture_opts->has_snaplen ? capture_opts->snaplen :
564                                                   WTAP_MAX_PACKET_SIZE,
565                        capture_opts->promisc_mode, CAP_READ_TIMEOUT,
566                        open_err_str);
567
568   if (ld->pcap_h != NULL) {
569     /* we've opened "cfile.iface" as a network device */
570 #ifdef _WIN32
571     /* try to set the capture buffer size */
572     if (pcap_setbuff(ld->pcap_h, capture_opts->buffer_size * 1024 * 1024) != 0) {
573         simple_dialog(ESD_TYPE_INFO, ESD_BTN_OK,
574           "%sCouldn't set the capture buffer size!%s\n"
575           "\n"
576           "The capture buffer size of %luMB seems to be too high for your machine,\n"
577           "the default of 1MB will be used.\n"
578           "\n"
579           "Nonetheless, the capture is started.\n",
580           simple_dialog_primary_start(), simple_dialog_primary_end(), capture_opts->buffer_size);
581     }
582 #endif
583
584     /* setting the data link type only works on real interfaces */
585     if (capture_opts->linktype != -1) {
586       set_linktype_err_str = set_pcap_linktype(ld->pcap_h, cfile.iface,
587         capture_opts->linktype);
588       if (set_linktype_err_str != NULL) {
589         g_snprintf(errmsg, errmsg_len, "Unable to set data link type (%s).",
590           set_linktype_err_str);
591         return FALSE;
592       }
593     }
594   } else {
595     /* We couldn't open "cfile.iface" as a network device. */
596 #ifdef _WIN32
597     /* On Windows, we don't support capturing on pipes, so we give up.
598        If this is a child process that does the capturing in sync
599        mode or fork mode, it shouldn't do any UI stuff until we pop up the
600        capture-progress window, and, since we couldn't start the
601        capture, we haven't popped it up. */
602     if (!capture_opts->capture_child) {
603       main_window_update();
604     }
605
606     /* On Win32 OSes, the capture devices are probably available to all
607        users; don't warn about permissions problems.
608
609        Do, however, warn that WAN devices aren't supported. */
610     g_snprintf(errmsg, errmsg_len,
611         "The capture session could not be initiated (%s).\n"
612         "Please check that you have the proper interface specified.\n"
613         "\n"
614         "Note that the WinPcap 2.x version of the driver Ethereal uses for packet\n"
615         "capture on Windows doesn't support capturing on PPP/WAN interfaces in\n"
616         "Windows NT/2000/XP/2003 Server, and that the WinPcap 3.0 and later versions\n"
617         "don't support capturing on PPP/WAN interfaces at all.",
618         open_err_str);
619     return FALSE;
620 #else
621     /* try to open cfile.iface as a pipe */
622     ld->cap_pipe_fd = cap_pipe_open_live(cfile.iface, &ld->cap_pipe_hdr, ld, errmsg, errmsg_len);
623
624     if (ld->cap_pipe_fd == -1) {
625
626       /* If this is a child process that does the capturing in sync
627        * mode or fork mode, it shouldn't do any UI stuff until we pop up the
628        * capture-progress window, and, since we couldn't start the
629        * capture, we haven't popped it up.
630        */
631       if (!capture_opts->capture_child) {
632           main_window_update();
633       }
634
635       if (ld->cap_pipe_err == PIPNEXIST) {
636         /* Pipe doesn't exist, so output message for interface */
637
638         /* If we got a "can't find PPA for XXX" message, warn the user (who
639            is running Ethereal on HP-UX) that they don't have a version
640            of libpcap that properly handles HP-UX (libpcap 0.6.x and later
641            versions, which properly handle HP-UX, say "can't find /dev/dlpi
642            PPA for XXX" rather than "can't find PPA for XXX"). */
643         if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
644           libpcap_warn =
645             "\n\n"
646             "You are running Ethereal with a version of the libpcap library\n"
647             "that doesn't handle HP-UX network devices well; this means that\n"
648             "Ethereal may not be able to capture packets.\n"
649             "\n"
650             "To fix this, you should install libpcap 0.6.2, or a later version\n"
651             "of libpcap, rather than libpcap 0.4 or 0.5.x.  It is available in\n"
652             "packaged binary form from the Software Porting And Archive Centre\n"
653             "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
654             "at the URL lists a number of mirror sites.";
655         else
656           libpcap_warn = "";
657         g_snprintf(errmsg, errmsg_len,
658           "The capture session could not be initiated (%s).\n"
659           "Please check to make sure you have sufficient permissions, and that\n"
660           "you have the proper interface or pipe specified.%s", open_err_str,
661           libpcap_warn);
662       }
663       /*
664        * Else pipe (or file) does exist and cap_pipe_open_live() has
665        * filled in errmsg
666        */
667       return FALSE;
668     } else
669       /* cap_pipe_open_live() succeeded; don't want
670          error message from pcap_open_live() */
671       open_err_str[0] = '\0';
672 #endif
673   }
674
675 #ifdef MUST_DO_SELECT
676   if (!ld->from_cap_pipe) ld->pcap_fd = pcap_fileno(ld->pcap_h);
677 #endif
678
679   /* Does "open_err_str" contain a non-empty string?  If so, "pcap_open_live()"
680      returned a warning; print it, but keep capturing. */
681   if (open_err_str[0] != '\0')
682     g_warning("%s.", open_err_str);
683
684   return TRUE;
685 }
686
687
688 /* open the capture input file (pcap or capture pipe) */
689 static void capture_loop_close_input(loop_data *ld) {
690 #ifndef _WIN32
691   /* if open, close the capture pipe "input file" */
692   if (ld->cap_pipe_fd >= 0) {
693     g_assert(ld->from_cap_pipe);
694     close(ld->cap_pipe_fd);
695   }
696 #endif
697
698   /* if open, close the pcap "input file" */
699   if(ld->pcap_h != NULL) {
700     g_assert(!ld->from_cap_pipe);
701     pcap_close(ld->pcap_h);
702   }
703
704 #ifdef _WIN32
705   /* Shut down windows sockets */
706   WSACleanup();
707 #endif
708 }
709
710
711 /* init the capture filter */
712 static int capture_loop_init_filter(loop_data *ld, char *errmsg, int errmsg_len) {
713   bpf_u_int32 netnum, netmask;
714   gchar       lookup_net_err_str[PCAP_ERRBUF_SIZE];
715   struct bpf_program fcode;
716
717   /* capture filters only work on real interfaces */
718   if (cfile.cfilter && !ld->from_cap_pipe) {
719     /* A capture filter was specified; set it up. */
720     if (pcap_lookupnet(cfile.iface, &netnum, &netmask, lookup_net_err_str) < 0) {
721       /*
722        * Well, we can't get the netmask for this interface; it's used
723        * only for filters that check for broadcast IP addresses, so
724        * we just punt and use 0.  It might be nice to warn the user,
725        * but that's a pain in a GUI application, as it'd involve popping
726        * up a message box, and it's not clear how often this would make
727        * a difference (only filters that check for IP broadcast addresses
728        * use the netmask).
729        */
730       netmask = 0;
731     }
732     if (pcap_compile(ld->pcap_h, &fcode, cfile.cfilter, 1, netmask) < 0) {
733       dfilter_t   *rfcode = NULL;
734       /* filter string invalid, did the user tried a display filter? */
735       if (dfilter_compile(cfile.cfilter, &rfcode) && rfcode != NULL) {
736         g_snprintf(errmsg, errmsg_len,
737           "%sInvalid capture filter: \"%s\"!%s\n"
738           "\n"
739           "That string looks like a valid display filter; however, it isn't a valid\n"
740           "capture filter (%s).\n"
741           "\n"
742           "Note that display filters and capture filters don't have the same syntax,\n"
743           "so you can't use most display filter expressions as capture filters.\n"
744           "\n"
745           "See the help for a description of the capture filter syntax.",
746           simple_dialog_primary_start(), cfile.cfilter, simple_dialog_primary_end(),
747           pcap_geterr(ld->pcap_h));
748         dfilter_free(rfcode);
749       } else {
750         g_snprintf(errmsg, errmsg_len,
751           "%sInvalid capture filter: \"%s\"!%s\n"
752           "\n"
753           "That string isn't a valid capture filter (%s).\n"
754           "See the help for a description of the capture filter syntax.",
755           simple_dialog_primary_start(), cfile.cfilter, simple_dialog_primary_end(),
756           pcap_geterr(ld->pcap_h));
757       }
758       return FALSE;
759     }
760     if (pcap_setfilter(ld->pcap_h, &fcode) < 0) {
761       g_snprintf(errmsg, errmsg_len, "Can't install filter (%s).",
762         pcap_geterr(ld->pcap_h));
763       return FALSE;
764     }
765   }
766
767   return TRUE;
768 }
769
770
771 /* open the wiretap part of the capture output file */
772 static int capture_loop_open_wiretap_output(capture_options *capture_opts, loop_data *ld, char *errmsg, int errmsg_len) {
773   int         pcap_encap;
774   int         file_snaplen;
775   int         err;
776
777
778   /* get packet encapsulation type and snaplen */
779 #ifndef _WIN32
780   if (ld->from_cap_pipe) {
781     pcap_encap = ld->cap_pipe_hdr.network;
782     file_snaplen = ld->cap_pipe_hdr.snaplen;
783   } else
784 #endif
785   {
786     pcap_encap = get_pcap_linktype(ld->pcap_h, cfile.iface);
787     file_snaplen = pcap_snapshot(ld->pcap_h);
788   }
789
790   /* Set up to write to the capture file. */
791   ld->wtap_linktype = wtap_pcap_encap_to_wtap_encap(pcap_encap);
792   if (ld->wtap_linktype == WTAP_ENCAP_UNKNOWN) {
793     g_snprintf(errmsg, errmsg_len,
794         "The network you're capturing from is of a type"
795         " that Ethereal doesn't support (data link type %d).", pcap_encap);
796     return FALSE;
797   }
798   if (capture_opts->multi_files_on) {
799     ld->wtap_pdh = ringbuf_init_wtap_dump_fdopen(WTAP_FILE_PCAP, ld->wtap_linktype,
800       file_snaplen, &err);
801   } else {
802     ld->wtap_pdh = wtap_dump_fdopen(cfile.save_file_fd, WTAP_FILE_PCAP,
803       ld->wtap_linktype, file_snaplen, &err);
804   }
805
806   if (ld->wtap_pdh == NULL) {
807     /* We couldn't set up to write to the capture file. */
808     switch (err) {
809
810     case WTAP_ERR_CANT_OPEN:
811       strcpy(errmsg, "The file to which the capture would be saved"
812                " couldn't be created for some unknown reason.");
813       break;
814
815     case WTAP_ERR_SHORT_WRITE:
816       strcpy(errmsg, "A full header couldn't be written to the file"
817                " to which the capture would be saved.");
818       break;
819
820     default:
821       if (err < 0) {
822         g_snprintf(errmsg, errmsg_len,
823                      "The file to which the capture would be"
824                      " saved (\"%s\") could not be opened: Error %d.",
825                         cfile.save_file, err);
826       } else {
827         g_snprintf(errmsg, errmsg_len,
828                      "The file to which the capture would be"
829                      " saved (\"%s\") could not be opened: %s.",
830                         cfile.save_file, strerror(err));
831       }
832       break;
833     }
834
835     return FALSE;
836   }
837
838   return TRUE;
839 }
840
841 static gboolean capture_loop_close_output(capture_options *capture_opts, loop_data *ld, int *err_close) {
842   if (capture_opts->multi_files_on) {
843     return ringbuf_wtap_dump_close(&cfile, err_close);
844   } else {
845     return wtap_dump_close(ld->wtap_pdh, err_close);
846   }
847 }
848
849 /* dispatch incoming packets (pcap or capture pipe) */
850 static int
851 capture_loop_dispatch(capture_options *capture_opts, loop_data *ld,
852                       char *errmsg, int errmsg_len) {
853   int       inpkts;
854 #ifndef _WIN32
855   fd_set    set1;
856   struct timeval timeout;
857   int         sel_ret;
858   struct pcaprec_modified_hdr rechdr;
859   guchar pcap_data[WTAP_MAX_PACKET_SIZE];
860 #endif
861
862 #ifndef _WIN32
863     /* dispatch from capture pipe */
864     if (ld->from_cap_pipe) {
865       FD_ZERO(&set1);
866       FD_SET(ld->cap_pipe_fd, &set1);
867       timeout.tv_sec = 0;
868       timeout.tv_usec = CAP_READ_TIMEOUT*1000;
869       sel_ret = select(ld->cap_pipe_fd+1, &set1, NULL, NULL, &timeout);
870       if (sel_ret <= 0) {
871         inpkts = 0;
872         if (sel_ret < 0 && errno != EINTR) {
873           g_snprintf(errmsg, errmsg_len,
874             "Unexpected error from select: %s", strerror(errno));
875           capture_loop_popup_errmsg(capture_opts, errmsg);
876           ld->go = FALSE;
877         }
878       } else {
879         /*
880          * "select()" says we can read from the pipe without blocking
881          */
882         inpkts = cap_pipe_dispatch(ld->cap_pipe_fd, ld, &ld->cap_pipe_hdr, &rechdr, pcap_data,
883           errmsg, errmsg_len);
884         if (inpkts < 0) {
885           ld->go = FALSE;
886         }
887       }
888     }
889     else
890 #endif /* _WIN32 */
891     {
892     /* dispatch from pcap using select */
893 #ifdef MUST_DO_SELECT
894       /*
895        * Sigh.  The semantics of the read timeout argument to
896        * "pcap_open_live()" aren't particularly well specified by
897        * the "pcap" man page - at least with the BSD BPF code, the
898        * intent appears to be, at least in part, a way of cutting
899        * down the number of reads done on a capture, by blocking
900        * until the buffer fills or a timer expires - and the Linux
901        * libpcap doesn't actually support it, so we can't use it
902        * to break out of the "pcap_dispatch()" every 1/4 of a second
903        * or so.  Linux's libpcap is not the only libpcap that doesn't
904        * support the read timeout.
905        *
906        * Furthermore, at least on Solaris, the bufmod STREAMS module's
907        * read timeout won't go off if no data has arrived, i.e. it cannot
908        * be used to guarantee that a read from a DLPI stream will return
909        * within a specified amount of time regardless of whether any
910        * data arrives or not.
911        *
912        * Thus, on all platforms other than BSD, we do a "select()" on the
913        * file descriptor for the capture, with a timeout of CAP_READ_TIMEOUT
914        * milliseconds, or CAP_READ_TIMEOUT*1000 microseconds.
915        *
916        * "select()", on BPF devices, doesn't work as you might expect;
917        * at least on some versions of some flavors of BSD, the timer
918        * doesn't start until a read is done, so it won't expire if
919        * only a "select()" or "poll()" is posted.
920        */
921       FD_ZERO(&set1);
922       FD_SET(ld->pcap_fd, &set1);
923       timeout.tv_sec = 0;
924       timeout.tv_usec = CAP_READ_TIMEOUT*1000;
925       sel_ret = select(ld->pcap_fd+1, &set1, NULL, NULL, &timeout);
926       if (sel_ret > 0) {
927         /*
928          * "select()" says we can read from it without blocking; go for
929          * it.
930          */
931         inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb, (gchar *)ld);
932         if (inpkts < 0) {
933           ld->pcap_err = TRUE;
934           ld->go = FALSE;
935         }
936       } else {
937         inpkts = 0;
938         if (sel_ret < 0 && errno != EINTR) {
939           g_snprintf(errmsg, errmsg_len,
940             "Unexpected error from select: %s", strerror(errno));
941           capture_loop_popup_errmsg(capture_opts, errmsg);
942           ld->go = FALSE;
943         }
944       }
945 #else
946       /* dispatch from pcap without select */
947       inpkts = pcap_dispatch(ld->pcap_h, 1, capture_loop_packet_cb, (gchar *) ld);
948       if (inpkts < 0) {
949         ld->pcap_err = TRUE;
950         ld->go = FALSE;
951       }
952 #endif /* MUST_DO_SELECT */
953     }
954
955     return inpkts;
956 }
957
958
959 /*
960  * This needs to be static, so that the SIGUSR1 handler can clear the "go"
961  * flag.
962  */
963 static loop_data   ld;
964
965 /* Do the low-level work of a capture.
966    Returns TRUE if it succeeds, FALSE otherwise. */
967 int
968 capture_loop_start(capture_options *capture_opts, gboolean *stats_known, struct pcap_stat *stats)
969 {
970   time_t      upd_time, cur_time;
971   time_t      start_time;
972   int         err_close, inpkts;
973   condition  *cnd_file_duration = NULL;
974   condition  *cnd_autostop_files = NULL;
975   condition  *cnd_autostop_size = NULL;
976   condition  *cnd_autostop_duration = NULL;
977   guint32     autostop_files = 0;
978   gboolean    write_ok;
979   gboolean    close_ok;
980   capture_info   capture_ui;
981   char        errmsg[4096+1];
982
983   gboolean    show_info = capture_opts->show_info || !capture_opts->sync_mode;
984
985
986   /* init the loop data */
987   ld.go                 = TRUE;
988   if (capture_opts->has_autostop_packets)
989     ld.packets_max      = capture_opts->autostop_packets;
990   else
991     ld.packets_max      = 0;    /* no limit */
992   ld.err                = 0;    /* no error seen yet */
993   ld.wtap_linktype      = WTAP_ENCAP_UNKNOWN;
994   ld.pcap_err           = FALSE;
995   ld.from_cap_pipe      = FALSE;
996   ld.packets_sync_pipe  = 0;
997   ld.counts.total       = 0;
998   ld.counts.sctp        = 0;
999   ld.counts.tcp         = 0;
1000   ld.counts.udp         = 0;
1001   ld.counts.icmp        = 0;
1002   ld.counts.ospf        = 0;
1003   ld.counts.gre         = 0;
1004   ld.counts.ipx         = 0;
1005   ld.counts.netbios     = 0;
1006   ld.counts.vines       = 0;
1007   ld.counts.other       = 0;
1008   ld.counts.arp         = 0;
1009   ld.wtap_pdh           = NULL;
1010 #ifndef _WIN32
1011   ld.cap_pipe_fd        = -1;
1012 #endif
1013 #ifdef MUST_DO_SELECT
1014   ld.pcap_fd            = 0;
1015 #endif
1016
1017   /* We haven't yet gotten the capture statistics. */
1018   *stats_known      = FALSE;
1019
1020
1021   /* open the "input file" from network interface or capture pipe */
1022   if (!capture_loop_open_input(capture_opts, &ld, errmsg, sizeof(errmsg))) {
1023     goto error;
1024   }
1025
1026   /* init the input filter from the network interface (capture pipe will do nothing) */
1027   if (!capture_loop_init_filter(&ld, errmsg, sizeof(errmsg))) {
1028     goto error;
1029   }
1030
1031   /* open the wiretap part of the output file (the output file is already open) */
1032   if (!capture_loop_open_wiretap_output(capture_opts, &ld, errmsg, sizeof(errmsg))) {
1033     goto error;
1034   }
1035
1036   /* XXX - capture SIGTERM and close the capture, in case we're on a
1037      Linux 2.0[.x] system and you have to explicitly close the capture
1038      stream in order to turn promiscuous mode off?  We need to do that
1039      in other places as well - and I don't think that works all the
1040      time in any case, due to libpcap bugs. */
1041
1042   if (capture_opts->capture_child) {
1043     /* Well, we should be able to start capturing.
1044
1045        This is the child process for a sync mode capture, so sync out
1046        the capture file, so the header makes it to the file system,
1047        and send a "capture started successfully and capture file created"
1048        message to our parent so that they'll open the capture file and
1049        update its windows to indicate that we have a live capture in
1050        progress. */
1051     fflush(wtap_dump_file(ld.wtap_pdh));
1052     sync_pipe_capstart_to_parent();
1053   }
1054
1055   /* initialize capture stop (and alike) conditions */
1056   init_capture_stop_conditions();
1057   /* create stop conditions */
1058   if (capture_opts->has_autostop_filesize)
1059     cnd_autostop_size =
1060         cnd_new(CND_CLASS_CAPTURESIZE,(long)capture_opts->autostop_filesize);
1061   if (capture_opts->has_autostop_duration)
1062     cnd_autostop_duration =
1063         cnd_new(CND_CLASS_TIMEOUT,(gint32)capture_opts->autostop_duration);
1064
1065   if (capture_opts->multi_files_on) {
1066       if (capture_opts->has_file_duration)
1067         cnd_file_duration =
1068             cnd_new(CND_CLASS_TIMEOUT, capture_opts->file_duration);
1069
1070       if (capture_opts->has_autostop_files)
1071         cnd_autostop_files =
1072             cnd_new(CND_CLASS_CAPTURESIZE, capture_opts->autostop_files);
1073   }
1074
1075   /* start capture info dialog */
1076   if(show_info) {
1077       capture_ui.callback_data  = &ld;
1078       capture_ui.counts         = &ld.counts;
1079       capture_info_create(&capture_ui, cfile.iface);
1080   }
1081
1082   /* init the time values */
1083   start_time = time(NULL);
1084   upd_time = time(NULL);
1085
1086   /* WOW, everything is prepared! */
1087   /* please fasten your seat belts, we will enter now the actual capture loop */
1088   while (ld.go) {
1089     main_window_update();
1090
1091     /* dispatch incoming packets */
1092     inpkts = capture_loop_dispatch(capture_opts, &ld, errmsg, sizeof(errmsg));
1093
1094     if (inpkts > 0) {
1095       ld.packets_sync_pipe += inpkts;
1096
1097       /* check capture size condition */
1098       if (cnd_autostop_size != NULL && cnd_eval(cnd_autostop_size,
1099                     (guint32)wtap_get_bytes_dumped(ld.wtap_pdh))){
1100         /* Capture size limit reached, do we have another file? */
1101         if (capture_opts->multi_files_on) {
1102           if (cnd_autostop_files != NULL && cnd_eval(cnd_autostop_files, ++autostop_files)) {
1103             /* no files left: stop here */
1104             ld.go = FALSE;
1105             continue;
1106           }
1107
1108           /* Switch to the next ringbuffer file */
1109           if (ringbuf_switch_file(&cfile, &ld.wtap_pdh, &ld.err)) {
1110             /* File switch succeeded: reset the conditions */
1111             cnd_reset(cnd_autostop_size);
1112             if (cnd_file_duration) {
1113               cnd_reset(cnd_file_duration);
1114             }
1115           } else {
1116             /* File switch failed: stop here */
1117             ld.go = FALSE;
1118             continue;
1119           }
1120         } else {
1121           /* single file, stop now */
1122           ld.go = FALSE;
1123           continue;
1124         }
1125       } /* cnd_autostop_size */
1126     } /* inpkts */
1127
1128     /* Only update once a second so as not to overload slow displays */
1129     cur_time = time(NULL);
1130     if (cur_time > upd_time) {
1131       upd_time = cur_time;
1132
1133       /*if (pcap_stats(pch, stats) >= 0) {
1134         *stats_known = TRUE;
1135       }*/
1136
1137       /* calculate and display running time */
1138       if(show_info) {
1139           cur_time -= start_time;
1140           capture_ui.running_time   = cur_time;
1141           capture_ui.new_packets    = ld.packets_sync_pipe;
1142           capture_info_update(&capture_ui);
1143       }
1144
1145       /* Let the parent process know. */
1146       if (ld.packets_sync_pipe) {
1147         /* do sync here */
1148         fflush(wtap_dump_file(ld.wtap_pdh));
1149
1150         if (capture_opts->capture_child) {
1151           /* This is the child process for a sync mode capture, so send
1152              our parent a message saying we've written out "ld.sync_packets"
1153              packets to the capture file. */
1154         sync_pipe_packet_count_to_parent(ld.packets_sync_pipe);
1155         }
1156
1157         ld.packets_sync_pipe = 0;
1158       }
1159
1160       /* check capture duration condition */
1161       if (cnd_autostop_duration != NULL && cnd_eval(cnd_autostop_duration)) {
1162         /* The maximum capture time has elapsed; stop the capture. */
1163         ld.go = FALSE;
1164         continue;
1165       }
1166       
1167       /* check capture file duration condition */
1168       if (cnd_file_duration != NULL && cnd_eval(cnd_file_duration)) {
1169         /* duration limit reached, do we have another file? */
1170         if (capture_opts->multi_files_on) {
1171           if (cnd_autostop_files != NULL && cnd_eval(cnd_autostop_files, ++autostop_files)) {
1172             /* no files left: stop here */
1173             ld.go = FALSE;
1174             continue;
1175           }
1176
1177           /* Switch to the next ringbuffer file */
1178           if (ringbuf_switch_file(&cfile, &ld.wtap_pdh, &ld.err)) {
1179             /* file switch succeeded: reset the conditions */
1180             cnd_reset(cnd_file_duration);
1181             if(cnd_autostop_size)
1182               cnd_reset(cnd_autostop_size);
1183           } else {
1184             /* File switch failed: stop here */
1185                 ld.go = FALSE;
1186             continue;
1187           }
1188         } else {
1189           /* single file, stop now */
1190           ld.go = FALSE;
1191           continue;
1192         }
1193       } /* cnd_file_duration */
1194     }
1195
1196   } /* while (ld.go) */
1197
1198   /* close capture info dialog */
1199   if(show_info) {
1200     capture_info_destroy(&capture_ui);
1201   }
1202
1203   /* delete stop conditions */
1204   if (cnd_file_duration != NULL)
1205     cnd_delete(cnd_file_duration);
1206   if (cnd_autostop_files != NULL)
1207     cnd_delete(cnd_autostop_files);
1208   if (cnd_autostop_size != NULL)
1209     cnd_delete(cnd_autostop_size);
1210   if (cnd_autostop_duration != NULL)
1211     cnd_delete(cnd_autostop_duration);
1212
1213   /* did we had a pcap (input) error? */
1214   if (ld.pcap_err) {
1215     g_snprintf(errmsg, sizeof(errmsg), "Error while capturing packets: %s",
1216       pcap_geterr(ld.pcap_h));
1217     capture_loop_popup_errmsg(capture_opts, errmsg);
1218   }
1219 #ifndef _WIN32
1220     else if (ld.from_cap_pipe && ld.cap_pipe_err == PIPERR)
1221       capture_loop_popup_errmsg(capture_opts, errmsg);
1222 #endif
1223
1224   /* did we had an error while capturing? */
1225   if (ld.err == 0) {
1226     write_ok = TRUE;
1227   } else {
1228     capture_loop_get_errmsg(errmsg, sizeof(errmsg), cfile.save_file, ld.err,
1229                               FALSE);
1230     capture_loop_popup_errmsg(capture_opts, errmsg);
1231     write_ok = FALSE;
1232   }
1233
1234   /* close the wiretap (output) file */
1235   close_ok = capture_loop_close_output(capture_opts, &ld, &err_close);
1236
1237   /* If we've displayed a message about a write error, there's no point
1238      in displaying another message about an error on close. */
1239   if (!close_ok && write_ok) {
1240     capture_loop_get_errmsg(errmsg, sizeof(errmsg), cfile.save_file, err_close,
1241                 TRUE);
1242     capture_loop_popup_errmsg(capture_opts, errmsg);
1243   }
1244
1245   /*
1246    * XXX We exhibit different behaviour between normal mode and sync mode
1247    * when the pipe is stdin and not already at EOF.  If we're a child, the
1248    * parent's stdin isn't closed, so if the user starts another capture,
1249    * cap_pipe_open_live() will very likely not see the expected magic bytes and
1250    * will say "Unrecognized libpcap format".  On the other hand, in normal
1251    * mode, cap_pipe_open_live() will say "End of file on pipe during open".
1252    */
1253
1254   /* get packet drop statistics from pcap */
1255   if(ld.pcap_h != NULL) {
1256     g_assert(!ld.from_cap_pipe);
1257     /* Get the capture statistics, so we know how many packets were
1258        dropped. */
1259     if (pcap_stats(ld.pcap_h, stats) >= 0) {
1260       *stats_known = TRUE;
1261       if (capture_opts->capture_child) {
1262         /* Let the parent process know. */
1263         sync_pipe_drops_to_parent(stats->ps_drop);
1264       }
1265     } else {
1266       g_snprintf(errmsg, sizeof(errmsg),
1267                 "Can't get packet-drop statistics: %s",
1268                 pcap_geterr(ld.pcap_h));
1269       capture_loop_popup_errmsg(capture_opts, errmsg);
1270     }
1271   }
1272
1273   /* close the input file (pcap or capture pipe) */
1274   capture_loop_close_input(&ld);
1275
1276   /* ok, if the write and the close were successful. */
1277   return write_ok && close_ok;
1278
1279 error:
1280   if (capture_opts->multi_files_on) {
1281     /* cleanup ringbuffer */
1282     ringbuf_error_cleanup();
1283   } else {
1284     /* We can't use the save file, and we have no wtap_dump stream
1285        to close in order to close it, so close the FD directly. */
1286     close(cfile.save_file_fd);
1287
1288     /* We couldn't even start the capture, so get rid of the capture
1289        file. */
1290     unlink(cfile.save_file); /* silently ignore error */
1291     g_free(cfile.save_file);
1292   }
1293   cfile.save_file = NULL;
1294   capture_loop_popup_errmsg(capture_opts, errmsg);
1295
1296   /* close the input file (pcap or cap_pipe) */
1297   capture_loop_close_input(&ld);
1298
1299   return FALSE;
1300 }
1301
1302
1303 void capture_loop_stop(void)
1304 {
1305     ld.go = FALSE;
1306 }
1307  
1308
1309 static void
1310 capture_loop_get_errmsg(char *errmsg, int errmsglen, const char *fname,
1311                           int err, gboolean is_close)
1312 {
1313   switch (err) {
1314
1315   case ENOSPC:
1316     g_snprintf(errmsg, errmsglen,
1317                 "Not all the packets could be written to the file"
1318                 " to which the capture was being saved\n"
1319                 "(\"%s\") because there is no space left on the file system\n"
1320                 "on which that file resides.",
1321                 fname);
1322     break;
1323
1324 #ifdef EDQUOT
1325   case EDQUOT:
1326     g_snprintf(errmsg, errmsglen,
1327                 "Not all the packets could be written to the file"
1328                 " to which the capture was being saved\n"
1329                 "(\"%s\") because you are too close to, or over,"
1330                 " your disk quota\n"
1331                 "on the file system on which that file resides.",
1332                 fname);
1333   break;
1334 #endif
1335
1336   case WTAP_ERR_CANT_CLOSE:
1337     g_snprintf(errmsg, errmsglen,
1338                 "The file to which the capture was being saved"
1339                 " couldn't be closed for some unknown reason.");
1340     break;
1341
1342   case WTAP_ERR_SHORT_WRITE:
1343     g_snprintf(errmsg, errmsglen,
1344                 "Not all the packets could be written to the file"
1345                 " to which the capture was being saved\n"
1346                 "(\"%s\").",
1347                 fname);
1348     break;
1349
1350   default:
1351     if (is_close) {
1352       g_snprintf(errmsg, errmsglen,
1353                 "The file to which the capture was being saved\n"
1354                 "(\"%s\") could not be closed: %s.",
1355                 fname, wtap_strerror(err));
1356     } else {
1357       g_snprintf(errmsg, errmsglen,
1358                 "An error occurred while writing to the file"
1359                 " to which the capture was being saved\n"
1360                 "(\"%s\"): %s.",
1361                 fname, wtap_strerror(err));
1362     }
1363     break;
1364   }
1365 }
1366
1367 static void
1368 capture_loop_popup_errmsg(capture_options *capture_opts, const char *errmsg)
1369 {
1370   if (capture_opts->capture_child) {
1371     /* This is the child process for a sync mode capture.
1372        Send the error message to our parent, so they can display a
1373        dialog box containing it. */
1374     sync_pipe_errmsg_to_parent(errmsg);
1375   } else {
1376     /* Display the dialog box ourselves; there's no parent. */
1377     simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", errmsg);
1378   }
1379 }
1380
1381
1382 /* one packet was captured, process it */
1383 static void
1384 capture_loop_packet_cb(guchar *user, const struct pcap_pkthdr *phdr,
1385   const guchar *pd)
1386 {
1387   struct wtap_pkthdr whdr;
1388   union wtap_pseudo_header pseudo_header;
1389   loop_data *ld = (loop_data *) user;
1390   int err;
1391
1392   /* if the user told us to stop after x packets, do we have enough? */
1393   ld->counts.total++;
1394   if ((ld->packets_max > 0) && (ld->counts.total >= ld->packets_max))
1395   {
1396      ld->go = FALSE;
1397   }
1398
1399   /* Convert from libpcap to Wiretap format.
1400      If that fails, set "ld->go" to FALSE, to stop the capture, and set
1401      "ld->err" to the error. */
1402   pd = wtap_process_pcap_packet(ld->wtap_linktype, phdr, pd, &pseudo_header,
1403                                 &whdr, &err);
1404   if (pd == NULL) {
1405     ld->go = FALSE;
1406     ld->err = err;
1407     return;
1408   }
1409
1410   if (ld->wtap_pdh) {
1411     /* We're supposed to write the packet to a file; do so.
1412        If this fails, set "ld->go" to FALSE, to stop the capture, and set
1413        "ld->err" to the error. */
1414     if (!wtap_dump(ld->wtap_pdh, &whdr, &pseudo_header, pd, &err)) {
1415       ld->go = FALSE;
1416       ld->err = err;
1417     }
1418   }
1419
1420   switch (ld->wtap_linktype) {
1421     case WTAP_ENCAP_ETHERNET:
1422       capture_eth(pd, 0, whdr.caplen, &ld->counts);
1423       break;
1424     case WTAP_ENCAP_FDDI:
1425     case WTAP_ENCAP_FDDI_BITSWAPPED:
1426       capture_fddi(pd, whdr.caplen, &ld->counts);
1427       break;
1428     case WTAP_ENCAP_PRISM_HEADER:
1429       capture_prism(pd, 0, whdr.caplen, &ld->counts);
1430       break;
1431     case WTAP_ENCAP_TOKEN_RING:
1432       capture_tr(pd, 0, whdr.caplen, &ld->counts);
1433       break;
1434     case WTAP_ENCAP_NULL:
1435       capture_null(pd, whdr.caplen, &ld->counts);
1436       break;
1437     case WTAP_ENCAP_PPP:
1438       capture_ppp_hdlc(pd, 0, whdr.caplen, &ld->counts);
1439       break;
1440     case WTAP_ENCAP_RAW_IP:
1441       capture_raw(pd, whdr.caplen, &ld->counts);
1442       break;
1443     case WTAP_ENCAP_SLL:
1444       capture_sll(pd, whdr.caplen, &ld->counts);
1445       break;
1446     case WTAP_ENCAP_LINUX_ATM_CLIP:
1447       capture_clip(pd, whdr.caplen, &ld->counts);
1448       break;
1449     case WTAP_ENCAP_IEEE_802_11:
1450     case WTAP_ENCAP_IEEE_802_11_WITH_RADIO:
1451       capture_ieee80211(pd, 0, whdr.caplen, &ld->counts);
1452       break;
1453     case WTAP_ENCAP_CHDLC:
1454       capture_chdlc(pd, 0, whdr.caplen, &ld->counts);
1455       break;
1456     case WTAP_ENCAP_LOCALTALK:
1457       capture_llap(&ld->counts);
1458       break;
1459     case WTAP_ENCAP_ATM_PDUS:
1460       capture_atm(&pseudo_header, pd, whdr.caplen, &ld->counts);
1461       break;
1462     case WTAP_ENCAP_IP_OVER_FC:
1463       capture_ipfc(pd, whdr.caplen, &ld->counts);
1464       break;
1465     case WTAP_ENCAP_ARCNET:
1466       capture_arcnet(pd, whdr.caplen, &ld->counts, FALSE, TRUE);
1467       break;
1468     case WTAP_ENCAP_ARCNET_LINUX:
1469       capture_arcnet(pd, whdr.caplen, &ld->counts, TRUE, FALSE);
1470       break;
1471     case WTAP_ENCAP_APPLE_IP_OVER_IEEE1394:
1472       capture_ap1394(pd, 0, whdr.caplen, &ld->counts);
1473       break;
1474     /* XXX - some ATM drivers on FreeBSD might prepend a 4-byte ATM
1475        pseudo-header to DLT_ATM_RFC1483, with LLC header following;
1476        we might have to implement that at some point. */
1477   }
1478 }
1479
1480 #endif /* HAVE_LIBPCAP */
1481