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