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