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