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