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