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