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