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