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