SIGINT is, at least as I read some Microsoft documentation, not
[obnox/wireshark/wip.git] / tethereal.c
1 /* tethereal.c
2  *
3  * $Id: tethereal.c,v 1.145 2002/06/28 09:47:36 guy Exp $
4  *
5  * Ethereal - Network traffic analyzer
6  * By Gerald Combs <gerald@ethereal.com>
7  * Copyright 1998 Gerald Combs
8  *
9  * Text-mode variant, by Gilbert Ramirez <gram@alumni.rice.edu>
10  * and Guy Harris <guy@alum.mit.edu>.
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * as published by the Free Software Foundation; either version 2
15  * of the License, or (at your option) any later version.
16  * 
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  * 
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25  */
26
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <ctype.h>
35 #include <locale.h>
36 #include <limits.h>
37
38 #ifdef HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif
41
42 #include <errno.h>
43
44 #ifdef HAVE_SYS_TYPES_H
45 #include <sys/types.h>
46 #endif
47
48 #ifdef HAVE_FCNTL_H
49 #include <fcntl.h>
50 #endif
51
52 #include <signal.h>
53
54 #ifdef HAVE_LIBPCAP
55 #include <pcap.h>
56 #include <setjmp.h>
57 #endif
58
59 #ifdef HAVE_LIBZ
60 #include <zlib.h>       /* to get the libz version number */
61 #endif
62
63 #ifdef NEED_SNPRINTF_H
64 # include "snprintf.h"
65 #endif
66
67 #ifdef HAVE_UCD_SNMP_VERSION_H
68 #include <ucd-snmp/version.h>
69 #endif /* HAVE_UCD_SNMP_VERSION_H */
70
71 #ifdef NEED_STRERROR_H
72 #include "strerror.h"
73 #endif
74
75 #ifdef NEED_GETOPT_H
76 #include "getopt.h"
77 #endif
78
79 #include <glib.h>
80 #include <epan/epan.h>
81 #include <epan/filesystem.h>
82
83 #include "globals.h"
84 #include <epan/timestamp.h>
85 #include <epan/packet.h>
86 #include "file.h"
87 #include "prefs.h"
88 #include "column.h"
89 #include "print.h"
90 #include <epan/resolv.h>
91 #include "util.h"
92 #ifdef HAVE_LIBPCAP
93 #include "pcap-util.h"
94 #endif
95 #include <epan/conversation.h>
96 #include <epan/plugins.h>
97 #include "register.h"
98 #include "conditions.h"
99 #include "capture_stop_conditions.h"
100 #include "ringbuffer.h"
101 #include <epan/epan_dissect.h>
102
103 #ifdef HAVE_LIBPCAP
104 #include <wiretap/wtap-capture.h>
105 #endif
106
107 #ifdef WIN32
108 #include "capture-wpcap.h"
109 #endif
110
111 static guint32 firstsec, firstusec;
112 static guint32 prevsec, prevusec;
113 static GString *comp_info_str;
114 static gboolean quiet;
115 static gboolean verbose;
116 static gboolean print_hex;
117 static gboolean line_buffered;
118
119 #ifdef HAVE_LIBPCAP
120 typedef struct _loop_data {
121   gboolean       go;           /* TRUE as long as we're supposed to keep capturing */
122   gint           linktype;
123   pcap_t        *pch;
124   wtap_dumper   *pdh;
125   jmp_buf        stopenv;
126   gboolean       output_to_pipe;
127   int            packet_count;
128 } loop_data;
129
130 static loop_data ld;
131
132 static int capture(int);
133 static void capture_pcap_cb(u_char *, const struct pcap_pkthdr *,
134   const u_char *);
135 #ifdef _WIN32
136 static BOOL WINAPI capture_cleanup(DWORD);
137 #else /* _WIN32 */
138 static void capture_cleanup(int);
139 #endif /* _WIN32 */
140 #endif /* HAVE_LIBPCAP */
141
142 typedef struct {
143   capture_file *cf;
144   wtap_dumper *pdh;
145 } cb_args_t;
146
147 static int load_cap_file(capture_file *, int);
148 static void wtap_dispatch_cb_write(u_char *, const struct wtap_pkthdr *, long,
149     union wtap_pseudo_header *, const u_char *);
150 static void show_capture_file_io_error(const char *, int, gboolean);
151 static void wtap_dispatch_cb_print(u_char *, const struct wtap_pkthdr *, long,
152     union wtap_pseudo_header *, const u_char *);
153
154 capture_file cfile;
155 ts_type timestamp_type = RELATIVE;
156 #ifdef HAVE_LIBPCAP
157 typedef struct {
158         int snaplen;                    /* Maximum captured packet length */
159         int promisc_mode;               /* Capture in promiscuous mode */
160         int autostop_count;             /* Maximum packet count */
161         gboolean has_autostop_duration; /* TRUE if maximum capture duration
162                                            is specified */
163         gint32 autostop_duration;       /* Maximum capture duration */
164         gboolean has_autostop_filesize; /* TRUE if maximum capture file size
165                                            is specified */
166         gint32 autostop_filesize;       /* Maximum capture file size */
167         gboolean ringbuffer_on;         /* TRUE if ring buffer in use */
168         guint32 ringbuffer_num_files;   /* Number of ring buffer files */
169 } capture_options;
170
171 static capture_options capture_opts = {
172         WTAP_MAX_PACKET_SIZE,           /* snapshot length - default is
173                                            infinite, in effect */
174         TRUE,                           /* promiscuous mode is the default */
175         0,                              /* max packet count - default is 0,
176                                            meaning infinite */
177         FALSE,                          /* maximum capture duration not
178                                            specified by default */
179         0,                              /* maximum capture duration */
180         FALSE,                          /* maximum capture file size not
181                                            specified by default */
182         0,                              /* maximum capture file size */
183         FALSE,                          /* ring buffer off by default */
184         RINGBUFFER_MIN_NUM_FILES        /* default number of ring buffer
185                                            files */
186 };
187 #endif
188
189 static void 
190 print_usage(gboolean print_ver)
191 {
192   int i;
193
194   if (print_ver) {
195     fprintf(stderr, "This is GNU t%s %s, compiled %s\n", PACKAGE, VERSION,
196         comp_info_str->str);
197   }
198 #ifdef HAVE_LIBPCAP
199   fprintf(stderr, "\nt%s [ -DvVhqlp ] [ -a <capture autostop condition> ] ...\n",
200           PACKAGE);
201   fprintf(stderr, "\t[ -b <number of ring buffer files> ] [ -c <count> ]\n");
202   fprintf(stderr, "\t[ -f <capture filter> ] [ -F <output file type> ]\n");
203   fprintf(stderr, "\t[ -i <interface> ] [ -n ] [ -N <resolving> ]\n");
204   fprintf(stderr, "\t[ -o <preference setting> ] ... [ -r <infile> ] [ -R <read filter> ]\n");
205   fprintf(stderr, "\t[ -s <snaplen> ] [ -t <time stamp format> ] [ -w <savefile> ] [ -x ]\n");
206 #else
207   fprintf(stderr, "\nt%s [ -vVhl ] [ -F <output file type> ] [ -n ] [ -N <resolving> ]\n", PACKAGE);
208   fprintf(stderr, "\t[ -o <preference setting> ] ... [ -r <infile> ] [ -R <read filter> ]\n");
209   fprintf(stderr, "\t[ -t <time stamp format> ] [ -w <savefile> ] [ -x ]\n");
210 #endif
211   fprintf(stderr, "Valid file type arguments to the \"-F\" flag:\n");
212   for (i = 0; i < WTAP_NUM_FILE_TYPES; i++) {
213     if (wtap_dump_can_open(i))
214       fprintf(stderr, "\t%s - %s\n",
215         wtap_file_type_short_string(i), wtap_file_type_string(i));
216   }
217   fprintf(stderr, "\tdefault is libpcap\n");
218 }
219
220 static int
221 get_positive_int(const char *string, const char *name)
222 {
223   long number;
224   char *p;
225
226   number = strtol(string, &p, 10);
227   if (p == string || *p != '\0') {
228     fprintf(stderr, "tethereal: The specified %s \"%s\" is not a decimal number\n",
229             name, string);
230     exit(1);
231   }
232   if (number < 0) {
233     fprintf(stderr, "tethereal: The specified %s is a negative number\n",
234             name);
235     exit(1);
236   }
237   if (number == 0) {
238     fprintf(stderr, "tethereal: The specified %s is zero\n",
239             name);
240     exit(1);
241   }
242   if (number > INT_MAX) {
243     fprintf(stderr, "tethereal: The specified %s is too large (greater than %d)\n",
244             name, INT_MAX);
245     exit(1);
246   }
247   return number;
248 }
249
250 #ifdef HAVE_LIBPCAP
251 /*
252  * Given a string of the form "<autostop criterion>:<value>", as might appear
253  * as an argument to a "-a" option, parse it and set the criterion in
254  * question.  Return an indication of whether it succeeded or failed
255  * in some fashion.
256  */
257 static gboolean
258 set_autostop_criterion(const char *autostoparg)
259 {
260   u_char *p, *colonp;
261
262   colonp = strchr(autostoparg, ':');
263   if (colonp == NULL)
264     return FALSE;
265
266   p = colonp;
267   *p++ = '\0';
268
269   /*
270    * Skip over any white space (there probably won't be any, but
271    * as we allow it in the preferences file, we might as well
272    * allow it here).
273    */
274   while (isspace(*p))
275     p++;
276   if (*p == '\0') {
277     /*
278      * Put the colon back, so if our caller uses, in an
279      * error message, the string they passed us, the message
280      * looks correct.
281      */
282     *colonp = ':';
283     return FALSE;
284   }
285   if (strcmp(autostoparg,"duration") == 0) {
286     capture_opts.has_autostop_duration = TRUE;
287     capture_opts.autostop_duration = get_positive_int(p,"autostop duration");
288   } else if (strcmp(autostoparg,"filesize") == 0) {
289     capture_opts.has_autostop_filesize = TRUE;
290     capture_opts.autostop_filesize = get_positive_int(p,"autostop filesize");
291   } else {
292     return FALSE;
293   }
294   *colonp = ':';        /* put the colon back */
295   return TRUE;
296 }
297 #endif
298
299 int
300 main(int argc, char *argv[])
301 {
302   int                  opt, i;
303   extern char         *optarg;
304   gboolean             arg_error = FALSE;
305 #ifdef HAVE_LIBPCAP
306 #ifdef HAVE_PCAP_VERSION
307   extern char          pcap_version[];
308 #endif /* HAVE_PCAP_VERSION */
309 #endif /* HAVE_LIBPCAP */
310
311 #ifdef WIN32
312   WSADATA               wsaData;
313 #endif
314
315   char                *gpf_path;
316   const char          *pf_path;
317   int                  gpf_open_errno, pf_open_errno;
318   int                  err;
319 #ifdef HAVE_LIBPCAP
320   gboolean             capture_filter_specified = FALSE;
321   GList               *if_list, *if_entry;
322   gchar                err_str[PCAP_ERRBUF_SIZE];
323 #else
324   gboolean             capture_option_specified = FALSE;
325 #endif
326   int                  out_file_type = WTAP_FILE_PCAP;
327   gchar               *cf_name = NULL, *rfilter = NULL, *if_text;
328   dfilter_t           *rfcode = NULL;
329   e_prefs             *prefs;
330   char                 badopt;
331
332   /* Register all dissectors; we must do this before checking for the
333      "-G" flag, as the "-G" flag dumps information registered by the
334      dissectors, and we must do it before we read the preferences, in
335      case any dissectors register preferences. */
336   epan_init(PLUGIN_DIR,register_all_protocols,register_all_protocol_handoffs);
337
338   /* Now register the preferences for any non-dissector modules.
339      We must do that before we read the preferences as well. */
340   prefs_register_modules();
341
342   /* If invoked with the "-G" flag, we dump out information based on
343      the argument to the "-G" flag; if no argument is specified,
344      for backwards compatibility we dump out a glossary of display
345      filter symbols.
346
347      We do this here to mirror what happens in the GTK+ version, although
348      it's not necessary here. */
349   if (argc >= 2 && strcmp(argv[1], "-G") == 0) {
350     if (argc == 2)
351       proto_registrar_dump_fields();
352     else {
353       if (strcmp(argv[2], "fields") == 0)
354         proto_registrar_dump_fields();
355       else if (strcmp(argv[2], "protocols") == 0)
356         proto_registrar_dump_protocols();
357       else {
358         fprintf(stderr, "tethereal: Invalid \"%s\" option for -G flag\n",
359                 argv[2]);
360         exit(1);
361       }
362     }
363     exit(0);
364   }
365
366   /* Set the C-language locale to the native environment. */
367   setlocale(LC_ALL, "");
368
369   prefs = read_prefs(&gpf_open_errno, &gpf_path, &pf_open_errno, &pf_path);
370   if (gpf_path != NULL) {
371     fprintf(stderr, "Can't open global preferences file \"%s\": %s.\n", pf_path,
372         strerror(gpf_open_errno));
373   }
374   if (pf_path != NULL) {
375     fprintf(stderr, "Can't open your preferences file \"%s\": %s.\n", pf_path,
376         strerror(pf_open_errno));
377   }
378
379   /* Set the name resolution code's flags from the preferences. */
380   g_resolv_flags = prefs->name_resolve;
381
382 #ifdef WIN32
383   /* Load Wpcap, if possible */
384   load_wpcap();
385 #endif
386     
387   /* Initialize the capture file struct */
388   cfile.plist           = NULL;
389   cfile.plist_end       = NULL;
390   cfile.wth             = NULL;
391   cfile.filename        = NULL;
392   cfile.user_saved      = FALSE;
393   cfile.is_tempfile     = FALSE;
394   cfile.rfcode          = NULL;
395   cfile.dfilter         = NULL;
396   cfile.dfcode          = NULL;
397 #ifdef HAVE_LIBPCAP
398   cfile.cfilter         = g_strdup("");
399 #endif
400   cfile.iface           = NULL;
401   cfile.save_file       = NULL;
402   cfile.save_file_fd    = -1;
403   cfile.has_snap        = FALSE;
404   cfile.snap            = WTAP_MAX_PACKET_SIZE;
405   cfile.count           = 0;
406   col_init(&cfile.cinfo, prefs->num_cols);
407
408   /* Assemble the compile-time options */
409   comp_info_str = g_string_new("");
410
411   g_string_append(comp_info_str, "with ");
412   g_string_sprintfa(comp_info_str,
413 #ifdef GLIB_MAJOR_VERSION
414     "GLib %d.%d.%d", GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION,
415     GLIB_MICRO_VERSION);
416 #else
417     "GLib (version unknown)");
418 #endif
419
420 #ifdef HAVE_LIBPCAP
421   g_string_append(comp_info_str, ", with libpcap ");
422 #ifdef HAVE_PCAP_VERSION
423   g_string_append(comp_info_str, pcap_version);
424 #else /* HAVE_PCAP_VERSION */
425   g_string_append(comp_info_str, "(version unknown)");
426 #endif /* HAVE_PCAP_VERSION */
427 #else /* HAVE_LIBPCAP */
428   g_string_append(comp_info_str, ", without libpcap");
429 #endif /* HAVE_LIBPCAP */
430
431 #ifdef HAVE_LIBZ
432   g_string_append(comp_info_str, ", with libz ");
433 #ifdef ZLIB_VERSION
434   g_string_append(comp_info_str, ZLIB_VERSION);
435 #else /* ZLIB_VERSION */
436   g_string_append(comp_info_str, "(version unknown)");
437 #endif /* ZLIB_VERSION */
438 #else /* HAVE_LIBZ */
439   g_string_append(comp_info_str, ", without libz");
440 #endif /* HAVE_LIBZ */
441
442 /* Oh, this is pretty */
443 #ifdef HAVE_UCD_SNMP
444   g_string_append(comp_info_str, ", with UCD SNMP ");
445 #ifdef HAVE_UCD_SNMP_VERSION_H
446   g_string_append(comp_info_str, VersionInfo);
447 #else /* HAVE_UCD_SNMP_VERSION_H */
448   g_string_append(comp_info_str, "(version unknown)");
449 #endif /* HAVE_UCD_SNMP_VERSION_H */
450 #else /* no SNMP library */
451   g_string_append(comp_info_str, ", without UCD SNMP");
452 #endif
453     
454   /* Now get our args */
455   while ((opt = getopt(argc, argv, "a:b:c:Df:F:hi:lnN:o:pqr:R:s:t:vw:Vx")) != -1) {
456     switch (opt) {
457       case 'a':        /* autostop criteria */
458 #ifdef HAVE_LIBPCAP
459         if (set_autostop_criterion(optarg) == FALSE) {
460           fprintf(stderr, "ethereal: Invalid or unknown -a flag \"%s\"\n", optarg);
461           exit(1);          
462         }
463 #else
464         capture_option_specified = TRUE;
465         arg_error = TRUE;
466 #endif
467         break;
468       case 'b':        /* Ringbuffer option */
469 #ifdef HAVE_LIBPCAP
470         capture_opts.ringbuffer_on = TRUE;
471         capture_opts.ringbuffer_num_files =
472             get_positive_int(optarg, "number of ring buffer files");
473 #else
474         capture_option_specified = TRUE;
475         arg_error = TRUE;
476 #endif
477         break;
478       case 'c':        /* Capture xxx packets */
479 #ifdef HAVE_LIBPCAP
480         capture_opts.autostop_count =
481             get_positive_int(optarg, "packet count");
482 #else
483         capture_option_specified = TRUE;
484         arg_error = TRUE;
485 #endif
486         break;
487       case 'D':        /* Print a list of capture devices */
488 #ifdef HAVE_LIBPCAP
489         if_list = get_interface_list(&err, err_str);
490         if (if_list == NULL) {
491             switch (err) {
492
493             case CANT_GET_INTERFACE_LIST:
494                 fprintf(stderr, "tethereal: Can't get list of interfaces: %s\n",
495                         err_str);
496                 break;
497
498             case NO_INTERFACES_FOUND:
499                 fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
500                 break;
501             }
502             exit(2);
503         }
504         for (if_entry = g_list_first(if_list); if_entry != NULL;
505                 if_entry = g_list_next(if_entry))
506           printf("%s\n", (char *)if_entry->data);
507         free_interface_list(if_list);
508         exit(0);
509 #else
510         capture_option_specified = TRUE;
511         arg_error = TRUE;
512 #endif
513         break;
514       case 'f':
515 #ifdef HAVE_LIBPCAP
516         capture_filter_specified = TRUE;
517         if (cfile.cfilter)
518                 g_free(cfile.cfilter);
519         cfile.cfilter = g_strdup(optarg);
520 #else
521         capture_option_specified = TRUE;
522         arg_error = TRUE;
523 #endif
524         break;
525       case 'F':
526         out_file_type = wtap_short_string_to_file_type(optarg);
527         if (out_file_type < 0) {
528           fprintf(stderr, "tethereal: \"%s\" is not a valid capture file type\n",
529                         optarg);
530           exit(1);
531         }
532         break;
533       case 'h':        /* Print help and exit */
534         print_usage(TRUE);
535         exit(0);
536         break;
537       case 'i':        /* Use interface xxx */
538 #ifdef HAVE_LIBPCAP
539         cfile.iface = g_strdup(optarg);
540 #else
541         capture_option_specified = TRUE;
542         arg_error = TRUE;
543 #endif
544         break;
545       case 'l':        /* "Line-buffer" standard output */
546         /* This isn't line-buffering, strictly speaking, it's just
547            flushing the standard output after the information for
548            each packet is printed; however, that should be good
549            enough for all the purposes to which "-l" is put.
550
551            See the comment in "wtap_dispatch_cb_print()" for an
552            explanation of why we do that, and why we don't just
553            use "setvbuf()" to make the standard output line-buffered
554            (short version: in Windows, "line-buffered" is the same
555            as "fully-buffered", and the output buffer is only flushed
556            when it fills up). */
557         line_buffered = TRUE;
558         break;
559       case 'n':        /* No name resolution */
560         g_resolv_flags = RESOLV_NONE;
561         break;
562       case 'N':        /* Select what types of addresses/port #s to resolve */
563         if (g_resolv_flags == RESOLV_ALL)
564           g_resolv_flags = RESOLV_NONE;
565         badopt = string_to_name_resolve(optarg, &g_resolv_flags);
566         if (badopt != '\0') {
567           fprintf(stderr, "tethereal: -N specifies unknown resolving option '%c'; valid options are 'm', 'n', and 't'\n",
568                         badopt);
569           exit(1);
570         }
571         break;
572       case 'o':        /* Override preference from command line */
573         switch (prefs_set_pref(optarg)) {
574
575         case PREFS_SET_SYNTAX_ERR:
576           fprintf(stderr, "tethereal: Invalid -o flag \"%s\"\n", optarg);
577           exit(1);
578           break;
579
580         case PREFS_SET_NO_SUCH_PREF:
581         case PREFS_SET_OBSOLETE:
582           fprintf(stderr, "tethereal: -o flag \"%s\" specifies unknown preference\n",
583                         optarg);
584           exit(1);
585           break;
586         }
587         break;
588       case 'p':        /* Don't capture in promiscuous mode */
589 #ifdef HAVE_LIBPCAP
590         capture_opts.promisc_mode = FALSE;
591 #else
592         capture_option_specified = TRUE;
593         arg_error = TRUE;
594 #endif
595         break;
596       case 'q':        /* Quiet */
597         quiet = TRUE;
598         break;
599       case 'r':        /* Read capture file xxx */
600         cf_name = g_strdup(optarg);
601         break;
602       case 'R':        /* Read file filter */
603         rfilter = optarg;
604         break;
605       case 's':        /* Set the snapshot (capture) length */
606 #ifdef HAVE_LIBPCAP
607         capture_opts.snaplen = get_positive_int(optarg, "snapshot length");
608 #else
609         capture_option_specified = TRUE;
610         arg_error = TRUE;
611 #endif
612         break;
613       case 't':        /* Time stamp type */
614         if (strcmp(optarg, "r") == 0)
615           timestamp_type = RELATIVE;
616         else if (strcmp(optarg, "a") == 0)
617           timestamp_type = ABSOLUTE;
618         else if (strcmp(optarg, "ad") == 0)
619           timestamp_type = ABSOLUTE_WITH_DATE;
620         else if (strcmp(optarg, "d") == 0)
621           timestamp_type = DELTA;
622         else {
623           fprintf(stderr, "tethereal: Invalid time stamp type \"%s\"\n",
624             optarg);
625           fprintf(stderr, "It must be \"r\" for relative, \"a\" for absolute,\n");
626           fprintf(stderr, "\"ad\" for absolute with date, or \"d\" for delta.\n");
627           exit(1);
628         }
629         break;
630       case 'v':        /* Show version and exit */
631         printf("t%s %s, %s\n", PACKAGE, VERSION, comp_info_str->str);
632         exit(0);
633         break;
634       case 'w':        /* Write to capture file xxx */
635         cfile.save_file = g_strdup(optarg);
636         break;
637       case 'V':        /* Verbose */
638         verbose = TRUE;
639         break;
640       case 'x':        /* Print packet data in hex (and ASCII) */
641         print_hex = TRUE;
642         break;
643       default:
644       case '?':        /* Bad flag - print usage message */
645         arg_error = TRUE;
646         break;
647     }
648   }
649   
650   /* If no capture filter or read filter has been specified, and there are
651      still command-line arguments, treat them as the tokens of a capture
652      filter (if no "-r" flag was specified) or a read filter (if a "-r"
653      flag was specified. */
654   if (optind < argc) {
655     if (cf_name != NULL) {
656       if (rfilter != NULL) {
657         fprintf(stderr,
658 "tethereal: Read filters were specified both with \"-R\" and with additional command-line arguments\n");
659         exit(2);
660       }
661       rfilter = get_args_as_string(argc, argv, optind);
662     } else {
663 #ifdef HAVE_LIBPCAP
664       if (capture_filter_specified) {
665         fprintf(stderr,
666 "tethereal: Capture filters were specified both with \"-f\" and with additional command-line arguments\n");
667         exit(2);
668       }
669       cfile.cfilter = get_args_as_string(argc, argv, optind);
670 #else
671       capture_option_specified = TRUE;
672 #endif
673     }
674   }
675
676   /* See if we're writing a capture file and the file is a pipe */
677   ld.output_to_pipe = FALSE;
678   if (cfile.save_file != NULL) {
679     err = test_for_fifo(cfile.save_file);
680     switch (errno) {
681
682     case ENOENT:        /* it doesn't exist, so we'll be creating it,
683                            and it won't be a FIFO */
684     case ENOTDIR:       /* XXX - why ignore this? */
685     case 0:             /* found it, but it's not a FIFO */
686       break;
687
688     case ESPIPE:        /* it is a FIFO */
689       ld.output_to_pipe = TRUE;
690       break;
691
692     default:            /* couldn't stat it */
693       fprintf(stderr,
694               "tethereal: Error testing whether capture file is a pipe: %s\n",
695               strerror(errno));
696       exit(2);
697     }
698   }
699
700 #ifdef HAVE_LIBPCAP
701   /* If they didn't specify a "-w" flag, but specified a maximum capture
702      file size, tell them that this doesn't work, and exit. */
703   if (capture_opts.has_autostop_filesize && cfile.save_file == NULL) {
704     fprintf(stderr, "tethereal: Maximum capture file size specified, but capture isn't being saved to a file.\n");
705     exit(2);
706   }
707
708   if (capture_opts.ringbuffer_on) {
709     /* Ring buffer works only under certain conditions:
710        a) ring buffer does not work if you're not saving the capture to
711           a file;
712        b) ring buffer only works if you're saving in libpcap format;
713        c) it makes no sense to enable the ring buffer if the maximum
714           file size is set to "infinite";
715        d) file must not be a pipe. */
716     if (cfile.save_file == NULL) {
717       fprintf(stderr, "tethereal: Ring buffer requested, but "
718         "capture isn't being saved to a file.\n");
719       exit(2);
720     }
721     if (out_file_type != WTAP_FILE_PCAP) {
722       fprintf(stderr, "tethereal: Ring buffer requested, but "
723         "capture isn't being saved in libpcap format.\n");
724       exit(2);
725     }
726     if (!capture_opts.has_autostop_filesize) {
727       fprintf(stderr, "tethereal: Ring buffer requested, but "
728         "no maximum capture file size was specified.\n");
729       exit(2);
730     }
731     if (ld.output_to_pipe) {
732       fprintf(stderr, "tethereal: Ring buffer requested, but "
733         "capture file is a pipe.\n");
734       exit(2);
735     }
736   }
737 #endif
738
739 #ifdef WIN32
740   /* Start windows sockets */
741   WSAStartup( MAKEWORD( 1, 1 ), &wsaData );
742 #endif
743
744   /* Notify all registered modules that have had any of their preferences
745      changed either from one of the preferences file or from the command
746      line that its preferences have changed. */
747   prefs_apply_all();
748
749 #ifndef HAVE_LIBPCAP
750   if (capture_option_specified)
751     fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
752 #endif
753   if (arg_error) {
754     print_usage(FALSE);
755     exit(1);
756   }
757
758   /* Build the column format array */  
759   for (i = 0; i < cfile.cinfo.num_cols; i++) {
760     cfile.cinfo.col_fmt[i] = get_column_format(i);
761     cfile.cinfo.col_title[i] = g_strdup(get_column_title(i));
762     cfile.cinfo.fmt_matx[i] = (gboolean *) g_malloc0(sizeof(gboolean) *
763       NUM_COL_FMTS);
764     get_column_format_matches(cfile.cinfo.fmt_matx[i], cfile.cinfo.col_fmt[i]);
765     cfile.cinfo.col_data[i] = NULL;
766     if (cfile.cinfo.col_fmt[i] == COL_INFO)
767       cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_INFO_LEN);
768     else
769       cfile.cinfo.col_buf[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
770
771     cfile.cinfo.col_expr[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
772     cfile.cinfo.col_expr_val[i] = (gchar *) g_malloc(sizeof(gchar) * COL_MAX_LEN);
773   }
774
775 #ifdef HAVE_LIBPCAP
776   if (capture_opts.snaplen < 1)
777     capture_opts.snaplen = WTAP_MAX_PACKET_SIZE;
778   else if (capture_opts.snaplen < MIN_PACKET_SIZE)
779     capture_opts.snaplen = MIN_PACKET_SIZE;
780   
781   /* Check the value range of the ringbuffer_num_files parameter */
782   if (capture_opts.ringbuffer_num_files < RINGBUFFER_MIN_NUM_FILES)
783     capture_opts.ringbuffer_num_files = RINGBUFFER_MIN_NUM_FILES;
784   else if (capture_opts.ringbuffer_num_files > RINGBUFFER_MAX_NUM_FILES)
785     capture_opts.ringbuffer_num_files = RINGBUFFER_MAX_NUM_FILES;
786 #endif
787   
788   if (rfilter != NULL) {
789     if (!dfilter_compile(rfilter, &rfcode)) {
790       fprintf(stderr, "tethereal: %s\n", dfilter_error_msg);
791       epan_cleanup();
792       exit(2);
793     }
794   }
795   cfile.rfcode = rfcode;
796   if (cf_name) {
797     err = open_cap_file(cf_name, FALSE, &cfile);
798     if (err != 0) {
799       epan_cleanup();
800       exit(2);
801     }
802     err = load_cap_file(&cfile, out_file_type);
803     if (err != 0) {
804       epan_cleanup();
805       exit(2);
806     }
807     cf_name[0] = '\0';
808   } else {
809     /* No capture file specified, so we're supposed to do a live capture;
810        do we have support for live captures? */
811 #ifdef HAVE_LIBPCAP
812
813 #ifdef _WIN32
814     if (!has_wpcap) {
815         fprintf(stderr, "tethereal: Could not load wpcap.dll.\n");
816         exit(2);
817     }
818 #endif
819
820     /* Yes; did the user specify an interface to use? */
821     if (cfile.iface == NULL) {
822         /* No - is a default specified in the preferences file? */
823         if (prefs->capture_device != NULL) {
824             /* Yes - use it. */
825             if_text = strrchr(prefs->capture_device, ' ');
826             if (if_text == NULL) {
827                 cfile.iface = g_strdup(prefs->capture_device);
828             } else {
829                 cfile.iface = g_strdup(if_text + 1); /* Skip over space */
830             }
831         } else {
832             /* No - pick the first one from the list of interfaces. */
833             if_list = get_interface_list(&err, err_str);
834             if (if_list == NULL) {
835                 switch (err) {
836
837                 case CANT_GET_INTERFACE_LIST:
838                     fprintf(stderr, "tethereal: Can't get list of interfaces: %s\n",
839                             err_str);
840                     break;
841
842                 case NO_INTERFACES_FOUND:
843                     fprintf(stderr, "tethereal: There are no interfaces on which a capture can be done\n");
844                     break;
845                 }
846                 exit(2);
847             }
848             if_text = strrchr(if_list->data, ' ');      /* first interface */
849             if (if_text == NULL) {
850                 cfile.iface = g_strdup(if_list->data);
851             } else {
852                 cfile.iface = g_strdup(if_text + 1); /* Skip over space */
853             }
854             free_interface_list(if_list);
855         }
856     }
857     capture(out_file_type);
858
859     if (capture_opts.ringbuffer_on) {
860       ringbuf_free();
861     }
862 #else
863     /* No - complain. */
864     fprintf(stderr, "This version of Tethereal was not built with support for capturing packets.\n");
865     exit(2);
866 #endif
867   }
868
869   epan_cleanup();
870
871   return 0;
872 }
873
874 #ifdef HAVE_LIBPCAP
875 /* Do the low-level work of a capture.
876    Returns TRUE if it succeeds, FALSE otherwise. */
877 static int
878 capture(int out_file_type)
879 {
880   gchar       open_err_str[PCAP_ERRBUF_SIZE];
881   gchar       lookup_net_err_str[PCAP_ERRBUF_SIZE];
882   bpf_u_int32 netnum, netmask;
883   struct bpf_program fcode;
884   void        (*oldhandler)(int);
885   int         err = 0;
886   volatile int inpkts = 0;
887   char        errmsg[1024+1];
888   condition  *volatile cnd_stop_capturesize = NULL;
889   condition  *volatile cnd_stop_timeout = NULL;
890 #ifndef _WIN32
891   static const char ppamsg[] = "can't find PPA for ";
892   char       *libpcap_warn;
893 #endif
894   struct pcap_stat stats;
895   gboolean    volatile write_err = FALSE;
896   gboolean    dump_ok;
897
898   /* Initialize all data structures used for dissection. */
899   init_dissection();
900
901   ld.linktype       = WTAP_ENCAP_UNKNOWN;
902   ld.pdh            = NULL;
903
904   /* Open the network interface to capture from it.
905      Some versions of libpcap may put warnings into the error buffer
906      if they succeed; to tell if that's happened, we have to clear
907      the error buffer, and check if it's still a null string.  */
908   open_err_str[0] = '\0';
909   ld.pch = pcap_open_live(cfile.iface, capture_opts.snaplen,
910                           capture_opts.promisc_mode, 1000, open_err_str);
911
912   if (ld.pch == NULL) {
913     /* Well, we couldn't start the capture. */
914 #ifdef _WIN32
915     /* On Win32 OSes, the capture devices are probably available to all
916        users; don't warn about permissions problems.
917
918        Do, however, warn that Token Ring and PPP devices aren't supported. */
919     snprintf(errmsg, sizeof errmsg,
920         "The capture session could not be initiated (%s).\n"
921         "Please check that you have the proper interface specified.\n"
922         "\n"
923         "Note that the driver Tethereal uses for packet capture on Windows\n"
924         "doesn't support capturing on Token Ring interfaces, and doesn't\n"
925         "support capturing on PPP/WAN interfaces in Windows NT/2000.\n",
926         open_err_str);
927 #else
928       /* If we got a "can't find PPA for XXX" message, warn the user (who
929          is running Ethereal on HP-UX) that they don't have a version
930          of libpcap that properly handles HP-UX (libpcap 0.6.x and later
931          versions, which properly handle HP-UX, say "can't find /dev/dlpi
932          PPA for XXX" rather than "can't find PPA for XXX"). */
933       if (strncmp(open_err_str, ppamsg, sizeof ppamsg - 1) == 0)
934         libpcap_warn =
935           "\n\n"
936           "You are running Tethereal with a version of the libpcap library\n"
937           "that doesn't handle HP-UX network devices well; this means that\n"
938           "Tethereal may not be able to capture packets.\n"
939           "\n"
940           "To fix this, you should install libpcap 0.6.2, or a later version\n"
941           "of libpcap, rather than libpcap 0.4 or 0.5.x.  It is available in\n"
942           "packaged binary form from the Software Porting And Archive Centre\n"
943           "for HP-UX; the Centre is at http://hpux.connect.org.uk/ - the page\n"
944           "at the URL lists a number of mirror sites.";
945       else
946         libpcap_warn = "";
947     snprintf(errmsg, sizeof errmsg,
948       "The capture session could not be initiated (%s).\n"
949       "Please check to make sure you have sufficient permissions, and that\n"
950       "you have the proper interface specified.%s", open_err_str, libpcap_warn);
951 #endif
952     goto error;
953   }
954
955   if (cfile.cfilter) {
956     /* A capture filter was specified; set it up. */
957     if (pcap_lookupnet(cfile.iface, &netnum, &netmask, lookup_net_err_str) < 0) {
958       /*
959        * Well, we can't get the netmask for this interface; it's used
960        * only for filters that check for broadcast IP addresses, so
961        * we just warn the user, and punt and use 0.
962        */
963       fprintf(stderr, 
964         "Warning:  Couldn't obtain netmask info (%s).\n", lookup_net_err_str);
965       netmask = 0;
966     }
967     if (pcap_compile(ld.pch, &fcode, cfile.cfilter, 1, netmask) < 0) {
968       snprintf(errmsg, sizeof errmsg, "Unable to parse filter string (%s).",
969         pcap_geterr(ld.pch));
970       goto error;
971     }
972     if (pcap_setfilter(ld.pch, &fcode) < 0) {
973       snprintf(errmsg, sizeof errmsg, "Can't install filter (%s).",
974         pcap_geterr(ld.pch));
975       goto error;
976     }
977   }
978
979   ld.linktype = wtap_pcap_encap_to_wtap_encap(get_pcap_linktype(ld.pch,
980         cfile.iface));
981   if (cfile.save_file != NULL) {
982     /* Set up to write to the capture file. */
983     if (ld.linktype == WTAP_ENCAP_UNKNOWN) {
984       strcpy(errmsg, "The network you're capturing from is of a type"
985                " that Tethereal doesn't support.");
986       goto error;
987     }
988     if (capture_opts.ringbuffer_on) {
989       cfile.save_file_fd = ringbuf_init(cfile.save_file,
990         capture_opts.ringbuffer_num_files);
991       if (cfile.save_file_fd != -1) {
992         ld.pdh = ringbuf_init_wtap_dump_fdopen(out_file_type, ld.linktype,
993           pcap_snapshot(ld.pch), &err);
994       } else {
995         ld.pdh = NULL;
996       }
997     } else {
998       ld.pdh = wtap_dump_open(cfile.save_file, out_file_type,
999                  ld.linktype, pcap_snapshot(ld.pch), &err);
1000     }
1001
1002     if (ld.pdh == NULL) {
1003       snprintf(errmsg, sizeof errmsg, file_open_error_message(errno, TRUE),
1004                 cfile.save_file);
1005       goto error;
1006     }
1007   }
1008
1009   /* Does "open_err_str" contain a non-empty string?  If so, "pcap_open_live()"
1010      returned a warning; print it, but keep capturing. */
1011   if (open_err_str[0] != '\0')
1012     fprintf(stderr, "tethereal: WARNING: %s.\n", open_err_str);
1013
1014 #ifdef _WIN32
1015   /* Catch a CTRL+C event and, if we get it, clean up and exit. */
1016   SetConsoleCtrlHandler(capture_cleanup, TRUE);
1017 #else /* _WIN32 */
1018   /* Catch SIGINT and SIGTERM and, if we get either of them, clean up
1019      and exit.
1020      XXX - deal with signal semantics on various UNIX platforms.  Or just
1021      use "sigaction()" and be done with it? */
1022   signal(SIGTERM, capture_cleanup);
1023   signal(SIGINT, capture_cleanup);
1024   if ((oldhandler = signal(SIGHUP, capture_cleanup)) != SIG_DFL)
1025     signal(SIGHUP, oldhandler);
1026 #endif /* _WIN32 */
1027
1028   /* Let the user know what interface was chosen. */
1029   fprintf(stderr, "Capturing on %s\n", cfile.iface);
1030
1031   /* initialize capture stop conditions */ 
1032   init_capture_stop_conditions();
1033   /* create stop conditions */
1034   if (capture_opts.has_autostop_filesize)
1035     cnd_stop_capturesize = cnd_new((char*)CND_CLASS_CAPTURESIZE,
1036                                    (long)capture_opts.autostop_filesize * 1000);
1037   if (capture_opts.has_autostop_duration)
1038     cnd_stop_timeout = cnd_new((char*)CND_CLASS_TIMEOUT,
1039                                (gint32)capture_opts.autostop_duration);
1040
1041   if (!setjmp(ld.stopenv))
1042     ld.go = TRUE;
1043   else
1044     ld.go = FALSE;
1045   ld.packet_count = 0;
1046   while (ld.go) {
1047     inpkts = pcap_dispatch(ld.pch, 1, capture_pcap_cb, (u_char *) &ld);
1048     if (inpkts < 0) {
1049       /* Error from "pcap_dispatch()". */
1050       ld.go = FALSE;
1051     } else if (capture_opts.autostop_count != 0 &&
1052                ld.packet_count >= capture_opts.autostop_count) {
1053       /* The specified number of packets have been captured and have
1054          passed both any capture filter in effect and any read filter
1055          in effect. */
1056       ld.go = FALSE;
1057     } else if (cnd_stop_timeout != NULL && cnd_eval(cnd_stop_timeout)) {
1058       /* The specified capture time has elapsed; stop the capture. */
1059       ld.go = FALSE;
1060     } else if (ld.pdh != NULL && cnd_stop_capturesize != NULL &&
1061                   cnd_eval(cnd_stop_capturesize, 
1062                             (guint32)wtap_get_bytes_dumped(ld.pdh))) {
1063       /* We're saving the capture to a file, and the capture file reached
1064          its maximum size. */
1065       if (capture_opts.ringbuffer_on) {
1066         /* Switch to the next ringbuffer file */
1067         if (ringbuf_switch_file(&cfile, &ld.pdh, &err)) {
1068           /* File switch succeeded: reset the condition */
1069           cnd_reset(cnd_stop_capturesize);
1070         } else {
1071           /* File switch failed: stop here */
1072           ld.go = FALSE;
1073           continue;
1074         }
1075       } else {
1076         /* No ringbuffer - just stop. */
1077         ld.go = FALSE;
1078       }
1079     }
1080   }
1081   
1082   /* delete stop conditions */
1083   if (cnd_stop_capturesize != NULL)
1084     cnd_delete(cnd_stop_capturesize);
1085   if (cnd_stop_timeout != NULL)
1086     cnd_delete(cnd_stop_timeout);
1087
1088   if ((cfile.save_file != NULL) && !quiet) {
1089     /* We're saving to a file, which means we're printing packet counts
1090        to the standard output if we are not running silent and deep.
1091        Send a newline so that we move to the line after the packet count. */
1092     fprintf(stderr, "\n");
1093   }
1094
1095   /* If we got an error while capturing, report it. */
1096   if (inpkts < 0) {
1097     fprintf(stderr, "tethereal: Error while capturing packets: %s\n",
1098         pcap_geterr(ld.pch));
1099   }
1100
1101   if (err != 0) {
1102     show_capture_file_io_error(cfile.save_file, err, FALSE);
1103     write_err = TRUE;
1104   }
1105
1106   if (cfile.save_file != NULL) {
1107     /* We're saving to a file or files; close all files. */
1108     if (capture_opts.ringbuffer_on) {
1109       dump_ok = ringbuf_wtap_dump_close(&cfile, &err);
1110     } else {
1111       dump_ok = wtap_dump_close(ld.pdh, &err);
1112     }
1113     if (!dump_ok && ! write_err)
1114       show_capture_file_io_error(cfile.save_file, err, TRUE);
1115   }
1116
1117   /* Get the capture statistics, and, if any packets were dropped, report
1118      that. */
1119   if (pcap_stats(ld.pch, &stats) >= 0) {
1120     if (stats.ps_drop != 0) {
1121       fprintf(stderr, "%u packets dropped\n", stats.ps_drop);
1122     }
1123   } else {
1124     fprintf(stderr, "tethereal: Can't get packet-drop statistics: %s\n",
1125         pcap_geterr(ld.pch));
1126   }
1127   /* Report the number of captured packets if not reported during capture
1128      and we are saving to a file. */
1129   if (quiet && (cfile.save_file != NULL)) {
1130     fprintf(stderr, "%u packets captured\n", ld.packet_count);
1131   }
1132
1133   pcap_close(ld.pch);
1134
1135   return TRUE;
1136
1137 error:
1138   if (capture_opts.ringbuffer_on) {
1139     ringbuf_error_cleanup();
1140   }
1141   g_free(cfile.save_file);
1142   cfile.save_file = NULL;
1143   fprintf(stderr, "tethereal: %s\n", errmsg);
1144   if (ld.pch != NULL)
1145     pcap_close(ld.pch);
1146
1147   return FALSE;
1148 }
1149
1150 static void
1151 capture_pcap_cb(u_char *user, const struct pcap_pkthdr *phdr,
1152   const u_char *pd)
1153 {
1154   struct wtap_pkthdr whdr;
1155   union wtap_pseudo_header pseudo_header;
1156   loop_data *ld = (loop_data *) user;
1157   cb_args_t args;
1158   int err;
1159
1160   /* Convert from libpcap to Wiretap format.
1161      If that fails, ignore the packet.
1162      XXX - print a message. */
1163   pd = wtap_process_pcap_packet(ld->linktype, phdr, pd, &pseudo_header,
1164                                 &whdr, &err);
1165   if (pd == NULL) {
1166     return;
1167   }
1168
1169   args.cf = &cfile;
1170   args.pdh = ld->pdh;
1171   if (ld->pdh) {
1172     wtap_dispatch_cb_write((u_char *)&args, &whdr, 0, &pseudo_header, pd);
1173     /* Report packet capture count if not quiet */
1174     if (!quiet) {
1175       if (ld->packet_count != 0) {
1176         fprintf(stderr, "\r%u ", ld->packet_count);
1177         /* stderr could be line buffered */
1178         fflush(stderr);
1179       }
1180     }
1181   } else {
1182     wtap_dispatch_cb_print((u_char *)&args, &whdr, 0, &pseudo_header, pd);
1183   }
1184 }
1185
1186 #ifdef _WIN32
1187 static BOOL WINAPI
1188 capture_cleanup(DWORD ctrltype _U_)
1189 {
1190   /* CTRL_C_EVENT is sort of like SIGINT, CTRL_BREAK_EVENT is unique to
1191      Windows, CTRL_CLOSE_EVENT is sort of like SIGHUP, CTRL_LOGOFF_EVENT
1192      is also sort of like SIGHUP, and CTRL_SHUTDOWN_EVENT is sort of
1193      like SIGTERM at least when the machine's shutting down.
1194
1195      For now, we handle them all as indications that we should clean up
1196      and quit, just as we handle SIGINT, SIGHUP, and SIGTERM in that
1197      way on UNIX.
1198
1199      However, as handlers run in a new thread, we can't just longjmp
1200      out; we have to set "ld.go" to FALSE, and must return TRUE so that
1201      no other handler - such as one that would terminate the process -
1202      gets called.
1203
1204      XXX - for some reason, typing ^C to Tethereal, if you run this in
1205      a Cygwin console window in at least some versions of Cygwin,
1206      causes Tethereal to terminate immediately; this routine gets
1207      called, but the main loop doesn't get a chance to run and
1208      exit cleanly, at least if this is compiled with Microsoft Visual
1209      C++ (i.e., it's a property of the Cygwin console window or Bash;
1210      it happens if Tethereal is not built with Cygwin - for all I know,
1211      building it with Cygwin may make the problem go away). */
1212   ld.go = FALSE;
1213   return TRUE;
1214 }
1215 #else
1216 static void
1217 capture_cleanup(int signum _U_)
1218 {
1219   /* Longjmp back to the starting point; "pcap_dispatch()", on many
1220      UNIX platforms, just keeps looping if it gets EINTR, so if we set
1221      "ld.go" to FALSE and return, we won't break out of it and quit
1222      capturing. */
1223   longjmp(ld.stopenv, 1);
1224 }
1225 #endif /* _WIN32 */
1226 #endif /* HAVE_LIBPCAP */
1227
1228 static int
1229 load_cap_file(capture_file *cf, int out_file_type)
1230 {
1231   gint         linktype;
1232   int          snapshot_length;
1233   wtap_dumper *pdh;
1234   int          err;
1235   int          success;
1236   cb_args_t    args;
1237
1238   linktype = wtap_file_encap(cf->wth);
1239   if (cf->save_file != NULL) {
1240     /* Set up to write to the capture file. */
1241     snapshot_length = wtap_snapshot_length(cf->wth);
1242     if (snapshot_length == 0) {
1243       /* Snapshot length of input file not known. */
1244       snapshot_length = WTAP_MAX_PACKET_SIZE;
1245     }
1246     pdh = wtap_dump_open(cf->save_file, out_file_type,
1247                 linktype, snapshot_length, &err);
1248
1249     if (pdh == NULL) {
1250       /* We couldn't set up to write to the capture file. */
1251       switch (err) {
1252
1253       case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
1254         fprintf(stderr,
1255                 "tethereal: Capture files can't be written in that format.\n");
1256         break;
1257
1258       case WTAP_ERR_UNSUPPORTED_ENCAP:
1259       case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
1260         fprintf(stderr,
1261 "tethereal: The capture file being read cannot be written in that format.\n");
1262         break;
1263
1264       case WTAP_ERR_CANT_OPEN:
1265         fprintf(stderr,
1266 "tethereal: The file \"%s\" couldn't be created for some unknown reason.\n",
1267                  cf->save_file);
1268         break;
1269
1270       case WTAP_ERR_SHORT_WRITE:
1271         fprintf(stderr,
1272 "tethereal: A full header couldn't be written to the file \"%s\".\n",
1273                 cf->save_file);
1274         break;
1275
1276       default:
1277         if (err < 0) {
1278           fprintf(stderr,
1279                 "tethereal: The file \"%s\" could not be opened: Error %d.\n",
1280                 cf->save_file, err);
1281         } else {
1282           fprintf(stderr,
1283                 "tethereal: The file \"%s\" could not be opened: %s\n.",
1284                 cf->save_file, strerror(err));
1285         }
1286         break;
1287       }
1288       goto out;
1289     }
1290     args.cf = cf;
1291     args.pdh = pdh;
1292     success = wtap_loop(cf->wth, 0, wtap_dispatch_cb_write, (u_char *) &args,
1293                         &err);
1294
1295     /* Now close the capture file. */
1296     if (!wtap_dump_close(pdh, &err))
1297       show_capture_file_io_error(cfile.save_file, err, TRUE);
1298   } else {
1299     args.cf = cf;
1300     args.pdh = NULL;
1301     success = wtap_loop(cf->wth, 0, wtap_dispatch_cb_print, (u_char *) &args,
1302                         &err);
1303   }
1304   if (!success) {
1305     /* Print up a message box noting that the read failed somewhere along
1306        the line. */
1307     switch (err) {
1308
1309     case WTAP_ERR_UNSUPPORTED_ENCAP:
1310       fprintf(stderr,
1311 "tethereal: \"%s\" is a capture file is for a network type that Tethereal doesn't support.\n",
1312         cf->filename);
1313       break;
1314
1315     case WTAP_ERR_CANT_READ:
1316       fprintf(stderr,
1317 "tethereal: An attempt to read from \"%s\" failed for some unknown reason.\n",
1318         cf->filename);
1319       break;
1320
1321     case WTAP_ERR_SHORT_READ:
1322       fprintf(stderr,
1323 "tethereal: \"%s\" appears to have been cut short in the middle of a packet.\n",
1324         cf->filename);
1325       break;
1326
1327     case WTAP_ERR_BAD_RECORD:
1328       fprintf(stderr,
1329 "tethereal: \"%s\" appears to be damaged or corrupt.\n",
1330         cf->filename);
1331       break;
1332
1333     default:
1334       fprintf(stderr,
1335 "tethereal: An error occurred while reading \"%s\": %s.\n",
1336         cf->filename, wtap_strerror(err));
1337       break;
1338     }
1339   }
1340
1341 out:
1342   wtap_close(cf->wth);
1343   cf->wth = NULL;
1344
1345   return err;
1346 }
1347
1348 static void
1349 fill_in_fdata(frame_data *fdata, capture_file *cf,
1350         const struct wtap_pkthdr *phdr, long offset)
1351 {
1352   fdata->next = NULL;
1353   fdata->prev = NULL;
1354   fdata->pfd = NULL;
1355   fdata->num = cf->count;
1356   fdata->pkt_len = phdr->len;
1357   fdata->cap_len = phdr->caplen;
1358   fdata->file_off = offset;
1359   fdata->lnk_t = phdr->pkt_encap;
1360   fdata->abs_secs  = phdr->ts.tv_sec;
1361   fdata->abs_usecs = phdr->ts.tv_usec;
1362   fdata->flags.passed_dfilter = 0;
1363   fdata->flags.encoding = CHAR_ASCII;
1364   fdata->flags.visited = 0;
1365   fdata->flags.marked = 0;
1366
1367   /* If we don't have the time stamp of the first packet in the
1368      capture, it's because this is the first packet.  Save the time
1369      stamp of this packet as the time stamp of the first packet. */
1370   if (!firstsec && !firstusec) {
1371     firstsec  = fdata->abs_secs;
1372     firstusec = fdata->abs_usecs;
1373   }
1374
1375   /* If we don't have the time stamp of the previous displayed packet,
1376      it's because this is the first displayed packet.  Save the time
1377      stamp of this packet as the time stamp of the previous displayed
1378      packet. */
1379   if (!prevsec && !prevusec) {
1380     prevsec  = fdata->abs_secs;
1381     prevusec = fdata->abs_usecs;
1382   }
1383
1384   /* Get the time elapsed between the first packet and this packet. */
1385   compute_timestamp_diff(&fdata->rel_secs, &fdata->rel_usecs,
1386                 fdata->abs_secs, fdata->abs_usecs, firstsec, firstusec);
1387
1388   /* If it's greater than the current elapsed time, set the elapsed time
1389      to it (we check for "greater than" so as not to be confused by
1390      time moving backwards). */
1391   if ((gint32)cf->esec < fdata->rel_secs
1392         || ((gint32)cf->esec == fdata->rel_secs && (gint32)cf->eusec < fdata->rel_usecs)) {
1393     cf->esec = fdata->rel_secs;
1394     cf->eusec = fdata->rel_usecs;
1395   }
1396   
1397   /* Get the time elapsed between the previous displayed packet and
1398      this packet. */
1399   compute_timestamp_diff(&fdata->del_secs, &fdata->del_usecs,
1400                 fdata->abs_secs, fdata->abs_usecs, prevsec, prevusec);
1401   prevsec = fdata->abs_secs;
1402   prevusec = fdata->abs_usecs;
1403 }
1404
1405 /* Free up all data attached to a "frame_data" structure. */
1406 static void
1407 clear_fdata(frame_data *fdata)
1408 {
1409   if (fdata->pfd)
1410     g_slist_free(fdata->pfd);
1411 }
1412
1413 static void
1414 wtap_dispatch_cb_write(u_char *user, const struct wtap_pkthdr *phdr,
1415   long offset, union wtap_pseudo_header *pseudo_header, const u_char *buf)
1416 {
1417   cb_args_t    *args = (cb_args_t *) user;
1418   capture_file *cf = args->cf;
1419   wtap_dumper  *pdh = args->pdh;
1420   frame_data    fdata;
1421   int           err;
1422   gboolean      io_ok;
1423   gboolean      passed;
1424   epan_dissect_t *edt;
1425
1426   cf->count++;
1427   if (cf->rfcode) {
1428     fill_in_fdata(&fdata, cf, phdr, offset);
1429     edt = epan_dissect_new(TRUE, FALSE);
1430     epan_dissect_prime_dfilter(edt, cf->rfcode);
1431     epan_dissect_run(edt, pseudo_header, buf, &fdata, NULL);
1432     passed = dfilter_apply_edt(cf->rfcode, edt);
1433   } else {
1434     passed = TRUE;
1435     edt = NULL;
1436   }
1437   if (passed) {
1438     /* The packet passed the read filter. */
1439     ld.packet_count++;
1440     io_ok = wtap_dump(pdh, phdr, pseudo_header, buf, &err);
1441     if (io_ok && ld.output_to_pipe) {
1442       io_ok = ! fflush(wtap_dump_file(ld.pdh));
1443       if (!io_ok)
1444         err = errno;
1445     }
1446     if (!io_ok) {
1447 #ifdef HAVE_LIBPCAP
1448       if (ld.pch != NULL && !quiet) {
1449         /* We're capturing packets, so (if -q not specified) we're printing
1450            a count of packets captured; move to the line after the count. */
1451         fprintf(stderr, "\n");
1452       }
1453 #endif
1454       show_capture_file_io_error(cf->save_file, err, FALSE);
1455 #ifdef HAVE_LIBPCAP
1456       if (ld.pch != NULL)
1457         pcap_close(ld.pch);
1458 #endif
1459       wtap_dump_close(pdh, &err);
1460       exit(2);
1461     }
1462   }
1463   if (edt != NULL)
1464     epan_dissect_free(edt);
1465   if (cf->rfcode)
1466     clear_fdata(&fdata);
1467 }
1468
1469 static void
1470 show_capture_file_io_error(const char *fname, int err, gboolean is_close)
1471 {
1472   switch (err) {
1473
1474   case ENOSPC:
1475     fprintf(stderr,
1476 "tethereal: Not all the packets could be written to \"%s\" because there is "
1477 "no space left on the file system.\n",
1478         fname);
1479     break;
1480
1481 #ifdef EDQUOT
1482   case EDQUOT:
1483     fprintf(stderr,
1484 "tethereal: Not all the packets could be written to \"%s\" because you are "
1485 "too close to, or over your disk quota.\n",
1486         fname);
1487   break;
1488 #endif
1489
1490   case WTAP_ERR_CANT_CLOSE:
1491     fprintf(stderr,
1492 "tethereal: \"%s\" couldn't be closed for some unknown reason.\n",
1493         fname);
1494     break;
1495
1496   case WTAP_ERR_SHORT_WRITE:
1497     fprintf(stderr,
1498 "tethereal: Not all the packets could be written to \"%s\".\n",
1499         fname);
1500     break;
1501
1502   default:
1503     if (is_close) {
1504       fprintf(stderr,
1505 "tethereal: \"%s\" could not be closed: %s.\n",
1506         fname, wtap_strerror(err));
1507     } else {
1508       fprintf(stderr,
1509 "tethereal: An error occurred while writing to \"%s\": %s.\n",
1510         fname, wtap_strerror(err));
1511     }
1512     break;
1513   }
1514 }
1515
1516 static void
1517 wtap_dispatch_cb_print(u_char *user, const struct wtap_pkthdr *phdr,
1518   long offset, union wtap_pseudo_header *pseudo_header, const u_char *buf)
1519 {
1520   cb_args_t    *args = (cb_args_t *) user;
1521   capture_file *cf = args->cf;
1522   frame_data    fdata;
1523   gboolean      passed;
1524   print_args_t  print_args;
1525   epan_dissect_t *edt;
1526   gboolean      create_proto_tree;
1527   int           i;
1528
1529   cf->count++;
1530
1531   fill_in_fdata(&fdata, cf, phdr, offset);
1532
1533   passed = TRUE;
1534   if (cf->rfcode || verbose)
1535     create_proto_tree = TRUE;
1536   else
1537     create_proto_tree = FALSE;
1538   /* The protocol tree will be "visible", i.e., printed, only if we're
1539      not printing a summary.
1540
1541      We only need the columns if we're *not* verbose; in verbose mode,
1542      we print the protocol tree, not the protocol summary. */
1543   edt = epan_dissect_new(create_proto_tree, verbose);
1544   if (cf->rfcode) {
1545     epan_dissect_prime_dfilter(edt, cf->rfcode);
1546   }
1547   epan_dissect_run(edt, pseudo_header, buf, &fdata, verbose ? NULL : &cf->cinfo);
1548   if (cf->rfcode) {
1549     passed = dfilter_apply_edt(cf->rfcode, edt);
1550   }
1551   if (passed) {
1552     /* The packet passed the read filter. */
1553     ld.packet_count++;
1554     if (verbose) {
1555       /* Print the information in the protocol tree. */
1556       print_args.to_file = TRUE;
1557       print_args.format = PR_FMT_TEXT;
1558       print_args.print_summary = FALSE;
1559       print_args.print_hex = print_hex;
1560       print_args.expand_all = TRUE;
1561       print_args.suppress_unmarked = FALSE;
1562       proto_tree_print(&print_args, edt, stdout);
1563       if (!print_hex) {
1564         /* "print_hex_data()" will put out a leading blank line, as well
1565            as a trailing one; print one here, to separate the packets,
1566            only if "print_hex_data()" won't be called. */
1567         printf("\n");
1568       }
1569     } else {
1570       /* Just fill in the columns. */
1571       epan_dissect_fill_in_columns(edt);
1572
1573       /* Now print them. */
1574       for (i = 0; i < cf->cinfo.num_cols; i++) {
1575         switch (cf->cinfo.col_fmt[i]) {
1576         case COL_NUMBER:
1577           /*
1578            * Don't print this if we're doing a live capture from a network
1579            * interface - if we're doing a live capture, you won't be
1580            * able to look at the capture in the future (it's not being
1581            * saved anywhere), so the frame numbers are unlikely to be
1582            * useful.
1583            *
1584            * (XXX - it might be nice to be able to save and print at
1585            * the same time, sort of like an "Update list of packets
1586            * in real time" capture in Ethereal.)
1587            */
1588           if (cf->iface != NULL)
1589             continue;
1590           printf("%3s", cf->cinfo.col_data[i]);
1591           break;
1592
1593         case COL_CLS_TIME:
1594         case COL_REL_TIME:
1595         case COL_ABS_TIME:
1596         case COL_ABS_DATE_TIME: /* XXX - wider */
1597           printf("%10s", cf->cinfo.col_data[i]);
1598           break;
1599
1600         case COL_DEF_SRC:
1601         case COL_RES_SRC:
1602         case COL_UNRES_SRC:
1603         case COL_DEF_DL_SRC:
1604         case COL_RES_DL_SRC:
1605         case COL_UNRES_DL_SRC:
1606         case COL_DEF_NET_SRC:
1607         case COL_RES_NET_SRC:
1608         case COL_UNRES_NET_SRC:
1609           printf("%12s", cf->cinfo.col_data[i]);
1610           break;
1611
1612         case COL_DEF_DST:
1613         case COL_RES_DST:
1614         case COL_UNRES_DST:
1615         case COL_DEF_DL_DST:
1616         case COL_RES_DL_DST:
1617         case COL_UNRES_DL_DST:
1618         case COL_DEF_NET_DST:
1619         case COL_RES_NET_DST:
1620         case COL_UNRES_NET_DST:
1621           printf("%-12s", cf->cinfo.col_data[i]);
1622           break;
1623
1624         default:
1625           printf("%s", cf->cinfo.col_data[i]);
1626           break;
1627         }
1628         if (i != cf->cinfo.num_cols - 1) {
1629           /*
1630            * This isn't the last column, so we need to print a
1631            * separator between this column and the next.
1632            *
1633            * If we printed a network source and are printing a
1634            * network destination of the same type next, separate
1635            * them with "->"; if we printed a network destination
1636            * and are printing a network source of the same type
1637            * next, separate them with "<-"; otherwise separate them
1638            * with a space.
1639            */
1640           switch (cf->cinfo.col_fmt[i]) {
1641
1642           case COL_DEF_SRC:
1643           case COL_RES_SRC:
1644           case COL_UNRES_SRC:
1645             switch (cf->cinfo.col_fmt[i + 1]) {
1646
1647             case COL_DEF_DST:
1648             case COL_RES_DST:
1649             case COL_UNRES_DST:
1650               printf(" -> ");
1651               break;
1652
1653             default:
1654               putchar(' ');
1655               break;
1656             }
1657             break;
1658
1659           case COL_DEF_DL_SRC:
1660           case COL_RES_DL_SRC:
1661           case COL_UNRES_DL_SRC:
1662             switch (cf->cinfo.col_fmt[i + 1]) {
1663
1664             case COL_DEF_DL_DST:
1665             case COL_RES_DL_DST:
1666             case COL_UNRES_DL_DST:
1667               printf(" -> ");
1668               break;
1669
1670             default:
1671               putchar(' ');
1672               break;
1673             }
1674             break;
1675
1676           case COL_DEF_NET_SRC:
1677           case COL_RES_NET_SRC:
1678           case COL_UNRES_NET_SRC:
1679             switch (cf->cinfo.col_fmt[i + 1]) {
1680
1681             case COL_DEF_NET_DST:
1682             case COL_RES_NET_DST:
1683             case COL_UNRES_NET_DST:
1684               printf(" -> ");
1685               break;
1686
1687             default:
1688               putchar(' ');
1689               break;
1690             }
1691             break;
1692
1693           case COL_DEF_DST:
1694           case COL_RES_DST:
1695           case COL_UNRES_DST:
1696             switch (cf->cinfo.col_fmt[i + 1]) {
1697
1698             case COL_DEF_SRC:
1699             case COL_RES_SRC:
1700             case COL_UNRES_SRC:
1701               printf(" <- ");
1702               break;
1703
1704             default:
1705               putchar(' ');
1706               break;
1707             }
1708             break;
1709
1710           case COL_DEF_DL_DST:
1711           case COL_RES_DL_DST:
1712           case COL_UNRES_DL_DST:
1713             switch (cf->cinfo.col_fmt[i + 1]) {
1714
1715             case COL_DEF_DL_SRC:
1716             case COL_RES_DL_SRC:
1717             case COL_UNRES_DL_SRC:
1718               printf(" <- ");
1719               break;
1720
1721             default:
1722               putchar(' ');
1723               break;
1724             }
1725             break;
1726
1727           case COL_DEF_NET_DST:
1728           case COL_RES_NET_DST:
1729           case COL_UNRES_NET_DST:
1730             switch (cf->cinfo.col_fmt[i + 1]) {
1731
1732             case COL_DEF_NET_SRC:
1733             case COL_RES_NET_SRC:
1734             case COL_UNRES_NET_SRC:
1735               printf(" <- ");
1736               break;
1737
1738             default:
1739               putchar(' ');
1740               break;
1741             }
1742             break;
1743
1744           default:
1745             putchar(' ');
1746             break;
1747           }
1748         }
1749       }
1750       putchar('\n');
1751     }
1752     if (print_hex) {
1753       print_hex_data(stdout, print_args.format, edt);
1754       putchar('\n');
1755     }
1756   }
1757
1758   /* The ANSI C standard does not appear to *require* that a line-buffered
1759      stream be flushed to the host environment whenever a newline is
1760      written, it just says that, on such a stream, characters "are
1761      intended to be transmitted to or from the host environment as a
1762      block when a new-line character is encountered".
1763
1764      The Visual C++ 6.0 C implementation doesn't do what is intended;
1765      even if you set a stream to be line-buffered, it still doesn't
1766      flush the buffer at the end of every line.
1767
1768      So, if the "-l" flag was specified, we flush the standard output
1769      at the end of a packet.  This will do the right thing if we're
1770      printing packet summary lines, and, as we print the entire protocol
1771      tree for a single packet without waiting for anything to happen,
1772      it should be as good as line-buffered mode if we're printing
1773      protocol trees.  (The whole reason for the "-l" flag in either
1774      tcpdump or Tethereal is to allow the output of a live capture to
1775      be piped to a program or script and to have that script see the
1776      information for the packet as soon as it's printed, rather than
1777      having to wait until a standard I/O buffer fills up. */
1778   if (line_buffered)
1779     fflush(stdout);
1780
1781   epan_dissect_free(edt);
1782
1783   clear_fdata(&fdata);
1784 }
1785
1786 char *
1787 file_open_error_message(int err, gboolean for_writing)
1788 {
1789   char *errmsg;
1790   static char errmsg_errno[1024+1];
1791
1792   switch (err) {
1793
1794   case WTAP_ERR_NOT_REGULAR_FILE:
1795     errmsg = "The file \"%s\" is a \"special file\" or socket or other non-regular file.";
1796     break;
1797
1798   case WTAP_ERR_FILE_UNKNOWN_FORMAT:
1799   case WTAP_ERR_UNSUPPORTED:
1800     /* Seen only when opening a capture file for reading. */
1801     errmsg = "The file \"%s\" is not a capture file in a format Tethereal understands.";
1802     break;
1803
1804   case WTAP_ERR_UNSUPPORTED_FILE_TYPE:
1805     /* Seen only when opening a capture file for writing. */
1806     errmsg = "Tethereal does not support writing capture files in that format.";
1807     break;
1808
1809   case WTAP_ERR_UNSUPPORTED_ENCAP:
1810   case WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED:
1811     if (for_writing)
1812       errmsg = "Tethereal cannot save this capture in that format.";
1813     else
1814       errmsg = "The file \"%s\" is a capture for a network type that Tethereal doesn't support.";
1815     break;
1816
1817   case WTAP_ERR_BAD_RECORD:
1818     errmsg = "The file \"%s\" appears to be damaged or corrupt.";
1819     break;
1820
1821   case WTAP_ERR_CANT_OPEN:
1822     if (for_writing)
1823       errmsg = "The file \"%s\" could not be created for some unknown reason.";
1824     else
1825       errmsg = "The file \"%s\" could not be opened for some unknown reason.";
1826     break;
1827
1828   case WTAP_ERR_SHORT_READ:
1829     errmsg = "The file \"%s\" appears to have been cut short"
1830              " in the middle of a packet or other data.";
1831     break;
1832
1833   case WTAP_ERR_SHORT_WRITE:
1834     errmsg = "A full header couldn't be written to the file \"%s\".";
1835     break;
1836
1837   case ENOENT:
1838     if (for_writing)
1839       errmsg = "The path to the file \"%s\" does not exist.";
1840     else
1841       errmsg = "The file \"%s\" does not exist.";
1842     break;
1843
1844   case EACCES:
1845     if (for_writing)
1846       errmsg = "You do not have permission to create or write to the file \"%s\".";
1847     else
1848       errmsg = "You do not have permission to read the file \"%s\".";
1849     break;
1850
1851   case EISDIR:
1852     errmsg = "\"%s\" is a directory (folder), not a file.";
1853     break;
1854
1855   default:
1856     snprintf(errmsg_errno, sizeof(errmsg_errno),
1857              "The file \"%%s\" could not be opened: %s.",
1858              wtap_strerror(err));
1859     errmsg = errmsg_errno;
1860     break;
1861   }
1862   return errmsg;
1863 }
1864
1865 int
1866 open_cap_file(char *fname, gboolean is_tempfile, capture_file *cf)
1867 {
1868   wtap       *wth;
1869   int         err;
1870   char        err_msg[2048+1];
1871
1872   wth = wtap_open_offline(fname, &err, FALSE);
1873   if (wth == NULL)
1874     goto fail;
1875
1876   /* The open succeeded.  Fill in the information for this file. */
1877
1878   /* Initialize all data structures used for dissection. */
1879   init_dissection();
1880
1881   cf->wth = wth;
1882   cf->filed = -1;       /* not used, but set it anyway */
1883   cf->f_len = 0;        /* not used, but set it anyway */
1884
1885   /* Set the file name because we need it to set the follow stream filter.
1886      XXX - is that still true?  We need it for other reasons, though,
1887      in any case. */
1888   cf->filename = g_strdup(fname);
1889
1890   /* Indicate whether it's a permanent or temporary file. */
1891   cf->is_tempfile = is_tempfile;
1892
1893   /* If it's a temporary capture buffer file, mark it as not saved. */
1894   cf->user_saved = !is_tempfile;
1895
1896   cf->cd_t      = wtap_file_type(cf->wth);
1897   cf->count     = 0;
1898   cf->drops_known = FALSE;
1899   cf->drops     = 0;
1900   cf->esec      = 0;
1901   cf->eusec     = 0;
1902   cf->snap      = wtap_snapshot_length(cf->wth);
1903   if (cf->snap == 0) {
1904     /* Snapshot length not known. */
1905     cf->has_snap = FALSE;
1906     cf->snap = WTAP_MAX_PACKET_SIZE;
1907   } else
1908     cf->has_snap = TRUE;
1909   cf->progbar_quantum = 0;
1910   cf->progbar_nextstep = 0;
1911   firstsec = 0, firstusec = 0;
1912   prevsec = 0, prevusec = 0;
1913  
1914   return (0);
1915
1916 fail:
1917   snprintf(err_msg, sizeof err_msg, file_open_error_message(err, FALSE), fname);
1918   fprintf(stderr, "tethereal: %s\n", err_msg);
1919   return (err);
1920 }