Rename "SP_ERROR" to "SP_ERROR_MSG" to avoid a #define collision with
[obnox/wireshark/wip.git] / capture.c
1 /* capture.c
2  * Routines for packet capture windows
3  *
4  * $Id: capture.c,v 1.143 2001/02/14 09:40:20 guy Exp $
5  *
6  * Ethereal - Network traffic analyzer
7  * By Gerald Combs <gerald@zing.org>
8  * Copyright 1998 Gerald Combs
9  *
10  * 
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License
13  * as published by the Free Software Foundation; either version 2
14  * of the License, or (at your option) any later version.
15  * 
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  * 
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
24  */
25
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #ifdef HAVE_LIBPCAP
31
32 #ifdef HAVE_SYS_TYPES_H
33 # include <sys/types.h>
34 #endif
35
36 #ifdef HAVE_SYS_STAT_H
37 # include <sys/stat.h>
38 #endif
39
40 #ifdef HAVE_SYS_WAIT_H
41 # include <sys/wait.h>
42 #endif
43
44 #ifndef _WIN32
45 /*
46  * Define various POSIX macros (and, in the case of WCOREDUMP, non-POSIX
47  * macros) on UNIX systems that don't have them.
48  */
49 #ifndef WIFEXITED
50 # define WIFEXITED(status)      (((status) & 0177) == 0)
51 #endif
52 #ifndef WIFSTOPPED
53 # define WIFSTOPPED(status)     (((status) & 0177) == 0177)
54 #endif
55 #ifndef WIFSIGNALED
56 # define WIFSIGNALED(status)    (!WIFSTOPPED(status) && !WIFEXITED(status))
57 #endif
58 #ifndef WEXITSTATUS
59 # define WEXITSTATUS(status)    ((status) >> 8)
60 #endif
61 #ifndef WTERMSIG
62 # define WTERMSIG(status)       ((status) & 0177)
63 #endif
64 #ifndef WCOREDUMP
65 # define WCOREDUMP(status)      ((status) & 0200)
66 #endif
67 #ifndef WSTOPSIG
68 # define WSTOPSIG(status)       ((status) >> 8)
69 #endif
70 #endif /* _WIN32 */
71
72 #ifdef HAVE_IO_H
73 # include <io.h>
74 #endif
75
76 #include <gtk/gtk.h>
77 #include <stdlib.h>
78 #include <stdio.h>
79 #include <ctype.h>
80 #include <string.h>
81
82 #ifdef HAVE_FCNTL_H
83 #include <fcntl.h>
84 #endif
85
86 #ifdef HAVE_UNISTD_H
87 #include <unistd.h>
88 #endif
89
90 #include <time.h>
91
92 #ifdef HAVE_SYS_SOCKET_H
93 #include <sys/socket.h>
94 #endif
95
96 #ifdef HAVE_SYS_IOCTL_H
97 #include <sys/ioctl.h>
98 #endif
99
100 #include <signal.h>
101 #include <errno.h>
102
103 #include <pcap.h>
104
105 #ifdef NEED_SNPRINTF_H
106 # include "snprintf.h"
107 #endif
108
109 #ifdef _WIN32
110 #include <process.h>    /* For spawning child process */
111 #endif
112
113 /*
114  * XXX - the various BSDs appear to define BSD in <sys/param.h>; we don't
115  * want to include it if it's not present on this platform, however.
116  */
117 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__bsdi__)
118 #ifndef BSD
119 #define BSD
120 #endif /* BSD */
121 #endif /* defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__bsdi__) */
122
123 /*
124  * We don't want to do a "select()" on the pcap_t's file descriptor on
125  * BSD (because "select()" doesn't work correctly on BPF devices on at
126  * least some releases of some flavors of BSD), and we don't want to do
127  * it on Windows (because "select()" is something for sockets, not for
128  * arbitrary handles).
129  *
130  * We *do* want to do it on other platforms, as, on other platforms (with
131  * the possible exception of Ultrix and Digital UNIX), the read timeout
132  * doesn't expire if no packets have arrived, so a "pcap_dispatch()" call
133  * will block until packets arrive, causing the UI to hang.
134  */
135 #if !defined(BSD) && !defined(_WIN32)
136 # define MUST_DO_SELECT
137 #endif
138
139 #include "gtk/main.h"
140 #include "gtk/gtkglobals.h"
141 #include "packet.h"
142 #include "file.h"
143 #include "capture.h"
144 #include "util.h"
145 #include "simple_dialog.h"
146 #include "prefs.h"
147 #include "globals.h"
148
149 #include "wiretap/libpcap.h"
150 #include "wiretap/wtap.h"
151
152 #include "packet-clip.h"
153 #include "packet-eth.h"
154 #include "packet-fddi.h"
155 #include "packet-null.h"
156 #include "packet-ppp.h"
157 #include "packet-raw.h"
158 #include "packet-sll.h"
159 #include "packet-tr.h"
160 #include "packet-ieee80211.h"
161
162 int promisc_mode = TRUE; /* capture in promiscuous mode */
163 int sync_mode;  /* fork a child to do the capture, and sync between them */
164 static int sync_pipe[2]; /* used to sync father */
165 enum PIPES { READ, WRITE }; /* Constants 0 and 1 for READ and WRITE */
166 int quit_after_cap; /* Makes a "capture only mode". Implies -k */
167 gboolean capture_child; /* if this is the child for "-S" */
168 static int fork_child;  /* In parent, process ID of child */
169 static guint cap_input_id;
170
171 /*
172  * Indications sent out on the sync pipe.
173  */
174 #define SP_CAPSTART     ';'     /* capture start message */
175 #define SP_PACKET_COUNT '*'     /* count of packets captured since last message */
176 #define SP_ERROR_MSG    '!'     /* length of error message that follows */
177 #define SP_DROPS        '#'     /* count of packets dropped in capture */
178
179 #ifdef _WIN32
180 static guint cap_timer_id;
181 static int cap_timer_cb(gpointer); /* Win32 kludge to check for pipe input */
182 #endif
183
184 static void cap_file_input_cb(gpointer, gint, GdkInputCondition);
185 static void wait_for_child(gboolean);
186 #ifndef _WIN32
187 static char *signame(int);
188 #endif
189 static void capture_delete_cb(GtkWidget *, GdkEvent *, gpointer);
190 static void capture_stop_cb(GtkWidget *, gpointer);
191 static void capture_pcap_cb(u_char *, const struct pcap_pkthdr *,
192   const u_char *);
193 static void get_capture_file_io_error(char *, int, const char *, int, gboolean);
194 static void send_errmsg_to_parent(const char *);
195 static float pct(gint, gint);
196 static void stop_capture(int signo);
197
198 typedef struct _loop_data {
199   gint           go;           /* TRUE as long as we're supposed to keep capturing */
200   gint           max;          /* Number of packets we're supposed to capture - 0 means infinite */
201   int            err;          /* if non-zero, error seen while capturing */
202   gint           linktype;
203   gint           sync_packets;
204   gboolean       from_pipe;    /* TRUE if we are capturing data from a pipe */
205   gboolean       modified;     /* TRUE if data in the pipe uses modified pcap headers */
206   gboolean       byte_swapped; /* TRUE if data in the pipe is byte swapped */
207   packet_counts  counts;
208   wtap_dumper   *pdh;
209 } loop_data;
210
211 #ifndef _WIN32
212 static void adjust_header(loop_data *, struct pcap_hdr *, struct pcaprec_hdr *);
213 static int pipe_open_live(char *, struct pcap_hdr *, loop_data *, char *);
214 static int pipe_dispatch(int, loop_data *, struct pcap_hdr *);
215 #endif
216
217 /* Win32 needs the O_BINARY flag for open() */
218 #ifndef O_BINARY
219 #define O_BINARY        0
220 #endif
221
222 #ifdef _WIN32
223 /* Win32 needs a handle to the child capture process */
224 int child_process;
225 #endif
226
227 /* Add a string pointer to a NULL-terminated array of string pointers. */
228 static char **
229 add_arg(char **args, int *argc, char *arg)
230 {
231   /* Grow the array; "*argc" currently contains the number of string
232      pointers, *not* counting the NULL pointer at the end, so we have
233      to add 2 in order to get the new size of the array, including the
234      new pointer and the terminating NULL pointer. */
235   args = g_realloc(args, (*argc + 2) * sizeof (char *));
236
237   /* Stuff the pointer into the penultimate element of the array, which
238      is the one at the index specified by "*argc". */
239   args[*argc] = arg;
240
241   /* Now bump the count. */
242   (*argc)++;
243
244   /* We overwrite the NULL pointer; put it back right after the
245      element we added. */
246   args[*argc] = NULL;
247
248   return args;
249 }
250
251 #ifdef _WIN32
252 /* Given a string, return a pointer to a quote-encapsulated version of
253    the string, so we can pass it as an argument with "spawnvp" even
254    if it contains blanks. */
255 char *
256 quote_encapsulate(const char *string)
257 {
258   char *encapsulated_string;
259
260   encapsulated_string = g_new(char, strlen(string) + 3);
261   sprintf(encapsulated_string, "\"%s\"", string);
262   return encapsulated_string;
263 }
264 #endif
265
266 /* Open a specified file, or create a temporary file, and start a capture
267    to the file in question. */
268 void
269 do_capture(char *capfile_name)
270 {
271   char tmpname[128+1];
272   gboolean is_tempfile;
273   u_char c;
274   int i;
275   guint byte_count;
276   char *msg;
277   int err;
278   int capture_succeeded;
279   gboolean stats_known;
280   struct pcap_stat stats;
281
282   if (capfile_name != NULL) {
283     /* Try to open/create the specified file for use as a capture buffer. */
284     cfile.save_file_fd = open(capfile_name, O_RDWR|O_BINARY|O_TRUNC|O_CREAT, 0600);
285     is_tempfile = FALSE;
286   } else {
287     /* Choose a random name for the capture buffer */
288     cfile.save_file_fd = create_tempfile(tmpname, sizeof tmpname, "ether");
289     capfile_name = g_strdup(tmpname);
290     is_tempfile = TRUE;
291   }
292   if (cfile.save_file_fd == -1) {
293     if (is_tempfile) {
294       simple_dialog(ESD_TYPE_CRIT, NULL,
295         "The temporary file to which the capture would be saved (\"%s\")"
296         "could not be opened: %s.", capfile_name, strerror(errno));
297     } else {
298       simple_dialog(ESD_TYPE_CRIT, NULL,
299         file_open_error_message(errno, TRUE), capfile_name);
300     }
301     return;
302   }
303   close_cap_file(&cfile, info_bar);
304   g_assert(cfile.save_file == NULL);
305   cfile.save_file = capfile_name;
306
307   if (sync_mode) {      /* do the capture in a child process */
308     char ssnap[24];
309     char scount[24];    /* need a constant for len of numbers */
310     char save_file_fd[24];
311     char errmsg[1024+1];
312     int error;
313     int argc;
314     char **argv;
315 #ifdef _WIN32
316     char sync_pipe_fd[24];
317     char *fontstring;
318     char *filterstring;
319 #endif
320
321     /* Allocate the string pointer array with enough space for the
322        terminating NULL pointer. */
323     argc = 0;
324     argv = g_malloc(sizeof (char *));
325     *argv = NULL;
326
327     /* Now add those arguments used on all platforms. */
328     argv = add_arg(argv, &argc, CHILD_NAME);
329
330     argv = add_arg(argv, &argc, "-i");
331     argv = add_arg(argv, &argc, cfile.iface);
332
333     argv = add_arg(argv, &argc, "-w");
334     argv = add_arg(argv, &argc, cfile.save_file);
335
336     argv = add_arg(argv, &argc, "-W");
337     sprintf(save_file_fd,"%d",cfile.save_file_fd);      /* in lieu of itoa */
338     argv = add_arg(argv, &argc, save_file_fd);
339
340     argv = add_arg(argv, &argc, "-c");
341     sprintf(scount,"%d",cfile.count);
342     argv = add_arg(argv, &argc, scount);
343
344     argv = add_arg(argv, &argc, "-s");
345     sprintf(ssnap,"%d",cfile.snap);
346     argv = add_arg(argv, &argc, ssnap);
347
348     if (!promisc_mode)
349       argv = add_arg(argv, &argc, "-p");
350
351 #ifdef _WIN32
352     /* Create a pipe for the child process */
353
354     if(_pipe(sync_pipe, 512, O_BINARY) < 0) {
355       /* Couldn't create the pipe between parent and child. */
356       error = errno;
357       unlink(cfile.save_file);
358       g_free(cfile.save_file);
359       cfile.save_file = NULL;
360       simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create sync pipe: %s",
361                         strerror(error));
362       return;
363     }
364
365     /* Convert font name to a quote-encapsulated string and pass to child */
366     argv = add_arg(argv, &argc, "-m");
367     fontstring = quote_encapsulate(prefs.gui_font_name);
368     argv = add_arg(argv, &argc, fontstring);
369
370     /* Convert pipe write handle to a string and pass to child */
371     argv = add_arg(argv, &argc, "-Z");
372     itoa(sync_pipe[WRITE], sync_pipe_fd, 10);
373     argv = add_arg(argv, &argc, sync_pipe_fd);
374
375     /* Convert filter string to a quote delimited string and pass to child */
376     if (cfile.cfilter != NULL && strlen(cfile.cfilter) != 0) {
377       argv = add_arg(argv, &argc, "-f");
378       filterstring = quote_encapsulate(cfile.cfilter);
379       argv = add_arg(argv, &argc, filterstring);
380     }
381
382     /* Spawn process */
383     fork_child = spawnvp(_P_NOWAIT, ethereal_path, argv);
384     g_free(fontstring);
385     g_free(filterstring);
386     /* Keep a copy for later evaluation by _cwait() */
387     child_process = fork_child;
388 #else
389     signal(SIGCHLD, SIG_IGN);
390     if (pipe(sync_pipe) < 0) {
391       /* Couldn't create the pipe between parent and child. */
392       error = errno;
393       unlink(cfile.save_file);
394       g_free(cfile.save_file);
395       cfile.save_file = NULL;
396       simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create sync pipe: %s",
397                         strerror(error));
398       return;
399     }
400
401     argv = add_arg(argv, &argc, "-m");
402     argv = add_arg(argv, &argc, prefs.gui_font_name);
403
404     if (cfile.cfilter != NULL && strlen(cfile.cfilter) != 0) {
405       argv = add_arg(argv, &argc, "-f");
406       argv = add_arg(argv, &argc, cfile.cfilter);
407     }
408
409     if ((fork_child = fork()) == 0) {
410       /*
411        * Child process - run Ethereal with the right arguments to make
412        * it just pop up the live capture dialog box and capture with
413        * the specified capture parameters, writing to the specified file.
414        *
415        * args: -i interface specification
416        * -w file to write
417        * -W file descriptor to write
418        * -c count to capture
419        * -s snaplen
420        * -m / -b fonts
421        * -f "filter expression"
422        */
423       close(1);
424       dup(sync_pipe[WRITE]);
425       close(sync_pipe[READ]);
426       execvp(ethereal_path, argv);
427       snprintf(errmsg, sizeof errmsg, "Couldn't run %s in child process: %s",
428                 ethereal_path, strerror(errno));
429       send_errmsg_to_parent(errmsg);
430
431       /* Exit with "_exit()", so that we don't close the connection
432          to the X server (and cause stuff buffered up by our parent but
433          not yet sent to be sent, as that stuff should only be sent by
434          our parent). */
435       _exit(2);
436     }
437 #endif
438
439     /* Parent process - read messages from the child process over the
440        sync pipe. */
441     g_free(argv);       /* free up arg array */
442
443     /* Close the write side of the pipe, so that only the child has it
444        open, and thus it completely closes, and thus returns to us
445        an EOF indication, if the child closes it (either deliberately
446        or by exiting abnormally). */
447     close(sync_pipe[WRITE]);
448
449     /* Close the save file FD, as we won't be using it - we'll be opening
450        it and reading the save file through Wiretap. */
451     close(cfile.save_file_fd);
452
453     if (fork_child == -1) {
454       /* We couldn't even create the child process. */
455       error = errno;
456       close(sync_pipe[READ]);
457       unlink(cfile.save_file);
458       g_free(cfile.save_file);
459       cfile.save_file = NULL;
460       simple_dialog(ESD_TYPE_CRIT, NULL, "Couldn't create child process: %s",
461                         strerror(error));
462       return;
463     }
464
465     /* Read a byte count from "sync_pipe[READ]", terminated with a
466        colon; if the count is 0, the child process created the
467        capture file and we should start reading from it, otherwise
468        the capture couldn't start and the count is a count of bytes
469        of error message, and we should display the message. */
470     byte_count = 0;
471     for (;;) {
472       i = read(sync_pipe[READ], &c, 1);
473       if (i == 0) {
474         /* EOF - the child process died.
475            Close the read side of the sync pipe, remove the capture file,
476            and report the failure. */
477         close(sync_pipe[READ]);
478         unlink(cfile.save_file);
479         g_free(cfile.save_file);
480         cfile.save_file = NULL;
481         wait_for_child(TRUE);
482         return;
483       }
484       if (c == SP_CAPSTART || c == SP_ERROR_MSG)
485         break;
486       if (!isdigit(c)) {
487         /* Child process handed us crap.
488            Close the read side of the sync pipe, remove the capture file,
489            and report the failure. */
490         close(sync_pipe[READ]);
491         unlink(cfile.save_file);
492         g_free(cfile.save_file);
493         cfile.save_file = NULL;
494         simple_dialog(ESD_TYPE_WARN, NULL,
495                         "Capture child process sent us a bad message");
496         return;
497       }
498       byte_count = byte_count*10 + c - '0';
499     }
500     if (c == SP_CAPSTART) {
501       /* Success.  Open the capture file, and set up to read it. */
502       err = start_tail_cap_file(cfile.save_file, is_tempfile, &cfile);
503       if (err == 0) {
504         /* We were able to open and set up to read the capture file;
505            arrange that our callback be called whenever it's possible
506            to read from the sync pipe, so that it's called when
507            the child process wants to tell us something. */
508 #ifdef _WIN32
509         /* Tricky to use pipes in win9x, as no concept of wait.  NT can
510            do this but that doesn't cover all win32 platforms.  GTK can do
511            this but doesn't seem to work over processes.  Attempt to do
512            something similar here, start a timer and check for data on every
513            timeout. */
514         cap_timer_id = gtk_timeout_add(1000, cap_timer_cb, NULL);
515 #else
516         cap_input_id = gtk_input_add_full(sync_pipe[READ],
517                                        GDK_INPUT_READ|GDK_INPUT_EXCEPTION,
518                                        cap_file_input_cb,
519                                        NULL,
520                                        (gpointer) &cfile,
521                                        NULL);
522 #endif
523       } else {
524         /* We weren't able to open the capture file; complain, and
525            close the sync pipe. */
526         simple_dialog(ESD_TYPE_CRIT, NULL,
527                         file_open_error_message(err, FALSE), cfile.save_file);
528
529         /* Close the sync pipe. */
530         close(sync_pipe[READ]);
531
532         /* Don't unlink the save file - leave it around, for debugging
533            purposes. */
534         g_free(cfile.save_file);
535         cfile.save_file = NULL;
536       }
537     } else {
538       /* Failure - the child process sent us a message indicating
539          what the problem was. */
540       msg = g_malloc(byte_count + 1);
541       if (msg == NULL) {
542         simple_dialog(ESD_TYPE_WARN, NULL,
543                 "Capture child process failed, but its error message was too big.");
544       } else if (byte_count == 0) {
545         /* Zero-length message? */
546         simple_dialog(ESD_TYPE_WARN, NULL,
547                 "Capture child process failed, but its error message was empty.");
548       } else {
549         i = read(sync_pipe[READ], msg, byte_count);
550         if (i < 0) {
551           simple_dialog(ESD_TYPE_WARN, NULL,
552                   "Capture child process failed: Error %s reading its error message.",
553                   strerror(errno));
554         } else if (i == 0) {
555           simple_dialog(ESD_TYPE_WARN, NULL,
556                   "Capture child process failed: EOF reading its error message.");
557           wait_for_child(FALSE);
558         } else
559           simple_dialog(ESD_TYPE_WARN, NULL, msg);
560         g_free(msg);
561
562         /* Close the sync pipe. */
563         close(sync_pipe[READ]);
564
565         /* Get rid of the save file - the capture never started. */
566         unlink(cfile.save_file);
567         g_free(cfile.save_file);
568         cfile.save_file = NULL;
569       }
570     }
571   } else {
572     /* Not sync mode. */
573     capture_succeeded = capture(&stats_known, &stats);
574     if (quit_after_cap) {
575       /* DON'T unlink the save file.  Presumably someone wants it. */
576       gtk_exit(0);
577     }
578     if (capture_succeeded) {
579       /* Capture succeeded; read in the capture file. */
580       if ((err = open_cap_file(cfile.save_file, is_tempfile, &cfile)) == 0) {
581         /* Set the read filter to NULL. */
582         cfile.rfcode = NULL;
583
584         /* Get the packet-drop statistics.
585
586            XXX - there are currently no packet-drop statistics stored
587            in libpcap captures, and that's what we're reading.
588
589            At some point, we will add support in Wiretap to return
590            packet-drop statistics for capture file formats that store it,
591            and will make "read_cap_file()" get those statistics from
592            Wiretap.  We clear the statistics (marking them as "not known")
593            in "open_cap_file()", and "read_cap_file()" will only fetch
594            them and mark them as known if Wiretap supplies them, so if
595            we get the statistics now, after calling "open_cap_file()" but
596            before calling "read_cap_file()", the values we store will
597            be used by "read_cap_file()".
598
599            If a future libpcap capture file format stores the statistics,
600            we'll put them into the capture file that we write, and will
601            thus not have to set them here - "read_cap_file()" will get
602            them from the file and use them. */
603         if (stats_known) {
604           cfile.drops_known = TRUE;
605
606           /* XXX - on some systems, libpcap doesn't bother filling in
607              "ps_ifdrop" - it doesn't even set it to zero - so we don't
608              bother looking at it.
609
610              Ideally, libpcap would have an interface that gave us
611              several statistics - perhaps including various interface
612              error statistics - and would tell us which of them it
613              supplies, allowing us to display only the ones it does. */
614           cfile.drops = stats.ps_drop;
615         }
616         switch (read_cap_file(&cfile, &err)) {
617
618         case READ_SUCCESS:
619         case READ_ERROR:
620           /* Just because we got an error, that doesn't mean we were unable
621              to read any of the file; we handle what we could get from the
622              file. */
623           break;
624
625         case READ_ABORTED:
626           /* Exit by leaving the main loop, so that any quit functions
627              we registered get called. */
628           gtk_main_quit();
629           return;
630         }
631       }
632     }
633     /* We're not doing a capture any more, so we don't have a save
634        file. */
635     g_free(cfile.save_file);
636     cfile.save_file = NULL;
637   }
638 }
639
640 #ifdef _WIN32
641 /* The timer has expired, see if there's stuff to read from the pipe,
642    if so call the cap_file_input_cb */
643 static gint
644 cap_timer_cb(gpointer data)
645 {
646   HANDLE handle;
647   DWORD avail = 0;
648   gboolean result, result1;
649   DWORD childstatus;
650
651   /* Oddly enough although Named pipes don't work on win9x,
652      PeekNamedPipe does !!! */
653   handle = (HANDLE) _get_osfhandle (sync_pipe[READ]);
654   result = PeekNamedPipe(handle, NULL, 0, NULL, &avail, NULL);
655
656   /* Get the child process exit status */
657   result1 = GetExitCodeProcess((HANDLE)child_process, &childstatus);
658
659   /* If the Peek returned an error, or there are bytes to be read
660      or the childwatcher thread has terminated then call the normal
661      callback */
662   if (!result || avail > 0 || childstatus != STILL_ACTIVE) {
663
664     /* avoid reentrancy problems and stack overflow */
665     gtk_timeout_remove(cap_timer_id);
666
667     /* And call the real handler */
668     cap_file_input_cb((gpointer) &cfile, 0, 0);
669
670     /* Return false so that the timer is not run again */
671     return FALSE;
672   }
673   else {
674     /* No data so let timer run again */
675     return TRUE;
676   }
677 }
678 #endif
679
680 /* There's stuff to read from the sync pipe, meaning the child has sent
681    us a message, or the sync pipe has closed, meaning the child has
682    closed it (perhaps because it exited). */
683 static void 
684 cap_file_input_cb(gpointer data, gint source, GdkInputCondition condition)
685 {
686   capture_file *cf = (capture_file *)data;
687 #define BUFSIZE 4096
688   char buffer[BUFSIZE+1], *p = buffer, *q = buffer, *msg, *r;
689   int  nread, msglen, chars_to_copy;
690   int  to_read = 0;
691   int  err;
692
693 #ifndef _WIN32
694   /* avoid reentrancy problems and stack overflow */
695   gtk_input_remove(cap_input_id);
696 #endif
697
698   if ((nread = read(sync_pipe[READ], buffer, BUFSIZE)) <= 0) {
699     /* The child has closed the sync pipe, meaning it's not going to be
700        capturing any more packets.  Pick up its exit status, and
701        complain if it did anything other than exit with status 0. */
702     wait_for_child(FALSE);
703       
704     /* Read what remains of the capture file, and finish the capture.
705        XXX - do something if this fails? */
706     switch (finish_tail_cap_file(cf, &err)) {
707
708     case READ_SUCCESS:
709     case READ_ERROR:
710       /* Just because we got an error, that doesn't mean we were unable
711          to read any of the file; we handle what we could get from the
712          file. */
713       break;
714
715     case READ_ABORTED:
716       /* Exit by leaving the main loop, so that any quit functions
717          we registered get called. */
718       gtk_main_quit();
719       return;
720     }
721
722     /* We're not doing a capture any more, so we don't have a save
723        file. */
724     g_free(cf->save_file);
725     cf->save_file = NULL;
726
727     return;
728   }
729
730   buffer[nread] = '\0';
731
732   while (nread != 0) {
733     /* look for (possibly multiple) indications */
734     switch (*q) {
735     case SP_PACKET_COUNT :
736       to_read += atoi(p);
737       p = q + 1;
738       q++;
739       nread--;
740       break;
741     case SP_DROPS :
742       cf->drops_known = TRUE;
743       cf->drops = atoi(p);
744       p = q + 1;
745       q++;
746       nread--;
747       break;
748     case SP_ERROR_MSG :
749       msglen = atoi(p);
750       p = q + 1;
751       q++;
752       nread--;
753
754       /* Read the entire message.
755          XXX - if the child hasn't sent it all yet, this could cause us
756          to hang until they do. */
757       msg = g_malloc(msglen + 1);
758       r = msg;
759       while (msglen != 0) {
760         if (nread == 0) {
761           /* Read more. */
762           if ((nread = read(sync_pipe[READ], buffer, BUFSIZE)) <= 0)
763             break;
764           p = buffer;
765           q = buffer;
766         }
767         chars_to_copy = MIN(msglen, nread);
768         memcpy(r, q, chars_to_copy);
769         r += chars_to_copy;
770         q += chars_to_copy;
771         nread -= chars_to_copy;
772         msglen -= chars_to_copy;
773       }
774       *r = '\0';
775       simple_dialog(ESD_TYPE_WARN, NULL, msg);
776       g_free(msg);
777       break;
778     default :
779       q++;
780       nread--;
781       break;
782     } 
783   }
784
785   /* Read from the capture file the number of records the child told us
786      it added.
787      XXX - do something if this fails? */
788   switch (continue_tail_cap_file(cf, to_read, &err)) {
789
790   case READ_SUCCESS:
791   case READ_ERROR:
792     /* Just because we got an error, that doesn't mean we were unable
793        to read any of the file; we handle what we could get from the
794        file.
795
796        XXX - abort on a read error? */
797     break;
798
799   case READ_ABORTED:
800     /* Kill the child capture process; the user wants to exit, and we
801        shouldn't just leave it running. */
802 #ifdef _WIN32
803     /* XXX - kill it. */
804 #else
805     kill(fork_child, SIGTERM);  /* SIGTERM so it can clean up if necessary */
806 #endif
807     break;
808   }
809
810   /* restore pipe handler */
811 #ifdef _WIN32
812   cap_timer_id = gtk_timeout_add(1000, cap_timer_cb, NULL);
813 #else
814   cap_input_id = gtk_input_add_full (sync_pipe[READ],
815                                      GDK_INPUT_READ|GDK_INPUT_EXCEPTION,
816                                      cap_file_input_cb,
817                                      NULL,
818                                      (gpointer) cf,
819                                      NULL);
820 #endif
821 }
822
823 static void
824 wait_for_child(gboolean always_report)
825 {
826   int  wstatus;
827
828 #ifdef _WIN32
829   /* XXX - analyze the wait stuatus and display more information
830      in the dialog box? */
831   if (_cwait(&wstatus, child_process, _WAIT_CHILD) == -1) {
832     simple_dialog(ESD_TYPE_WARN, NULL, "Child capture process stopped unexpectedly");
833   }
834 #else
835   if (wait(&wstatus) != -1) {
836     if (WIFEXITED(wstatus)) {
837       /* The child exited; display its exit status, if it's not zero,
838          and even if it's zero if "always_report" is true. */
839       if (always_report || WEXITSTATUS(wstatus) != 0) {
840         simple_dialog(ESD_TYPE_WARN, NULL,
841                       "Child capture process exited: exit status %d",
842                       WEXITSTATUS(wstatus));
843       }
844     } else if (WIFSTOPPED(wstatus)) {
845       /* It stopped, rather than exiting.  "Should not happen." */
846       simple_dialog(ESD_TYPE_WARN, NULL,
847                     "Child capture process stopped: %s",
848                     signame(WSTOPSIG(wstatus)));
849     } else if (WIFSIGNALED(wstatus)) {
850       /* It died with a signal. */
851       simple_dialog(ESD_TYPE_WARN, NULL,
852                     "Child capture process died: %s%s",
853                     signame(WTERMSIG(wstatus)),
854                     WCOREDUMP(wstatus) ? " - core dumped" : "");
855     } else {
856       /* What?  It had to either have exited, or stopped, or died with
857          a signal; what happened here? */
858       simple_dialog(ESD_TYPE_WARN, NULL,
859                     "Child capture process died: wait status %#o", wstatus);
860     }
861   }
862 #endif
863 }
864
865 #ifndef _WIN32
866 static char *
867 signame(int sig)
868 {
869   char *sigmsg;
870   static char sigmsg_buf[6+1+3+1];
871
872   switch (sig) {
873
874   case SIGHUP:
875     sigmsg = "Hangup";
876     break;
877
878   case SIGINT:
879     sigmsg = "Interrupted";
880     break;
881
882   case SIGQUIT:
883     sigmsg = "Quit";
884     break;
885
886   case SIGILL:
887     sigmsg = "Illegal instruction";
888     break;
889
890   case SIGTRAP:
891     sigmsg = "Trace trap";
892     break;
893
894   case SIGABRT:
895     sigmsg = "Abort";
896     break;
897
898   case SIGFPE:
899     sigmsg = "Arithmetic exception";
900     break;
901
902   case SIGKILL:
903     sigmsg = "Killed";
904     break;
905
906   case SIGBUS:
907     sigmsg = "Bus error";
908     break;
909
910   case SIGSEGV:
911     sigmsg = "Segmentation violation";
912     break;
913
914   /* http://metalab.unc.edu/pub/Linux/docs/HOWTO/GCC-HOWTO 
915      Linux is POSIX compliant.  These are not POSIX-defined signals ---
916      ISO/IEC 9945-1:1990 (IEEE Std 1003.1-1990), paragraph B.3.3.1.1 sez:
917
918         ``The signals SIGBUS, SIGEMT, SIGIOT, SIGTRAP, and SIGSYS
919         were omitted from POSIX.1 because their behavior is
920         implementation dependent and could not be adequately catego-
921         rized.  Conforming implementations may deliver these sig-
922         nals, but must document the circumstances under which they
923         are delivered and note any restrictions concerning their
924         delivery.''
925
926      So we only check for SIGSYS on those systems that happen to
927      implement them (a system can be POSIX-compliant and implement
928      them, it's just that POSIX doesn't *require* a POSIX-compliant
929      system to implement them).
930    */
931
932 #ifdef SIGSYS
933   case SIGSYS:
934     sigmsg = "Bad system call";
935     break;
936 #endif
937
938   case SIGPIPE:
939     sigmsg = "Broken pipe";
940     break;
941
942   case SIGALRM:
943     sigmsg = "Alarm clock";
944     break;
945
946   case SIGTERM:
947     sigmsg = "Terminated";
948     break;
949
950   default:
951     sprintf(sigmsg_buf, "Signal %d", sig);
952     sigmsg = sigmsg_buf;
953     break;
954   }
955   return sigmsg;
956 }
957 #endif
958
959 /*
960  * Timeout, in milliseconds, for reads from the stream of captured packets.
961  */
962 #define CAP_READ_TIMEOUT        250
963
964 #ifndef _WIN32
965 /* Take carre of byte order in the libpcap headers read from pipes.
966  * (function taken from wiretap/libpcap.c) */
967 static void
968 adjust_header(loop_data *ld, struct pcap_hdr *hdr, struct pcaprec_hdr *rechdr)
969 {
970   if (ld->byte_swapped) {
971     /* Byte-swap the record header fields. */
972     rechdr->ts_sec = BSWAP32(rechdr->ts_sec);
973     rechdr->ts_usec = BSWAP32(rechdr->ts_usec);
974     rechdr->incl_len = BSWAP32(rechdr->incl_len);
975     rechdr->orig_len = BSWAP32(rechdr->orig_len);
976   }
977
978   /* In file format version 2.3, the "incl_len" and "orig_len" fields were
979      swapped, in order to match the BPF header layout.
980
981      Unfortunately, some files were, according to a comment in the "libpcap"
982      source, written with version 2.3 in their headers but without the
983      interchanged fields, so if "incl_len" is greater than "orig_len" - which
984      would make no sense - we assume that we need to swap them.  */
985   if (hdr->version_major == 2 &&
986       (hdr->version_minor < 3 ||
987        (hdr->version_minor == 3 && rechdr->incl_len > rechdr->orig_len))) {
988     guint32 temp;
989
990     temp = rechdr->orig_len;
991     rechdr->orig_len = rechdr->incl_len;
992     rechdr->incl_len = temp;
993   }
994 }
995
996 /* Mimic pcap_open_live() for pipe captures 
997  * We check if "pipename" is "-" (stdin) or a FIFO, open it, and read the
998  * header.
999  * N.B. : we can't read the libpcap formats used in RedHat 6.1 or SuSE 6.3
1000  * because we can't seek on pipes (see wiretap/libpcap.c for details) */
1001 static int
1002 pipe_open_live(char *pipename, struct pcap_hdr *hdr, loop_data *ld, char *ebuf)
1003 {
1004   struct stat pipe_stat;
1005   int         fd;
1006   guint32     magic;
1007   int         bytes_read, b;
1008
1009   if (strcmp(pipename, "-") == 0) fd = 0; /* read from stdin */
1010   else if (stat(pipename, &pipe_stat) == 0 && S_ISFIFO(pipe_stat.st_mode)) {
1011     if ((fd = open(pipename, O_RDONLY)) == -1) return -1;
1012   } else return -1;
1013
1014   ld->from_pipe = TRUE;
1015   /* read the pcap header */
1016   if (read(fd, &magic, sizeof magic) != sizeof magic) {
1017     close(fd);
1018     return -1;
1019   }
1020
1021   switch (magic) {
1022   case PCAP_MAGIC:
1023     /* Host that wrote it has our byte order, and was running
1024        a program using either standard or ss990417 libpcap. */
1025     ld->byte_swapped = FALSE;
1026     ld->modified = FALSE;
1027     break;
1028   case PCAP_MODIFIED_MAGIC:
1029     /* Host that wrote it has our byte order, but was running
1030        a program using either ss990915 or ss991029 libpcap. */
1031     ld->byte_swapped = FALSE;
1032     ld->modified = TRUE;
1033     break;
1034   case PCAP_SWAPPED_MAGIC:
1035     /* Host that wrote it has a byte order opposite to ours,
1036        and was running a program using either standard or
1037        ss990417 libpcap. */
1038     ld->byte_swapped = TRUE;
1039     ld->modified = FALSE;
1040     break;
1041   case PCAP_SWAPPED_MODIFIED_MAGIC:
1042     /* Host that wrote it out has a byte order opposite to
1043        ours, and was running a program using either ss990915
1044        or ss991029 libpcap. */
1045     ld->byte_swapped = TRUE;
1046     ld->modified = TRUE;
1047     break;
1048   default:
1049     /* Not a "libpcap" type we know about. */
1050     close(fd);
1051     return -1;
1052   }
1053
1054   /* Read the rest of the header */
1055   bytes_read = read(fd, hdr, sizeof(struct pcap_hdr));
1056   if (bytes_read <= 0) {
1057     close(fd);
1058     return -1;
1059   }
1060   while (bytes_read < sizeof(struct pcap_hdr))
1061   {
1062     b = read(fd, ((char *)&hdr)+bytes_read, sizeof(struct pcap_hdr) - bytes_read);
1063     if (b <= 0) {
1064       close(fd);
1065       return -1;
1066     }
1067     bytes_read += b;
1068   }
1069   if (ld->byte_swapped) {
1070     /* Byte-swap the header fields about which we care. */
1071     hdr->version_major = BSWAP16(hdr->version_major);
1072     hdr->version_minor = BSWAP16(hdr->version_minor);
1073     hdr->snaplen = BSWAP32(hdr->snaplen);
1074     hdr->network = BSWAP32(hdr->network);
1075   }
1076   if (hdr->version_major < 2) {
1077     close(fd);
1078     return -1;
1079   }
1080
1081   return fd;
1082 }
1083
1084 /* We read one record from the pipe, take care of byte order in the record
1085  * header, write the record in the capture file, and update capture statistics. */
1086 static int
1087 pipe_dispatch(int fd, loop_data *ld, struct pcap_hdr *hdr)
1088 {
1089   struct wtap_pkthdr whdr;
1090   struct pcaprec_modified_hdr rechdr;
1091   int bytes_to_read, bytes_read, b;
1092   u_char pd[WTAP_MAX_PACKET_SIZE];
1093   int err;
1094
1095   /* read the record header */
1096   bytes_to_read = ld->modified ? sizeof rechdr : sizeof rechdr.hdr;
1097   bytes_read = read(fd, &rechdr, bytes_to_read);
1098   if (bytes_read <= 0) {
1099     close(fd);
1100     ld->go = FALSE;
1101     return 0;
1102   }
1103   while (bytes_read < bytes_to_read)
1104   {
1105     b = read(fd, ((char *)&rechdr)+bytes_read, bytes_to_read - bytes_read);
1106     if (b <= 0) {
1107       close(fd);
1108       ld->go = FALSE;
1109       return 0;
1110     }
1111     bytes_read += b;
1112   }
1113   /* take care of byte order */
1114   adjust_header(ld, hdr, &rechdr.hdr);
1115   if (rechdr.hdr.incl_len > WTAP_MAX_PACKET_SIZE) {
1116     close(fd);
1117     ld->go = FALSE;
1118     return 0;
1119   }
1120   /* read the packet data */
1121   bytes_read = read(fd, pd, rechdr.hdr.incl_len);
1122   if (bytes_read <= 0) {
1123     close(fd);
1124     ld->go = FALSE;
1125     return 0;
1126   }
1127   while (bytes_read < rechdr.hdr.incl_len)
1128   {
1129     b = read(fd, pd+bytes_read, rechdr.hdr.incl_len - bytes_read);
1130     if (b <= 0) {
1131       close(fd);
1132       ld->go = FALSE;
1133       return 0;
1134     }
1135     bytes_read += b;
1136   }
1137   /* dump the packet data to the capture file */
1138   whdr.ts.tv_sec = rechdr.hdr.ts_sec;
1139   whdr.ts.tv_usec = rechdr.hdr.ts_usec;
1140   whdr.caplen = rechdr.hdr.incl_len;
1141   whdr.len = rechdr.hdr.orig_len;
1142   whdr.pkt_encap = ld->linktype;
1143   wtap_dump(ld->pdh, &whdr, NULL, pd, &err);
1144
1145   /* Set the initial payload to the packet length, and the initial
1146      captured payload to the capture length (other protocols may
1147      reduce them if their headers say they're less). */
1148   pi.len = whdr.len;
1149   pi.captured_len = whdr.caplen;
1150     
1151   /* update capture statistics */
1152   switch (ld->linktype) {
1153     case WTAP_ENCAP_ETHERNET:
1154       capture_eth(pd, 0, &ld->counts);
1155       break;
1156     case WTAP_ENCAP_FDDI:
1157     case WTAP_ENCAP_FDDI_BITSWAPPED:
1158       capture_fddi(pd, &ld->counts);
1159       break;
1160     case WTAP_ENCAP_TOKEN_RING:
1161       capture_tr(pd, 0, &ld->counts);
1162       break;
1163     case WTAP_ENCAP_NULL:
1164       capture_null(pd, &ld->counts);
1165       break;
1166     case WTAP_ENCAP_PPP:
1167       capture_ppp(pd, 0, &ld->counts);
1168       break;
1169     case WTAP_ENCAP_RAW_IP:
1170       capture_raw(pd, &ld->counts);
1171       break;
1172     case WTAP_ENCAP_LINUX_ATM_CLIP:
1173       capture_clip(pd, &ld->counts);
1174       break;
1175     case WTAP_ENCAP_IEEE_802_11:
1176       capture_ieee80211(pd,0,&ld->counts);
1177       break;
1178     /* XXX - FreeBSD may append 4-byte ATM pseudo-header to DLT_ATM_RFC1483,
1179        with LLC header following; we should implement it at some
1180        point. */
1181   }
1182
1183   return 1;
1184 }
1185 #endif
1186
1187 /*
1188  * This needs to be static, so that the SIGUSR1 handler can clear the "go"
1189  * flag.
1190  */
1191 static loop_data   ld;
1192
1193 /* Do the low-level work of a capture.
1194    Returns TRUE if it succeeds, FALSE otherwise. */
1195 int
1196 capture(gboolean *stats_known, struct pcap_stat *stats)
1197 {
1198   GtkWidget  *cap_w, *main_vb, *stop_bt, *counts_tb;
1199   pcap_t     *pch;
1200   int         pcap_encap;
1201   int         snaplen;
1202   gchar       err_str[PCAP_ERRBUF_SIZE], label_str[64];
1203   bpf_u_int32 netnum, netmask;
1204   struct bpf_program fcode;
1205   time_t      upd_time, cur_time;
1206   int         err, inpkts, i;
1207   static const char capstart_msg = SP_CAPSTART;
1208   char        errmsg[4096+1];
1209 #ifndef _WIN32
1210   static const char ppamsg[] = "can't find PPA for ";
1211   char       *libpcap_warn;
1212 #endif
1213   fd_set      set1;
1214   struct timeval timeout;
1215 #ifdef MUST_DO_SELECT
1216   int         pcap_fd = 0;
1217 #endif
1218 #ifdef _WIN32 
1219   WORD wVersionRequested; 
1220   WSADATA wsaData; 
1221 #endif
1222 #ifndef _WIN32
1223   int         pipe_fd = -1;
1224   struct pcap_hdr hdr;
1225 #endif
1226   struct {
1227       const gchar *title;
1228       gint *value_ptr;
1229       GtkWidget *label, *value, *percent;
1230   } counts[] = {
1231       { "Total", &ld.counts.total },
1232       { "SCTP", &ld.counts.sctp },
1233       { "TCP", &ld.counts.tcp },
1234       { "UDP", &ld.counts.udp },
1235       { "ICMP", &ld.counts.icmp },
1236       { "OSPF", &ld.counts.ospf },
1237       { "GRE", &ld.counts.gre },
1238       { "NetBIOS", &ld.counts.netbios },
1239       { "IPX", &ld.counts.ipx },
1240       { "VINES", &ld.counts.vines },
1241       { "Other", &ld.counts.other }
1242   };
1243
1244 #define N_COUNTS (sizeof counts / sizeof counts[0])
1245
1246   /* Initialize Windows Socket if we are in a WIN32 OS 
1247      This needs to be done before querying the interface for network/netmask */
1248 #ifdef _WIN32 
1249   wVersionRequested = MAKEWORD( 1, 1 ); 
1250   err = WSAStartup( wVersionRequested, &wsaData ); 
1251   if (err!=0) { 
1252     snprintf(errmsg, sizeof errmsg, 
1253       "Couldn't initialize Windows Sockets."); 
1254         pch=NULL; 
1255     goto error; 
1256   } 
1257 #endif 
1258
1259   ld.go             = TRUE;
1260   ld.counts.total   = 0;
1261   ld.max            = cfile.count;
1262   ld.err            = 0;        /* no error seen yet */
1263   ld.linktype       = WTAP_ENCAP_UNKNOWN;
1264   ld.from_pipe      = FALSE;
1265   ld.sync_packets   = 0;
1266   ld.counts.sctp    = 0;
1267   ld.counts.tcp     = 0;
1268   ld.counts.udp     = 0;
1269   ld.counts.icmp    = 0;
1270   ld.counts.ospf    = 0;
1271   ld.counts.gre     = 0;
1272   ld.counts.ipx     = 0;
1273   ld.counts.netbios = 0;
1274   ld.counts.vines   = 0;
1275   ld.counts.other   = 0;
1276   ld.pdh            = NULL;
1277
1278   /* We haven't yet gotten the capture statistics. */
1279   *stats_known      = FALSE;
1280
1281   /* Open the network interface to capture from it. */
1282   pch = pcap_open_live(cfile.iface, cfile.snap, promisc_mode,
1283                         CAP_READ_TIMEOUT, err_str);
1284
1285   if (pch == NULL) {
1286 #ifdef _WIN32
1287     /* Well, we couldn't start the capture.
1288        If this is a child process that does the capturing in sync
1289        mode or fork mode, it shouldn't do any UI stuff until we pop up the
1290        capture-progress window, and, since we couldn't start the
1291        capture, we haven't popped it up. */
1292     if (!capture_child) {
1293       while (gtk_events_pending()) gtk_main_iteration();
1294     }
1295
1296     /* On Win32 OSes, the capture devices are probably available to all
1297        users; don't warn about permissions problems.
1298
1299        Do, however, warn that Token Ring and PPP devices aren't supported. */
1300     snprintf(errmsg, sizeof errmsg,
1301         "The capture session could not be initiated (%s).\n"
1302         "Please check that you have the proper interface specified.\n"
1303         "\n"
1304         "Note that the driver Ethereal uses for packet capture on Windows\n"
1305         "doesn't support capturing on Token Ring interfaces, and doesn't\n"
1306         "support capturing on PPP/WAN interfaces in Windows NT/2000.\n",
1307         err_str);
1308     goto error;
1309 #else
1310     /* try to open cfile.iface as a pipe */
1311     pipe_fd = pipe_open_live(cfile.iface, &hdr, &ld, err_str);
1312
1313     if (pipe_fd == -1) {
1314       /* Well, we couldn't start the capture.
1315          If this is a child process that does the capturing in sync
1316          mode or fork mode, it shouldn't do any UI stuff until we pop up the
1317          capture-progress window, and, since we couldn't start the
1318          capture, we haven't popped it up. */
1319       if (!capture_child) {
1320         while (gtk_events_pending()) gtk_main_iteration();
1321       }
1322
1323       /* If we got a "can't find PPA for XXX" message, warn the user (who
1324          is running Ethereal on HP-UX) that they don't have a version
1325          of libpcap patched to properly handle HP-UX (the patched version
1326          says "can't find /dev/dlpi PPA for XXX" rather than "can't find
1327          PPA for XXX"). */
1328       if (strncmp(err_str, ppamsg, sizeof ppamsg - 1) == 0)
1329         libpcap_warn =
1330           "\n\n"
1331           "You are running Ethereal with a version of the libpcap library\n"
1332           "that doesn't handle HP-UX network devices well; this means that\n"
1333           "Ethereal may not be able to capture packets.\n"
1334           "\n"
1335           "To fix this, you will need to download the source to Ethereal\n"
1336           "from www.ethereal.com if you have not already done so, read\n"
1337           "the instructions in the \"README.hpux\" file in the source\n"
1338           "distribution, download the source to libpcap if you have not\n"
1339           "already done so, patch libpcap as per the instructions, rebuild\n"
1340           "and install libpcap, and then build Ethereal (if you have already\n"
1341           "built Ethereal from source, do a \"make distclean\" and re-run\n"
1342           "configure before building).";
1343       else
1344         libpcap_warn = "";
1345       snprintf(errmsg, sizeof errmsg,
1346           "The capture session could not be initiated (%s).\n"
1347           "Please check to make sure you have sufficient permissions, and that\n"
1348           "you have the proper interface or pipe specified.%s", err_str,
1349           libpcap_warn);
1350       goto error;
1351     }
1352 #endif
1353   }
1354
1355   /* capture filters only work on real interfaces */
1356   if (cfile.cfilter && !ld.from_pipe) {
1357     /* A capture filter was specified; set it up. */
1358     if (pcap_lookupnet (cfile.iface, &netnum, &netmask, err_str) < 0) {
1359       /*
1360        * Well, we can't get the netmask for this interface; it's used
1361        * only for filters that check for broadcast IP addresses, so
1362        * we just punt and use 0.  It might be nice to warn the user,
1363        * but that's a pain in a GUI application, as it'd involve popping
1364        * up a message box, and it's not clear how often this would make
1365        * a difference (only filters that check for IP broadcast addresses
1366        * use the netmask).
1367        */
1368       netmask = 0;
1369     }
1370     if (pcap_compile(pch, &fcode, cfile.cfilter, 1, netmask) < 0) {
1371       snprintf(errmsg, sizeof errmsg, "Unable to parse filter string (%s).",
1372         pcap_geterr(pch));
1373       goto error;
1374     }
1375     if (pcap_setfilter(pch, &fcode) < 0) {
1376       snprintf(errmsg, sizeof errmsg, "Can't install filter (%s).",
1377         pcap_geterr(pch));
1378       goto error;
1379     }
1380   }
1381
1382   /* Set up to write to the capture file. */
1383 #ifndef _WIN32
1384   if (ld.from_pipe) {
1385     pcap_encap = hdr.network;
1386     snaplen = hdr.snaplen;
1387   } else
1388 #endif
1389   {
1390     pcap_encap = pcap_datalink(pch);
1391     snaplen = pcap_snapshot(pch);
1392   }
1393   ld.linktype = wtap_pcap_encap_to_wtap_encap(pcap_encap);
1394   if (ld.linktype == WTAP_ENCAP_UNKNOWN) {
1395     snprintf(errmsg, sizeof errmsg,
1396         "The network you're capturing from is of a type"
1397         " that Ethereal doesn't support (data link type %d).", pcap_encap);
1398     goto error;
1399   }
1400   ld.pdh = wtap_dump_fdopen(cfile.save_file_fd, WTAP_FILE_PCAP,
1401       ld.linktype, snaplen, &err);
1402
1403   if (ld.pdh == NULL) {
1404     /* We couldn't set up to write to the capture file. */
1405     switch (err) {
1406
1407     case WTAP_ERR_CANT_OPEN:
1408       strcpy(errmsg, "The file to which the capture would be saved"
1409                " couldn't be created for some unknown reason.");
1410       break;
1411
1412     case WTAP_ERR_SHORT_WRITE:
1413       strcpy(errmsg, "A full header couldn't be written to the file"
1414                " to which the capture would be saved.");
1415       break;
1416
1417     default:
1418       if (err < 0) {
1419         snprintf(errmsg, sizeof(errmsg),
1420                      "The file to which the capture would be"
1421                      " saved (\"%s\") could not be opened: Error %d.",
1422                         cfile.save_file, err);
1423       } else {
1424         snprintf(errmsg, sizeof(errmsg),
1425                      "The file to which the capture would be"
1426                      " saved (\"%s\") could not be opened: %s.",
1427                         cfile.save_file, strerror(err));
1428       }
1429       break;
1430     }
1431     goto error;
1432   }
1433
1434   /* XXX - capture SIGTERM and close the capture, in case we're on a
1435      Linux 2.0[.x] system and you have to explicitly close the capture
1436      stream in order to turn promiscuous mode off?  We need to do that
1437      in other places as well - and I don't think that works all the
1438      time in any case, due to libpcap bugs. */
1439
1440   if (capture_child) {
1441     /* Well, we should be able to start capturing.
1442
1443        This is the child process for a sync mode capture, so sync out
1444        the capture file, so the header makes it to the file system,
1445        and send a "capture started successfully and capture file created"
1446        message to our parent so that they'll open the capture file and
1447        update its windows to indicate that we have a live capture in
1448        progress. */
1449     fflush(wtap_dump_file(ld.pdh));
1450     write(1, &capstart_msg, 1);
1451   }
1452
1453   cap_w = gtk_window_new(GTK_WINDOW_TOPLEVEL);
1454   gtk_window_set_title(GTK_WINDOW(cap_w), "Ethereal: Capture");
1455   gtk_window_set_modal(GTK_WINDOW(cap_w), TRUE);
1456
1457   /* Container for capture display widgets */
1458   main_vb = gtk_vbox_new(FALSE, 1);
1459   gtk_container_border_width(GTK_CONTAINER(main_vb), 5);
1460   gtk_container_add(GTK_CONTAINER(cap_w), main_vb);
1461   gtk_widget_show(main_vb);
1462
1463   /* Individual statistic elements */
1464   counts_tb = gtk_table_new(N_COUNTS, 3, TRUE);
1465   gtk_box_pack_start(GTK_BOX(main_vb), counts_tb, TRUE, TRUE, 3);
1466   gtk_widget_show(counts_tb);
1467
1468   for (i = 0; i < N_COUNTS; i++) {
1469       counts[i].label = gtk_label_new(counts[i].title);
1470       gtk_misc_set_alignment(GTK_MISC(counts[i].label), 0.0f, 0.0f);
1471
1472       counts[i].value = gtk_label_new("0");
1473       gtk_misc_set_alignment(GTK_MISC(counts[i].value), 0.0f, 0.0f);
1474
1475       counts[i].percent = gtk_label_new("0.0%");
1476       gtk_misc_set_alignment(GTK_MISC(counts[i].percent), 0.0f, 0.0f);
1477
1478       gtk_table_attach_defaults(GTK_TABLE(counts_tb),
1479                                 counts[i].label, 0, 1, i, i + 1);
1480
1481       gtk_table_attach(GTK_TABLE(counts_tb),
1482                        counts[i].value,
1483                        1, 2, i, i + 1, 0, 0, 5, 0);
1484
1485       gtk_table_attach_defaults(GTK_TABLE(counts_tb),
1486                                 counts[i].percent, 2, 3, i, i + 1);
1487
1488       gtk_widget_show(counts[i].label);
1489       gtk_widget_show(counts[i].value);
1490       gtk_widget_show(counts[i].percent);
1491   }
1492
1493   /* allow user to either click a stop button, or the close button on
1494         the window to stop a capture in progress. */
1495   stop_bt = gtk_button_new_with_label ("Stop");
1496   gtk_signal_connect(GTK_OBJECT(stop_bt), "clicked",
1497     GTK_SIGNAL_FUNC(capture_stop_cb), (gpointer) &ld);
1498   gtk_signal_connect(GTK_OBJECT(cap_w), "delete_event",
1499         GTK_SIGNAL_FUNC(capture_delete_cb), (gpointer) &ld);
1500   gtk_box_pack_end(GTK_BOX(main_vb), stop_bt, FALSE, FALSE, 3);
1501   GTK_WIDGET_SET_FLAGS(stop_bt, GTK_CAN_DEFAULT);
1502   gtk_widget_grab_default(stop_bt);
1503   GTK_WIDGET_SET_FLAGS(stop_bt, GTK_CAN_DEFAULT);
1504   gtk_widget_grab_default(stop_bt);
1505   gtk_widget_show(stop_bt);
1506
1507   gtk_widget_show(cap_w);
1508
1509   upd_time = time(NULL);
1510 #ifdef MUST_DO_SELECT
1511   if (!ld.from_pipe) pcap_fd = pcap_fileno(pch);
1512 #endif
1513
1514 #ifndef _WIN32
1515   /*
1516    * Catch SIGUSR1, so that we exit cleanly if the parent process
1517    * kills us with it due to the user selecting "Capture->Stop".
1518    */
1519   signal(SIGUSR1, stop_capture);
1520 #endif
1521   while (ld.go) {
1522     while (gtk_events_pending()) gtk_main_iteration();
1523
1524 #ifndef _WIN32
1525     if (ld.from_pipe) {
1526       FD_ZERO(&set1);
1527       FD_SET(pipe_fd, &set1);
1528       timeout.tv_sec = 0;
1529       timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1530       if (select(pipe_fd+1, &set1, NULL, NULL, &timeout) != 0) {
1531         /*
1532          * "select()" says we can read from the pipe without blocking; go for
1533          * it. We are not sure we can read a whole record, but at least the
1534          * begninning of one. pipe_dispatch() will block reading the whole
1535          * record.
1536          */
1537         inpkts = pipe_dispatch(pipe_fd, &ld, &hdr);
1538       } else
1539         inpkts = 0;
1540     }
1541     else
1542 #endif
1543     {
1544 #ifdef MUST_DO_SELECT
1545       /*
1546        * Sigh.  The semantics of the read timeout argument to
1547        * "pcap_open_live()" aren't particularly well specified by
1548        * the "pcap" man page - at least with the BSD BPF code, the
1549        * intent appears to be, at least in part, a way of cutting
1550        * down the number of reads done on a capture, by blocking
1551        * until the buffer fills or a timer expires - and the Linux
1552        * libpcap doesn't actually support it, so we can't use it
1553        * to break out of the "pcap_dispatch()" every 1/4 of a second
1554        * or so.  Linux's libpcap is not the only libpcap that doesn't
1555        * support the read timeout.
1556        *
1557        * Furthermore, at least on Solaris, the bufmod STREAMS module's
1558        * read timeout won't go off if no data has arrived, i.e. it cannot
1559        * be used to guarantee that a read from a DLPI stream will return
1560        * within a specified amount of time regardless of whether any
1561        * data arrives or not.
1562        *
1563        * Thus, on all platforms other than BSD, we do a "select()" on the
1564        * file descriptor for the capture, with a timeout of CAP_READ_TIMEOUT
1565        * milliseconds, or CAP_READ_TIMEOUT*1000 microseconds.
1566        *
1567        * "select()", on BPF devices, doesn't work as you might expect;
1568        * at least on some versions of some flavors of BSD, the timer
1569        * doesn't start until a read is done, so it won't expire if
1570        * only a "select()" or "poll()" is posted.
1571        */
1572       FD_ZERO(&set1);
1573       FD_SET(pcap_fd, &set1);
1574       timeout.tv_sec = 0;
1575       timeout.tv_usec = CAP_READ_TIMEOUT*1000;
1576       if (select(pcap_fd+1, &set1, NULL, NULL, &timeout) != 0) {
1577         /*
1578          * "select()" says we can read from it without blocking; go for
1579          * it.
1580          */
1581         inpkts = pcap_dispatch(pch, 1, capture_pcap_cb, (u_char *) &ld);
1582       } else
1583         inpkts = 0;
1584 #else
1585       inpkts = pcap_dispatch(pch, 1, capture_pcap_cb, (u_char *) &ld);
1586 #endif
1587     }
1588     if (inpkts > 0)
1589       ld.sync_packets += inpkts;
1590     /* Only update once a second so as not to overload slow displays */
1591     cur_time = time(NULL);
1592     if (cur_time > upd_time) {
1593       upd_time = cur_time;
1594
1595       for (i = 0; i < N_COUNTS; i++) {
1596           snprintf(label_str, sizeof(label_str), "%d",
1597                    *counts[i].value_ptr);
1598
1599           gtk_label_set(GTK_LABEL(counts[i].value), label_str);
1600
1601           snprintf(label_str, sizeof(label_str), "(%.1f%%)",
1602                    pct(*counts[i].value_ptr, ld.counts.total));
1603
1604           gtk_label_set(GTK_LABEL(counts[i].percent), label_str);
1605       }
1606
1607       /* do sync here, too */
1608       fflush(wtap_dump_file(ld.pdh));
1609       if (capture_child && ld.sync_packets) {
1610         /* This is the child process for a sync mode capture, so send
1611            our parent a message saying we've written out "ld.sync_packets"
1612            packets to the capture file. */
1613         char tmp[20];
1614         sprintf(tmp, "%d%c", ld.sync_packets, SP_PACKET_COUNT);
1615         write(1, tmp, strlen(tmp));
1616         ld.sync_packets = 0;
1617       }
1618     }
1619   }
1620     
1621   if (ld.err != 0) {
1622     get_capture_file_io_error(errmsg, sizeof(errmsg), cfile.save_file, ld.err,
1623                               FALSE);
1624     if (capture_child) {
1625       /* Tell the parent, so that they can pop up the message;
1626          we're going to exit, so if we try to pop it up, either
1627          it won't pop up or it'll disappear as soon as we exit. */
1628       send_errmsg_to_parent(errmsg);
1629     } else {
1630      /* Just pop up the message ourselves. */
1631      simple_dialog(ESD_TYPE_WARN, NULL, "%s", errmsg);
1632     }
1633
1634     /* A write failed, so we've already told the user there's a problem;
1635        if the close fails, there's no point in telling them about that
1636        as well. */
1637     wtap_dump_close(ld.pdh, &err);
1638   } else {
1639     if (!wtap_dump_close(ld.pdh, &err)) {
1640       get_capture_file_io_error(errmsg, sizeof(errmsg), cfile.save_file, err,
1641                                 TRUE);
1642       if (capture_child) {
1643         /* Tell the parent, so that they can pop up the message;
1644            we're going to exit, so if we try to pop it up, either
1645            it won't pop up or it'll disappear as soon as we exit. */
1646         send_errmsg_to_parent(errmsg);
1647       } else {
1648        /* Just pop up the message ourselves. */
1649        simple_dialog(ESD_TYPE_WARN, NULL, "%s", errmsg);
1650       }
1651     }
1652   }
1653 #ifndef _WIN32
1654   if (ld.from_pipe)
1655     close(pipe_fd);
1656   else
1657 #endif
1658   {
1659     /* Get the capture statistics, so we know how many packets were
1660        dropped. */
1661     if (pcap_stats(pch, stats) >= 0) {
1662       *stats_known = TRUE;
1663       if (capture_child) {
1664         /* Let the parent process know. */
1665         char tmp[20];
1666         sprintf(tmp, "%d%c", stats->ps_drop, SP_DROPS);
1667         write(1, tmp, strlen(tmp));
1668       }
1669     } else {
1670       snprintf(errmsg, sizeof(errmsg),
1671                 "Can't get packet-drop statistics: %s",
1672                 pcap_geterr(pch));
1673       if (capture_child) {
1674         /* Tell the parent, so that they can pop up the message;
1675            we're going to exit, so if we try to pop it up, either
1676            it won't pop up or it'll disappear as soon as we exit. */
1677         send_errmsg_to_parent(errmsg);
1678       } else {
1679        /* Just pop up the message ourselves. */
1680        simple_dialog(ESD_TYPE_WARN, NULL, "%s", errmsg);
1681       }
1682     }
1683     pcap_close(pch);
1684   }
1685
1686 #ifdef WIN32
1687   /* Shut down windows sockets */
1688   WSACleanup();
1689 #endif
1690
1691   gtk_grab_remove(GTK_WIDGET(cap_w));
1692   gtk_widget_destroy(GTK_WIDGET(cap_w));
1693
1694   return TRUE;
1695
1696 error:
1697   /* We can't use the save file, and we have no wtap_dump stream
1698      to close in order to close it, so close the FD directly. */
1699   close(cfile.save_file_fd);
1700
1701   /* We couldn't even start the capture, so get rid of the capture
1702      file. */
1703   unlink(cfile.save_file); /* silently ignore error */
1704   g_free(cfile.save_file);
1705   cfile.save_file = NULL;
1706   if (capture_child) {
1707     /* This is the child process for a sync mode capture.
1708        Send the error message to our parent, so they can display a
1709        dialog box containing it. */
1710     send_errmsg_to_parent(errmsg);
1711   } else {
1712     /* Display the dialog box ourselves; there's no parent. */
1713     simple_dialog(ESD_TYPE_CRIT, NULL, "%s", errmsg);
1714   }
1715   if (pch != NULL && !ld.from_pipe)
1716     pcap_close(pch);
1717
1718   return FALSE;
1719 }
1720
1721 static void
1722 get_capture_file_io_error(char *errmsg, int errmsglen, const char *fname,
1723                           int err, gboolean is_close)
1724 {
1725   switch (err) {
1726
1727   case ENOSPC:
1728     snprintf(errmsg, errmsglen,
1729                 "Not all the packets could be written to the file"
1730                 " to which the capture was being saved\n"
1731                 "(\"%s\") because there is no space left on the file system\n"
1732                 "on which that file resides.",
1733                 fname);
1734     break;
1735
1736 #ifdef EDQUOT
1737   case EDQUOT:
1738     snprintf(errmsg, errmsglen,
1739                 "Not all the packets could be written to the file"
1740                 " to which the capture was being saved\n"
1741                 "(\"%s\") because you are too close to, or over,"
1742                 " your disk quota\n"
1743                 "on the file system on which that file resides.",
1744                 fname);
1745   break;
1746 #endif
1747
1748   case WTAP_ERR_CANT_CLOSE:
1749     snprintf(errmsg, errmsglen,
1750                 "The file to which the capture was being saved"
1751                 " couldn't be closed for some unknown reason.");
1752     break;
1753
1754   case WTAP_ERR_SHORT_WRITE:
1755     snprintf(errmsg, errmsglen,
1756                 "Not all the packets could be written to the file"
1757                 " to which the capture was being saved\n"
1758                 "(\"%s\").",
1759                 fname);
1760     break;
1761
1762   default:
1763     if (is_close) {
1764       snprintf(errmsg, errmsglen,
1765                 "The file to which the capture was being saved\n"
1766                 "(\"%s\") could not be closed: %s.",
1767                 fname, wtap_strerror(err));
1768     } else {
1769       snprintf(errmsg, errmsglen,
1770                 "An error occurred while writing to the file"
1771                 " to which the capture was being saved\n"
1772                 "(\"%s\"): %s.",
1773                 fname, wtap_strerror(err));
1774     }
1775     break;
1776   }
1777 }
1778
1779 static void
1780 send_errmsg_to_parent(const char *errmsg)
1781 {
1782     int msglen = strlen(errmsg);
1783     char lenbuf[10+1+1];
1784
1785     sprintf(lenbuf, "%u%c", msglen, SP_ERROR_MSG);
1786     write(1, lenbuf, strlen(lenbuf));
1787     write(1, errmsg, msglen);
1788 }
1789
1790 static float
1791 pct(gint num, gint denom) {
1792   if (denom) {
1793     return (float) num * 100.0 / (float) denom;
1794   } else {
1795     return 0.0;
1796   }
1797 }
1798
1799 static void
1800 stop_capture(int signo)
1801 {
1802   ld.go = FALSE;
1803 }
1804
1805 static void
1806 capture_delete_cb(GtkWidget *w, GdkEvent *event, gpointer data) {
1807   capture_stop_cb(NULL, data);
1808 }
1809
1810 static void
1811 capture_stop_cb(GtkWidget *w, gpointer data) {
1812   loop_data *ld = (loop_data *) data;
1813   
1814   ld->go = FALSE;
1815 }
1816
1817 void
1818 capture_stop(void)
1819 {
1820   /*
1821    * XXX - find some way of signaling the child in Win32.
1822    */
1823 #ifndef _WIN32
1824   if (fork_child != -1)
1825       kill(fork_child, SIGUSR1);
1826 #endif
1827 }
1828
1829 static void
1830 capture_pcap_cb(u_char *user, const struct pcap_pkthdr *phdr,
1831   const u_char *pd) {
1832   struct wtap_pkthdr whdr;
1833   loop_data *ld = (loop_data *) user;
1834   int err;
1835
1836   if ((++ld->counts.total >= ld->max) && (ld->max > 0)) 
1837   {
1838      ld->go = FALSE;
1839   }
1840   if (ld->pdh) {
1841      /* "phdr->ts" may not necessarily be a "struct timeval" - it may
1842         be a "struct bpf_timeval", with member sizes wired to 32
1843         bits - and we may go that way ourselves in the future, so
1844         copy the members individually. */
1845      whdr.ts.tv_sec = phdr->ts.tv_sec;
1846      whdr.ts.tv_usec = phdr->ts.tv_usec;
1847      whdr.caplen = phdr->caplen;
1848      whdr.len = phdr->len;
1849      whdr.pkt_encap = ld->linktype;
1850
1851      /* If this fails, set "ld->go" to FALSE, to stop the capture, and set
1852         "ld->err" to the error. */
1853      if (!wtap_dump(ld->pdh, &whdr, NULL, pd, &err)) {
1854        ld->go = FALSE;
1855        ld->err = err;
1856      }
1857   }
1858
1859   /* Set the initial payload to the packet length, and the initial
1860      captured payload to the capture length (other protocols may
1861      reduce them if their headers say they're less). */
1862   pi.len = phdr->len;
1863   pi.captured_len = phdr->caplen;
1864     
1865   switch (ld->linktype) {
1866     case WTAP_ENCAP_ETHERNET:
1867       capture_eth(pd, 0, &ld->counts);
1868       break;
1869     case WTAP_ENCAP_FDDI:
1870     case WTAP_ENCAP_FDDI_BITSWAPPED:
1871       capture_fddi(pd, &ld->counts);
1872       break;
1873     case WTAP_ENCAP_TOKEN_RING:
1874       capture_tr(pd, 0, &ld->counts);
1875       break;
1876     case WTAP_ENCAP_NULL:
1877       capture_null(pd, &ld->counts);
1878       break;
1879     case WTAP_ENCAP_PPP:
1880       capture_ppp(pd, 0, &ld->counts);
1881       break;
1882     case WTAP_ENCAP_RAW_IP:
1883       capture_raw(pd, &ld->counts);
1884       break;
1885     case WTAP_ENCAP_SLL:
1886       capture_sll(pd, &ld->counts);
1887       break;
1888     case WTAP_ENCAP_LINUX_ATM_CLIP:
1889       capture_clip(pd, &ld->counts);
1890       break;
1891     /* XXX - FreeBSD may append 4-byte ATM pseudo-header to DLT_ATM_RFC1483,
1892        with LLC header following; we should implement it at some
1893        point. */
1894   }
1895 }
1896
1897 #endif /* HAVE_LIBPCAP */