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