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