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